positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def _create(self): """Create the Whisper file on disk""" if not os.path.exists(settings.SALMON_WHISPER_DB_PATH): os.makedirs(settings.SALMON_WHISPER_DB_PATH) archives = [whisper.parseRetentionDef(retentionDef) for retentionDef in settings.ARCHIVES.split(",")] ...
Create the Whisper file on disk
def p_arr_access_expr(p): """ func_call : ARRAY_ID arg_list """ # This is an array access p[0] = make_call(p[1], p.lineno(1), p[2]) if p[0] is None: return entry = SYMBOL_TABLE.access_call(p[1], p.lineno(1)) entry.accessed = True
func_call : ARRAY_ID arg_list
def launch_browser(self, profile, timeout=30): """Launches the browser for the given profile name. It is assumed the profile already exists. """ self.profile = profile self._start_from_profile_path(self.profile.path) self._wait_until_connectable(timeout=timeout)
Launches the browser for the given profile name. It is assumed the profile already exists.
def clone(self, into=None): """Clone this chroot. :keyword into: (optional) An optional destination directory to clone the Chroot into. If not specified, a temporary directory will be created. .. versionchanged:: 0.8 The temporary directory created when ``into`` is not specified is now garbag...
Clone this chroot. :keyword into: (optional) An optional destination directory to clone the Chroot into. If not specified, a temporary directory will be created. .. versionchanged:: 0.8 The temporary directory created when ``into`` is not specified is now garbage collected on interpreter ex...
def list_staged_files(self) -> typing.List[str]: """ :return: staged files :rtype: list of str """ staged_files: typing.List[str] = [x.a_path for x in self.repo.index.diff('HEAD')] LOGGER.debug('staged files: %s', staged_files) return staged_files
:return: staged files :rtype: list of str
def load(self, fname): """ .. todo:: REPO.load docstring """ # Imports import h5py as h5 from ..error import RepoError # If repo not None, complain if not self._repo == None: raise RepoError(RepoError.STATUS, "Repository already o...
.. todo:: REPO.load docstring
def _unpack_content(raw_data, content_type=None): """Extract the correct structure for deserialization. If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. if we can't, raise. Your Pipeline should have a RawDeserializer. If not a pipeline response and raw_d...
Extract the correct structure for deserialization. If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. if we can't, raise. Your Pipeline should have a RawDeserializer. If not a pipeline response and raw_data is bytes or string, use content-type to decode it...
def create(message: str, pubkey: Optional[str] = None, signing_keys: Optional[List[SigningKey]] = None, message_comment: Optional[str] = None, signatures_comment: Optional[str] = None) -> str: """ Encrypt a message in ascii armor format, optionally signing it :param message: Utf-...
Encrypt a message in ascii armor format, optionally signing it :param message: Utf-8 message :param pubkey: Public key of recipient for encryption :param signing_keys: Optional list of SigningKey instances :param message_comment: Optional message comment field :param signatures_...
def find_xor_mask(data, alphabet=None, max_depth=3, min_depth=0, iv=None): """ Produce a series of bytestrings that when XORed together end up being equal to ``data`` and only contain characters from the giving ``alphabet``. The initial state (or previous state) can be given as ``iv``. Argument...
Produce a series of bytestrings that when XORed together end up being equal to ``data`` and only contain characters from the giving ``alphabet``. The initial state (or previous state) can be given as ``iv``. Arguments: data (bytes): The data to recreate as a series of XOR operations. al...
def remove_stage_from_deployed_values(key, filename): # type: (str, str) -> None """Delete a top level key from the deployed JSON file.""" final_values = {} # type: Dict[str, Any] try: with open(filename, 'r') as f: final_values = json.load(f) except IOError: # If there ...
Delete a top level key from the deployed JSON file.
def set_border(self, thickness, color="black"): """ Sets the border thickness and color. :param int thickness: The thickenss of the border. :param str color: The color of the border. """ self._set_tk_config("highlightthickness", thickness) ...
Sets the border thickness and color. :param int thickness: The thickenss of the border. :param str color: The color of the border.
def authenticate(self, msg: Dict, identifier: Optional[str] = None, signature: Optional[str] = None, threshold: Optional[int] = None, key: Optional[str] = None) -> str: """ Authenticate the client's ...
Authenticate the client's message with the signature provided. :param identifier: some unique identifier; if None, then try to use msg['identifier'] as identifier :param signature: a utf-8 and base58 encoded signature :param msg: the message to authenticate :param threshold: The...
def show_input(self, template_helper, language, seed): """ Show multiple choice problems """ choices = [] limit = self._limit if limit == 0: limit = len(self._choices) # no limit rand = Random("{}#{}#{}".format(self.get_task().get_id(), self.get_id(), seed)) ...
Show multiple choice problems
def update(cls, **kwargs): ''' If a record matching the instance id already exists in the database, update it. If a record matching the instance id does not already exist, create a new record. ''' q = cls._get_instance(**{'id': kwargs['id']}) if q: fo...
If a record matching the instance id already exists in the database, update it. If a record matching the instance id does not already exist, create a new record.
async def parallel_results(future_map: Sequence[Tuple]) -> Dict: """ Run parallel execution of futures and return mapping of their results to the provided keys. Just a neat shortcut around ``asyncio.gather()`` :param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_conten...
Run parallel execution of futures and return mapping of their results to the provided keys. Just a neat shortcut around ``asyncio.gather()`` :param future_map: Keys to futures mapping, e.g.: ( ('nav', get_nav()), ('content, get_content()) ) :return: Dict with futures results mapped to keys {'nav': {1:2}, '...
def invoke_function(self, ctx, name, arguments): """ Invokes the given function :param ctx: the evaluation context :param name: the function name (case insensitive) :param arguments: the arguments to be passed to the function :return: the function return value """...
Invokes the given function :param ctx: the evaluation context :param name: the function name (case insensitive) :param arguments: the arguments to be passed to the function :return: the function return value
def decode_network(objects): """Return root object from ref-containing obj table entries""" def resolve_ref(obj, objects=objects): if isinstance(obj, Ref): # first entry is 1 return objects[obj.index - 1] else: return obj # Reading the ObjTable backwards ...
Return root object from ref-containing obj table entries
def git_support(fn, command): """Resolves git aliases and supports testing for both git and hub.""" # supports GitHub's `hub` command # which is recommended to be used with `alias git=hub` # but at this point, shell aliases have already been resolved if not is_app(command, 'git', 'hub'): ret...
Resolves git aliases and supports testing for both git and hub.
def get_port_area(self, view): """Calculates the drawing area affected by the (hovered) port """ state_v = self.parent center = self.handle.pos margin = self.port_side_size / 4. if self.side in [SnappedSide.LEFT, SnappedSide.RIGHT]: height, width = self.port_s...
Calculates the drawing area affected by the (hovered) port
def search_and_extract_nucleotides_matching_nucleotide_database(self, unpack, euk_check, search_method, ...
As per nt_db_search() except slightly lower level. Search an input read set (unpack) and then extract the sequences that hit. Parameters ---------- hmmsearch_output_table: str path to hmmsearch output table hit_reads_fasta: str path to hit nucleotide sequ...
def apns_send_bulk_message( registration_ids, alert, application_id=None, certfile=None, **kwargs ): """ Sends an APNS notification to one or more registration_ids. The registration_ids argument needs to be a list. Note that if set alert should always be a string. If it is not set, it won"t be included in the no...
Sends an APNS notification to one or more registration_ids. The registration_ids argument needs to be a list. Note that if set alert should always be a string. If it is not set, it won"t be included in the notification. You will need to pass None to this for silent notifications.
def getRemainingCredits(self): """ Returns the remaining credits for the license key used after the request was made :return: String with remaining credits """ if 'status' in self._response.keys(): if (self._response['status'] is not None) and ('remainin...
Returns the remaining credits for the license key used after the request was made :return: String with remaining credits
def vote_up_idea(self, *args, **kwargs): """ :allowed_param: 'ideaId', 'myVote' (optional) """ kwargs.update({'headers': {'content-type':'application/json'}}) return bind_api( api=self, path='/ideas/{ideaId}/vote/up', method='POST', payload...
:allowed_param: 'ideaId', 'myVote' (optional)
def term_count_buckets(self): """ Returns: dict: A dictionary that maps occurrence counts to the terms that appear that many times in the text. """ buckets = {} for term, count in self.term_counts().items(): if count in buckets: buckets[count...
Returns: dict: A dictionary that maps occurrence counts to the terms that appear that many times in the text.
def _contains_blinded_text(stats_xml): """ Heuristic to determine whether the treebank has blinded texts or not """ tree = ET.parse(stats_xml) root = tree.getroot() total_tokens = int(root.find('size/total/tokens').text) unique_lemmas = int(root.find('lemmas').get('unique')) # assume the corpus...
Heuristic to determine whether the treebank has blinded texts or not
def close(self): """ Close all pooled connections and disable the pool. """ # Disable access to the pool old_pool, self.pool = self.pool, None try: while True: conn = old_pool.get(block=False) if conn: conn....
Close all pooled connections and disable the pool.
def alert_type(self, alert_type): """Sets the alert_type of this Alert. Alert type. # noqa: E501 :param alert_type: The alert_type of this Alert. # noqa: E501 :type: str """ allowed_values = ["CLASSIC", "THRESHOLD"] # noqa: E501 if alert_type not in allowed_v...
Sets the alert_type of this Alert. Alert type. # noqa: E501 :param alert_type: The alert_type of this Alert. # noqa: E501 :type: str
def _create_repo(line, filename): ''' Create repo ''' repo = {} if line.startswith('#'): repo['enabled'] = False line = line[1:] else: repo['enabled'] = True cols = salt.utils.args.shlex_split(line.strip()) repo['compressed'] = not cols[0] in 'src' repo['name'...
Create repo
def resize(self, logical_size): """Starts resizing this medium. This means that the nominal size of the medium is set to the new value. Both increasing and decreasing the size is possible, and there are no safety checks, since VirtualBox does not make any assumptions about the medium con...
Starts resizing this medium. This means that the nominal size of the medium is set to the new value. Both increasing and decreasing the size is possible, and there are no safety checks, since VirtualBox does not make any assumptions about the medium contents. Resizing usually ne...
def verb_chain_texts(self): """The list of texts of ``verb_chains`` layer elements.""" if not self.is_tagged(VERB_CHAINS): self.tag_verb_chains() return self.texts(VERB_CHAINS)
The list of texts of ``verb_chains`` layer elements.
def metrics_for_mode(self, mode): """Metrics available for a given mode.""" if mode not in self._values: logging.info("Mode %s not found", mode) return [] return sorted(list(self._values[mode].keys()))
Metrics available for a given mode.
def probabilities(value, rows=0, cols=0): """ :param value: input string, comma separated or space separated :param rows: the number of rows if the floats are in a matrix (0 otherwise) :param cols: the number of columns if the floats are in a matrix (or 0 :returns: a list of probabilities >>> p...
:param value: input string, comma separated or space separated :param rows: the number of rows if the floats are in a matrix (0 otherwise) :param cols: the number of columns if the floats are in a matrix (or 0 :returns: a list of probabilities >>> probabilities('') [] >>> probabilities('1') ...
def event_params(segments, params, band=None, n_fft=None, slopes=None, prep=None, parent=None): """Compute event parameters. Parameters ---------- segments : instance of wonambi.trans.select.Segments list of segments, with time series and metadata params : dict of bool...
Compute event parameters. Parameters ---------- segments : instance of wonambi.trans.select.Segments list of segments, with time series and metadata params : dict of bool, or str 'dur', 'minamp', 'maxamp', 'ptp', 'rms', 'power', 'peakf', 'energy', 'peakef'. If 'all', a dict...
def spy(object): """Spy an object. Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afterwards. Returns Dummy-like, almost empty object as proxy to `object`. The *returned* object must be injected and used by the code under ...
Spy an object. Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afterwards. Returns Dummy-like, almost empty object as proxy to `object`. The *returned* object must be injected and used by the code under test; after that all...
def generate_ulid_as_uuid(timestamp=None, monotonic=False): """ Generate an ULID, but expressed as an UUID. :param timestamp: An optional timestamp override. If `None`, the current time is used. :type timestamp: int|float|datetime.datetime|None :param monotonic: Attempt to ens...
Generate an ULID, but expressed as an UUID. :param timestamp: An optional timestamp override. If `None`, the current time is used. :type timestamp: int|float|datetime.datetime|None :param monotonic: Attempt to ensure ULIDs are monotonically increasing. Monotonic ...
def flux_variability(model, reactions, fixed, tfba, solver): """Find the variability of each reaction while fixing certain fluxes. Yields the reaction id, and a tuple of minimum and maximum value for each of the given reactions. The fixed reactions are given in a dictionary as a reaction id to value ma...
Find the variability of each reaction while fixing certain fluxes. Yields the reaction id, and a tuple of minimum and maximum value for each of the given reactions. The fixed reactions are given in a dictionary as a reaction id to value mapping. This is an implementation of flux variability analysis (...
def class_name(self) -> str: """ Makes the fist letter big, keep the rest of the camelCaseApiName. """ if not self.api_name: # empty string return self.api_name # end if return self.api_name[0].upper() + self.api_name[1:]
Makes the fist letter big, keep the rest of the camelCaseApiName.
def _matrix_grad(q, h, h_dx, t, t_prime): ''' Returns the gradient with respect to a single variable''' N = len(q) W = np.zeros([N, N]) Wprime = np.zeros([N, N]) for i in range(N): W[i, i] = 0.5*(h[min(i+1, N-1)] - h[max(i-1, 0)]) Wprime[i, i] = \ 0.5*(h_dx[min(i+1, N-1)...
Returns the gradient with respect to a single variable
def close(self): ''' Close the application and all installed plugins. ''' for plugin in self.plugins: if hasattr(plugin, 'close'): plugin.close() self.stopped = True
Close the application and all installed plugins.
def get_recordInfo(self, headers, zoneID, zone, records): """Get the information of the records.""" if 'None' in records: #If ['None'] in record argument, query all. recordQueryEnpoint = '/' + zoneID + '/dns_records&per_page=100' recordUrl = self.BASE_URL + recordQueryEnpoint ...
Get the information of the records.
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs): ''' Boot a cloud server. ''' nt_ks = self.compute_conn kwargs['name'] = name kwargs['flavor'] = flavor_id kwargs['image'] = image_id or None ephemeral = kwargs.pop('ephemeral', []) ...
Boot a cloud server.
def post(self, request, key): """Create new email address that will wait for validation""" email = request.POST.get('email') user_id = request.POST.get('user') if not email: return http.HttpResponseBadRequest() try: EmailAddressValidation.objects.create(...
Create new email address that will wait for validation
def getFactory(self): """ Return a server factory which creates AMP protocol instances. """ factory = ServerFactory() def protocol(): proto = CredReceiver() proto.portal = Portal( self.loginSystem, [self.loginSystem, ...
Return a server factory which creates AMP protocol instances.
def Cx(mt, x): """ Return the Cx """ return ((1 / (1 + mt.i)) ** (x + 1)) * mt.dx[x] * ((1 + mt.i) ** 0.5)
Return the Cx
def image_import(infile, force): """Import image anchore data from a JSON file.""" ecode = 0 try: with open(infile, 'r') as FH: savelist = json.loads(FH.read()) except Exception as err: anchore_print_err("could not load input file: " + str(err)) ecode = 1 if...
Import image anchore data from a JSON file.
def get_stats(self, start=int(time()), stop=int(time())+10, step=10): """ Get stats of a monitored machine :param start: Time formatted as integer, from when to fetch stats (default now) :param stop: Time formatted as integer, until when to fetch stats (default +10 seconds) :par...
Get stats of a monitored machine :param start: Time formatted as integer, from when to fetch stats (default now) :param stop: Time formatted as integer, until when to fetch stats (default +10 seconds) :param step: Step to fetch stats (default 10 seconds) :returns: A dict of stats
def save(self): ''' Save an instance of a Union object ''' client = self._new_api_client() params = {'id': self.id} if hasattr(self, 'id') else {} action = 'patch' if hasattr(self, 'id') else 'post' saved_model = client.make_request(self, action, url_params=param...
Save an instance of a Union object
def WriteUInt256(self, value): """ Write a UInt256 type to the stream. Args: value (UInt256): Raises: Exception: when `value` is not of neocore.UInt256 type. """ if type(value) is UInt256: value.Serialize(self) else: ...
Write a UInt256 type to the stream. Args: value (UInt256): Raises: Exception: when `value` is not of neocore.UInt256 type.
def stop_polling(self): """ Break long-polling process. :return: """ if hasattr(self, '_polling') and self._polling: log.info('Stop polling...') self._polling = False
Break long-polling process. :return:
def pull_astro_coords(voevent, index=0): """ Deprecated alias of :func:`.get_event_position` """ import warnings warnings.warn( """ The function `pull_astro_coords` has been renamed to `get_event_position`. This alias is preserved for backwards compatibility, and may ...
Deprecated alias of :func:`.get_event_position`
def execute_plan(self, plan, allow_rf_change=False): """Submit reassignment plan for execution.""" reassignment_path = '{admin}/{reassignment_node}'\ .format(admin=ADMIN_PATH, reassignment_node=REASSIGNMENT_NODE) plan_json = dump_json(plan) base_plan = self.get_cluster_plan()...
Submit reassignment plan for execution.
def timeseries(self): """ Load time series It returns the actual time series used in power flow analysis. If :attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise, :meth:`timeseries()` looks for time series of the according sector in :class:`~.grid.network.Ti...
Load time series It returns the actual time series used in power flow analysis. If :attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise, :meth:`timeseries()` looks for time series of the according sector in :class:`~.grid.network.TimeSeries` object. Returns ...
def validate_wrap(self, value): ''' Checks that value is a ``dict``, that every key is a valid MongoDB key, and that every value validates based on DictField.value_type ''' if not isinstance(value, dict): self._fail_validation_type(value, dict) for k, v in value.i...
Checks that value is a ``dict``, that every key is a valid MongoDB key, and that every value validates based on DictField.value_type
def copy(self): ''' makes a clone copy of the mapper. It won't clone the serializers or deserializers and it won't copy the events ''' try: tmp = self.__class__() except Exception: tmp = self.__class__(self._pdict) tmp._serializers = ...
makes a clone copy of the mapper. It won't clone the serializers or deserializers and it won't copy the events
def get_path(): ''' Returns a list of items in the SYSTEM path CLI Example: .. code-block:: bash salt '*' win_path.get_path ''' ret = salt.utils.stringutils.to_unicode( __utils__['reg.read_value']( 'HKEY_LOCAL_MACHINE', 'SYSTEM\\CurrentControlSet\\Contr...
Returns a list of items in the SYSTEM path CLI Example: .. code-block:: bash salt '*' win_path.get_path
def get_library_state_copy_instance(self, lib_os_path): """ A method to get a state copy of the library specified via the lib_os_path. :param lib_os_path: the location of the library to get a copy for :return: """ # originally libraries were called like this; DO NOT DELETE; int...
A method to get a state copy of the library specified via the lib_os_path. :param lib_os_path: the location of the library to get a copy for :return:
def get_resource(url): """ Issue a GET request to R25 with the given url and return a response as an etree element. """ response = R25_DAO().getURL(url, {"Accept": "text/xml"}) if response.status != 200: raise DataFailureException(url, response.status, response.data) tree = etree.fr...
Issue a GET request to R25 with the given url and return a response as an etree element.
def flush(**kwargs): """Flush the specified names from the specified databases. This can be highly destructive as it destroys all data. """ expression = lambda target, table: target.execute(table.delete()) test = lambda target, table: not table.exists(target) op(expression, reversed(metadata.s...
Flush the specified names from the specified databases. This can be highly destructive as it destroys all data.
def prior(self): """ Model prior for particular model. Product of eclipse probability (``self.prob``), the fraction of scenario that is allowed by the various constraints (``self.selectfrac``), and all additional factors in ``self.priorfactors``. """ pri...
Model prior for particular model. Product of eclipse probability (``self.prob``), the fraction of scenario that is allowed by the various constraints (``self.selectfrac``), and all additional factors in ``self.priorfactors``.
def _query_select_options(self, query, select_columns=None): """ Add select load options to query. The goal is to only SQL select what is requested :param query: SQLAlchemy Query obj :param select_columns: (list) of columns :return: SQLAlchemy Query obj "...
Add select load options to query. The goal is to only SQL select what is requested :param query: SQLAlchemy Query obj :param select_columns: (list) of columns :return: SQLAlchemy Query obj
def rfc2822_datetime(s): """ Parses an RFC 2822 date string and returns a UTC datetime object, or the string if parsing failed. :param s: RFC 2822-formatted string date :return: datetime or str """ date_tuple = parsedate(s) if date_tuple is None: return None return datetime.d...
Parses an RFC 2822 date string and returns a UTC datetime object, or the string if parsing failed. :param s: RFC 2822-formatted string date :return: datetime or str
def write_roi(self, outfile=None, save_model_map=False, **kwargs): """Write current state of the analysis to a file. This method writes an XML model definition, a ROI dictionary, and a FITS source catalog file. A previously saved analysis state can be reloaded from th...
Write current state of the analysis to a file. This method writes an XML model definition, a ROI dictionary, and a FITS source catalog file. A previously saved analysis state can be reloaded from the ROI dictionary file with the `~fermipy.gtanalysis.GTAnalysis.load_roi` method. ...
def _parse_single_response(cls, response_data): """de-serialize a JSON-RPC Response/error :Returns: | [result, id] for Responses :Raises: | RPCFault+derivates for error-packages/faults, RPCParseError, RPCInvalidRPC """ if not isinstance(response_data, dict): raise ...
de-serialize a JSON-RPC Response/error :Returns: | [result, id] for Responses :Raises: | RPCFault+derivates for error-packages/faults, RPCParseError, RPCInvalidRPC
def parse_roles(self, fetched_role, params): """ Parse a single IAM role and fetch additional data """ role = {} role['instances_count'] = 'N/A' # When resuming upon throttling error, skip if already fetched if fetched_role['RoleName'] in self.roles: r...
Parse a single IAM role and fetch additional data
def set_interface(self, interface): """Add update toolbar callback to the interface""" self.interface = interface self.interface.callbacks.update_toolbar = self._update self._update()
Add update toolbar callback to the interface
def topk(self, column_name, k=10, reverse=False): """ Get top k rows according to the given column. Result is according to and sorted by `column_name` in the given order (default is descending). When `k` is small, `topk` is more efficient than `sort`. Parameters --------...
Get top k rows according to the given column. Result is according to and sorted by `column_name` in the given order (default is descending). When `k` is small, `topk` is more efficient than `sort`. Parameters ---------- column_name : string The column to sort on ...
def prepare_namespace(self, func): """ Prepares the function to be run after deserializing it. Re-associates any previously bound variables and modules from the closure Returns: callable: ready-to-call function """ if self.is_imethod: to_run = get...
Prepares the function to be run after deserializing it. Re-associates any previously bound variables and modules from the closure Returns: callable: ready-to-call function
def get_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet: """ Get valid user attempts that match the given request and credentials. """ attempts = filter_user_attempts(request, credentials) if settings.AXES_COOLOFF_TIME is None: log.debug('AXES: Getting all acc...
Get valid user attempts that match the given request and credentials.
def get_pressure(self): """ Returns the pressure in Millibars """ self._init_pressure() # Ensure pressure sensor is initialised pressure = 0 data = self._pressure.pressureRead() if (data[0]): # Pressure valid pressure = data[1] return pressu...
Returns the pressure in Millibars
def refresh_events(self): """ Retrieve the next N events from Google. """ now = datetime.datetime.now(tz=pytz.UTC) try: now, later = self.get_timerange_formatted(now) events_result = self.service.events().list( calendarId='primary', ...
Retrieve the next N events from Google.
def urlunsplit (urlparts): """Same as urlparse.urlunsplit but with extra UNC path handling for Windows OS.""" res = urlparse.urlunsplit(urlparts) if os.name == 'nt' and urlparts[0] == 'file' and '|' not in urlparts[2]: # UNC paths must have 4 slashes: 'file:////server/path' # Depending o...
Same as urlparse.urlunsplit but with extra UNC path handling for Windows OS.
def register(self, name, func): """ Register a new callback.\ When the name/id is not found\ a new hook is created under its name,\ meaning the hook is usually created by\ the first registered callback :param str name: Hook name :param callable func: A fu...
Register a new callback.\ When the name/id is not found\ a new hook is created under its name,\ meaning the hook is usually created by\ the first registered callback :param str name: Hook name :param callable func: A func reference (callback)
def get(cls, id): """ Get the pool with id 'id'. """ # cached? if CACHE: if id in _cache['Pool']: log.debug('cache hit for pool %d' % id) return _cache['Pool'][id] log.debug('cache miss for pool %d' % id) try: ...
Get the pool with id 'id'.
def _flush_tile_queue_blits(self, surface): """ Blit the queued tiles and block until the tile queue is empty for pygame 1.9.4 + """ tw, th = self.data.tile_size ltw = self._tile_view.left * tw tth = self._tile_view.top * th self.data.prepare_tiles(self._tile_vi...
Blit the queued tiles and block until the tile queue is empty for pygame 1.9.4 +
def update_placeholders(self, format_string, placeholders): """ Update a format string renaming placeholders. """ # Tokenize the format string and process them output = [] for token in self.tokens(format_string): if token.group("key") in placeholders: ...
Update a format string renaming placeholders.
def diff_with_models(self): """ Return a dict stating the differences between current state of models and the configuration itself. TODO: Detect fields that are in conf, but not in models """ missing_from_conf = defaultdict(set) for model in get_models(): ...
Return a dict stating the differences between current state of models and the configuration itself. TODO: Detect fields that are in conf, but not in models
def segs(self, word): """Returns a list of segments from a word Args: word (unicode): input word as Unicode IPA string Returns: list: list of strings corresponding to segments found in `word` """ return [m.group('all') for m in self.seg_regex.finditer(wo...
Returns a list of segments from a word Args: word (unicode): input word as Unicode IPA string Returns: list: list of strings corresponding to segments found in `word`
def get(self, sid): """ Constructs a TaskChannelContext :param sid: The sid :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext """ return TaskChannelContext(se...
Constructs a TaskChannelContext :param sid: The sid :returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext :rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelContext
def filter_unmanaged_physnets(query): """Filter ports managed by other ML2 plugins """ config = cfg.CONF.ml2_arista managed_physnets = config['managed_physnets'] # Filter out ports bound to segments on physnets that we're not # managing segment_model = segment_models.NetworkSegment if manag...
Filter ports managed by other ML2 plugins
def _query_iterator(self, result, chunksize, columns, coerce_float=True, parse_dates=None): """Return generator through chunked result set.""" while True: data = result.fetchmany(chunksize) if not data: break else: ...
Return generator through chunked result set.
def get_outcome(self, outcome): """ Returns the details of the outcome with the given id. :calls: `GET /api/v1/outcomes/:id \ <https://canvas.instructure.com/doc/api/outcomes.html#method.outcomes_api.show>`_ :param outcome: The outcome object or ID to return. :type outc...
Returns the details of the outcome with the given id. :calls: `GET /api/v1/outcomes/:id \ <https://canvas.instructure.com/doc/api/outcomes.html#method.outcomes_api.show>`_ :param outcome: The outcome object or ID to return. :type outcome: :class:`canvasapi.outcome.Outcome` or int ...
def get(self, *args, **kwargs): """Handle reading of the model :param args: :param kwargs: """ # Create the model and fetch its data self.model = self.get_model(kwargs.get('id')) result = yield self.model.fetch() # If model is not found, return 404 ...
Handle reading of the model :param args: :param kwargs:
def cli(env, volume_id, schedule_type): """Disables snapshots on the specified schedule for a given volume""" if (schedule_type not in ['INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY']): raise exceptions.CLIAbort( '--schedule_type must be INTERVAL, HOURLY, DAILY, or WEEKLY') file_manager = Sof...
Disables snapshots on the specified schedule for a given volume
def floor(self): """Round `x` and `y` down to integers.""" return Point(int(math.floor(self.x)), int(math.floor(self.y)))
Round `x` and `y` down to integers.
def _parse_transactions(self, response): """ This method parses the CSV output in `get_transactions` to generate a usable list of transactions that use native python data types """ transactions = list() if response: f = StringIO(response) ...
This method parses the CSV output in `get_transactions` to generate a usable list of transactions that use native python data types
def add_word(self, word, value): """ Adds word and associated value. If word already exists, its value is replaced. """ if not word: return node = self.root for c in word: try: node = node.children[c] except KeyError: n = TrieNode(c) node.children[c] = n node = n node.output ...
Adds word and associated value. If word already exists, its value is replaced.
def ConsultarTiposContingencia(self, sep="||"): "Obtener el código y descripción para cada tipo de contingencia que puede reportar" ret = self.client.consultarTiposContingencia( authRequest={ 'token': self.Token, 'sign': self.Sign, ...
Obtener el código y descripción para cada tipo de contingencia que puede reportar
def QA_fetch_get_option_50etf_contract_time_to_market(): ''' #🛠todo 获取期权合约的上市日期 ? 暂时没有。 :return: list Series ''' result = QA_fetch_get_option_list('tdx') # pprint.pprint(result) # category market code name desc code ''' fix here : See the caveats in the documenta...
#🛠todo 获取期权合约的上市日期 ? 暂时没有。 :return: list Series
def newick_from_string(self): "Reads a newick string in the New Hampshire format." # split on parentheses to traverse hierarchical tree structure for chunk in self.data.split("(")[1:]: # add child to make this node a parent. self.current_parent = ( self.r...
Reads a newick string in the New Hampshire format.
def get_user_info(self): """ Get information on the authenticated user. :rtype: .UserInfo """ response = self.get_proto(path='/user') message = yamcsManagement_pb2.UserInfo() message.ParseFromString(response.content) return UserInfo(message)
Get information on the authenticated user. :rtype: .UserInfo
def msg_curse(self, args=None, max_width=None): """Return the list to display in the UI.""" # Init the return message ret = [] # Only process if stats exist and plugin not disable if not self.stats or self.args.percpu or self.is_disable(): return ret # Build...
Return the list to display in the UI.
def get_reader_classes(parent=Reader): """Get all childless the descendants of a parent class, recursively.""" children = parent.__subclasses__() descendants = children[:] for child in children: grandchildren = get_reader_classes(child) if grandchildren: descendants.remove(ch...
Get all childless the descendants of a parent class, recursively.
def str_max_bit_rate(self): """ Returns a human readable maximun upstream- and downstream-rate of the given connection. The rate is given in bits/sec. """ upstream, downstream = self.max_bit_rate return ( fritztools.format_rate(upstream, unit='bits'), ...
Returns a human readable maximun upstream- and downstream-rate of the given connection. The rate is given in bits/sec.
def solveConsIndShock(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rfree,PermGroFac, BoroCnstArt,aXtraGrid,vFuncBool,CubicBool): ''' Solves a single period consumption-saving problem with CRRA utility and risky income (subject to permanent and transitory shocks). Can generat...
Solves a single period consumption-saving problem with CRRA utility and risky income (subject to permanent and transitory shocks). Can generate a value function if requested; consumption function can be linear or cubic splines. Parameters ---------- solution_next : ConsumerSolution The sol...
def _save_training_state(self, train_iter: data_io.BaseParallelSampleIter): """ Saves current training state. """ # Create temporary directory for storing the state of the optimization process training_state_dirname = os.path.join(self.model.output_dir, C.TRAINING_STATE_TEMP_DIRN...
Saves current training state.
def should_reuse_driver(self, scope, test_passed, context=None): """Check if the driver should be reused :param scope: execution scope (function, module, class or session) :param test_passed: True if the test has passed :param context: behave context :returns: True if the driver...
Check if the driver should be reused :param scope: execution scope (function, module, class or session) :param test_passed: True if the test has passed :param context: behave context :returns: True if the driver should be reused
def _fake_designspace(self, ufos): """Build a fake designspace with the given UFOs as sources, so that all builder functions can rely on the presence of a designspace. """ designspace = designspaceLib.DesignSpaceDocument() ufo_to_location = defaultdict(dict) # Make weig...
Build a fake designspace with the given UFOs as sources, so that all builder functions can rely on the presence of a designspace.
def ack(self): """Acknowledge this message as being processed., This will remove the message from the queue. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected. """ if self.acknowledged: raise self.MessageStateError...
Acknowledge this message as being processed., This will remove the message from the queue. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected.
def predict(self, X): """ Predict the less costly class for a given observation Parameters ---------- X : array (n_samples, n_features) Data for which to predict minimum cost label. Returns ------- y_hat : array (n_samples,) ...
Predict the less costly class for a given observation Parameters ---------- X : array (n_samples, n_features) Data for which to predict minimum cost label. Returns ------- y_hat : array (n_samples,) Label with expected minimum cos...
def file_or_folder(path): """ Returns a File or Folder object that would represent the given path. """ target = unicode(path) return Folder(target) if os.path.isdir(target) else File(target)
Returns a File or Folder object that would represent the given path.