Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
344,100
def validate_trail_settings(self, ct, aws_region, trail): self.log.debug(.format( self.account.account_name, aws_region, trail[] )) status = ct.get_trail_status(Name=trail[]) if not status[]: self.log.warning(.format( ...
Validates logging, SNS and S3 settings for the global trail. Has the capability to: - start logging for the trail - create SNS topics & queues - configure or modify a S3 bucket for logging
344,101
def set_current(self, panel): where = slice(self._start_index, self._pos) self.buffer.values[:, where, :] = panel.values
Set the values stored in our current in-view data to be values of the passed panel. The passed panel must have the same indices as the panel that would be returned by self.get_current.
344,102
def _assert_transition(self, event): state = self.domain.state()[0] if event not in STATES_MAP[state]: raise RuntimeError("State transition %s not allowed" % event)
Asserts the state transition validity.
344,103
def bg_phase_mask_from_sim(sim, radial_clearance=1.1): cx, cy = sim["sim center"] radius = sim["sim radius"] px_um = sim["pixel size"] x = np.arange(sim.shape[0]).reshape(-1, 1) y = np.arange(sim.shape[1]).reshape(1, -1) rsq = (x - cx)**2 + (y - cy)**2 mask = rsq > (radius/px_um * ...
Return the background phase mask of a qpsphere simulation Parameters ---------- sim: qpimage.QPImage Quantitative phase data simulated with qpsphere; The simulation keyword arguments "sim center", "sim radius", and "pixel size" must be present in `sim.meta`. radial_clearance: fl...
344,104
def baby_names(max_length=15): names = [] lengths = [] targets = [] with open(os.path.join(os.path.dirname(sys.modules[__name__].__file__), ), ) as f: first = True for l in csv.reader(f, delimiter=): if first: first = False continue assert len(l) =...
Opens the baby_names csv file and produces numpy array. Args: max_length: The maximum length, 15 was the longest name when this was written. Short entries will be padded with the EOS marker. Returns: A numpy array of the names converted to ascii codes, the labels and an array of lengths. Raise...
344,105
def type(self): "The type of elements stored in the mapping." if self._type is None and len(self): self._type = self.values()[0].__class__ return self._type
The type of elements stored in the mapping.
344,106
def clone(self, *args, **overrides): clone = super(Layout, self).clone(*args, **overrides) clone._max_cols = self._max_cols return clone
Clones the Layout, overriding data and parameters. Args: data: New data replacing the existing data shared_data (bool, optional): Whether to use existing data new_type (optional): Type to cast object to *args: Additional arguments to pass to constructor ...
344,107
def load_models_using_filepattern( self, filename_pattern, model, glob_args, is_main_model=False, encoding=, add_to_local_models=True): if (model): self.update_model_in_repo_based_on_filename(model) filenames = glob.glob(filename_pattern, **glob_args) ...
add a new model to all relevant objects Args: filename_pattern: models to be loaded model: model holding the loaded models in its _tx_model_repository field (may be None). glob_args: arguments passed to the glob.glob function. Returns: ...
344,108
def handle_hooks(stage, hooks, provider, context, dump, outline): if not outline and not dump and hooks: util.handle_hooks( stage=stage, hooks=hooks, provider=provider, context=context )
Handle pre/post hooks. Args: stage (str): The name of the hook stage - pre_build/post_build. hooks (list): A list of dictionaries containing the hooks to execute. provider (:class:`stacker.provider.base.BaseProvider`): The provider the current stack is using. context (:c...
344,109
def close_to_close(self, pxs): if not isinstance(pxs, pd.Series): raise ValueError() blotter = TradeBlotter() signal = self.signal.dropna() diff = signal.diff() diff.iloc[0] = 0 changes = signal[diff != 0] lsig = 0 qtyfct = self._qty_...
:param pxs: :return:
344,110
def derive_single_fernet_key(password, user_id): password = ascii_unicode_to_bytes(password) user_id = ascii_unicode_to_bytes(user_id) kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=user_id, iterations=100000, backend=default_backend(), ) r...
Convert a secret key and a user ID into an encryption key to use with a ``cryptography.fernet.Fernet``. Taken from https://cryptography.io/en/latest/fernet/#using-passwords-with-fernet Parameters ---------- password : unicode ascii-encodable key to derive user_id : unicode ...
344,111
def value_to_python(self, value): if not isinstance(value, bytes): raise tldap.exceptions.ValidationError("should be a bytes") value = value.decode("utf_8") return value
Converts the input single value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this.
344,112
def create_from_snapshot(self, data, timeout=-1): uri = self.URI + "/from-snapshot" return self._client.create(data, uri=uri, timeout=timeout)
Creates a new volume on the storage system from a snapshot of a volume. A volume template must also be specified when creating a volume from a snapshot. The global setting "StorageVolumeTemplateRequired" controls whether or not root volume templates can be used to provision volumes. The...
344,113
def create_user(self, account_id, pseudonym_unique_id, communication_channel_address=None, communication_channel_confirmation_url=None, communication_channel_skip_confirmation=None, communication_channel_type=None, enable_sis_reactivation=None, force_validations=None, pseudonym_authentication_provider_id=None, pseudony...
Create a user. Create and return a new user and pseudonym for an account. If you don't have the "Modify login details for users" permission, but self-registration is enabled on the account, you can still use this endpoint to register new users. Certain fields will be requ...
344,114
def encode_hdr(self, boundary): boundary = encode_and_quote(boundary) headers = ["--%s" % boundary] if self.filename: disposition = % (self.name, self.filename) else: disposition = % s...
Returns the header of the encoding of this parameter
344,115
def prompt(self, matches): if Config.options.autoyes: return matches deletions = [] for match in matches: os.system() print(self.cells[match]) print() print("Delete cell %s of ?" % (str(match + 1), self.filename)) ...
Prompt user to remove cells from subtitle file.
344,116
def get_title(mode=): titleicon title = None if is_a_tty() and not env.SSH_CLIENT: if os_name == : from .windows import get_title return get_title() elif sys.platform == : if env.TERM_PROGRAM and env.TERM_PROGRAM == : pass else...
Return the terminal/console title. Arguments: str: mode, one of ('title', 'icon') or int (20-21): see links below. - `Control sequences <http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Operating-System-Commands>`_ Returns: title ...
344,117
def check_config(config): "basic checks that the configuration file is valid" shortnames = [count[] for count in config[]] if len(shortnames) != len(set(shortnames)): logger.error("error: duplicate `shortname' in count configuration.") return False return True
basic checks that the configuration file is valid
344,118
def _sentences(self, clean_visible): previous_end = 0 clean_visible = clean_visible.decode() for start, end in self.sentence_tokenizer.span_tokenize(clean_visible): if start < previous_end: start = previous_...
generate strings identified as sentences
344,119
def filtered_to_forecast(self): A, C = self.ss.A, self.ss.C Q = np.dot(C, C.T) self.x_hat = dot(A, self.x_hat) self.Sigma = dot(A, dot(self.Sigma, A.T)) + Q
Updates the moments of the time t filtering distribution to the moments of the predictive distribution, which becomes the time t+1 prior
344,120
def make_multi_metatile(parent, tiles, date_time=None): assert parent is not None, \ "Parent tile must be provided and not None to make a metatile." if len(tiles) == 0: return [] if date_time is None: date_time = gmtime()[0:6] layer = tiles[0][] buf = StringIO.Strin...
Make a metatile containing a list of tiles all having the same layer, with coordinates relative to the given parent. Set date_time to a 6-tuple of (year, month, day, hour, minute, second) to set the timestamp for members. Otherwise the current wall clock time is used.
344,121
def flush(self): if not self._buffer: self.stdout.flush() return data = .join(self._buffer) if _DEBUG_RENDER_OUTPUT: self.LOG.write(( % data).encode() + b) self.LOG.flush() ...
Write to output stream and flush.
344,122
async def locate_tip_probe_center( self, mount, tip_length=None) -> top_types.Point: opt_pip = self._attached_instruments[mount] assert opt_pip, .format(mount.name.lower()) pip = opt_pip if pip.has_tip and tip_length: pip.remove_tip() if not tip...
Use the specified mount (which should have a tip) to find the position of the tip probe target center relative to its definition :param mount: The mount to use for the probe :param tip_length: If specified (it should usually be specified), the length of the tip assume...
344,123
def dist(self, src, tar): if tar == src: return 0.0 if not src or not tar: return 1.0 max_length = max(len(src), len(tar)) return self.dist_abs(src, tar) / max_length
Return the normalized bag distance between two strings. Bag distance is normalized by dividing by :math:`max( |src|, |tar| )`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison Returns --...
344,124
def load_profile(self, profile): profile_path = os.path.join( self.root_directory, , profile + ) self.read_from_file(profile_path)
Load a specific profile into the current minimum needs. :param profile: The profile's name :type profile: basestring, str
344,125
async def read_headers(stream: asyncio.StreamReader) -> "Headers": headers = Headers() for _ in range(MAX_HEADERS + 1): line = await read_line(stream) if line == b"": break raw_name, raw_value = line.split(b":", 1) if not _token_re.fullmatch...
Read HTTP headers from ``stream``. ``stream`` is an :class:`~asyncio.StreamReader`. Return a :class:`Headers` instance Non-ASCII characters are represented with surrogate escapes.
344,126
def binary_weight_affine(inp, n_outmaps, base_axis=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True): if not hasattr(n_outmaps, ): n_outmaps = [n_outmaps] n_outm...
Binary Weight Affine, multiplier-less inner-product with a scale factor. Binary Weight Affine is the affine function, but the inner product in this function is the following, .. math:: y_j = \\frac{1}{\\|\\mathbf{w}_j\\|_{\\ell_1}} \sum_{i} sign(w_{ji}) x_i Therefore :math:`sign(w_{ji})` is ...
344,127
def show_all_categories(call=None): if call == : raise SaltCloudSystemExit( ) conn = get_conn(service=) categories = [] for category in conn.getCategories(id=50): categories.append(category[]) return {: categories}
Return a dict of all available categories on the cloud provider. .. versionadded:: 2016.3.0
344,128
def get_news_content(self, url): res = WyuNews.__wyu_news_content(url) soup = BeautifulSoup(res, from_encoding=) tag_table = soup.find(self.__get_tag_table) tr = tag_table.findAll()[4] return tr.decode()
获取新闻内容 :param url: 新闻url :return: html code
344,129
def max(self, default=None): return numpy.asscalar(numpy.max(self.values)) if self.values else default
Calculate the maximum value over the time series. :param default: Value to return as a default should the calculation not be possible. :return: Float representing the maximum value or `None`.
344,130
def read(self, directory): usable = False try: status_file = os.path.join(directory, self.STATUS_FILE) fstatus = open(status_file, "rb") try: status = pickle.load(fstatus) finally: fstatus.close() except (IO...
Read the last status in `directory`.
344,131
def validate_record_type(self, cls): if self.record_types and cls not in self.record_types: raise ValueError( + cls + )
Validate given record is acceptable. >>> s = teststore() >>> s.validate_record_type('tstoretest') >>> s.validate_record_type('bad') Traceback (most recent call last): ... ValueError: Unsupported record type "bad"
344,132
def _insert_img(self, cursor, img, fmt): try: image = QtGui.QImage() image.loadFromData(img, fmt.upper()) except ValueError: self._insert_plain_text(cursor, %fmt) else: format = self._add_image(image) cursor.insertBlock() ...
insert a raw image, jpg or png
344,133
def debug(self, *args) -> "Err": error = self._create_err("debug", *args) print(self._errmsg(error)) return error
Creates a debug message
344,134
def distance(self,value): self.stars[] = value.to().value old_distmod = self.stars[].copy() new_distmod = distancemodulus(self.stars[]) for m in self.bands: self.stars[m] += new_distmod - old_distmod self.stars[] = new_distmod logging.warning()
New distance value must be a ``Quantity`` object
344,135
def get_surrogate_id(self): surrogate_id = "%s,%s,%s,%s,%s" % (self.year, self.quarter, self.curriculum_abbr.lower(), self.course_number, ...
This is responsible for building the surrogate id from the model
344,136
def iadhore(args): p = OptionParser(iadhore.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) lastfile = args[0] bedfiles = args[1:] blast_table = "blast_table.txt" fp = open(lastfile) seen = set() for row in fp: c = BlastL...
%prog iadhore athaliana.athaliana.last athaliana.bed Wrap around iADHoRe.
344,137
def re_sort(data): keys = sorted(data.keys()) new_data = {} for number, key in enumerate(keys): new_data[number] = data[key] return new_data
A data with keys that are not enumerated sequentially will be re sorted and sequentially ordered. For example:: >>> data = {16: ('1', 'b'), 3: ('1', 'a')} >>> re_sort(data) >>> {0: ('1', 'a'), 1: ('1', 'b')}
344,138
def get_species(species_id): result = _get(species_id, settings.SPECIES) return Species(result.content)
Return a single species
344,139
def _load_jamo_short_names(): filename = "Jamo.txt" current_dir = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(current_dir, filename), mode="r", encoding="utf-8") as fp: for line in fp: if not line.strip() or line.startswith(" continue ...
Function for parsing the Jamo short names from the Unicode Character Database (UCD) and generating a lookup table For more info on how this is used, see the Unicode Standard, ch. 03, section 3.12, "Conjoining Jamo Behavior" and ch. 04, section 4.8, "Name". https://www.unicode.org/versions/latest/ch03.pdf ...
344,140
def start(self): if not self.__initialized: raise RuntimeError("thread.__init__() not called") if self.__started.is_set(): raise RuntimeError("threads can only be started once") if __debug__: self._note("%s.start(): starting thread", self) wit...
Start the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object.
344,141
def html(cls, string, show_everything=False, translation=gettext.NullTranslations()): out, _ = tidylib.tidy_fragment(string) return out
Parses HTML
344,142
def locate_fixed_differences(ac1, ac2): ac1 = asarray_ndim(ac1, 2) ac2 = asarray_ndim(ac2, 2) check_dim0_aligned(ac1, ac2) ac1, ac2 = ensure_dim1_aligned(ac1, ac2) pac = np.dstack([ac1, ac2]) pan = np.sum(pac, axis=1) npa = np.sum(pac > 0, axis=2) non_m...
Locate variants with no shared alleles between two populations. Parameters ---------- ac1 : array_like, int, shape (n_variants, n_alleles) Allele counts array from the first population. ac2 : array_like, int, shape (n_variants, n_alleles) Allele counts array from the second population. ...
344,143
def _proc_builtin(self, tarfile): self.offset_data = tarfile.fileobj.tell() offset = self.offset_data if self.isreg() or self.type not in SUPPORTED_TYPES: offset += self._block(self.size) tarfile.offset = offset self._apply_pax...
Process a builtin type or an unknown type which will be treated as a regular file.
344,144
def sec_to_public_pair(sec, generator=None, strict=True): byte_count = (generator.p().bit_length() + 7) >> 3 if generator else (len(sec) - 1) x = from_bytes_32(sec[1:1 + byte_count]) sec0 = sec[:1] if len(sec) == 1 + byte_count * 2: isok = sec0 == b if not strict: isok =...
Convert a public key in sec binary format to a public pair.
344,145
def maybe_cast_to_integer_array(arr, dtype, copy=False): try: if not hasattr(arr, "astype"): casted = np.array(arr, dtype=dtype, copy=copy) else: casted = arr.astype(dtype, copy=copy) except OverflowError: raise OverflowError("The elements provided in the da...
Takes any dtype and returns the casted version, raising for when data is incompatible with integer/unsigned integer dtypes. .. versionadded:: 0.24.0 Parameters ---------- arr : array-like The array to cast. dtype : str, np.dtype The integer dtype to cast the array to. copy:...
344,146
def _resolve_template(value, model_instance=None, context=None): if isinstance(value, string_types) and "{" in value: if context is None: context = Context() if model_instance is not None: context[model_instance._meta.model_name] = model_instance ...
Resolves any template references in the given value.
344,147
def get_activations(self): act_events = self.tree.findall("EVENT/[type=]") inact_events = self.tree.findall("EVENT/[type=]") inact_events += self.tree.findall("EVENT/[type=]") for event in (act_events + inact_events): event_id = event.attrib[] if event_id...
Extract direct Activation INDRA Statements.
344,148
def set_arbitrary(self, freq, low_volt, high_volt, output_state=True): commands = [, , , , .format(freq), .format(high_volt), .format(low_volt), ] if outpu...
Programs the function generator to output the arbitrary waveform.
344,149
async def disconnect(self, abort=False): if self.state == : await self._send_packet(packet.Packet(packet.CLOSE)) await self.queue.put(None) self.state = await self._trigger_event(, run_async=False) if self.current_transport == : ...
Disconnect from the server. :param abort: If set to ``True``, do not wait for background tasks associated with the connection to end. Note: this method is a coroutine.
344,150
def _create_dictionary_of_veron( self): self.log.debug( ) dictList = [] lines = string.split(self.catData, ) totalCount = len(lines) count = 0 switch = 0 for line in lines: if (len(line) == 0 or line[0] in [" ...
create a list of dictionaries containing all the rows in the veron catalogue **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the veron catalogue .. todo :: - update key arguments values and definitions with defaults - update return va...
344,151
def create_service(kwargs=None, conn=None, call=None): West US if call != : raise SaltCloudSystemExit( ) if not conn: conn = get_conn() if kwargs is None: kwargs = {} if not in kwargs: raise SaltCloudSystemExit() if not in kwargs: ...
.. versionadded:: 2015.8.0 Create a new hosted service CLI Example: .. code-block:: bash salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
344,152
def active(self, name_id, entity_id): try: cni = code(name_id) (timestamp, info) = self._db[cni][entity_id] except KeyError: return False if not info: return False else: return time_util.not_on_or_after(timestamp)
Returns the status of assertions from a specific entity_id. :param name_id: The ID of the subject :param entity_id: The entity ID of the entity_id of the assertion :return: True or False depending on if the assertion is still valid or not.
344,153
def _process_return_multi_z(self, data, names, dim_sizes): d1 = 0 d2 = 0 for name, dim_size in zip(names, dim_sizes): d2 = d1 + dim_size if dim_size == 1: self.data[name.rstrip()] = data[d1, :] else: self.data[...
process and attach data from fortran_cdf.get_multi_*
344,154
def dfa_trimming(dfa: dict) -> dict: dfa = dfa_reachable(dfa) dfa = dfa_co_reachable(dfa) return dfa
Side effects on input! Returns the DFA in input trimmed, so both reachable and co-reachable. Given a DFA A, the corresponding trimmed DFA contains only those states that are reachable from the initial state and that lead to a final state. The trimmed dfa :math:`A_{RF}` corresponding to A is defined...
344,155
def one(self, default=None, as_dict=False, as_ordereddict=False):
Returns a single record for the RecordCollection, ensuring that it is the only record, or returns `default`. If `default` is an instance or subclass of Exception, then raise it instead of returning it.
344,156
def subnet_create(request, network_id, **kwargs): LOG.debug("subnet_create(): netid=%(network_id)s, kwargs=%(kwargs)s", {: network_id, : kwargs}) body = {: {: network_id}} if not in kwargs: kwargs[] = request.user.project_id body[].update(kwargs) subnet = neutronclient(re...
Create a subnet on a specified network. :param request: request context :param network_id: network id a subnet is created on :param cidr: (optional) subnet IP address range :param ip_version: (optional) IP version (4 or 6) :param gateway_ip: (optional) IP address of gateway :param tenant_id: (o...
344,157
def from_binary( cls, fname, vocab_unicode_size=78, desired_vocab=None, encoding="utf-8", new_lines=True, ): with open(fname, "rb") as fin: header = fin.readline() vocab_size, vector_size = ...
Create a WordVectors class based on a word2vec binary file Parameters ---------- fname : path to file vocabUnicodeSize: the maximum string length (78, by default) desired_vocab: if set any words that don't fall into this vocab will be droped Returns ------- ...
344,158
def action(cls, view): name = "%s:%s" % (cls.name, view.__name__) path = "%s/%s" % (cls.url, view.__name__) cls.actions.append((view.__doc__, path)) return cls.register(path, name=name)(view)
Register admin view action.
344,159
def _map_generator(f, generator): item = next(generator) while True: try: result = yield f(item) except Exception: item = generator.throw(*sys.exc_info()) else: item = generator.send(result)
Apply ``f`` to the results of the given bi-directional generator. Unfortunately, generator comprehension (``f(x) for x in gen``) does not work for as expected for bi-directional generators. It won't send exceptions and results back. This function implements a map function for generators that sends val...
344,160
def update_stale(self): for etype, echannels in self.event_states.items(): for eprop in echannels: if eprop[3] is not None: sec_elap = ((datetime.datetime.now()-eprop[3]) .total_seconds()) ...
Update stale active statuses
344,161
def parse_vars(self, args): result = {} for arg in args: if not in arg: raise ValueError( % arg) name, value = arg.split(, 1) result[name] = value return result
Given variables like ``['a=b', 'c=d']`` turns it into ``{'a': 'b', 'c': 'd'}``
344,162
async def migrate_redis1_to_redis2(storage1: RedisStorage, storage2: RedisStorage2): if not isinstance(storage1, RedisStorage): raise TypeError(f"{type(storage1)} is not RedisStorage instance.") if not isinstance(storage2, RedisStorage): raise TypeError(f"{type(storage2)} is not RedisStor...
Helper for migrating from RedisStorage to RedisStorage2 :param storage1: instance of RedisStorage :param storage2: instance of RedisStorage2 :return:
344,163
def load_probe_file(recording, probe_file, channel_map=None, channel_groups=None): locationgrouplocation probe_file = Path(probe_file) if probe_file.suffix == : probe_dict = read_python(probe_file) if in probe_dict.keys(): ordered_channels = np.array([], dtype=int) g...
Loads channel information into recording extractor. If a .prb file is given, then 'location' and 'group' information for each channel is stored. If a .csv file is given, then it will only store 'location' Parameters ---------- recording: RecordingExtractor The recording extractor to channel...
344,164
def samples_by_indices_nomapping(self, indices): batch = tuple([d[indices] for d in self.data]) if self.include_indices: if isinstance(indices, slice): indices = np.arange(indices.start, indices.stop, indices.step) retu...
Gather a batch of samples by indices *without* applying any index mapping resulting from the (optional) use of the `indices` array passed to the constructor. Parameters ---------- indices: 1D-array of ints or slice The samples to retrieve Returns ---...
344,165
def normalize_value(val): if val is not None: if val.lower() == : val = False elif val.lower() == : val = True return val
Normalize strings with booleans into Python types.
344,166
def _format_help(self, scope_info): scope = scope_info.scope description = scope_info.description show_recursive = self._help_request.advanced show_advanced = self._help_request.advanced color = sys.stdout.isatty() help_formatter = HelpFormatter(scope, show_recursive, show_advanced, color) ...
Return a help message for the options registered on this object. Assumes that self._help_request is an instance of OptionsHelp. :param scope_info: Scope of the options.
344,167
def apply_config_file(self, filename): def extractor(template, options): for name, val in options: normalised = self.normalise_key(name) if normalised in self.values and not isinstance(self.values[normalised], Default): contin...
Add options from config file to self.values Leave alone existing values that are not an instance of Default
344,168
def add_selected(self, ): browser = self.shot_browser if self.browser_tabw.currentIndex() == 1 else self.asset_browser selelements = browser.selected_indexes(2) if not selelements: return seltypes = browser.selected_indexes(3) if not seltypes: ret...
Create a new reftrack with the selected element and type and add it to the root. :returns: None :rtype: None :raises: NotImplementedError
344,169
def lnprob(self,theta): global niter params,priors,loglike = self.params,self.priors,self.loglike _lnprior = self.lnprior(theta) if np.isfinite(_lnprior): _lnlike = self.lnlike(theta) else: _lnprior = -np.inf _lnlike = -np.inf...
Logarithm of the probability
344,170
def _map_call(self, cmd): if config.debug and cmd != self._mapping.get(cmd, cmd): self.LOG.debug("MAP %s ==> %s" % (cmd, self._mapping[cmd])) cmd = self._mapping.get(cmd, cmd) if not self._use_deprecated and any(cmd.startswith(i) for i in ("d.get_", "f.get_", "p.ge...
Map old to new command names.
344,171
def version(which="num"): if which in VERSIONS: return VERSIONS[which] else: raise CoconutException( "invalid version type " + ascii(which), extra="valid versions are " + ", ".join(VERSIONS), )
Get the Coconut version.
344,172
def creditusage(cls): rating = cls.call() if not rating: return 0 rating = rating.pop() usage = [sum(resource.values()) for resource in rating.values() if isinstance(resource, dict)] return sum(usage)
Get credit usage per hour
344,173
def _write_single_batch_images_internal(self, batch_id, client_batch): client = self._datastore_client batch_key = client.key(self._entity_kind_batches, batch_id) for img_id, img in iteritems(self._data[batch_id][]): img_entity = client.entity( client.key(self._entity_kind_images, img_i...
Helper method to write images from single batch into datastore.
344,174
def get_arguments(self): ApiCli.get_arguments(self) self._actions = self.args.actions if self.args.actions is not None else None self._alarm_name = self.args.alarm_name if self.args.alarm_name is not None else None self._metric = self.args.metric if self.args.metric is not Non...
Extracts the specific arguments of this CLI
344,175
def hvals(key, host=None, port=None, db=None, password=None): * server = _connect(host, port, db, password) return server.hvals(key)
Return all the values in a hash. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' redis.hvals foo_hash bar_field1 bar_value1
344,176
def read_memory(library, session, space, offset, width, extended=False): if width == 8: return in_8(library, session, space, offset, extended) elif width == 16: return in_16(library, session, space, offset, extended) elif width == 32: return in_32(library, session, space, offset...
Reads in an 8-bit, 16-bit, 32-bit, or 64-bit value from the specified memory space and offset. Corresponds to viIn* functions of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param space: Specifies the address space. (Con...
344,177
def solve(self, value, filter_): try: return value[filter_.slice or filter_.index] except IndexError: return None
Get slice or entry defined by an index from the given value. Arguments --------- value : ? A value to solve in combination with the given filter. filter_ : dataql.resource.SliceFilter An instance of ``SliceFilter``to solve with the given value. Example ...
344,178
def _fetch_pdb(pdb_code): txt = None url = % pdb_code.lower() try: response = urlopen(url) txt = response.read() if sys.version_info[0] >= 3: txt = txt.decode() else: txt = txt.encode() except HTTPE...
Load PDB file from rcsb.org.
344,179
def tensor_index(self, datapoint_index): if datapoint_index >= self._num_datapoints: raise ValueError( %(datapoint_index, self._num_datapoints)) return self._index_to_file_num[datapoint_index]
Returns the index of the tensor containing the referenced datapoint.
344,180
def CreateDetAugmenter(data_shape, resize=0, rand_crop=0, rand_pad=0, rand_gray=0, rand_mirror=False, mean=None, std=None, brightness=0, contrast=0, saturation=0, pca_noise=0, hue=0, inter_method=2, min_object_covered=0.1, aspect_ratio_range=(0.75, 1....
Create augmenters for detection. Parameters ---------- data_shape : tuple of int Shape for output data resize : int Resize shorter edge if larger than 0 at the begining rand_crop : float [0, 1], probability to apply random cropping rand_pad : float [0, 1], probab...
344,181
def ess(weights): r w = _np.asarray(weights) / _np.sum(weights) coeff_var = _np.sum((len(w) * w - 1)**2) / len(w) return 1.0 / (1.0 + coeff_var)
r"""Calculate the normalized effective sample size :math:`ESS` [LC95]_ of samples with ``weights`` :math:`\omega_i`. :math:`ESS=0` is terrible and :math:`ESS=1` is perfect. .. math:: ESS = \frac{1}{1+C^2} where .. math:: C^2 = \frac{1}{N} \sum_{i=1}^N (N \bar{\omega}_i - 1)^2 ...
344,182
def user_can_delete_attachments(self): context = self.context user = api.get_current_user() if not self.is_ar_editable(): return False return (self.user_can_add_attachments() and not user.allowed(context, ["Client"])) or \ self.user_can_up...
Checks if the current logged in user is allowed to delete attachments
344,183
def get_boundaries_module(boundaries_id): if boundaries_id == "gt": return None try: module = eval(algorithms.__name__ + "." + boundaries_id) except AttributeError: raise RuntimeError("Algorithm %s can not be found in msaf!" % boundaries_id) if not...
Obtains the boundaries module given a boundary algorithm identificator. Parameters ---------- boundaries_id: str Boundary algorithm identificator (e.g., foote, sf). Returns ------- module: object Object containing the selected boundary module. None for "ground truth".
344,184
def optimal_distribution(data, distr_to_check=(, , )): fit_results = [fit(data, d) for d in distr_to_check] return min(fit_results, key=lambda fit: fit.errs[0])
Calculate the parameters of a fit of different distributions to a data set and returns the distribution of the minimal ks-distance. Parameters: data: array of data points to be fitted Options: distr_to_check: tuple of distributions to be checked Returns: FitResults object w...
344,185
def showCode(self, width=80): symbolStrings = [ (self.bitPattern(s.index), self.mnemonic(s.index)) for s in self ] leftColWidth, rightColWidth = map(max, map( map, repeat(len), zip(*symbolStrings) ...
Show all words of the code in a nice format.
344,186
def get_xpath(self, node, type=Tag.XPATH, instance=True): type/oc-if:interfaces/interface[name="GigabitEthernet0/0"]/oc-if:interfaces/oc-if:interface[oc-if:name="GigabitEthernet0/0"]/oc-if:interfaces/interface return Composer(self, node).get_xpath(type, instance=instance)
get_xpath High-level api: Given a config or schema node, get_xpath returns an xpath of the node, which starts from the model root. Each identifier uses the `prefix:tagname` notation if argument 'type' is not specified. Parameters ---------- node : `Element` ...
344,187
def get_card_information(self, query_params=None): return self.fetch_json( uri_path=self.base_uri, query_params=query_params or {} )
Get information for this card. Returns a dictionary of values.
344,188
def _report_completion(self): rem_clust = self.remaining_clusters if rem_clust is not None: with self.remaining_clusters_lock: rem_clust.value -= 1 self.remaining_clusters = None print("{} reported completion".format(...
Update shared counters to signal that we are done with this cluster. Call just before exiting run() method (in a finally clause)
344,189
def wheel_delta(self): delta = self._libinput.libinput_event_tablet_tool_get_wheel_delta( self._handle) changed = self._libinput.libinput_event_tablet_tool_wheel_has_changed( self._handle) return delta, changed
The delta for the wheel in degrees and whether it has changed in this event. Returns: (float, bool): The delta of the wheel, in degrees, compared to the last event and whether it has changed.
344,190
def start(self, host=, port=None, debug=False, **kwargs): self.server.run(host=host, port=port, debug=debug, **kwargs)
Start the built in webserver, bound to the host and port you'd like. Default host is `127.0.0.1` and port 8080. :param host: The host you want to bind the build in webserver to :param port: The port number you want the webserver to run on :param debug: Set to `True` to enable debug leve...
344,191
def make_grid(image_batch): m, ir, ic, ch = image_batch.shape pad = 3 padded = np.zeros((m, ir + pad * 2, ic + pad * 2, ch)) padded[:, pad:-pad, pad:-pad, :] = image_batch m, ir, ic, ch = padded.shape pr = int(np.sqrt(m)) pc = int(np.ceil(float(m) / pr)) extra_m = pr * pc assert extra_m > m ...
Turns a batch of images into one big image. :param image_batch: ndarray, shape (batch_size, rows, cols, channels) :returns : a big image containing all `batch_size` images in a grid
344,192
def x_y_by_col_lbl_inplace(df, y_col_lbl): y = df[y_col_lbl] df.drop( labels=y_col_lbl, axis=1, inplace=True, ) return df, y
Breaks the given dataframe into an X frame and a y series by the given column name. The original frame is returned, without the y series column, as the X frame, so no new dataframes are created. Parameters ---------- df : pandas.DataFrame The dataframe to split. y_col_lbl : object...
344,193
def _write_module_descriptor_file(handle, module_dir): readme = _module_descriptor_file(module_dir) readme_content = ( "Module: %s\nDownload Time: %s\nDownloader Hostname: %s (PID:%d)" % (handle, str(datetime.datetime.today()), socket.gethostname(), os.getpid())) tf_utils.atomic_wri...
Writes a descriptor file about the directory containing a module. Args: handle: Module name/handle. module_dir: Directory where a module was downloaded.
344,194
def std(self) -> Optional[float]: if self._stats: return np.sqrt(self.variance()) else: return None
Standard deviation of all values entered into histogram. This number is precise, because we keep the necessary data separate from bin contents. Returns ------- float
344,195
def get(self, key, *, default=None, cast_func=None, case_sensitive=None, raise_exception=None, warn_missing=None, use_cache=True, additional_sources=[]): case_sensitive = self.case_sensitive if case_sensitive is None else case_sensitive raise_exception = self.raise_exception if raise_exception...
Gets the setting specified by ``key``. For efficiency, we cache the retrieval of settings to avoid multiple searches through the sources list. :param str key: settings key to retrieve :param str default: use this as default value when the setting key is not found :param func cast_func: cast the...
344,196
def delete_collection_csi_driver(self, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_collection_csi_driver_with_http_info(**kwargs) else: (data) = self.delete_collection_csi_driver_with_http_info(**kwargs) return data
delete collection of CSIDriver This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_csi_driver(async_req=True) >>> result = thread.get() :param async_req bool :param s...
344,197
def _collect_layer_output_min_max(mod, data, include_layer=None, max_num_examples=None, logger=None): collector = _LayerOutputMinMaxCollector(include_layer=include_layer, logger=logger) num_examples = _collect_layer_statistics(mod, data, collector, max_num_examples, logger...
Collect min and max values from layer outputs and save them in a dictionary mapped by layer names.
344,198
def infer(cls, sub_ija, T_ia, root_state, pc=0.01, gap_limit=0.01, Nit=30, dp=1e-5, **kwargs): from scipy import linalg as LA gtr = cls(**kwargs) gtr.logger("GTR: model inference ",1) q = len(gtr.alphabet) L = sub_ija.shape[-1] n_iter = 0 n...
Infer a GTR model by specifying the number of transitions and time spent in each character. The basic equation that is being solved is :math:`n_{ij} = pi_i W_{ij} T_j` where :math:`n_{ij}` are the transitions, :math:`pi_i` are the equilibrium state frequencies, :math:`W_{ij}` is the "s...
344,199
def _init_client(self): self._get_services() env = self._bucket_name = self._get_and_update_setting(env) self._build_bucket_name = "%s_cloudbuild" % self._bucket_name self._bucket = self._get_bucket(self._bucket_name) sel...
init client will check if the user has defined a bucket that differs from the default, use the application credentials to get the bucket, and then instantiate the client.