code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def dump(self): """ For testing, return a list of dicts describing every currently connected context. """ return [ { 'context_name': context.name, 'via': getattr(self._via_by_context.get(context), 'name', ...
For testing, return a list of dicts describing every currently connected context.
def grid_to_obj(cls, file_path=None, text='', edges=None, columns=None, eval_cells=True, key_on=None): """ This will convert a grid file or grid text into a seaborn table and return it :param file_path: str of the path to the file :param text: str of ...
This will convert a grid file or grid text into a seaborn table and return it :param file_path: str of the path to the file :param text: str of the grid text :param columns: list of str of columns to use :param key_on: list of str of columns to key on :p...
def get_prefix(dir="../"): """ Look for prefix.gkpStore in the upper directory. """ prefix = glob(dir + "*.gkpStore")[0] prefix = op.basename(prefix).rsplit(".", 1)[0] return prefix
Look for prefix.gkpStore in the upper directory.
def makeGln(segID, N, CA, C, O, geo): '''Creates a Glutamine residue''' ##R-Group CA_CB_length=geo.CA_CB_length C_CA_CB_angle=geo.C_CA_CB_angle N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle CB_CG_length=geo.CB_CG_length CA_CB_CG_angle=geo.CA_CB_CG_angle N_CA_CB_CG_diangle=geo.N_CA_CB_CG_d...
Creates a Glutamine residue
def get_display_name(self): """Creates a display name""" return DisplayText(text=self.id_.get_identifier(), language_type=DEFAULT_LANGUAGE_TYPE, script_type=DEFAULT_SCRIPT_TYPE, format_type=DEFAULT_FORMAT_TYPE,)
Creates a display name
def import_private_key_from_file(filename, passphrase=None): """ Read a private Elliptic Curve key from a PEM file. :param filename: The name of the file :param passphrase: A pass phrase to use to unpack the PEM file. :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePriv...
Read a private Elliptic Curve key from a PEM file. :param filename: The name of the file :param passphrase: A pass phrase to use to unpack the PEM file. :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey instance
def groupByKey(self, numPartitions=None): """ Return a new DStream by applying groupByKey on each RDD. """ if numPartitions is None: numPartitions = self._sc.defaultParallelism return self.transform(lambda rdd: rdd.groupByKey(numPartitions))
Return a new DStream by applying groupByKey on each RDD.
def uniform(low:Number, high:Number=None, size:Optional[List[int]]=None)->FloatOrTensor: "Draw 1 or shape=`size` random floats from uniform dist: min=`low`, max=`high`." if high is None: high=low return random.uniform(low,high) if size is None else torch.FloatTensor(*listify(size)).uniform_(low,high)
Draw 1 or shape=`size` random floats from uniform dist: min=`low`, max=`high`.
def _friends_bootstrap_radius(args): """Internal method used to compute the radius (half-side-length) for each ball (cube) used in :class:`RadFriends` (:class:`SupFriends`) using bootstrapping.""" # Unzipping. points, ftype = args rstate = np.random # Resampling. npoints, ndim = points...
Internal method used to compute the radius (half-side-length) for each ball (cube) used in :class:`RadFriends` (:class:`SupFriends`) using bootstrapping.
def get_for_object(self, instance): """ Get log entries for the specified model instance. :param instance: The model instance to get log entries for. :type instance: Model :return: QuerySet of log entries for the given model instance. :rtype: QuerySet """ ...
Get log entries for the specified model instance. :param instance: The model instance to get log entries for. :type instance: Model :return: QuerySet of log entries for the given model instance. :rtype: QuerySet
def get_output_key(self, args, kwargs): """Return the key that the output should be cached with, given arguments, keyword arguments, and a list of arguments to ignore. """ # Get a dictionary mapping argument names to argument values where # ignored arguments are omitted. ...
Return the key that the output should be cached with, given arguments, keyword arguments, and a list of arguments to ignore.
def ipix_swap_axes(self, ipix, colwise=False): """ Return the transposed pixel index from the pixel xy coordinates if colwise is True (False) this assumes the original index was in column wise scheme """ xy = self.ipix_to_xypix(ipix, colwise) return self.xypix_to_ipix(xy...
Return the transposed pixel index from the pixel xy coordinates if colwise is True (False) this assumes the original index was in column wise scheme
def download_url(url, dir_name='.', save_name=None, store_directory=None, messages=True, suffix=''): """Download a file from a url and save it to disk.""" if sys.version_info>=(3,0): from urllib.parse import quote from urllib.request import urlopen from urllib.error import HTTPError, UR...
Download a file from a url and save it to disk.
def close(self): """ Close the link. """ # Stop the comm thread self._thread.stop() # Close the USB dongle try: if self.cfusb: self.cfusb.set_crtp_to_usb(False) self.cfusb.close() except Exception as e: # If we pull...
Close the link.
def compare_hdf_files(file1, file2): """ Compare two hdf files. :param file1: First file to compare. :param file2: Second file to compare. :returns True if they are the same. """ data1 = FileToDict() data2 = FileToDict() scanner1 = data1.scan scanner2 = data2.scan with h5py.File...
Compare two hdf files. :param file1: First file to compare. :param file2: Second file to compare. :returns True if they are the same.
def id_for(self, city_name): """ Returns the long ID corresponding to the first city found that matches the provided city name. The lookup is case insensitive. .. deprecated:: 3.0.0 Use :func:`ids_for` instead. :param city_name: the city name whose ID is looked up ...
Returns the long ID corresponding to the first city found that matches the provided city name. The lookup is case insensitive. .. deprecated:: 3.0.0 Use :func:`ids_for` instead. :param city_name: the city name whose ID is looked up :type city_name: str :returns: a lo...
def set_name_filters(self, name_filters): """Set name filters""" self.name_filters = name_filters self.fsmodel.setNameFilters(name_filters)
Set name filters
async def probe(self): """Probe for devices. This method will probe all adapters that can probe and will send a notification for all devices that we have seen from all adapters. See :meth:`AbstractDeviceAdapter.probe`. """ for adapter in self.adapters: if a...
Probe for devices. This method will probe all adapters that can probe and will send a notification for all devices that we have seen from all adapters. See :meth:`AbstractDeviceAdapter.probe`.
def worker(module_path, python_version, operator_name, occurrence, test_command, timeout): """Mutate the OCCURRENCE-th site for OPERATOR_NAME in MODULE_PATH, run the tests, and report the results. This is fundamentally the single-mutation-and-test-run ...
Mutate the OCCURRENCE-th site for OPERATOR_NAME in MODULE_PATH, run the tests, and report the results. This is fundamentally the single-mutation-and-test-run process implementation. There are three high-level ways that a worker can finish. First, it could fail exceptionally, meaning that some unca...
def unregister(self, observers): u""" Concrete method of Subject.unregister(). Unregister observers as an argument to self.observers. """ if isinstance(observers, list) or isinstance(observers, tuple): for observer in observers: try: ...
u""" Concrete method of Subject.unregister(). Unregister observers as an argument to self.observers.
def mpstatus_to_json(status): '''Translate MPStatus in json string''' msg_keys = list(status.msgs.keys()) data = '{' for key in msg_keys[:-1]: data += mavlink_to_json(status.msgs[key]) + ',' data += mavlink_to_json(status.msgs[msg_keys[-1]]) data += '}' return data
Translate MPStatus in json string
def _parse_json_with_fieldnames(self): """ Parse the raw JSON with all attributes/methods defined in the class, except for the ones defined starting with '_' or flagged in cls._TO_EXCLUDE. The final result is stored in self.json """ for key in dir(self): if n...
Parse the raw JSON with all attributes/methods defined in the class, except for the ones defined starting with '_' or flagged in cls._TO_EXCLUDE. The final result is stored in self.json
def derivatives(self, x, y, Rs, theta_Rs, r_core, center_x=0, center_y=0): """ deflection angles :param x: x coordinate :param y: y coordinate :param Rs: scale radius :param rho0: central core density :param r_core: core radius :param center_x: :pa...
deflection angles :param x: x coordinate :param y: y coordinate :param Rs: scale radius :param rho0: central core density :param r_core: core radius :param center_x: :param center_y: :return:
def validate_access_token(self, client_key, token, request): """Validates access token is available for client.""" log.debug('Validate access token %r for %r', token, client_key) tok = request.access_token or self._tokengetter( client_key=client_key, tok...
Validates access token is available for client.
def cli( ctx, config_file=None, requirements=None, profile=None): ''' An abstraction layer for data storage systems DataFS is a package manager for data. It manages file versions, dependencies, and metadata for individual use or large organizations. For more informa...
An abstraction layer for data storage systems DataFS is a package manager for data. It manages file versions, dependencies, and metadata for individual use or large organizations. For more information, see the docs at https://datafs.readthedocs.io
def find_version(file_path): """ Scrape version information from specified file path. """ with open(file_path, 'r') as f: file_contents = f.read() version_match = re.search(r"^__version__\s*=\s*['\"]([^'\"]*)['\"]", file_contents, re.M) if version_match: ...
Scrape version information from specified file path.
def write_xml_root(xml_root, output_loc=None, filename=None): """Outputs the XML content (from XML element) into a file. If `output_loc` is supplied and it's a file (not directory), the output will be saved there and the `filename` is ignored. Args: xml_root: root element ot the XML document ...
Outputs the XML content (from XML element) into a file. If `output_loc` is supplied and it's a file (not directory), the output will be saved there and the `filename` is ignored. Args: xml_root: root element ot the XML document output_loc: file or directory for saving the file file...
def fix(self, value=None): """ Fix all instances of this variable to a value if provided or to their current value otherwise. Args: value: value to be set. """ if value is None: self._impl.fix() else: self._impl.fix(value)
Fix all instances of this variable to a value if provided or to their current value otherwise. Args: value: value to be set.
def stream_emit(self, record, source_name): """ Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. I...
Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an 'encoding' attribute, it is us...
def iter_fields(node): """Iterate over all fields of a node, only yielding existing fields.""" # CPython 2.5 compat if not hasattr(node, '_fields') or not node._fields: return for field in node._fields: try: yield field, getattr(node, field) except AttributeError: ...
Iterate over all fields of a node, only yielding existing fields.
def validate_configuration(self): """ Validates the provided settings. * Checks ``inherit_image`` format. * Checks ``use_registry_name`` format. * Checks that ``apt_dependencies`` is not set when ``inherit_image`` is set. :raise ArcaMisconfigured: If some of the setting...
Validates the provided settings. * Checks ``inherit_image`` format. * Checks ``use_registry_name`` format. * Checks that ``apt_dependencies`` is not set when ``inherit_image`` is set. :raise ArcaMisconfigured: If some of the settings aren't valid.
def make_heap(n_points, size): """Constructor for the numba enabled heap objects. The heaps are used for approximate nearest neighbor search, maintaining a list of potential neighbors sorted by their distance. We also flag if potential neighbors are newly added to the list or not. Internally this is sto...
Constructor for the numba enabled heap objects. The heaps are used for approximate nearest neighbor search, maintaining a list of potential neighbors sorted by their distance. We also flag if potential neighbors are newly added to the list or not. Internally this is stored as a single ndarray; the first...
def delete_hosted_zone(Id, region=None, key=None, keyid=None, profile=None): ''' Delete a Route53 hosted zone. CLI Example:: salt myminion boto3_route53.delete_hosted_zone Z1234567890 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: r = conn.delet...
Delete a Route53 hosted zone. CLI Example:: salt myminion boto3_route53.delete_hosted_zone Z1234567890
def kill_all(self): """ Kill all currently running jobs. """ logger.info('Job {0} killing all currently running tasks'.format(self.name)) for task in self.tasks.itervalues(): if task.started_at and not task.completed_at: task.kill()
Kill all currently running jobs.
def plotter_cls(self): """The plotter class""" ret = self._plotter_cls if ret is None: self._logger.debug('importing %s', self.module) mod = import_module(self.module) plotter = self.plotter_name if plotter not in vars(mod): raise I...
The plotter class
def countOf(a, b): "Return the number of times b occurs in a." count = 0 for i in a: if i == b: count += 1 return count
Return the number of times b occurs in a.
def _print_csv(result): """Print a JSON list of JSON objects in CSV format.""" if type(result) is not list: raise TypeError("output not able to be displayed as CSV.") first_line = result[0] w = csv.DictWriter(sys.stdout, fieldnames=sorted(first_line.keys())) w.writeheader() for line in r...
Print a JSON list of JSON objects in CSV format.
def push_location( self, element_path, # type: Text array_index=None # type: Optional[int] ): # type: (...) -> None """Push an item onto the state's stack of locations.""" location = ProcessorLocation(element_path=element_path, array_index=array_index) ...
Push an item onto the state's stack of locations.
def transform(self, x, use_spln=False, **kwargs): """ Apply transform to x Parameters ---------- x : float-array-convertible Data to be transformed. Should support conversion to an array of floats. use_spln: bool True - transform using...
Apply transform to x Parameters ---------- x : float-array-convertible Data to be transformed. Should support conversion to an array of floats. use_spln: bool True - transform using the spline specified in self.slpn. If self.spln i...
def setFigForm(): """set the rcparams to EmulateApJ columnwidth=245.26 pts """ fig_width_pt = 245.26*2 inches_per_pt = 1.0/72.27 golden_mean = (math.sqrt(5.)-1.0)/2.0 fig_width = fig_width_pt*inches_per_pt fig_height = fig_width*golden_mean fig_size = [1.5*fig_width, fig_height] pa...
set the rcparams to EmulateApJ columnwidth=245.26 pts
def filter(self, path_filters): """ Filters the loaded AttrTree using the supplied path_filters. """ if not path_filters: return self # Convert string path filters path_filters = [tuple(pf.split('.')) if not isinstance(pf, tuple) else pf for pf in...
Filters the loaded AttrTree using the supplied path_filters.
def filterbank_mel(sr, n_freq, n_mels=128, fmin=0.0, fmax=None, htk=False, norm=1): """[np] """ return mel(sr, (n_freq - 1) * 2, n_mels=n_mels, fmin=fmin, fmax=fmax , htk=htk, norm=norm).astype(K.floatx())
[np]
def _add(app, endpoint, payload): ''' POST a payload ''' nb = _nb_obj(auth_required=True) try: return getattr(getattr(nb, app), endpoint).create(**payload) except RequestError as e: log.error('%s, %s, %s', e.req.request.headers, e.request_body, e.error) return False
POST a payload
def call_senders(self, routing, clients_list, *args, **kwargs): """ Calls senders callbacks """ for func, routings, routings_re in self.senders: call_callback = False # Message is published globally if routing is None or (routings is None and routings...
Calls senders callbacks
def create_order(self, order_deets): """Creates a new order transaction.""" request = self._post('transactions/orders', order_deets) return self.responder(request)
Creates a new order transaction.
def analyze(self, scratch, **kwargs): """Run and return the results from the BlockCounts plugin.""" file_blocks = Counter() for script in self.iter_scripts(scratch): for name, _, _ in self.iter_blocks(script.blocks): file_blocks[name] += 1 self.blocks.update(f...
Run and return the results from the BlockCounts plugin.
def substrate_a(self, **kwargs): ''' Returns the substrate's lattice parameter. ''' if self.substrate is not None: return self.substrate.a(**kwargs) else: return (self.unstrained.a(**kwargs) / (1. - self.strain_in_plane(**kwargs)))
Returns the substrate's lattice parameter.
def replace_variables(self, text): """Replace variable placeholders in `text` with values from the virtual env. The variables are: - {python-executable} Args: text: The text to do replacment int. Returns: The text after replacement. """ variables ...
Replace variable placeholders in `text` with values from the virtual env. The variables are: - {python-executable} Args: text: The text to do replacment int. Returns: The text after replacement.
def stacked(requestContext, seriesLists, stackName='__DEFAULT__'): """ Takes one metric or a wildcard seriesList and change them so they are stacked. This is a way of stacking just a couple of metrics without having to use the stacked area mode (that stacks everything). By means of this a mixed stac...
Takes one metric or a wildcard seriesList and change them so they are stacked. This is a way of stacking just a couple of metrics without having to use the stacked area mode (that stacks everything). By means of this a mixed stacked and non stacked graph can be made It can also take an optional argumen...
def compose(self, bbox=None, **kwargs): """ Compose the artboard. See :py:func:`~psd_tools.compose` for available extra arguments. :param bbox: Viewport tuple (left, top, right, bottom). :return: :py:class:`PIL.Image`, or `None` if there is no pixel. """ from ps...
Compose the artboard. See :py:func:`~psd_tools.compose` for available extra arguments. :param bbox: Viewport tuple (left, top, right, bottom). :return: :py:class:`PIL.Image`, or `None` if there is no pixel.
def create_authorization_response(self, uri, http_method='GET', body=None, headers=None, scopes=None, credentials=None): """Extract response_type and route to the designated handler.""" request = Request( uri, http_method=http_method, body=body, headers=...
Extract response_type and route to the designated handler.
def identify_marker_genes_corr(self, labels=None, n_genes=4000): """ Ranking marker genes based on their respective magnitudes in the correlation dot products with cluster-specific reference expression profiles. Parameters ---------- labels - numpy.array or str...
Ranking marker genes based on their respective magnitudes in the correlation dot products with cluster-specific reference expression profiles. Parameters ---------- labels - numpy.array or str, optional, default None Cluster labels to use for marker gene identifica...
def get_global(self): """Gets the current global evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations. """ if self._has_global_stats: if self.global_num_inst ...
Gets the current global evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations.
def get_multi_word_keywords(features): """This returns an OrderedDict containing the multi word keywords in order of length. This is so the tokenizer will match the longer matches before the shorter matches """ keys = { 'is not': Token(TokenTypes.NOT_EQUAL, 'is not'), ...
This returns an OrderedDict containing the multi word keywords in order of length. This is so the tokenizer will match the longer matches before the shorter matches
def approximate_inverse( distribution, qloc, parameters=None, cache=None, iterations=100, tol=1e-5, seed=None, ): """ Calculate the approximation of the inverse Rosenblatt transformation. Uses forward Rosenblatt, probability density function (derivati...
Calculate the approximation of the inverse Rosenblatt transformation. Uses forward Rosenblatt, probability density function (derivative) and boundary function to apply hybrid Newton-Raphson and binary search method. Args: distribution (Dist): Distribution to estimate inverse Rosenblatt. ql...
def AddAnalysisReport(self, analysis_report): """Adds an analysis report. Args: analysis_report (AnalysisReport): analysis report. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed. """ self._RaiseIfNotWritable() analysis_report =...
Adds an analysis report. Args: analysis_report (AnalysisReport): analysis report. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
def start_timer(self, timer_id, timeout): """ Start a timer or restart an active one. The timeout is given in milliseconds. If a timer with the same name already exists, it is restarted with the specified timeout. Note that the timeout is intended as the minimum time until the t...
Start a timer or restart an active one. The timeout is given in milliseconds. If a timer with the same name already exists, it is restarted with the specified timeout. Note that the timeout is intended as the minimum time until the timer's expiration, but may vary due to the state of th...
def convert_csv_str_to_list(csv_str: str) -> list: """Convert CSV str to list""" csv_str = re.sub("^\s*{", "", csv_str) csv_str = re.sub("}\s*$", "", csv_str) r = csv.reader([csv_str]) row = list(r)[0] new = [] for col in row: col = re.sub('^\s*"?\s*', "", col) col = re.sub(...
Convert CSV str to list
def parse_schema(schema): """Parse a val schema definition.""" if isinstance(schema, BaseSchema): return schema.validate if type(schema) is type: return _build_type_validator(schema) if isinstance(schema, dict): return _build_dict_validator(schema) if type(schema) in (lis...
Parse a val schema definition.
def get_default_config(self): """ Returns the default collector settings """ config = super(MemoryCollector, self).get_default_config() config.update({ 'path': 'memory', 'method': 'Threaded', 'force_psutil': 'False' # Collect all th...
Returns the default collector settings
def _get_operation_http(self): """Checks the status of the current operation. Uses HTTP request to check. :rtype: :class:`~google.longrunning.operations_pb2.Operation` :returns: The latest status of the current operation. """ path = "operations/%s" % (self.name,) ...
Checks the status of the current operation. Uses HTTP request to check. :rtype: :class:`~google.longrunning.operations_pb2.Operation` :returns: The latest status of the current operation.
def top2_full(votes): """ Description: Top 2 alternatives 16 moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers) """ res = np.zeros(16) for vote in votes: # the top ranked alternative is in vote[0][0], second in vote...
Description: Top 2 alternatives 16 moment conditions values calculation Parameters: votes: ordinal preference data (numpy ndarray of integers)
def __Script_Editor_Output_plainTextEdit_set_default_view_state(self): """ Sets the **Script_Editor_Output_plainTextEdit** Widget default View state. """ self.Script_Editor_Output_plainTextEdit.moveCursor(QTextCursor.End) self.Script_Editor_Output_plainTextEdit.ensureCursorVisib...
Sets the **Script_Editor_Output_plainTextEdit** Widget default View state.
def find_class(self): """Return a class related with this type.""" if self.value <= 1: return InstructionsProperty elif self.value <= 3: return NextTablesProperty elif self.value <= 7: return ActionsProperty return OxmProperty
Return a class related with this type.
def _setup_config(self, dist, filename, section, vars, verbosity): """ Called to setup an application, given its configuration file/directory. The default implementation calls ``package.websetup.setup_config(command, filename, section, vars)`` or ``package.websetup.setup...
Called to setup an application, given its configuration file/directory. The default implementation calls ``package.websetup.setup_config(command, filename, section, vars)`` or ``package.websetup.setup_app(command, config, vars)`` With ``setup_app`` the ``config`` object...
def index(self, x, y): """ Given (x, y) in crs, return the (row, column) on the raster """ col, row = [math.floor(a) for a in (~self.affine * (x, y))] return row, col
Given (x, y) in crs, return the (row, column) on the raster
def sync(self, folders): """Syncs a list of folders to their assicated buckets. folders: A list of 2-tuples in the form (folder, bucket) """ if not folders: raise ValueError("No folders to sync given") for folder in folders: self.sync_folder(*fold...
Syncs a list of folders to their assicated buckets. folders: A list of 2-tuples in the form (folder, bucket)
def fix_schema_node_ordering(parent): """ Fix the ordering of children under the criteria node to ensure that IndicatorItem/Indicator order is preserved, as per XML Schema. :return: """ children = parent.getchildren() i_nodes = [node for node in children if node....
Fix the ordering of children under the criteria node to ensure that IndicatorItem/Indicator order is preserved, as per XML Schema. :return:
def generate_thumbnail_url(image_url, height, width, favicon_domain=None, zoom_face=True, api_key=None): """Take an image URL and generate a thumbnail URL for that image. Args: image_url -- unicode (or utf8 encoded str), URL of the image you want to th...
Take an image URL and generate a thumbnail URL for that image. Args: image_url -- unicode (or utf8 encoded str), URL of the image you want to thumbnail. height -- int, requested thumbnail height in pixels, maximum 500. width -- int, requested thumbnail width in pixels, max...
def verify_environment(self, environment_id): ''' verify_environment(self, environment_id) Verifies validity of an existing environment :Parameters: * *environment_id* (`string`) -- Environment identifier :return: Success or errors in case the verification failed ...
verify_environment(self, environment_id) Verifies validity of an existing environment :Parameters: * *environment_id* (`string`) -- Environment identifier :return: Success or errors in case the verification failed :Return Example: .. code-block:: json # ...
def ml(line, cell=None): """Implements the datalab cell magic for MLWorkbench operations. Args: line: the contents of the ml command line. Returns: The results of executing the cell. """ parser = google.datalab.utils.commands.CommandParser( prog='%ml', description=textwrap.dedent("""\ ...
Implements the datalab cell magic for MLWorkbench operations. Args: line: the contents of the ml command line. Returns: The results of executing the cell.
def load_byte(buf, pos): """Load single byte""" end = pos + 1 if end > len(buf): raise BadRarFile('cannot load byte') return S_BYTE.unpack_from(buf, pos)[0], end
Load single byte
async def get_track(self, spotify_id: str) -> Track: """Retrive an track with a spotify ID. Parameters ---------- spotify_id : str The ID to search for. Returns ------- track : Track The track from the ID """ data = await ...
Retrive an track with a spotify ID. Parameters ---------- spotify_id : str The ID to search for. Returns ------- track : Track The track from the ID
def shrink(self, new_size): """ Reduce the size of this block :param int new_size: The new size :return: None """ self.size = new_size if self.sort == 'string': self.null_terminated = False # string without the null byte terminator self._...
Reduce the size of this block :param int new_size: The new size :return: None
def exact_match(pred, target): """ Compute "Exact match" metric, also called "Subset accuracy" indicating the number of samples that have all their labels classified correctly. See https://en.wikipedia.org/wiki/Multi-label_classification :param pred: Predicted labels :param target: Correct labels :return...
Compute "Exact match" metric, also called "Subset accuracy" indicating the number of samples that have all their labels classified correctly. See https://en.wikipedia.org/wiki/Multi-label_classification :param pred: Predicted labels :param target: Correct labels :return: containing a 1 at the prediction wher...
def reply_location( self, latitude: float, longitude: float, quote: bool = None, disable_notification: bool = None, reply_to_message_id: int = None, reply_markup: Union[ "pyrogram.InlineKeyboardMarkup", "pyrogram.ReplyKeyboardMarkup", ...
Bound method *reply_location* of :obj:`Message <pyrogram.Message>`. Use as a shortcut for: .. code-block:: python client.send_location( chat_id=message.chat.id, latitude=41.890251, longitude=12.492373 ) Example: ...
def _init_file(self): """ Initialize a new password file and set the reference password. """ self.keyring_key = self._get_new_password() # set a reference password, used to check that the password provided # matches for subsequent checks. self.set_password('keyri...
Initialize a new password file and set the reference password.
def keep_everything_scorer(checked_ids): """Returns every query and every match in checked_ids, with best score.""" result = checked_ids.keys() for i in checked_ids.values(): result.extend(i.keys()) return dict.fromkeys(result).keys()
Returns every query and every match in checked_ids, with best score.
def transform(self, fn, lazy=True): """Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. ...
Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. lazy : bool, default True If False...
def kick_jobs(self, num_jobs): """Kick some number of jobs from the buried queue onto the ready queue. :param num_jobs: Number of jobs to kick :type num_jobs: int If not that many jobs are in the buried queue, it will kick as many as it can.""" with self._sock_ctx() as socket: ...
Kick some number of jobs from the buried queue onto the ready queue. :param num_jobs: Number of jobs to kick :type num_jobs: int If not that many jobs are in the buried queue, it will kick as many as it can.
def find_best_periods(self, model, n_periods=5, return_scores=False): """Find the `n_periods` best periods in the model""" # compute the estimated peak width from the data range tmin, tmax = np.min(model.t), np.max(model.t) width = 2 * np.pi / (tmax - tmin) # raise a ValueError...
Find the `n_periods` best periods in the model
def prompt_unset_inputs(self, force=False): """ Prompt for unset input values """ for k, v in self._inputs.items(): if force or v.is_empty(False): self.get_input(k, force=force)
Prompt for unset input values
def _make_gist(contents, description='', filename='data.geojson'): """ Create and return an anonymous gist with a single file and specified contents """ ghapi = github3.GitHub() files = {filename: {'content': contents}} gist = ghapi.create_gist(description, files) return gist
Create and return an anonymous gist with a single file and specified contents
def block_comment(solver, start, end): '''embedable block comment''' text, pos = solver.parse_state length = len(text) startlen = len(start) endlen = len(end) if pos==length: return if not text[pos:].startswith(start): return level = 1 p = pos+1 while p<length: if text[p:].starts...
embedable block comment
def iodp_samples_csv(lims_sample_file, spec_file='specimens.txt',samp_file="samples.txt", site_file="sites.txt",loc_file="locations.txt",dir_path='.', input_dir_path='',comp_depth_key="",lat="",lon="", exp_name="",exp_desc="",age_low=0,age_high=200e6): ...
Convert IODP samples data file downloaded from LIMS as .csv file into datamodel 3.0 MagIC samples file. Default is to overwrite samples.txt in your working directory. Parameters ---------- lims_sample_file : str path to IODP sample file to convert dir_path : str working directory, d...
def attention_check(self, participant=None): """Check a participant paid attention.""" if self.catch_repeats == 0: return True scores = [n.score for n in participant.nodes() if n.network.role == "catch"] avg = float(sum(scores)) / float(len(scores)) return avg >= sel...
Check a participant paid attention.
def add_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Adds `filepaths` to the `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an it...
Adds `filepaths` to the `self.plugin_filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable If `except_blacklisted` is `True`, all `filepaths` that have bee...
def xml_report(self, file_path): """Generate and save XML report""" self.logger.debug('Generating XML report') report = self.zap.core.xmlreport() self._write_report(report, file_path)
Generate and save XML report
def _list_response(self, response): """ This method check if the response is a dict and wrap it into a list. If the response is already a list, it returns the response directly. This workaround is necessary because the API doesn't return a list if only one item is found. ...
This method check if the response is a dict and wrap it into a list. If the response is already a list, it returns the response directly. This workaround is necessary because the API doesn't return a list if only one item is found.
def get_complete_slug(self, language=None, hideroot=True): """Return the complete slug of this page by concatenating all parent's slugs. :param language: the wanted slug language.""" if not language: language = settings.PAGE_DEFAULT_LANGUAGE if self._complete_slug a...
Return the complete slug of this page by concatenating all parent's slugs. :param language: the wanted slug language.
def LoadCHM(self, archiveName): '''Loads a CHM archive. This function will also call GetArchiveInfo to obtain information such as the index file name and the topics file. It returns 1 on success, and 0 if it fails. ''' if self.filename is not None: self.CloseC...
Loads a CHM archive. This function will also call GetArchiveInfo to obtain information such as the index file name and the topics file. It returns 1 on success, and 0 if it fails.
def _folder_item_calculation(self, analysis_brain, item): """Set the analysis' calculation and interims to the item passed in. :param analysis_brain: Brain that represents an analysis :param item: analysis' dictionary counterpart that represents a row """ is_editable = self.is_...
Set the analysis' calculation and interims to the item passed in. :param analysis_brain: Brain that represents an analysis :param item: analysis' dictionary counterpart that represents a row
def _dayofmonth(hardday, month, year): ''' Returns a valid day of the month given the desired value. Negative values are interpreted as offset backwards from the last day of the month, with -1 representing the last day of the month. Out-of-range values are clamped to the first or last day of the month...
Returns a valid day of the month given the desired value. Negative values are interpreted as offset backwards from the last day of the month, with -1 representing the last day of the month. Out-of-range values are clamped to the first or last day of the month.
def imported_from_bootstrap(self, module): """Return ``True`` if the given ``module`` object was imported from bootstrap code. :param module: The module to check the provenance of. :type module: :class:`types.ModuleType` :rtype: bool """ # A vendored module. path = getattr(module, '__file_...
Return ``True`` if the given ``module`` object was imported from bootstrap code. :param module: The module to check the provenance of. :type module: :class:`types.ModuleType` :rtype: bool
def _load_dataset_with_area(self, dsid, coords): """Loads *dsid* and it's area if available.""" file_handlers = self._get_file_handlers(dsid) if not file_handlers: return area = self._load_dataset_area(dsid, file_handlers, coords) try: ds = self._load_da...
Loads *dsid* and it's area if available.
def library_hierarchy_depth(self): """ Calculates the library hierarchy depth Counting starts at the current library state. So if the there is no upper library state the depth is one. :return: library hierarchy depth :rtype: int """ current_library_hierarchy_dep...
Calculates the library hierarchy depth Counting starts at the current library state. So if the there is no upper library state the depth is one. :return: library hierarchy depth :rtype: int
def eeg_gfp(raws, gflp_method="GFPL1", scale=True, normalize=True, smoothing=None): """ Run the GFP analysis. """ # Load data if necessary # if isinstance(raws, str): # raws = load_object(filename=raws) # Initialize empty dict gfp = {} for participant in raws: gfp[partic...
Run the GFP analysis.
def write(self, file_name): """ Writes the chapter object to an xhtml file. Args: file_name (str): The full name of the xhtml file to save to. """ try: assert file_name[-6:] == '.xhtml' except (AssertionError, IndexError): raise ValueE...
Writes the chapter object to an xhtml file. Args: file_name (str): The full name of the xhtml file to save to.
def world_to_view(v): """world coords to view coords; v an eu.Vector2, returns (float, float)""" return v.x * config.scale_x, v.y * config.scale_y
world coords to view coords; v an eu.Vector2, returns (float, float)
def input_format(self, content_type): """Returns the set input_format handler for the given content_type""" return getattr(self, '_input_format', {}).get(content_type, hug.defaults.input_format.get(content_type, None))
Returns the set input_format handler for the given content_type