Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
338,200
def hill_climber(objective_function, initial_array, lower_bound=-float(), acceptance_criteria=None, max_iterations=10 ** 3): X = initial_array if acceptance_criteria is not None: acceptance_bound = acceptance_criteria(X) iter...
Implement a basic hill climbing algorithm. Has two stopping conditions: 1. Maximum number of iterations; 2. A known lower bound, a none is passed then this is not used. If acceptance_criteria (a callable) is not None then this is used to obtain an upper bound on some other measure (different to t...
338,201
def get_subgraph_for_concept( self, concept: str, depth: int = 1, reverse: bool = False ): nodeset = {concept} if reverse: func = self.predecessors else: func = self.successors for i in range(depth): nodeset.update( ...
Returns a new subgraph of the analysis graph for a single concept. Args: concept: The concept that the subgraph will be centered around. depth: The depth to which the depth-first search must be performed. reverse: Sets the direction of causal influence flow to examine. ...
338,202
def get_sequence_rule_admin_session(self): if not self.supports_sequence_rule_admin(): raise errors.Unimplemented() return sessions.SequenceRuleAdminSession(runtime=self._runtime)
Gets the ``OsidSession`` associated with the sequence rule administration service. return: (osid.assessment.authoring.SequenceRuleAdminSession) - a ``SequenceRuleAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_sequence_rule_...
338,203
def save(self, path): for relative_path_and_filename, content in self.files.items(): full_path_and_filename = os.path.join(path, relative_path_and_filename) full_path = os.path.dirname(full_path_and_filename) if not os.path.isdir(full_path): os.maked...
Saving stored files at a given path (relative paths are added). Args: path (str): root path where to save the files.
338,204
def GrantApproval(self, requestor_username, approval_id, grantor_username): try: approval = self.approvals_by_username[requestor_username][approval_id] approval.grants.append( rdf_objects.ApprovalGrant( grantor_username=grantor_username, timestamp=rdfvalue.RDFD...
Grants approval for a given request using given username.
338,205
def formfield_for_foreignkey_helper(inline, *args, **kwargs): db_field = args[0] if db_field.name != "related_type": return args, kwargs initial_filter = getattr(settings, RELATED_TYPE_INITIAL_FILTER, False) if "initial" not in kwargs and initial_filter: initia...
The implementation for ``RelatedContentInline.formfield_for_foreignkey`` This takes the takes all of the ``args`` and ``kwargs`` from the call to ``formfield_for_foreignkey`` and operates on this. It returns the updated ``args`` and ``kwargs`` to be passed on to ``super``. This is solely an implement...
338,206
def rename(self, from_, to): blueprint = self._create_blueprint(from_) blueprint.rename(to) self._build(blueprint)
Rename a table on the schema.
338,207
def create_args(line, namespace): args = [] for arg in shlex.split(line): if not arg: continue if arg[0] == : var_name = arg[1:] if var_name in namespace: args.append((namespace[var_name])) else: raise Exception( % arg) else: ...
Expand any meta-variable references in the argument list.
338,208
def _read_json(fn_json): is_json = set() is_db = {} with open(fn_json) as handle: data = json.load(handle) for item in list(data[0].values()): seqs_name = [list(x.keys()) for x in item[]] db_name = item[] if "valid" in item els...
read json information
338,209
def get_family_search_session(self, proxy=None): if not self.supports_family_search(): raise Unimplemented() try: from . import sessions except ImportError: raise OperationFailed() proxy = self._convert_proxy(proxy) try: se...
Gets the ``OsidSession`` associated with the family search service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.FamilySearchSession) - a ``FamilySearchSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to comp...
338,210
def restore(cls, metadata_checkpoint_dir, search_alg=None, scheduler=None, trial_executor=None): newest_ckpt_path = _find_newest_ckpt(metadata_checkpoint_dir) with open(newest_ckpt_path, "r") as f: runner_state = json....
Restores all checkpointed trials from previous run. Requires user to manually re-register their objects. Also stops all ongoing trials. Args: metadata_checkpoint_dir (str): Path to metadata checkpoints. search_alg (SearchAlgorithm): Search Algorithm. Defaults to ...
338,211
def readinto(self, b): data = self.read(len(b)) if not data: return 0 b[:len(data)] = data return len(data)
Read up to len(b) bytes into b, and return the number of bytes read.
338,212
def split_param_vec(beta, rows_to_alts=None, design=None, return_all_types=False, *args, **kwargs): if return_all_types: return None, None, None, beta else: return None, None, beta
Parameters ---------- beta : 1D ndarray. All elements should by ints, floats, or longs. Should have 1 element for each utility coefficient being estimated (i.e. num_features). rows_to_alts : None, Not actually used. Included merely for consistency with other models. design : None...
338,213
def set_workdir(self, workdir, chroot=False): if not chroot and hasattr(self, "workdir") and self.workdir != workdir: raise ValueError("self.workdir != workdir: %s, %s" % (self.workdir, workdir)) self.workdir = os.path.abspath(workdir) self.input_file = File(os.p...
Set the working directory. Cannot be set more than once unless chroot is True
338,214
def get_last_failed_access_attempt(cls, **kwargs): try: lockout = cls.objects.get( **kwargs ) except cls.DoesNotExist: lockout = None if lockout: time_remaining = lockout.expiration_time if time_remaining and t...
Return Failed access attempt of Client :param ip_adress: String :return:
338,215
def find_centroid(cvects, idx_list, weights=None): if weights is None: weighted = cvects.T[idx_list].sum(0) sum_weights = float(len(idx_list)) else: weighted = ((cvects * weights).T[idx_list]).sum(0) sum_weights = weights.sum(0) weighted /= sum_weights norm = np...
Find the centroid for a set of vectors Parameters ---------- cvects : ~numpy.ndarray(3,nsrc) with directional cosine (i.e., x,y,z component) values idx_list : [int,...] list of the source indices in the cluster weights : ~numpy.ndarray(nsrc) with the weights to use. None for equal weightin...
338,216
def get_raw_data(self): if self.__report_kind != HidP_Output \ and self.__report_kind != HidP_Feature: raise HIDError("Only for output or feature reports") self.__prepare_raw_data() return helpers.ReadOnlyList(self.__raw_data)
Get raw HID report based on internal report item settings, creates new c_ubytes storage
338,217
def _get_kmeans_lookup_table_and_weight(nbits, w, init=, tol=1e-2, n_init=1, rand_seed=0): if _HAS_SKLEARN: from sklearn.cluster import KMeans else: raise Exception() units = _np.prod(w.shape) lut_len = 1 << nbits n_clusters = units if (units < lut_len) else lut_len wf = w.r...
Generate K-Means lookup table given a weight parameter field :param nbits: Number of bits for quantization :param w: Weight as numpy array Returns ------- lut: numpy.array Lookup table, numpy array of shape (1 << nbits, ); wq: numpy.array Quantized weight of ty...
338,218
def parse_ouput(self, data, context, response): parsedData = data.split("!-!") nameList = [, , , , ] for x in range(0, len(parsedData)): if "ComputerName" in parsedData[x] and "UserName" in parsedData[x] : log_name = .format(nameList[0], response.client_addr...
Parse the output from Invoke-BloodHound
338,219
def plot_ES(q: np.ndarray, sim_name: str, fname: Optional[str] = None): sun_x = q[:,0] / au2m sun_y = q[:,1] / au2m earth_x = q[:,3] / au2m earth_y = q[:,4] / au2m fig, ax = plt.subplots(figsize=[12,12]) ax.set_title(f) ax.set_xlabel() ax.set_ylabel() a ...
Plot the earth-sun orbits. q is a Tx6 array. T indexes time points. 6 columns are sun (x, y, z) and earth (x, y, z)
338,220
def on_websocket_message(message: str) -> None: msgs = json.loads(message) for msg in msgs: if not isinstance(msg, dict): logger.error(.format(message)) continue _type = msg.get() if _type == : log_handler(msg[], msg[]) elif _type == : ...
Handle messages from browser.
338,221
def show_tricky_tasks(self, verbose=0): nids, tasks = [], [] for task in self.iflat_tasks(): if task.num_launches > 1 or any(n > 0 for n in (task.num_restarts, task.num_corrections)): nids.append(task.node_id) tasks.append(task) if not nids: ...
Print list of tricky tasks i.e. tasks that have been restarted or launched more than once or tasks with corrections. Args: verbose: Verbosity level. If > 0, task history and corrections (if any) are printed.
338,222
def _leave(ins): global FLAG_use_function_exit output = [] if ins.quad[1] == : output.append() return output nbytes = int(ins.quad[1]) if nbytes == 0: output.append() output.append() output.append() return output if nbytes == 1: ...
Return from a function popping N bytes from the stack Use '__fastcall__' as 1st parameter, to just return
338,223
def to_svc_hst_distinct_lists(ref, tab): res = {: [], : []} for elem in tab: cls = elem.__class__ name = elem.get_full_name() if cls.my_type == : res[].append(name) else: res[].append(name) return res
create a dict with 2 lists:: * services: all services of the tab * hosts: all hosts of the tab :param ref: Not used :type ref: :param tab: list of Host and Service :type tab: list :return: dict with hosts and services names :rtype: dict
338,224
def mapvo(ol,map_func,*args,**kwargs): lngth = ol.__len__() args = list(args) if(args.__len__()==0): diff_args_arr = kwargs[] else: diff_args_arr = args[0] rslt = [] for i in range(0,lngth): index = i value = ol[i] func = map_func args = diff_...
#mapvo 共享相同的f,i不作为map_func参数 # share common map_func,NOT take index as a param for map_func # common_func(value,*priv_args)
338,225
def map_vars(self, comps, funcname=, diffmap=None, **kwargs): out = {} diffmap = diffmap or {} for c in comps: cat = c.category if cat in diffmap: symbol = self.diffname(self.ivarmap[cat]) out[symbol] = diffmap[cat] e...
Map component function ``funcname`` result into model variables dictionary for use in eval of the model. If ``diffmap`` is provided then that symbol is translated into 'd'+diffmap.key and is replaced by diffmap.value. ``**kwargs` are passed to the ``comp.funcname(**kwargs)``.
338,226
def render_children(self, context, fragment, can_reorder=True, can_add=False): contents = [] child_context = {: set()} if context: child_context.update(context) for child_id in self.children: child = self.runtime.get_block(child_id) if can_r...
Renders the children of the module with HTML appropriate for Studio. If can_reorder is True, then the children will be rendered to support drag and drop.
338,227
def get_symbol_list(rank, dim=6): indices = list( itertools.combinations_with_replacement(range(dim), r=rank)) c_vec = np.zeros(len(indices), dtype=object) c_arr = np.zeros([dim]*rank, dtype=object) for n, idx in enumerate(indices): c_vec[n] = sp.Symbol(+.join([str(i) for i in idx])...
Returns a symbolic representation of the voigt-notation tensor that places identical symbols for entries related by index transposition, i. e. C_1121 = C_1211 etc. Args: dim (int): dimension of matrix/tensor, e. g. 6 for voigt notation and 3 for standard rank (int): rank of tens...
338,228
def get_woeid(lat, lon): yql = _YQL_WOEID.format(lat, lon) tmpData = _yql_query(yql) if tmpData is None: _LOGGER.error("No woid is received!") return None return tmpData.get("place", {}).get("woeid", None)
Ask Yahoo! who is the woeid from GPS position.
338,229
def serialize_input(input, signature_script_hex=): if not (isinstance(input, dict) and in input \ and in input): raise Exception() if is_hex(str(input[])) and len(str(input[])) != 64: raise Exception("Transaction hash must be 32 bytes" % input[]) elif not is_hex(str(inp...
Serializes a transaction input.
338,230
def _diff_text(left, right, verbose=False): from difflib import ndiff explanation = [] if isinstance(left, py.builtin.bytes): left = u(repr(left)[1:-1]).replace(r, ) if isinstance(right, py.builtin.bytes): right = u(repr(right)[1:-1]).replace(r, ) if not verbose: i = 0 ...
Return the explanation for the diff between text or bytes Unless --verbose is used this will skip leading and trailing characters which are identical to keep the diff minimal. If the input are bytes they will be safely converted to text.
338,231
def line_column(self) -> Tuple[int, int]: ln = self.input.count("\n", 0, self.offset) c = (self.offset if ln == 0 else self.offset - self.input.rfind("\n", 0, self.offset) - 1) return (ln + 1, c)
Return line and column coordinates.
338,232
def ehh_decay(h, truncate=False): h = HaplotypeArray(np.asarray(h), copy=False) if h.min() < 0: raise NotImplementedError() n_variants = h.n_variants n_haplotypes = h.n_haplotypes n_pairs = (n_haplotypes * (n_haplotypes - 1)) // 2 spl = pairwise_shared_pre...
Compute the decay of extended haplotype homozygosity (EHH) moving away from the first variant. Parameters ---------- h : array_like, int, shape (n_variants, n_haplotypes) Haplotype array. truncate : bool, optional If True, the return array will exclude trailing zeros. Returns ...
338,233
def encrypt(self, password, kdf=None, iterations=None): return self._publicapi.encrypt(self.privateKey, password, kdf=kdf, iterations=iterations)
Generate a string with the encrypted key, as in :meth:`~eth_account.account.Account.encrypt`, but without a private key argument.
338,234
def get_value(self, field_name): if field_name in self.fields: return self._dict[][field_name] elif field_name.upper() in [, , "GEOMETRY"]: return self._dict[] return None
returns a value for a given field name
338,235
def is_image_loaded(webdriver, webelement): script = (u("return arguments[0].complete && type of arguments[0].naturalWidth != \"undefined\" ") + u("&& arguments[0].naturalWidth > 0")) try: return webdriver.execute_script(script, webelement) except: ...
Check if an image (in an image tag) is loaded. Note: This call will not work against background images. Only Images in <img> tags. Args: webelement (WebElement) - WebDriver web element to validate.
338,236
def Distance(lat0, lng0, lat1, lng1): deg2rad = math.pi / 180.0 lat0 = lat0 * deg2rad lng0 = lng0 * deg2rad lat1 = lat1 * deg2rad lng1 = lng1 * deg2rad dlng = lng1 - lng0 dlat = lat1 - lat0 a = math.sin(dlat*0.5) b = math.sin(dlng*0.5) a = a * a + math.cos(lat0) * math.cos(lat1) * b * b c = 2.0...
Compute the geodesic distance in meters between two points on the surface of the Earth. The latitude and longitude angles are in degrees. Approximate geodesic distance function (Haversine Formula) assuming a perfect sphere of radius 6367 km (see "What are some algorithms for calculating the distance between...
338,237
def validate(self, metadata, path, value): if isinstance(value, Requirement): if metadata.testing and self.mock_value is not None: value = self.mock_value elif self.default_value is not None: value = self.default_value eli...
Validate this requirement.
338,238
def any_ipaddress_field(field, **kwargs): nums = [str(xunit.any_int(min_value=0, max_value=255)) for _ in xrange(0, 4)] return ".".join(nums)
Return random value for IPAddressField >>> result = any_field(models.IPAddressField()) >>> type(result) <type 'str'> >>> from django.core.validators import ipv4_re >>> re.match(ipv4_re, result) is not None True
338,239
def remove_field(self, path, name): path = make_path(path) container = self.get_container(path) try: value = container._values[name] if isinstance(value, ValueTree): raise TypeError() del container._values[name] except KeyError...
:param path: str or Path instance :param name: :type name: str
338,240
def _extend_component_definitions(self, graph): for def_uri, comp_def in self._components.items(): component_index = {} identity = URIRef(def_uri) for comp in graph.triples((identity, SBOL.component, None)): comp_identity = ...
Read graph and update component definitions with related elements
338,241
def embed(inp, n_inputs, n_features, initializer=None, fix_parameters=False, apply_w=None): if not initializer: initializer = UniformInitializer((-np.sqrt(3.), np.sqrt(3))) w = get_parameter_or_create("W", [n_inputs, n_features], initializer, True, not fix_...
Embed. Embed slices a matrix/tensor with indexing array/tensor. Weights are initialized with :obj:`nnabla.initializer.UniformInitializer` within the range of :math:`-\\sqrt{3}` and :math:`\\sqrt{3}`. Args: x(~nnabla.Variable): [Integer] Indices with shape :math:`(I_0, ..., I_N)` n_inputs : num...
338,242
def export_keys(self, keys=None, secret=False, passphrase=None, binary=False): args = [] if binary else [] if secret: args += (, ) else: args.append() if keys: args += make_list(keys) return self.execute(ExportResult(), args, passphras...
Export keys :param keys: Single key ID or list of mutiple IDs. If None export all of the keys. :param secret: Export secret keys :param passphrase: Secret key password, you need this if secret=true :param binary: If false, create ASCII armored output :rtype: ExportResult
338,243
def get_username(self, userid): username = self.user_map.get(userid) if not username: users = self.get_users() if users: members = { m[]: m[] for m in users.get(, [{}]) if m.get() ...
Perform a lookup of users to resolve a userid to a username Args: userid (string): Slack userid to lookup. Returns: string: Human-friendly name of the user
338,244
def serialize(self, as_private=None): if as_private is None: as_private = self.secret_exponent() is not None if self.secret_exponent() is None and as_private: raise PublicPrivateMismatchError("public key has no private parts") ba = bytearray() ba.extend(...
Yield a 74-byte binary blob corresponding to this node. You must add a 4-byte prefix before converting to base58.
338,245
def is_injective(self): codomain_residues = [v.to_pdb_residue_id for k, v in self.mapping.iteritems()] return(len(codomain_residues) == len(set(codomain_residues)))
Returns True if the mapping is injective (1-to-1).
338,246
def connect(self, func): l = _alleged_receivers[id(self)] if func not in l: l.append(func)
Arrange to call this function whenever something changes here. The arguments will be this object, the key changed, and the value set.
338,247
def clear(self, fill = 0x00): self._buffer = [ fill ] * ( self.width * self.height )
! Clear buffer data and other data RPiDiaplay object just implemented clear buffer data
338,248
def stop(self, join = False, timeout = None): logger.debug("Closing the io handlers...") for handler in self.io_handlers: handler.close() if self.event_thread and self.event_thread.is_alive(): logger.debug("Sending the QUIT signal") self.event_queue.p...
Stop the threads. :Parameters: - `join`: join the threads (wait until they exit) - `timeout`: maximum time (in seconds) to wait when `join` is `True`). No limit when `timeout` is `None`.
338,249
def set_distance_units(value=np.NaN, from_units=, to_units=): if from_units == to_units: return value if from_units == : if to_units == : coeff = 10 elif to_units == : coeff = 0.01 else: raise ValueError("to_units not supported [,,]!") ...
convert distance into new units Parameters: =========== value: float. value to convert from_units: string. Must be 'mm', 'cm' or 'm' to_units: string. must be 'mm','cm' or 'm' Returns: ======== converted value Raises: ======= ValueError if from_units is not a v...
338,250
def make_echoicefield(echoices, *args, klass_name=None, **kwargs): assert issubclass(echoices, EChoice) value_type = echoices.__getvaluetype__() if value_type is str: cls_ = models.CharField elif value_type is int: cls_ = models.IntegerField elif value_type is float: cls...
Construct a subclass of a derived `models.Field` specific to the type of the `EChoice` values. Parameters ---------- echoices : subclass of EChoice args Passed to the derived `models.Field` klass_name : str Give a specific name to the returned class. By default for Django < ...
338,251
def is_http_log_entry(self, string): if in string: return False for token in string.replace(, ).split(): try: if (token.count() is 3 and token.replace(, ).isnumeric()): return True except Exception: ...
Determines if a log entry is an HTTP-formatted log string or not.
338,252
def database( state, host, name, present=True, collate=None, charset=None, user=None, user_hostname=, user_privileges=, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=None, ): current_databases = host.fact.mysql_databases( mysql_user, mysql_password...
Add/remove MySQL databases. + name: the name of the database + present: whether the database should exist or not + collate: the collate to use when creating the database + charset: the charset to use when creating the database + user: MySQL user to grant privileges on this database to + user_ho...
338,253
def create_daily_trade_source(sids, sim_params, asset_finder, trading_calendar): return create_trade_source( sids, timedelta(days=1), sim_params, asset_finder, trading_calendar=trad...
creates trade_count trades for each sid in sids list. first trade will be on sim_params.start_session, and daily thereafter for each sid. Thus, two sids should result in two trades per day.
338,254
def _make_random_string(length): chars = string.ascii_lowercase + string.ascii_uppercase + string.digits return .join(random.choice(chars) for x in range(length))
Returns a random lowercase, uppercase, alphanumerical string. :param int length: The length in bytes of the string to generate.
338,255
def save(self): api = Client.instance().api index_details = { : self.index_type_obj.type_name } extra_index_attributes = self.index_type_obj.get_extra_attributes() for extra_attribute_key in extra_index_attributes: extra_attribute_value = extr...
Creates this index in the collection if it hasn't been already created
338,256
def convert_all(folder, dest_path=, force_all=False): "Convert modified notebooks in `folder` to html pages in `dest_path`." path = Path(folder) changed_cnt = 0 for fname in path.glob("*.ipynb"): fname_out = Path(dest_path)/fname.with_suffix().name if not force_all and fname_ou...
Convert modified notebooks in `folder` to html pages in `dest_path`.
338,257
def map_title(self): try: title = self._keyword_io.read_keywords( self.impact, ) return title except KeywordNotFoundError: return None except Exception: return None
Get the map title from the layer keywords if possible. :returns: None on error, otherwise the title. :rtype: None, str
338,258
def set_int_attribute(self, target, display_mask, attr, value): reply = NVCtrlSetAttributeAndGetStatusReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=targ...
Set the value of an integer attribute
338,259
def listDatasetAccessTypes(self, dataset_access_type=""): if isinstance(dataset_access_type, basestring): try: dataset_access_type = str(dataset_access_type) except: dbsExceptionHandler(, %dataset_access_type) else: dbsExc...
List dataset access types
338,260
def get_artifact_metadata(self, package_name): filename = self.metadata.get(package_name) if not filename or not exists(filename): return {} with open(filename, encoding=) as fd: contents = fd.read() try: is_json_compat(contents) exc...
Return metadata of the artifacts built through this registry.
338,261
def get_entities_text(self, cls=None): ent = self.entities if not ent: return [] if cls: ent = [c for c in ent if isinstance(c, cls)] texts = utils.get_inner_text(self.message, ent) return list(zip(ent, texts))
Returns a list of tuples [(:tl:`MessageEntity`, `str`)], the string being the inner text of the message entity (like bold, italics, etc). Args: cls (`type`): Returns entities matching this type only. For example, the following will print the text for all ``co...
338,262
def remove(self, paths, **params): log = self._getparam(, self._discard, **params) commit = self._getparam(, True, **params) if type(paths) is not list: paths = [paths] rebuild = False for path in paths: if path in self.paths_pending: ...
Delete paths from the watched list.
338,263
def get_logger(name, CFG=None): logger = logging.getLogger(name) if CFG: raise return logger
set up logging for a service using the py 2.7 dictConfig
338,264
def assign(name, value): * ret = {} cmd = .format(name, value) data = __salt__[](cmd) if re.match(r, data[]) or \ data[] != 0: raise CommandExecutionError(.format( data[])) new_name, new_value = data[].split(, 1) ret[new_name] = new_value.split()[-1]...
Assign a single sysctl parameter for this minion CLI Example: .. code-block:: bash salt '*' sysctl.assign net.inet.ip.forwarding 1
338,265
def default(self, value): if isinstance(value, datetime): return value.isoformat() elif isinstance(value, date): dt = datetime(value.year, value.month, value.day, 0, 0, 0) return dt.isoformat() elif isinstance(value, Decimal): return floa...
Convert rogue and mysterious data types. Conversion notes: - ``datetime.date`` and ``datetime.datetime`` objects are converted into datetime strings.
338,266
def add_text(self, text): index = self.findText(text) while index != -1: self.removeItem(index) index = self.findText(text) self.insertItem(0, text) index = self.findText() if index != -1: self.removeItem(index) s...
Add text to combo box: add a new item if text is not found in combo box items.
338,267
def load(input_data, key_is_name=False): exif_dict = {"0th":{}, "Exif":{}, "GPS":{}, "Interop":{}, "1st":{}, "thumbnail":None} exifReader = _ExifReader(input_data) if exifReader.tiftag is None: return exif_dict...
py:function:: piexif.load(filename) Return exif data as dict. Keys(IFD name), be contained, are "0th", "Exif", "GPS", "Interop", "1st", and "thumbnail". Without "thumbnail", the value is dict(tag name/tag value). "thumbnail" value is JPEG as bytes. :param str filename: JPEG or TIFF :return: Exif data({"0t...
338,268
def enterPhase(self): super(_IterationPhaseLearnOnly, self).enterPhase() self.__model.enableLearning() self.__model.disableInference() return
[_IterationPhase method implementation] Performs initialization that is necessary upon entry to the phase. Must be called before handleInputRecord() at the beginning of each phase
338,269
def findOPLocalIdentifier(service_element, type_uris): local_id_tags = [] if (OPENID_1_1_TYPE in type_uris or OPENID_1_0_TYPE in type_uris): local_id_tags.append(nsTag(OPENID_1_0_NS, )) if OPENID_2_0_TYPE in type_uris: local_id_tags.append(nsTag(XRD_NS_2_0, )) ...
Find the OP-Local Identifier for this xrd:Service element. This considers openid:Delegate to be a synonym for xrd:LocalID if both OpenID 1.X and OpenID 2.0 types are present. If only OpenID 1.X is present, it returns the value of openid:Delegate. If only OpenID 2.0 is present, it returns the value of x...
338,270
def docker_call(tool, tool_parameters, work_dir, java_opts=None, outfile=None, dockerhub=, interactive=False): if outfile: assert isinstance(outfile, file), assert outfile.mode in [, , , ], assert not outfile.closed, if interactive: interact...
Makes subprocess call of a command to a docker container. work_dir MUST BE AN ABSOLUTE PATH or the call will fail. outfile is an open file descriptor to a writeable file.
338,271
def prior_tuples_ordered_by_id(self): return sorted(list(self.prior_tuples), key=lambda prior_tuple: prior_tuple.prior.id)
Returns ------- priors: [Prior] An ordered list of unique priors associated with this mapper
338,272
def frequency_to_probability(frequency_map, decorator=lambda f: f): total = sum(frequency_map.values()) return {k: decorator(v / total) for k, v in frequency_map.items()}
Transform a ``frequency_map`` into a map of probability using the sum of all frequencies as the total. Example: >>> frequency_to_probability({'a': 2, 'b': 2}) {'a': 0.5, 'b': 0.5} Args: frequency_map (dict): The dictionary to transform decorator (function): A function to manipu...
338,273
def _get_session(self, request): _session = requests.session() response = _session.post(**request) logger.info(, self.api_version) if response.status_code != 200: raise SMCConnectionError( % ( response.status_c...
Authenticate the request dict :param dict request: request dict built from user input :raises SMCConnectionError: failure to connect :return: python requests session :rtype: requests.Session
338,274
def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): componentType = self.componentType try: currentValue = self._componentVa...
Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`) or list.append() (when idx == len(self)). Parameters ---------- idx: :class:`int` Component index (zero-based). Must either refer to existing c...
338,275
def get_path(filename, location=, cache=True, show_progress=False): datasets_url = ( .format(filename)) if location == : path = get_pkg_data_filename( + filename) elif location == : try: url = .format(filename) path = download_file(url, ...
Get path (location on your disk) for a given file. Parameters ---------- filename : str File name in the local or remote data folder. location : {'local', 'remote', 'photutils-datasets'} File location. ``'local'`` means bundled with ``photutils``. ``'remote'`` means the astropy...
338,276
def refresh_maps(self): for robot in self.robots: resp2 = ( requests.get(urljoin(self.ENDPOINT, .format(robot.serial)), headers=self._headers)) resp2.raise_for_status() self._maps.update({robot.serial: resp2.json()})
Get information about maps of the robots. :return:
338,277
def edmonds_karp(graph, capacity, source, target): add_reverse_arcs(graph, capacity) V = range(len(graph)) flow = [[0 for v in V] for u in V] while True: augm_path, delta = _augment(graph, capacity, flow, source, target) if delta == 0: break v = target ...
Maximum flow by Edmonds-Karp :param graph: directed graph in listlist or listdict format :param capacity: in matrix format or same listdict graph :param int source: vertex :param int target: vertex :returns: flow matrix, flow value :complexity: :math:`O(|V|*|E|^2)`
338,278
def daily_table(context, day, start=8, end=20, increment=30): user = context[].user addable = CHECK_EVENT_PERM_FUNC(None, user) if in context: addable = addable and CHECK_CALENDAR_PERM_FUNC(context[], user) context[] = addable day_part = day.get_time_slot(day.start + datetime.timedelta...
Display a nice table with occurrences and action buttons. Arguments: start - hour at which the day starts end - hour at which the day ends increment - size of a time slot (in minutes)
338,279
def _license_obj(license): obj = None if license in (, ): obj = { : , : } elif license in (): obj = { : , : } elif license in (): obj = { : , : } elif license in (): ...
A helper function to look up license object information Use names from: https://api.github.com/licenses
338,280
def intersection(self, other): if not self.is_valid_range(other): msg = "Unsupported type to test for intersection " raise TypeError(msg.format(other)) if not self or not other or not self.overlap(other): return self.empty() lower_end_span...
Returns a new range containing all points shared by both ranges. If no points are shared an empty range is returned. >>> intrange(1, 5).intersection(intrange(1, 10)) intrange([1,5)) >>> intrange(1, 5).intersection(intrange(5, 10)) intrange(empty) >>> ...
338,281
def roll_up_capture(returns, factor_returns, window=10, **kwargs): return roll(returns, factor_returns, window=window, function=up_capture, **kwargs)
Computes the up capture measure over a rolling window. see documentation for :func:`~empyrical.stats.up_capture`. (pass all args, kwargs required) Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~...
338,282
def render(self, data, accepted_media_type=None, renderer_context=None): renderer_context = renderer_context or {} callback = self.get_callback(renderer_context) json = super(JSONPRenderer, self).render(data, accepted_media_type, renderer...
Renders into jsonp, wrapping the json output in a callback function. Clients may set the callback function name using a query parameter on the URL, for example: ?callback=exampleCallbackName
338,283
def subdirs(self, pattern=None, sort_key=lambda k: k, sort_reverse=False, abspath=False): return sorted(self.itersubdirs(pattern, abspath=abspath), key=sort_key, reverse=sort_reverse)
Return a sorted list containing relative path of all subdirs (recursively). :type pattern: str :param pattern: Unix style (glob like/gitignore like) pattern :param sort_key: key argument for sorted :param sort_reverse: reverse argument for sorted :rtype: list :return:...
338,284
def check_is_injectable(func): @wraps(func) def wrapper(**kwargs): name = kwargs[] if not orca.is_injectable(name): abort(404) return func(**kwargs) return wrapper
Decorator that will check whether the "inj_name" keyword argument to the wrapped function matches a registered Orca injectable.
338,285
def DeriveDataRegex(fieldName, db, deriveInput, overwrite, fieldVal, histObj={}, blankIfNoMatch=False): if len(deriveInput) > 1: raise Exception("more than one value in deriveInput") field_val_new = fieldVal check_match = False row = list(deriveInput.keys())[0] ...
Return a new field value based on match (of another field) against regex queried from MongoDB :param string fieldName: Field name to query against :param MongoClient db: MongoClient instance connected to MongoDB :param dict deriveInput: Values to perform lookup against: {"lookupField1": "loo...
338,286
def is_in_bounds(self, width, height) -> bool: if self._top < 0 \ or self._bottom > height \ or self._left < 0 \ or self._right > width: return False return True
Check if this entire region is contained within the bounds of a given stage size.
338,287
def cigarWrite(fileHandle, pairwiseAlignment, withProbs=True): if len(pairwiseAlignment.operationList) == 0: logger.info("Writing zero length pairwiseAlignment to file!") strand1 = "+" if not pairwiseAlignment.strand1: strand1 = "-" strand2 = "+" if not pairwiseAlignment.stran...
Writes out the pairwiseAlignment to the file stream. Query and target are reversed from normal order.
338,288
def injected(self, filename): full_path = os.path.expanduser(filename) if not os.path.exists(full_path): return False with codecs.open(full_path, , encoding="utf-8") as fh: contents = fh.read() return self.wrapper_match.search(contents) is not None
Return true if the file has already been injected before.
338,289
def load_content(self, path): "Attempts to open the file and read the content." log.debug(.format(path, __name__)) with open(path) as fin: self.path = path self.content = fin.read()
Attempts to open the file and read the content.
338,290
def get_api(i): p=i.get(,) f=i.get(,) o=i.get(,) muoa=i.get(,) t= t_orig= l=0 a= if p== and muoa!=: rx=load({:cfg[], :muoa}) if rx[]>0: return rx p=rx[] if p==: p1=os.path.dirname(os.path.dirname(work[])) ...
Input: { (path) - path to module, if comes from access function or (module_uoa) - if comes from CMD (func) - func for API (out) - output } Output: { return - return code = 0, if successful ...
338,291
def dijkstra_single_path_length(G, start, end): if start not in G.vertices: raise GraphInsertError("Vertex %s doesnt exist." % (end,)) dijkstra_data = dijkstra(G, start) length = dijkstra_data[0][end] path = [end] current = end while current is not start: for vertex...
Compute shortest path length between satrt and end for a weight graph. return -> (length, [path])
338,292
def toprettyxml(self, indent=" ", newl=os.linesep, encoding="UTF-8"): domtree = self.todom() if sys.version_info >= (2,3): xmlstr = domtree.toprettyxml(indent, newl, encoding) else: xmlstr = domtree.toprettyxml(indent, newl) ...
Return the manifest as pretty-printed XML
338,293
def _handle_properties(self, stmt: Statement, sctx: SchemaContext) -> None: self._handle_restrictions(stmt, sctx)
Handle type substatements.
338,294
def itervalues(self, index=None): N = len(self.indices) if index is None: if N <= 1: return elif N == 2: index = 1 single = True else: index = slice(1, None) single = False ...
Iterate through values in the ``index`` (defaults to all indices except the first index). When ``index is None``, yielded values depend on the length of indices (``N``): * if N <= 1: return * if N == 2: yield values in the 2nd index * if N > 2: yield values in all i...
338,295
def run(self): self.thr = threading.Thread(target=self.collect_and_report) self.thr.daemon = True self.thr.name = "Instana Metric Collection" self.thr.start()
Spawns the metric reporting thread
338,296
def _defaultReducePartitions(self): if self.ctx._conf.contains("spark.default.parallelism"): return self.ctx.defaultParallelism else: return self.getNumPartitions()
Returns the default number of partitions to use during reduce tasks (e.g., groupBy). If spark.default.parallelism is set, then we'll use the value from SparkContext defaultParallelism, otherwise we'll use the number of partitions in this RDD. This mirrors the behavior of the Scala Partitioner#d...
338,297
def _getConfig(self, num, device): cmd = self._COMMAND.get() self._writeData(cmd, device, params=(num,)) try: result = self._serial.read(size=1) result = ord(result) except serial.SerialException as e: self._log and self._log.error("Error: %s...
Low level method used for all get config commands. :Parameters: num : `int` Number that indicates the config option to get from the hardware. device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Proto...
338,298
def main(): register_config_opts() common_config.init(sys.argv[1:]) neutron_config.setup_logging() proxy = MetadataProxy() proxy.run()
The entry point for neutron-hnv-metadata-proxy.
338,299
def fetch(self, select=None, include=None): data = {} if select: if not isinstance(select, (list, tuple)): raise TypeError() data[] = .join(select) if include: if not isinstance(include, (list, tuple)): raise TypeError(...
从服务器获取当前对象所有的值,如果与本地值不同,将会覆盖本地的值。 :return: 当前对象