code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def get_configuration_dict(self, secret_attrs=False): cd = super(TaxonomicAmendmentsShard, self).get_configuration_dict(secret_attrs=secret_attrs) cd[] = cd.pop() cd[] = cd.pop() if self._next_ott_id is not None: cd[] = self._next_ott_id, re...
Overrides superclass method and renames some properties
def disconnect(cls): app = AndroidApplication.instance() f = app.create_future() def on_permission_result(result): if not result: f.set_result(None) return def on_ready(mgr): mgr.disconnect().then(f.set_result) ...
Disconnect from the current network (if connected). Returns -------- result: future A future that resolves to true if the disconnect was successful. Will be set to None if the change network permission is denied.
def _wire_events(self): self._device.on_open += self._on_open self._device.on_close += self._on_close self._device.on_read += self._on_read self._device.on_write += self._on_write self._zonetracker.on_fault += self._on_zone_fault self._zonetracker.on_restore += s...
Wires up the internal device events.
def refetch_fields(self, missing_fields): db_fields = self.mongokat_collection.find_one({"_id": self["_id"]}, fields={k: 1 for k in missing_fields}) self._fetched_fields += tuple(missing_fields) if not db_fields: return for k, v in db_fields.items(): s...
Refetches a list of fields from the DB
def _force_https(self): if self.session_cookie_secure: if not self.app.debug: self.app.config[] = True criteria = [ self.app.debug, flask.request.is_secure, flask.request.headers.get(, ) == , ] local_options = se...
Redirect any non-https requests to https. Based largely on flask-sslify.
def create(self, dataset_id): from google.cloud.bigquery import Dataset if self.exists(dataset_id): raise DatasetCreationError( "Dataset {0} already " "exists".format(dataset_id) ) dataset = Dataset(self.client.dataset(dataset_id)) if s...
Create a dataset in Google BigQuery Parameters ---------- dataset : str Name of dataset to be written
def _create_session(self): logger.debug("Create new phantomjs web driver") self.driver = webdriver.PhantomJS(desired_capabilities=self.dcap, **self.driver_args) self.set_cookies(self.current_cookies) self.driver.set_window_size(1920, 108...
Creates a fresh session with no/default headers and proxies
def compact(self) -> str: doc = "TX:{0}:{1}:{2}:{3}:{4}:{5}:{6}\n".format(self.version, len(self.issuers), len(self.inputs), l...
Return a transaction in its compact format from the instance :return:
def query(url, output=True, **kwargs): key1=val1&key2=val2<xml>somecontent</xml> if output is not True: log.warning() if not in kwargs: kwargs[] = opts = __opts__.copy() if in kwargs: opts.update(kwargs[]) del kwargs[] ret = salt.utils.http.query(url=url, opts...
Query a resource, and decode the return data Passes through all the parameters described in the :py:func:`utils.http.query function <salt.utils.http.query>`: CLI Example: .. code-block:: bash salt-run http.query http://somelink.com/ salt-run http.query http://somelink.com/ method=POS...
def _parse_tree(self, node): if in node.attrib: self.kind = node.attrib[] if in node.attrib: self.width = int(node.attrib[]) if in node.attrib: self.height = int(node.attrib[]) self.url = node.text
Parse a <image> object
def set_data(self, adjacency_mat=None, **kwargs): if adjacency_mat is not None: if adjacency_mat.shape[0] != adjacency_mat.shape[1]: raise ValueError("Adjacency matrix should be square.") self._adjacency_mat = adjacency_mat for k in self._arrow_attribut...
Set the data Parameters ---------- adjacency_mat : ndarray | None The adjacency matrix. **kwargs : dict Keyword arguments to pass to the arrows.
def free(self): data = WebDavXmlUtils.create_free_space_request_content() response = self.execute_request(action=, path=, data=data) return WebDavXmlUtils.parse_free_space_response(response.content, self.webdav.hostname)
Returns an amount of free space on remote WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :return: an amount of free space in bytes.
def _on_message(channel, method, header, body): print "Message:" print "\t%r" % method print "\t%r" % header print "\t%r" % body channel.basic_ack(method.delivery_tag) channel.stop_consuming()
Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the me...
def generate_screenshots(self): headers = {: , : } resp = requests.post(self.api_url, data=json.dumps(self.config), \ headers=headers, auth=self.auth) resp = self._process_response(resp) return resp.json()
Take a config file as input and generate screenshots
def get_endpoint(self, session, **kwargs): if self.endpoint is None: try: self._refresh_tokens(session) self._fetch_credentials(session) except: raise AuthorizationFailure() return self.endpoint
Get the HubiC storage endpoint uri. If the current session has not been authenticated, this will trigger a new authentication to the HubiC OAuth service. :param keystoneclient.Session session: The session object to use for queries. :raise...
def _create_variables_no_pretrain(self, n_features): self.encoding_w_ = [] self.encoding_b_ = [] for l, layer in enumerate(self.layers): w_name = .format(l) b_name = .format(l) if l == 0: w_shape = [n_features, self.layers[l]] ...
Create model variables (no previous unsupervised pretraining). :param n_features: number of features :return: self
def individual(self, ind_id=None): for ind_obj in self.individuals: if ind_obj.ind_id == ind_id: return ind_obj return None
Return a individual object Args: ind_id (str): A individual id Returns: individual (puzzle.models.individual)
async def request( self, method: str, endpoint: str, *, headers: dict = None, params: dict = None) -> dict: url = .format(API_URL_SCAFFOLD, endpoint) if not headers: headers = {} headers.update({: self....
Make a request against air-matters.com.
def p_expr_BAND_expr(p): p[0] = make_binary(p.lineno(2), , p[1], p[3], lambda x, y: x & y)
expr : expr BAND expr
def attribute_rewrite_map(self): rewrite_map = dict() token_rewrite_map = self.generate_attribute_token_rewrite_map() for attribute_name, type_instance in self.getmembers(): if isinstance(type_instance, DataType): attribute_tokens = attribute_name.split() ...
Example: long_name -> a_b :return: the rewrite map :rtype: dict
def delete(self, request, key): request.DELETE = http.QueryDict(request.body) email_addr = request.DELETE.get() user_id = request.DELETE.get() if not email_addr: return http.HttpResponseBadRequest() try: email = EmailAddressValidation.objects.g...
Remove an email address, validated or not.
def join_room(self, room_id_or_alias): if not room_id_or_alias: raise MatrixError("No alias or room ID to join.") path = "/join/%s" % quote(room_id_or_alias) return self._send("POST", path)
Performs /join/$room_id Args: room_id_or_alias (str): The room ID or room alias to join.
def private_download_url(self, url, expires=3600): deadline = int(time.time()) + expires if in url: url += else: url += url = .format(url, str(deadline)) token = self.token(url) return .format(url, token)
生成私有资源下载链接 Args: url: 私有空间资源的原始URL expires: 下载凭证有效期,默认为3600s Returns: 私有资源的下载链接
def read(self): line = self.trace_file.readline() if line == : if self.loop: self._reopen_file() else: self.trace_file.close() self.trace_file = None raise DataSourceError() message = JsonFormatter....
Read a line of data from the input source at a time.
def create(self, req, **kwargs): response = requests.post(self.url, json=req, **self.req_args()) return self.parse_response(response)
Uses POST to send a first metadata statement signing request to a signing service. :param req: The metadata statement that the entity wants signed :return: returns a dictionary with 'sms' and 'loc' as keys.
def _to_graph(self, contexts): prev = None for context in contexts: if prev is None: prev = context continue yield prev[0], context[1], context[0] prev = context
This is an iterator that returns each edge of our graph with its two nodes
def to_igraph(self, weighted=None): return ig
Converts this Graph object to an igraph-compatible object. Requires the python-igraph library.
def doi(self, doi, only_message=True): request_url = build_url_endpoint( .join([self.ENDPOINT, doi]) ) request_params = {} result = self.do_http_request( , request_url, data=request_params, custom_header=str(self.etiqu...
This method retrieve the DOI metadata related to a given DOI number. args: Crossref DOI id (String) return: JSON Example: >>> from crossref.restful import Works >>> works = Works() >>> works.doi('10.1590/S0004-28032013005000001') {'is-re...
def zonal_stats(raster, vector): output_layer_name = zonal_stats_steps[] exposure = raster.keywords[] if raster.crs().authid() != vector.crs().authid(): layer = reproject(vector, raster.crs()) output_layer = create_memory_layer( output_layer_name, vect...
Reclassify a continuous raster layer. Issue https://github.com/inasafe/inasafe/issues/3190 The algorithm will take care about projections. We don't want to reproject the raster layer. So if CRS are different, we reproject the vector layer and then we do a lookup from the reprojected layer to the o...
def guard_submit(analysis): if not analysis.getResult(): return False for interim in analysis.getInterimFields(): if not interim.get("value", ""): return False if not analysis.getAttachment(): if analysis.getAttachmentOption() == : return...
Return whether the transition "submit" can be performed or not
def get_argument_parser(): desc = parser = cli.get_argument_parser(desc=desc) g = parser.add_argument_group() g.add_argument( , , type=cli.str_type, required=True, metavar=cli.file_mv, help= ) g.add_argument( , , type=cli.str_type, required=True, ...
Create the argument parser for the script. Parameters ---------- Returns ------- `argparse.ArgumentParser` The arguemnt parser.
def deferred(timeout=None): reactor, reactor_thread = threaded_reactor() if reactor is None: raise ImportError("twisted is not available or could not be imported") try: timeout is None or timeout + 0 except TypeError: raise TypeError(" argument must be a numbe...
By wrapping a test function with this decorator, you can return a twisted Deferred and the test will wait for the deferred to be triggered. The whole test function will run inside the Twisted event loop. The optional timeout parameter specifies the maximum duration of the test. The difference with time...
def invert(interval): interval.reverse() res = list(interval) interval.reverse() return res
Invert an interval. Example: >>> invert(['C', 'E']) ['E', 'C']
def pos_tag_sents( sentences: List[List[str]], engine: str = "perceptron", corpus: str = "orchid" ) -> List[List[Tuple[str, str]]]: if not sentences: return [] return [pos_tag(sent, engine=engine, corpus=corpus) for sent in sentences]
Part of Speech tagging Sentence function. :param list sentences: a list of lists of tokenized words :param str engine: * unigram - unigram tagger * perceptron - perceptron tagger (default) * artagger - RDR POS tagger :param str corpus: * orchid - annotated Thai academic arti...
def can_unsubscribe_from_topic(self, topic, user): return ( user.is_authenticated and topic.has_subscriber(user) and self._perform_basic_permission_check(topic.forum, user, ) )
Given a topic, checks whether the user can remove it from their subscription list.
def discover_setup_packages(): logger = logging.getLogger(__name__) import eups eups_client = eups.Eups() products = eups_client.getSetupProducts() packages = {} for package in products: name = package.name info = { : package.dir, : package.ve...
Summarize packages currently set up by EUPS, listing their set up directories and EUPS version names. Returns ------- packages : `dict` Dictionary with keys that are EUPS package names. Values are dictionaries with fields: - ``'dir'``: absolute directory path of the set up package...
def show_help(name): print(.format(name)) print() print() print() print() print() print() print(DEADBEEF DEADBEEF DEADBEEF DEADBEEF\) print(ABABABAB CDCDCDCD EFEFEFEF AEAEAEAE\) print()
Show help and basic usage
def _back_compatible_gemini(conf_files, data): if vcfanno.is_human(data, builds=["37"]): for f in conf_files: if f and os.path.basename(f) == "gemini.conf" and os.path.exists(f): with open(f) as in_handle: for line in in_handle: if...
Provide old install directory for configuration with GEMINI supplied tidy VCFs. Handles new style (bcbio installed) and old style (GEMINI installed) configuration and data locations.
def fit(self, X, *args, **kwargs): self.constant_value = self._get_constant_value(X) if self.constant_value is None: if self.unfittable_model: self.model = getattr(scipy.stats, self.model_class)(*args, **kwargs) else: self.model = getatt...
Fit scipy model to an array of values. Args: X(`np.ndarray` or `pd.DataFrame`): Datapoints to be estimated from. Must be 1-d Returns: None
def set(self, data=None): self.__data = data self.__exception = None self.__event.set()
Sets the event
def get_permissions_for_registration(self): qs = Permission.objects.none() for instance in self.modeladmin_instances: qs = qs | instance.get_permissions_for_registration() return qs
Utilised by Wagtail's 'register_permissions' hook to allow permissions for a all models grouped by this class to be assigned to Groups in settings.
def _pre_analysis(self): for item in self._starts: callstack = None if isinstance(item, tuple): ip = item[0] state = self._create_initial_state(item[0], item[1]) elif isinstance(item, SimState): ...
Initialization work. Executed prior to the analysis. :return: None
def timeseries(self): if self._timeseries is None: if isinstance(self.grid.network.timeseries.generation_fluctuating. columns, pd.MultiIndex): if self.weather_cell_id: try: ...
Feed-in time series of generator It returns the actual time series used in power flow analysis. If :attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise, :meth:`timeseries` looks for generation and curtailment time series of the according type of technology (and weather cell...
def from_schema(self, schema_node): params = [] for param_schema in schema_node.children: location = param_schema.name if location is : name = param_schema.__class__.__name__ if name == : name = schema_node.__class__....
Creates a list of Swagger params from a colander request schema. :param schema_node: Request schema to be transformed into Swagger. :param validators: Validators used in colander with the schema. :rtype: list :returns: List of Swagger parameters.
def select_candidates(config): download_candidates = [] for group in config.group: summary_file = get_summary(config.section, group, config.uri, config.use_cache) entries = parse_summary(summary_file) for entry in filter_entries(entries, config): download_candidates.ap...
Select candidates to download. Parameters ---------- config: NgdConfig Runtime configuration object Returns ------- list of (<candidate entry>, <taxonomic group>)
def process_dividends(self, next_session, asset_finder, adjustment_reader): position_tracker = self.position_tracker held_sids = set(position_tracker.positions) if held_sids: cash_dividends = adjustment_reader.get_dividends_with_ex_date( ...
Process dividends for the next session. This will earn us any dividends whose ex-date is the next session as well as paying out any dividends whose pay-date is the next session
def reset_trial(self, trial, new_config, new_experiment_tag): trial.experiment_tag = new_experiment_tag trial.config = new_config trainable = trial.runner with warn_if_slow("reset_config"): reset_val = ray.get(trainable.reset_config.remote(new_config)) return...
Tries to invoke `Trainable.reset_config()` to reset trial. Args: trial (Trial): Trial to be reset. new_config (dict): New configuration for Trial trainable. new_experiment_tag (str): New experiment name for trial. Returns: ...
def RegisterTextKey(cls, key, atomid): def getter(tags, key): return tags[atomid] def setter(tags, key, value): tags[atomid] = value def deleter(tags, key): del(tags[atomid]) cls.RegisterKey(key, getter, setter, deleter)
Register a text key. If the key you need to register is a simple one-to-one mapping of MP4 atom name to EasyMP4Tags key, then you can use this function:: EasyMP4Tags.RegisterTextKey("artist", "\xa9ART")
def _to_dict(self): _dict = {} if hasattr(self, ) and self.class_name is not None: _dict[] = self.class_name if hasattr(self, ) and self.score is not None: _dict[] = self.score if hasattr(self, ) and self.type_hierarchy is not None: _dict[] = ...
Return a json dictionary representing this model.
def ticker(ctx, market): market = Market(market, bitshares_instance=ctx.bitshares) ticker = market.ticker() t = [["key", "value"]] for key in ticker: t.append([key, str(ticker[key])]) print_table(t)
Show ticker of a market
def worker_collectionfinish(self, node, ids): if self.shuttingdown: return self.config.hook.pytest_xdist_node_collection_finished(node=node, ids=ids) self._session.testscollected = len(ids) self.sched.add_node_collection(node, ids) if self.t...
worker has finished test collection. This adds the collection for this node to the scheduler. If the scheduler indicates collection is finished (i.e. all initial nodes have submitted their collections), then tells the scheduler to schedule the collected items. When initiating ...
def rounding_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): outputs = tf.squeeze(tf.to_int32(predictions)) labels = tf.squeeze(labels) weights = weights_fn(labels) labels = tf.to_int32(labels) return tf.to_float(tf.equal(outputs, labels)...
Rounding accuracy for L1/L2 losses: round down the predictions to ints.
def _repr_png_(self): app.process_events() QApplication.processEvents() img = read_pixels() return bytes(_make_png(img))
This is used by ipython to plot inline.
def bots_create(self, bot): self.client.bots(_method="POST", _json=bot.to_json(), _params=dict(userToken=self.token))
Save new bot :param bot: bot object to save :type bot: Bot
def raise_for_execution_errors(nb, output_path): error = None for cell in nb.cells: if cell.get("outputs") is None: continue for output in cell.outputs: if output.output_type == "error": error = PapermillExecutionError( exec_count...
Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object output_path : str Path to write executed notebook
def read(self, pos, size, **kwargs): short_reads = kwargs.pop(, None) if self.write_mode is None: self.write_mode = False elif self.write_mode is True: raise SimFileError("Cannot read and write to the same SimPackets") if pos is None: ...
Read a packet from the stream. :param int pos: The packet number to read from the sequence of the stream. May be None to append to the stream. :param size: The size to read. May be symbolic. :param short_reads: Whether to replace the size with a symbolic value constrained to less tha...
def simxGetDistanceHandle(clientID, distanceObjectName, operationMode): handle = ct.c_int() if (sys.version_info[0] == 3) and (type(distanceObjectName) is str): distanceObjectName=distanceObjectName.encode() return c_GetDistanceHandle(clientID, distanceObjectName, ct.byref(handle), operationMo...
Please have a look at the function description/documentation in the V-REP user manual
def _new_masterpassword(self, password): if self.config_key in self.config and self.config[self.config_key]: raise Exception("Storage already has a masterpassword!") self.decrypted_master = hexlify(os.urandom(32)).decode("ascii") self.password = password ...
Generate a new random masterkey, encrypt it with the password and store it in the store. :param str password: Password to use for en-/de-cryption
def has_ocsp_must_staple_extension(certificate: cryptography.x509.Certificate) -> bool: has_ocsp_must_staple = False try: tls_feature_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.TLS_FEATURE) for feature_type in tls_feature_ext.value: i...
Return True if the certificate has the OCSP Must-Staple extension defined in RFC 6066.
def _fix_set_options(cls, options): optional_set_options = (, ) mandatory_set_options = (, ) def _get_set(value_str): return cls._expand_error_codes(set(value_str.split()) - {}) for opt in optional_set_options: value = getattr(options, opt)...
Alter the set options from None/strings to sets in place.
def update_md5(filenames): import re for name in filenames: base = os.path.basename(name) f = open(name,) md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.sort() repl = "".join(data) import...
Update our built-in md5 registry
def auth(name, nodes, pcsuser=, pcspasswd=, extra_args=None): pcs cluster auth\ ret = {: name, : True, : , : {}} auth_required = False authorized = __salt__[](nodes=nodes) log.trace(, authorized) authorized_dict = {} for line in authorized[].splitlines(): node = line.split()[0].st...
Ensure all nodes are authorized to the cluster name Irrelevant, not used (recommended: pcs_auth__auth) nodes a list of nodes which should be authorized to the cluster pcsuser user for communication with pcs (default: hacluster) pcspasswd password for pcsuser (default: ha...
def reaction_charge(reaction, compound_charge): charge_sum = 0.0 for compound, value in reaction.compounds: charge = compound_charge.get(compound.name, float()) charge_sum += charge * float(value) return charge_sum
Calculate the overall charge for the specified reaction. Args: reaction: :class:`psamm.reaction.Reaction`. compound_charge: a map from each compound to charge values.
def gen_mapname(): filepath = None while (filepath is None) or (os.path.exists(os.path.join(config[], filepath))): filepath = % _gen_string() return filepath
Generate a uniq mapfile pathname.
def backpropagate_3d(uSin, angles, res, nm, lD=0, coords=None, weight_angles=True, onlyreal=False, padding=(True, True), padfac=1.75, padval=None, intp_order=2, dtype=None, num_cores=ncores, save_memory=False, ...
r"""3D backpropagation Three-dimensional diffraction tomography reconstruction algorithm for scattering of a plane wave :math:`u_0(\mathbf{r}) = u_0(x,y,z)` by a dielectric object with refractive index :math:`n(x,y,z)`. This method implements the 3D backpropagation algorithm :cite:`Mueller...
def replace_config(config, name): global static_stages if static_stages is None: static_stages = PipelineStages() stages = static_stages if in config: path = config[] if not os.path.isabs(path) and config.get(): path = os.path.join(config[], ...
Replace the top-level pipeline configurable object. This investigates a number of sources, including `external_stages_path` and `external_stages_modules` configuration and `streamcorpus_pipeline.stages` entry points, and uses these to find the actual :data:`sub_modules` for :mod:`streamcorpus_pipel...
def _ret8(ins): output = _8bit_oper(ins.quad[1]) output.append() output.append( % str(ins.quad[2])) return output
Returns from a procedure / function an 8bits value
def children(self, p_todo, p_only_direct=False): children = \ self._depgraph.outgoing_neighbors(hash(p_todo), not p_only_direct) return [self._tododict[child] for child in children]
Returns a list of child todos that the given todo (in)directly depends on.
def is_businessdate(in_date): if not isinstance(in_date, BaseDate): try: in_date = BusinessDate(in_date) except: return False y, m, d, = in_date.to_ymd() return is_va...
checks whether the provided date is a date :param BusinessDate, int or float in_date: :return bool:
def convert(self, vroot, entry_variables): self.graph_info = GraphInfo(vroot) self.entry_variables = entry_variables cnt = 0 with nn.parameter_scope(self.name): for t, func in enumerate(self.graph_info.funcs): if func.name == "BatchNorma...
All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.
def get_init_kwargs(self): init_kwargs = {} for k in self.init_kwargs: if k in self.core_property_set: init_kwargs[k] = getattr(self, k) elif k in self: init_kwargs[k] = self[k] return init_kwargs
Generates keyword arguments for creating a new Docker client instance. :return: Keyword arguments as defined through this configuration. :rtype: dict
def current(self, value): current = min(max(self._min, value), self._max) self._current = current if current > self._stop : self._stop = current self._start = current-self._width elif current < self._start : self._start = current ...
set current cursor position
def _release_lock(self): if not self._has_lock(): return lfp = self._lock_file_path() try: if os.name == : os.chmod(lfp, 0777) os.remove(lfp) except OSError: ...
Release our lock if we have one
def trace(msg): if os.environ.get() == : print(, msg, file=sys.stderr)
Print a trace message to stderr if environment variable is set.
def random_variants( count, genome_name="GRCh38", deletions=True, insertions=True, random_seed=None): rng = random.Random(random_seed) ensembl = genome_for_reference_name(genome_name) if ensembl in _transcript_ids_cache: transcript_ids = _transcript_ids_...
Generate a VariantCollection with random variants that overlap at least one complete coding transcript.
def check_crystal_equivalence(crystal_a, crystal_b): cryst_a = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_a), symprec=1e-5, angle_tolerance=-1.0, hall_number=0) cryst_b = spglib.get_symmetry_dataset(ase_to_spgcell(crystal_b), symprec=1e-5, angle_tolerance=-1.0, hall_number=0) samecell = ...
Function that identifies whether two crystals are equivalent
def simple_moving_matrix(x, n=10): if x.ndim > 1 and len(x[0]) > 1: x = np.average(x, axis=1) h = n / 2 o = 0 if h * 2 == n else 1 xx = [] for i in range(h, len(x) - h): xx.append(x[i-h:i+h+o]) return np.array(xx)
Create simple moving matrix. Parameters ---------- x : ndarray A numpy array n : integer The number of sample points used to make average Returns ------- ndarray A n x n numpy array which will be useful for calculating confidentail interval of simple moving ...
def char(i): i = ord(i) if i not in font: return [(0,)] * 8 return [(ord(row),) for row in font[i].decode()]
Get image data for the character `i` (a one character string). Returned as a list of rows. Each row is a tuple containing the packed pixels.
def casefold_with_i_dots(text): text = unicodedata.normalize(, text).replace(, ).replace(, ) return text.casefold()
Convert capital I's and capital dotted İ's to lowercase in the way that's appropriate for Turkish and related languages, then case-fold the rest of the letters.
def query_publishers(self, publisher_query): content = self._serialize.body(publisher_query, ) response = self._send(http_method=, location_id=, version=, content=content) return self._deserialize(...
QueryPublishers. [Preview API] :param :class:`<PublisherQuery> <azure.devops.v5_0.gallery.models.PublisherQuery>` publisher_query: :rtype: :class:`<PublisherQueryResult> <azure.devops.v5_0.gallery.models.PublisherQueryResult>`
def addFilter(self, *lstFilters, **dctFilters) : "add a new filter to the query" dstF = {} if len(lstFilters) > 0 : if type(lstFilters[0]) is types.DictType : dstF = lstFilters[0] lstFilters = lstFilters[1:] if len(dctFilters) > 0 : dstF = dict(dstF, **dctFilters) filts = {} for k, v in dst...
add a new filter to the query
def trigger_actions(self, subsystem): for py3_module, trigger_action in self.udev_consumers[subsystem]: if trigger_action in ON_TRIGGER_ACTIONS: self.py3_wrapper.log( "%s udev event, refresh consumer %s" % (subsystem, py3_module.module...
Refresh all modules which subscribed to the given subsystem.
def post_status(self, body="", id="", parentid="", stashid=""): if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req(, post_d...
Post a status :param username: The body of the status :param id: The id of the object you wish to share :param parentid: The parentid of the object you wish to share :param stashid: The stashid of the object you wish to add to the status
def make_clusters(span_tree, cut_value): iv0, iv1 = span_tree.nonzero() match_dict = {} for i0, i1 in zip(iv0, iv1): d = span_tree[i0, i1] if d > cut_value: continue imin = int(min(i0, i1)) imax = int(max(i0, i1)) if imin in match_dic...
Find clusters from the spanning tree Parameters ---------- span_tree : a sparse nsrcs x nsrcs array Filled with zeros except for the active edges, which are filled with the edge measures (either distances or sigmas cut_value : float Value used to cluster group. All links with mea...
def to_netcdf(dataset, path_or_file=None, mode=, format=None, group=None, engine=None, encoding=None, unlimited_dims=None, compute=True, multifile=False): if isinstance(path_or_file, Path): path_or_file = str(path_or_file) if encoding is None: encoding = {} ...
This function creates an appropriate datastore for writing a dataset to disk as a netCDF file See `Dataset.to_netcdf` for full API docs. The ``multifile`` argument is only for the private use of save_mfdataset.
def interpret_header(self): if in self.header: self.date = self.header[] elif in self.header: self.date = self.header[] else: raise Exception("Image does not have a DATE_OBS or DATE-OBS field") self.cy, self.cx = self.header[], sel...
Read pertinent information from the image headers, especially location and radius of the Sun to calculate the default thematic map :return: setes self.date, self.cy, self.cx, and self.sun_radius_pixel
def _computeStatus(self, dfile, service): if service: if not dfile[].has_key(service): return self.ST_UNTRACKED else: return dfile[][service][] first_service_key=dfile[].keys()[0] fir...
Computes status for file, basically this means if more than one service handles the file, it will place a 'C' (for complicated) otherwise if status matches between all services, will place that status
def _handle_state_change_msg(self, new_helper): assert self.my_pplan_helper is not None assert self.my_instance is not None and self.my_instance.py_class is not None if self.my_pplan_helper.get_topology_state() != new_helper.get_topology_state(): self.my_pplan_helper = new_helper ...
Called when state change is commanded by stream manager
def is_valid_group(group_name, nova_creds): valid_groups = [] for key, value in nova_creds.items(): supernova_groups = value.get(, []) if hasattr(supernova_groups, ): supernova_groups = [supernova_groups] valid_groups.extend(supernova_groups) valid_groups.append() ...
Checks to see if the configuration file contains a SUPERNOVA_GROUP configuration option.
def _draw_fold_indicator(self, top, mouse_over, collapsed, painter): rect = QtCore.QRect(0, top, self.sizeHint().width(), self.sizeHint().height()) if self._native: if os.environ[].lower() not in PYQT5_API: opt = QtGui.QStyleOptionViewItem...
Draw the fold indicator/trigger (arrow). :param top: Top position :param mouse_over: Whether the mouse is over the indicator :param collapsed: Whether the trigger is collapsed or not. :param painter: QPainter
def get_spark_context(conf=None): if hasattr(SparkContext, "getOrCreate"): with SparkContext._lock: if SparkContext._active_spark_context is None: spark_conf = create_spark_conf() if conf is None else conf return SparkContext.getOrCreate(spark_conf) ...
Get the current active spark context and create one if no active instance :param conf: combining bigdl configs into spark conf :return: SparkContext
def get_distutils_display_options(): short_display_opts = set( + o[1] for o in Distribution.display_options if o[1]) long_display_opts = set( + o[0] for o in Distribution.display_options) short_display_opts.add() long_display_opts.add() d...
Returns a set of all the distutils display options in their long and short forms. These are the setup.py arguments such as --name or --version which print the project's metadata and then exit. Returns ------- opts : set The long and short form display option arguments, including the - or -...
def cluster(x, cluster=, n_clusters=3, ndims=None, format_data=True): if cluster == None: return x elif (isinstance(cluster, six.string_types) and cluster==) or \ (isinstance(cluster, dict) and cluster[]==): if not _has_hdbscan: raise ImportError() if ndims != None: ...
Performs clustering analysis and returns a list of cluster labels Parameters ---------- x : A Numpy array, Pandas Dataframe or list of arrays/dfs The data to be clustered. You can pass a single array/df or a list. If a list is passed, the arrays will be stacked and the clustering w...
def gemini_query(self, query_id): logger.debug("Looking for query with id {0}".format(query_id)) return self.query(GeminiQuery).filter_by(id=query_id).first()
Return a gemini query Args: name (str)
def deprecated(msg=): def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): warning_string = "Call to deprecated function or property `%s`." % func.__name__ warning_string = warning_string + + msg warnings.warn( warning_st...
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. :param msg: Additional message added to the warning.
def template_sphere_shell(outer_radius, inner_radius=0): r img = _template_sphere_disc(dim=3, outer_radius=outer_radius, inner_radius=inner_radius) return img
r""" This method generates an image array of a sphere-shell. It is useful for passing to Cubic networks as a ``template`` to make spherical shaped networks. Parameters ---------- outer_radius : int Number of nodes in the outer radius of the sphere. inner_radius : int Number...
def get_PolyFromPolyFileObj(PolyFileObj, SavePathInp=None, units=, comments=, skiprows=0, shape0=2): assert type(PolyFileObj) in [list,str] or hasattr(PolyFileObj,"Poly") or np.asarray(PolyFileObj).ndim==2, "Arg PolyFileObj must be str (PathFileExt), a ToFu object with attribute Poly or an iterable convertible...
Return a polygon as a np.ndarray, extracted from a txt file or from a ToFu object, with appropriate units Useful for :meth:`tofu.plugins.AUG.Ves._create()` Parameters ---------- PolyFileObj : str / :mod:`tofu.geom` object / np.ndarray The source where the polygon is to be found, either: ...
def get_upgrades(self, remove_applied=True): if self.upgrades is None: plugins = self._load_upgrades(remove_applied=remove_applied) self.upgrades = self.order_upgrades(plugins, self.history) return self.upgrades
Get upgrades (ordered according to their dependencies). :param remove_applied: Set to false to return all upgrades, otherwise already applied upgrades are removed from their graph (incl. all their dependencies.
def _upload_file(compute, project_id, file_path, path): path = "/projects/{}/files/{}".format(project_id, path.replace("\\", "/")) with open(file_path, "rb") as f: yield from compute.http_query("POST", path, f, timeout=None)
Upload a file to a remote project :param file_path: File path on the controller file system :param path: File path on the remote system relative to project directory
def admeig(classname, f, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau): args = f, m_u, m_d, m_s, m_c, m_b, m_e, m_mu, m_tau A = getattr(adm, + classname)(*args) perm_keys = get_permissible_wcs(classname, f) if perm_keys != : A = A[perm_keys][:, perm_keys] w, v = np.linalg.eig(A.T...
Compute the eigenvalues and eigenvectors for a QCD anomalous dimension matrix that is defined in `adm.adm_s_X` where X is the name of the sector. Supports memoization. Output analogous to `np.linalg.eig`.