Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
352,300
def get_queue_for( self, queue_identifier: QueueIdentifier, ) -> NotifyingQueue: queue = self.queueids_to_queues.get(queue_identifier) if queue is None: items: List[QueueItem_T] = list() queue = self.init_queue_for(queue_identifier, items) ...
Return the queue identified by the given queue identifier. If the queue doesn't exist it will be instantiated.
352,301
def cache_train(self): filename = self.get_cache_location() if not os.path.exists(filename): return False categories = pickle.load(open(filename, )) assert isinstance(categories, BayesCategories), \ "Cache data is either corrupt or invalid" se...
Loads the data for this classifier from a cache file :return: whether or not we were successful :rtype: bool
352,302
def load_kbs(kbs_files): return { : build_journals_re_kb(kbs_files[]), : load_kb(kbs_files[], build_journals_kb), : build_reportnum_kb(kbs_files[]), : build_authors_kb(kbs_files[]), : build_books_kb(kbs_files[]), : load_kb(kbs_files[], build_publishers_kb), ...
Load kbs (without caching) Args: - kb_files: list of custom paths you can specify to override the default values If path starts with "kb:", the kb will be loaded from the database
352,303
def pagebreak(type=, orient=): page validtypes = [, ] if type not in validtypes: tmpl = raise ValueError(tmpl % (type, validtypes)) pagebreak = makeelement() if type == : run = makeelement() br = makeelement(, attributes={: type}) run.append(br) ...
Insert a break, default 'page'. See http://openxmldeveloper.org/forums/thread/4075.aspx Return our page break element.
352,304
def _GetHashes(self, target_queue, max_hashes): hashes = [] for _ in range(0, max_hashes): try: item = target_queue.get_nowait() except Queue.Empty: continue hashes.append(item) return hashes
Retrieves a list of items from a queue. Args: target_queue (Queue.queue): queue to retrieve hashes from. max_hashes (int): maximum number of items to retrieve from the target_queue. Returns: list[object]: list of at most max_hashes elements from the target_queue. The list...
352,305
def to_array(self): array = super(InlineQueryResultCachedMpeg4Gif, self).to_array() array[] = u(self.type) array[] = u(self.id) array[] = u(self.mpeg4_file_id) if self.title is not None: array[] = u(self.title) if self.caption is not None:...
Serializes this InlineQueryResultCachedMpeg4Gif to a dictionary. :return: dictionary representation of this object. :rtype: dict
352,306
def least_role() -> Role: LOGGER.debug() rv = Role.USER LOGGER.debug(, rv) return rv
Return the indy-sdk null role for a tails sync anchor, which does not need write access. :return: USER role
352,307
def ungettext(singular, plural, number, context=None): singular_stripped = strip_whitespace(singular) plural_stripped = strip_whitespace(plural) if context: singular = add_context(context, singular_stripped) plural = add_context(context, plural_stripped) else: singular = si...
Always return a stripped string, localized if possible
352,308
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs): if not self.can_handle(input_dict): return input_dict key = self.intrinsic_name value = input_dict[key] if not isinstance(value, list) or len(value) < 2: retu...
Resolve resource references within a GetAtt dict. Example: { "Fn::GetAtt": ["LogicalId", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]} Theoretically, only the first element of the array can contain reference to SAM resources. The second element is name of an attribut...
352,309
def _comic_archive_write_zipfile(new_filename, tmp_dir): if Settings.verbose: print(, end=) with zipfile.ZipFile(new_filename, , compression=zipfile.ZIP_DEFLATED) as new_zf: root_len = len(os.path.abspath(tmp_dir)) for r_d_f in os.walk(tmp_dir): ...
Zip up the files in the tempdir into the new filename.
352,310
def summary(self, stream): if len(self.node_descs) == 1: self.sep(stream, , % .join(self.node_descs)) else: self.sep(stream, , ) for node_desc in sorted(self.node_descs): self.sep(stream, , % node_desc) if in sel...
Produce coverage reports.
352,311
def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument(, , required=True, action=, help=) arg_parser.add_argument(, , required=True, action=, help=) arg_parser.add_argument(, , required=True, action=, help=) arg_p...
Main routine.
352,312
def describe(Name, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) rule = conn.describe_rule(Name=Name) if rule: keys = (, , , , , , ...
Given a rule name describe its properties. Returns a dictionary of interesting properties. CLI Example: .. code-block:: bash salt myminion boto_cloudwatch_event.describe myrule
352,313
def generate_synthetic_liver(return_dataplus=False): slab = {"none": 0, "liver": 1, "porta": 2} voxelsize_mm = np.array([1.0, 1.0, 1.2]) segm = np.zeros([80, 256, 250], dtype=np.int16) segm[30:60, 70:180, 40:190] = slab["liver"] segm[40:45, 120:130, 70:190] = slab["porta"] ...
Create synthetic data. There is some liver and porta -like object. :return data3d, segmentation, voxelsize_mm, slab, seeds_liver, seeds_porta:
352,314
def mixer(inputs, mix=None): if mix == None: mix = ([constant(1.0 / len(inputs))] * len(inputs),) duped_inputs = zip(*[itertools.tee(i, len(mix)) for i in inputs]) return [\ sum(*[multiply(m,i) for m,i in zip(channel_mix, channel_inputs)])\ for channel_mix, channel_inputs in zip(mix, duped_inputs) \ ...
Mix `inputs` together based on `mix` tuple `inputs` should be a tuple of *n* generators. `mix` should be a tuple of *m* tuples, one per desired output channel. Each of the *m* tuples should contain *n* generators, corresponding to the time-sequence of the desired mix levels for each of the *n* input channels. ...
352,315
def insert(self, key, item): return lib.zhashx_insert(self._as_parameter_, key, item)
Insert item into hash table with specified key and item. If key is already present returns -1 and leaves existing item unchanged Returns 0 on success.
352,316
def add_group(self, group_name, payment_address): if (self.is_group_name_exists(group_name)): raise Exception("the group \"%s\" is already present"%str(group_name)) group_id_base64 = base64.b64encode(secrets.token_bytes(32)) self.m["groups"] += [{"group_name" : group_na...
Return new group_id in base64
352,317
def content(self): if self._content is not None: return self._content if self._content_consumed: raise RuntimeError( ) try: self._content = self.raw.read() except AttributeError: return No...
Content of the response, in bytes or unicode (if available).
352,318
def remove_from_groups(self, groups=None, all_groups=False, group_type=None): if all_groups: if groups or group_type: raise ArgumentError("When removing from all groups, do not specify specific groups or types") glist = "all" else: if not grou...
Remove user from some PLC groups, or all of them. :param groups: list of group names the user should be removed from :param all_groups: a boolean meaning remove from all (don't specify groups or group_type in this case) :param group_type: the type of group (defaults to "product") :return...
352,319
def node_insert_before(self, node, new_node): assert(not self.node_is_on_list(new_node)) assert(node is not new_node) prev = self.node_prev(node) assert(prev is not None) self.node_set_prev(node, new_node) self.node_set_next(new_node, node) self.node_s...
Insert the new node before node.
352,320
def getName(self, innerFlag=False): if self._currentIdx is None: raise error.PyAsn1Error() else: if innerFlag: c = self._componentValues[self._currentIdx] if isinstance(c, Choice): return c.getName(innerFlag) ...
Return the name of currently assigned component of the |ASN.1| object. Returns ------- : :py:class:`str` |ASN.1| component name
352,321
def Find(self, find_specs=None): if not find_specs: find_specs.append(FindSpec()) for find_spec in find_specs: find_spec.PrepareMatches(self._file_system) if path_spec_factory.Factory.IsSystemLevelTypeIndicator( self._file_system.type_indicator): file_entry = self._file_syst...
Searches for matching file entries within the file system. Args: find_specs (list[FindSpec]): find specifications. where None will return all allocated file entries. Yields: PathSpec: path specification of a matching file entry.
352,322
def get_input_from_submission(self, submission, only_input=False): inp = bson.BSON.decode(self._gridfs.get(submission[]).read()) if only_input: return inp else: submission["input"] = inp return submission
Get the input of a submission. If only_input is False, returns the full submissions with a dictionnary object at the key "input". Else, returns only the dictionnary.
352,323
def compute_u_val_for_sky_loc_stat(hplus, hcross, hphccorr, hpnorm=None, hcnorm=None, indices=None): if indices is not None: hplus = hplus[indices] hcross = hcross[indices] if hpnorm is not None: hplus = hplus * hpnorm if hcnorm is not None: ...
The max-over-sky location detection statistic maximizes over a phase, an amplitude and the ratio of F+ and Fx, encoded in a variable called u. Here we return the value of u for the given indices.
352,324
def tar(self, appname, appversion): name_tmpl = time = utc.now() name = name_tmpl % {: appname, : appversion, : time.strftime()} if not os.path.exists(TARBALL_HOME): os.mkdir(TARBALL_HOME) tarball = os...
Given an app name and version to be used in the tarball name, create a tar.bz2 file with all of this folder's contents inside. Return a Build object with attributes for appname, appversion, time, and path.
352,325
def has_dependencies(node, dag): for downstream_nodes in dag.values(): if node in downstream_nodes: return True return False
Checks if the node has dependencies.
352,326
def recognize_array(self, byte_array): if type(byte_array) != bytes: raise TypeError("Expected a byte array (string in Python 2, bytes in Python 3)") pb = ctypes.cast(byte_array, ctypes.POINTER(ctypes.c_ubyte)) ptr = self._recognize_array_func(self.alpr_pointer, pb, len(byte...
This causes OpenALPR to attempt to recognize an image passed in as a byte array. :param byte_array: This should be a string (Python 2) or a bytes object (Python 3) :return: An OpenALPR analysis in the form of a response dictionary
352,327
def update_keyjar(keyjar): for iss, kbl in keyjar.items(): for kb in kbl: kb.update()
Go through the whole key jar, key bundle by key bundle and update them one by one. :param keyjar: The key jar to update
352,328
def GE(classical_reg1, classical_reg2, classical_reg3): classical_reg1, classical_reg2, classical_reg3 = prepare_ternary_operands(classical_reg1, classical_reg2, ...
Produce an GE instruction. :param classical_reg1: Memory address to which to store the comparison result. :param classical_reg2: Left comparison operand. :param classical_reg3: Right comparison operand. :return: A ClassicalGreaterEqual instance.
352,329
def crs(self, crs): if isinstance(crs, QgsCoordinateReferenceSystem): self._crs = crs self._is_ready = False else: raise InvalidExtentError( % crs)
Setter for extent_crs property. :param crs: The coordinate reference system for the analysis boundary. :type crs: QgsCoordinateReferenceSystem
352,330
def _set_ipv6_routes(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=ipv6_routes.ipv6_routes, is_container=, presence=False, yang_name="ipv6-routes", rest_name="ipv6-routes", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, reg...
Setter method for ipv6_routes, mapped from YANG variable /isis_state/ipv6_routes (container) If this variable is read-only (config: false) in the source YANG file, then _set_ipv6_routes is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ip...
352,331
def _infer_transform_options(transform): TransformOptions = collections.namedtuple("TransformOptions", [, , , , ]) CB = False SB = False MB = False dual_index = False triple_index = False for rx in transform.values(): if not rx: ...
figure out what transform options should be by examining the provided regexes for keywords
352,332
def get_train_examples(self, data_dir): logger.info("LOOKING AT {}".format(os.path.join(data_dir, "train.tsv"))) return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")
See base class.
352,333
def parse_crop(crop, xy_image, xy_window): x_alias_percent = { : , : , : , } y_alias_percent = { : , : , : , } xy_crop = crop.split() if len(xy_crop) == 1: if crop in x_alias_percent: x_crop = x_alias_percent[crop] ...
Returns x, y offsets for cropping. The window area should fit inside image but it works out anyway
352,334
def check_feature(self, feature, readwrite): if readwrite == "read": features = self.can_read if readwrite == "write": features = self.can_write if feature not in features: matches = difflib.get_close_matches(feature, features) ...
Check if the *feature* is supported in the handler and raise an exception otherwise. **Parameters** feature: str Identifier for a certain feature. readwrite: "read" or "write" Check if the feature is available for reading or writing.
352,335
def single(self): return not in self._looking_for_xpb.li(id=).\ one_(self._profile.profile_tree).attrib[]
Whether or not the user is only interested in people that are single.
352,336
def cublasZhpr2(handle, uplo, n, alpha, x, inx, y, incy, AP): status = _libcublas.cublasZhpr2_v2(handle, _CUBLAS_FILL_MODE[uplo], n, ctypes.byref(cuda.cuDoubleComplex(alpha.real, ...
Rank-2 operation on Hermitian-packed matrix.
352,337
def prepare_post_parameters(self, post_params=None, files=None): params = post_params or [] for key, values in (files or {}).items(): for maybe_file_or_path in values if isinstance(values, list) else [values]: try: data = mayb...
Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. :return: Form parameters with files.
352,338
def without(self, other): if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth") self._demote_all() opd = set(other.get_demoted()) self.pixeldict[self.maxdepth].difference_update(opd) self._renorm() ...
Subtract another Region by performing a difference operation on their pixlists. Requires both regions to have the same maxdepth. Parameters ---------- other : :class:`AegeanTools.regions.Region` The region to be combined.
352,339
def add_spin_by_element(self, spins): for site in self.sites: new_sp = {} for sp, occu in site.species.items(): sym = sp.symbol oxi_state = getattr(sp, "oxi_state", None) new_sp[Specie(sym, oxidation_state=oxi_state, ...
Add spin states to a structure. Args: spisn (dict): Dict of spins associated with elements or species, e.g. {"Ni":+5} or {"Ni2+":5}
352,340
def add_event_type(self, name): if name in self.event_types: lg.info( + name + ) return events = self.rater.find() new_event_type = SubElement(events, ) new_event_type.set(, name) self.save()
Raises ------ IndexError When there is no selected rater
352,341
def add_input(self, input_): if not isinstance(input_, Input): raise TypeError() self.inputs.append(input_)
Adds an input to a Transaction's list of inputs. Args: input_ (:class:`~bigchaindb.common.transaction. Input`): An Input to be added to the Transaction.
352,342
def find_contour_file(rtdc_dataset): cont_id = rtdc_dataset.path.stem cands = [c.name for c in rtdc_dataset._fdir.rglob("*_contours.txt")] cands = sorted(cands) for c1 in cands: if c1.startswith(cont_id): cfile = rtdc_datase...
Tries to find a contour file that belongs to an RTDC dataset Returns None if no contour file is found.
352,343
def get_all_blockstack_ops_at( self, block_number, offset=None, count=None, include_history=None, restore_history=None ): if include_history is not None: log.warn("DEPRECATED use of include_history") if restore_history is not None: log.warn("DEPRECATED use of restore_hi...
Get all name, namespace, and account records affected at a particular block, in the state they were at the given block number. Paginate if offset, count are given.
352,344
def fromkeys (cls, iterable, value=None): d = cls() for k in iterable: dict.__setitem__(d, k.lower(), value) return d
Construct new caseless dict from given data.
352,345
def download_file(image_name, output_path, width=DEFAULT_WIDTH): image_name = clean_up_filename(image_name) logging.info("Downloading %s with width %s", image_name, width) try: contents, output_file_name = get_thumbnail_of_file(image_name, width) except RequestedWidthBiggerThanSourceExcepti...
Download a given Wikimedia Commons file.
352,346
def query_download_tasks(self, task_ids, operate_type=1, expires=None, **kwargs): params = { : .join(map(str, task_ids)), : operate_type, : expires, } return self._request(, , extra_params=par...
根据任务ID号,查询离线下载任务信息及进度信息。 :param task_ids: 要查询的任务ID列表 :type task_ids: list or tuple :param operate_type: * 0:查任务信息 * 1:查进度信息,默认为1 :param expires: 请求失效时间,如果有,则会校验。 :type expires: int :return: Response 对象
352,347
def aes_cbc_encrypt_data(symkey, iv, data, pad): cipher = cryptography.hazmat.primitives.ciphers.Cipher( cryptography.hazmat.primitives.ciphers.algorithms.AES(symkey), cryptography.hazmat.primitives.ciphers.modes.CBC(iv), backend=cryptography.hazmat.backends.default_backend()).encr...
Encrypt data using AES CBC :param bytes symkey: symmetric key :param bytes iv: initialization vector :param bytes data: data to encrypt :param bool pad: pad data :rtype: bytes :return: encrypted data
352,348
def check_recipe_choices(self): recipes = [] built_recipes = self.ctx.recipe_build_order for recipe in self.depends: if isinstance(recipe, (tuple, list)): for alternative in recipe: if alternative in built_recipes: ...
Checks what recipes are being built to see which of the alternative and optional dependencies are being used, and returns a list of these.
352,349
def Hash(self): if not self.__hash: hashdata = self.RawData() ba = bytearray(binascii.unhexlify(hashdata)) hash = bin_dbl_sha256(ba) self.__hash = UInt256(data=hash) return self.__hash
Get the hash value of the Blockbase. Returns: UInt256: containing the hash of the data.
352,350
def lock_variable(self, key, block=False): key = str(key) try: if key in self.__variable_locks: lock_successful = self.__variable_locks[key].acquire(False) if lock_successful or block: if (not lock_success...
Locks a global variable :param key: the key of the global variable to be locked :param block: a flag to specify if to wait for locking the variable in blocking mode
352,351
def _get_cache_key(self, **kwargs): m = md5() for significant_kwarg in self.significant_kwargs: key, to_str = significant_kwarg try: m.update(to_str(kwargs[key])) except (TypeError, UnicodeEncodeError):
Take this task's configured ``significant_kwargs`` and build a hash that all equivalent task calls will match. Takes in kwargs and returns a string. To change the way the cache key is generated or do more in-depth processing, override this method.
352,352
def random_combination(nsets, n, k): sets = set() while len(sets) < nsets: newset = tuple(sorted(np.random.choice(n, k, replace=False))) sets.add(newset) return tuple(sets)
Returns nsets unique random quartet sets sampled from n-choose-k without replacement combinations.
352,353
def parse_wiod(path, year=None, names=(, ), popvector=None): path = os.path.abspath(os.path.normpath(str(path))) wiot_ext = wiot_start = if not os.path.isdir(path): if os.path.isfile(path): wiot_file = path else: ...
Parse the wiod source files for the IOSystem WIOD provides the MRIO tables in excel - format (xlsx) at http://www.wiod.org/new_site/database/wiots.htm (release November 2013). To use WIOD in pymrio these (for the year of analysis) must be downloaded. The interindustry matrix of these files gets parsed ...
352,354
def collection(cls, cid): url = urljoin(config.API_URL, % cid) return Collection(cls.query(url=url))
Get a Collection record
352,355
def resize(self, dims): width, height = dims[:2] self.dims = (width, height) self.logger.debug("renderer reconfigured to %dx%d" % ( width, height)) depth = len(self.rgb_order) self.surface_arr = np.zeros((height, width, depth), dtype=np.uin...
Resize our drawing area to encompass a space defined by the given dimensions.
352,356
def parse_rules(content=None): rules = content.split(DELIMITER) parsed_rules = list() order = 1 for rule in rules: if rule.strip() == : continue parsed_rule = {} lines = rule.split("\n") parsed_rule[] = order order += 1 for line in lines: ...
Helper to parse the input from the user into a list of rules. :param string content: the content of the editor :returns: a list of rules
352,357
def get_prep_value(self, value): try: return json.dumps(value, cls=DjangoJSONEncoder) except Exception as e: raise ValidationError(str(e))
Convert value to JSON string before save
352,358
def _process_file_continue_ftp_response(self, response: FTPResponse): if response.request.restart_value and response.restart_value: self.open_file(self._filename, response, mode=) else: self._raise_cannot_continue_error()
Process a restarted content response.
352,359
def getServiceJobsToStart(self, maxWait): try: serviceJob = self._serviceJobGraphsToStart.get(timeout=maxWait) assert self.jobsIssuedToServiceManager >= 0 self.jobsIssuedToServiceManager -= 1 return serviceJob except Empty: return None
:param float maxWait: Time in seconds to wait to get a job before returning. :return: a tuple of (serviceJobStoreID, memory, cores, disk, ..) representing a service job to start. :rtype: toil.job.ServiceJobNode
352,360
def validate(self, strict=True): valid = True try: jsonschema.validate(self.__json_light__, schema.JAMS_SCHEMA) for ann in self.annotations: if isinstance(ann, Annotation): valid &= ann.validate(strict=strict) else: ...
Validate a JAMS object against the schema. Parameters ---------- strict : bool If `True`, an exception will be raised on validation failure. If `False`, a warning will be raised on validation failure. Returns ------- valid : bool `Tru...
352,361
def equal(x, y): x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_equal_p(x, y)
Return True if x == y and False otherwise. This function returns False whenever x and/or y is a NaN.
352,362
def visit_named_arg(self, _, children): return self.NamedArg( arg=children[0], arg_type=children[2], value=children[4], )
Named argument of a filter. Arguments --------- _ (node) : parsimonious.nodes.Node. children : list - 0: name of the arg - 1: for ``WS`` (whitespace): ``None``. - 2: operator - 3: for ``WS`` (whitespace): ``None``. - 4: value o...
352,363
def get_arg_name(self, param): if self.current_command in self.cmdtab: for arg in self.cmdtab[self.current_command].arguments: for name in self.cmdtab[self.current_command].arguments[arg].options_list: if name == param: return arg...
gets the argument name used in the command table for a parameter
352,364
def fetch_items(self, category, **kwargs): from_date = kwargs[] logger.info("Looking for messages from on since %s", self.uri, self.dirpath, str(from_date)) mailing_list = MailingList(self.uri, self.dirpath) messages = self._fetch_and_parse_messages(mail...
Fetch the messages :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
352,365
def to_pandas(self): if not all(ind.is_raw() for ind in self.values): raise ValueError() from pandas import MultiIndex as PandasMultiIndex arrays = [ind.values for ind in self.values] return PandasMultiIndex.from_arrays(arrays, names=self.names)
Convert to pandas MultiIndex. Returns ------- pandas.base.MultiIndex
352,366
def make_diag_scale(loc=None, scale_diag=None, scale_identity_multiplier=None, shape_hint=None, validate_args=False, assert_positive=False, name=None, dtype=None): def _maybe...
Creates a LinearOperator representing a diagonal matrix. Args: loc: Floating-point `Tensor`. This is used for inferring shape in the case where only `scale_identity_multiplier` is set. scale_diag: Floating-point `Tensor` representing the diagonal matrix. `scale_diag` has shape [N1, N2, ... k], w...
352,367
def run(self, args): if len(args) <= 1: step_ignore = 0 else: step_ignore = self.proc.get_int(args[1], default=1, cmdname=) if step_ignore is None: return False step_ignore -= 1 ...
**next**[**+**|**-**] [*count*] Step one statement ignoring steps into function calls at this level. With an integer argument, perform `next` that many times. However if an exception occurs at this level, or we *return*, *yield* or the thread changes, we stop regardless of count. A suffix of `+` on the command or an...
352,368
def copy(self): req = type(self)() req.__dict__ = self.__dict__.copy() req._headers = self.headers.copy() return req
Copies the current Request object instance for side-effects purposes. Returns: pook.Request: copy of the current Request instance.
352,369
def _to_dict(self): _dict = {} if hasattr(self, ) and self.anger is not None: _dict[] = self.anger if hasattr(self, ) and self.disgust is not None: _dict[] = self.disgust if hasattr(self, ) and self.fear is not None: _dict[] = self.fear ...
Return a json dictionary representing this model.
352,370
def address_data(data, dims=None, surface=0.5, strict=True): whitepialmidgray if data is None: return (None, None) if not is_address(data): raise ValueError() faces = np.asarray(data[]) coords = np.asarray(data[]) if len(faces.shape) > 2 or len(coords.shape) > 2: raise ValueError() e...
address_data(addr) yields the tuple (faces, coords) of the address data where both faces and coords are guaranteed to be numpy arrays with sizes (3 x n) and (d x n); this will coerce the data found in addr if necessary to do this. If the data is not valid, then an error is raised. If the address is em...
352,371
def open(self): self.__sf = _sftp_open(self.__sftp_session_int, self.__filepath, self.access_type_int, self.__create_mode) if self.access_type_is_append is True: self.seek(self.filesize...
This is the only way to open a file resource.
352,372
def hpx_to_axes(h, npix): x = h.ebins z = np.arange(npix[-1] + 1) return x, z
Generate a sequence of bin edge vectors corresponding to the axes of a HPX object.
352,373
def extract_xyz_matrix_from_pdb_chain(pdb_lines, chain_id, atoms_of_interest = backbone_atoms, expected_num_residues = None, expected_num_residue_atoms = None, fail_on_model_records = True, include_all_columns = False): if fail_on_model_records and [l for l in pdb_lines if l.startswith()]: ...
Returns a pandas dataframe of X, Y, Z coordinates for the PDB chain. Note: This function is not intended to handle structures with MODELs e.g. from NMR although the fail_on_model_records check is optional for convenience in case the chain of the first model is to be parsed.
352,374
def manage_crawlers(self): sites = self.json.get_site_objects() for index, site in enumerate(sites): if "daemonize" in site: self.daemon_list.add_daemon(index, site["daemonize"]) elif "additional_rss_daemon" in site: self.daemon_list.add_d...
Manages all crawlers, threads and limites the number of parallel running threads.
352,375
def is_unit_acceptable(self, unit, raise_exception=True): _is_acceptable = unit in self.units if _is_acceptable or raise_exception is False: return _is_acceptable else: raise ValueError( .format( unit, self.__...
Check if a certain unit is acceptable for the data type. Args: unit: A text string representing the abbreviated unit. raise_exception: Set to True to raise an exception if not acceptable.
352,376
def print_ipython(self): from IPython.display import display, HTML self._listen() try: shutil.rmtree() except: None shutil.copytree(self.html_path, ) pth = "viz/index.html" html = open(pth).read() html = html.replace("__SERVER_DATA__", +str(self....
Renders the javascript table to a jupyter/ipython notebook cell Usage example: >>> t = Table(ind) >>> t.print_ipython() ... renders the table to notebook cell
352,377
def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]: return [utter for utter in utterances if utter.text.strip() != ""]
Remove empty utterances from a list of utterances Args: utterances: The list of utterance we are processing
352,378
def check_table_formats(files): cont = True formats = get_table_formats() for t in files.split(): _, ext = os.path.splitext(t) ext = ext[1:].lower() if ext not in formats: cont = False log.warn("Format not supported for {0} ({1})".format(t, ext)) if n...
Determine whether a list of files are of a recognizable output type. Parameters ---------- files : str A list of file names Returns ------- result : bool True if *all* the file names are supported
352,379
def update_collection(self, payload, last_modified=None): modified = payload["version"] if last_modified is not None: modified = last_modified key = payload["key"] headers = {"If-Unmodified-Since-Version": str(modified)} headers.update(self.default_headers())...
Update a Zotero collection property such as 'name' Accepts one argument, a dict containing collection data retrieved using e.g. 'collections()'
352,380
def iterable(self, iterable_name, *, collection, attribute, word, func=None, operation=None): if func is None and operation is None: raise ValueError() elif func is not None and operation is not None: raise ValueError( ) current...
Performs a filter with the OData 'iterable_name' keyword on the collection For example: q.iterable('any', collection='email_addresses', attribute='address', operation='eq', word='george@best.com') will transform to a filter such as: emailAddresses/any(a:a/address eq 'ge...
352,381
def get_direct_ancestors(G, list_of_nodes): parents = [] for item in list_of_nodes: anc = G.predecessors(item) for one in anc: parents.append(one) return parents
Returns a list of nodes that are the parents from all of the nodes given as an argument. This is for use in the parallel topo sort
352,382
def sort_sentences_by_token_order(sentence_root_nodes, token_nodes): def sentence_sort_key(sentence_token_tuple): return natural_sort_key(sentence_token_tuple[1][0]) sentence_token_tuples = zip(sentence_root_nodes, token_nodes) return sorted(sentence_token_tuples, key=sentence_sort_ke...
Given a list of sentence markables (i.e. sentence root nodes) and a list of lists of token markables (one list per sentence), returns a list of (sentence root node, token nodes) tuples. The result is sorted by the order in which the tokens occur in the text. Parameters ---------- sentence_root_...
352,383
def _get_renamed_deleted_sourcesapp(self): renamed_sources = {} deleted_sources = {} tags = ["GetRenameSource", "GetDeletedSource"] root = self.exec_appcommand_post(tags) if root is None: _LOGGER.error("Getting re...
Get renamed and deleted sources lists from receiver . Internal method which queries device via HTTP to get names of renamed input sources. In this method AppCommand.xml is used.
352,384
def _get_namespace_filter( taxon_filter: Optional[int]=None, category_filter: Optional[str]=None) -> Union[None, str]: namespace_filter = None taxon_category_default = { 10090: , 9606: , 7227: , 6239: , 7955:...
Given either a taxon and/or category, return the correct namespace :raises ValueError: If category is provided without a taxon
352,385
def load(hdf5_file_name, data, minPts, eps = None, quantile = 50, subsamples_matrix = None, samples_weights = None, metric = , p = 2, verbose = True): data = np.array(data, copy = False) if data.ndim > 2: raise ValueError("\nERROR: DBSCAN_multiplex @ load:\n" "the da...
Determines the radius 'eps' for DBSCAN clustering of 'data' in an adaptive, data-dependent way. Parameters ---------- hdf5_file_name : file object or string The handle or name of an HDF5 data structure where any array needed for DBSCAN and too large to fit into memory is to be stored. ...
352,386
def _api_delete(self, api_key=None, **kwargs): api_key = api_key or self.default_api_key return self.api_retrieve(api_key=api_key).delete(**kwargs)
Call the stripe API's delete operation for this model :param api_key: The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY. :type api_key: string
352,387
def remove_intent(self, name): self.intents.remove(name) self.padaos.remove_intent(name) self.must_train = True
Unload an intent
352,388
def getaddrinfo_wrapper(host, port, family=socket.AF_INET, socktype=0, proto=0, flags=0): return orig_getaddrinfo(host, port, family, socktype, proto, flags)
Patched 'getaddrinfo' with default family IPv4 (enabled by settings IPV4_ONLY=True)
352,389
def ensure_output(self): if not os.path.exists(self.output): os.makedirs(self.output)
Ensure output's directory exists
352,390
def copy(self, *, continuations: List[memoryview] = None, expected: Sequence[Type[]] = None, list_expected: Sequence[Type[]] = None, command_name: bytes = None, uid: bool = None, charset: str = None, tag: bytes = None, max_append...
Copy the parameters, possibly replacing a subset.
352,391
def handle_send( entity: BaseEntity, author_user: UserType, recipients: List[Dict], parent_user: UserType = None, ) -> None: payloads = [] public_payloads = { "activitypub": { "auth": None, "payload": None, "urls": set(), }...
Send an entity to remote servers. Using this we will build a list of payloads per protocol. After that, each recipient will get the generated protocol payload delivered. Delivery to the same endpoint will only be done once so it's ok to include the same endpoint as a receiver multiple times. Any given...
352,392
def get_cheapest_instance_type(cores, memory): pricelist = get_gcloud_pricelist() us_instance_types = {k: v for k, v in pricelist.items() if k.startswith() and not k.endswith() and in v and v[] != } price_array = [...
Determine the cheapest instance type given a minimum number of cores and minimum amount of RAM (in GB).
352,393
def get_logged_in_account(token_manager=None, app_url=defaults.APP_URL): headers = token_manager.get_access_token_headers() auth_url = environment.get_auth_url(app_url=app_url) url = "%s/api/v1/account" % auth_url response = requests.get(url, h...
get the account details for credentials provided
352,394
def public_key_from_ed25519_key(hex_public_key): public_key = crypto.Ed25519VerifyingKey(bytes.fromhex(hex_public_key), encoding=) return public_key.encode(encoding=).decode()
Generate base58 public key from hex encoded public key
352,395
def get_reports(self): return sorted(self._reports, key=lambda x: x[][], reverse=True)
Returns a minimized version of the aggregation
352,396
def add_artifact( self, filename, name=None, metadata=None, content_type=None, ): filename = os.path.abspath(filename) name = os.path.basename(filename) if name is None else name self._emit_artifact_added(name, filename, me...
Add a file as an artifact. In Sacred terminology an artifact is a file produced by the experiment run. In case of a MongoObserver that means storing the file in the database. See also :py:meth:`sacred.Experiment.add_artifact`. Parameters ---------- filename : s...
352,397
def create_session(self, user_agent, remote_address, client_version): self.session_counter += 1 self.sessions[self.session_counter] = session = self.session_class() session.user_agent = user_agent session.remote_address = remote_address session.client_version ...
Create a new session. :param str user_agent: Client user agent :param str remote_addr: Remote address of client :param str client_version: Remote client version :return: The new session id :rtype: int
352,398
def next_request(self): method_frame, header_frame, url = self.server.basic_get(queue=self.rabbitmq_key) print url if url: return self.make_requests_from_url(url)
Provides a request to be scheduled. :return: Request object or None
352,399
def split_infinitive_warning(sentence_str): sent_doc = textacy.Doc(sentence_str, lang=) inf_pattern = r infinitives = textacy.extract.pos_regex_matches(sent_doc, inf_pattern) for inf in infinitives: if inf[0].text.lower() != : continue if inf[-1].tag_ != : co...
Return a warning for a split infinitive, else, None