code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def context_id(self): if not self._context_id: self._context_id = self._get_context_id() self.update_options(context_id=self._context_id) return self._context_id
Return this Async's Context Id if it exists.
def losses_by_period(losses, return_periods, num_events=None, eff_time=None): if len(losses) == 0: return numpy.zeros(len(return_periods)) if num_events is None: num_events = len(losses) elif num_events < len(losses): raise ValueError( % (num_events, ...
:param losses: array of simulated losses :param return_periods: return periods of interest :param num_events: the number of events (>= to the number of losses) :param eff_time: investigation_time * ses_per_logic_tree_path :returns: interpolated losses for the return periods, possibly with NaN NB: t...
def make_figure(plots): import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.grid(True) ax.set_xlabel() ax.set_ylabel() start = 0 for task_name, mem in plots: ax.plot(range(start, start + len(mem)), mem, label=task_name) start += len(mem) ax.legend() ...
:param plots: list of pairs (task_name, memory array)
def get_catalogs_by_query(self, catalog_query): if self._catalog_session is not None: return self._catalog_session.get_catalogs_by_query(catalog_query) query_terms = dict(catalog_query._query_terms) collection = JSONClientValidated(, ...
Gets a list of ``Catalogs`` matching the given catalog query. arg: catalog_query (osid.cataloging.CatalogQuery): the catalog query return: (osid.cataloging.CatalogList) - the returned ``CatalogList`` raise: NullArgument - ``catalog_query`` is ``null`` ...
def refresh(self) -> None: if self._do_refresh: if self.anns: self.__sann = annutils.SeasonalANN(self.anns) setattr(self.fastaccess, self.name, self._sann) self._set_shape((None, self._sann.nmb_anns)) if self._sann.nmb...
Prepare the actual |anntools.SeasonalANN| object for calculations. Dispite all automated refreshings explained in the general documentation on class |anntools.SeasonalANN|, it is still possible to destroy the inner consistency of a |anntools.SeasonalANN| instance, as it stores its |annt...
def update_resources(self, dstpath, names=None, languages=None): UpdateManifestResourcesFromXML(dstpath, self.toprettyxml(), names, languages)
Update or add manifest resource in dll/exe file dstpath
def get_sonos_playlist_by_attr(self, attr_name, match): for sonos_playlist in self.get_sonos_playlists(): if getattr(sonos_playlist, attr_name) == match: return sonos_playlist raise ValueError(.format(attr_name, ...
Return the first Sonos Playlist DidlPlaylistContainer that matches the attribute specified. Args: attr_name (str): DidlPlaylistContainer attribute to compare. The most useful being: 'title' and 'item_id'. match (str): Value to match. Returns: ...
def check_datasource_perms(self, datasource_type=None, datasource_id=None): form_data = get_form_data()[0] datasource_id, datasource_type = get_datasource_info( datasource_id, datasource_type, form_data) viz_obj = get_viz( datasource_type=datasource_type, datasource_id=datasourc...
Check if user can access a cached response from explore_json. This function takes `self` since it must have the same signature as the the decorated method.
def check_overlap(a, b): if a.isAnalytic or b.isAnalytic: return result
Check for wavelength overlap between two spectra. .. note:: Generalized from :meth:`pysynphot.spectrum.SpectralElement.check_overlap`. Parameters ---------- a, b : `~pysynphot.spectrum.SourceSpectrum` or `~pysynphot.spectrum.SpectralElement` Typically a source spectrum, spectra...
def with_port(self, port): if port is not None and not isinstance(port, int): raise TypeError("port should be int or None, got {}".format(type(port))) if not self.is_absolute(): raise ValueError("port replacement is not allowed " "for relative URLs") val...
Return a new URL with port replaced. Clear port to default if None is passed.
def getElementDeclaration(cls, namespaceURI, name, isref=False, lazy=False): key = (namespaceURI, name) if isref: klass = cls.elements.get(key,None) if klass is not None and lazy is True: return _Mirage(klass) return klass typecode =...
Grab an element declaration, returns a typecode instance representation or a typecode class definition. An element reference has its own facets, and is local so it will not be cached. Parameters: namespaceURI -- name -- isref -- if element referen...
def get_layer_output(self, name): if not name in self._f_layer_outputs: layer = self.net.get_layer(name) self._f_layer_outputs[name] = layer.output return self._f_layer_outputs[name]
Get symbolic output of a layer.
def run_healthchecks(self): if not self._registry_loaded: self.load_healthchecks() def get_healthcheck_name(hc): if hasattr(hc, ): return hc.name return hc.__name__ responses = [] for healthcheck in self._registry: ...
Runs all registered healthchecks and returns a list of HealthcheckResponse.
def mean_harmonic(self): res = self.price.groupby(level=1 ).apply(lambda x: statistics.harmonic_mean(x)) res.name = return res
返回DataStruct.price的调和平均数
def create_api_key(self): apikeys = self.client.get_api_keys() for key in apikeys[]: if key[] == self.app_name: self.log.info("Key %s already exists", self.app_name) break else: self.client.create_api_key( name=self...
Create API Key for API access.
def atq(tag=None): tag*** jobs = [] if tag == job_tag or tag == job: jobs.append({: job, : specs[0], : specs[1], : specs[2], : specs[3], : job_tag}) else: jobs.append({: job, : specs[0], : specs[1], : spe...
List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number]
def get_current_selection(self, i=None): taskfile = None if (i is None and self.selection_tabw.currentIndex() == 0) or (i is not None and i == 0): indexes = self.assetverbrws.selected_indexes(0) if indexes and indexes[0].isValid(): item = indexes[0].inter...
Get the :class:`TaskFileInfo` for the file selected in the active tab :param i: If None, returns selection of active tab. If 0, assetselection. If 1, shotselection :type i: :returns: The taskfile info in the currently active tab :rtype: :class:`TaskFileInfo` | None :raises: None
def make_plot(self): self.get_contour_values() colors1 = [, , , , , , ] self.snr_contour_value = (self.SNR_CUT if self.snr_contour_value is None else self.snr_contour_value) for j in range(len(sel...
Make the horizon plot.
def ani_depthplot2(ani_file=, meas_file=, samp_file=, age_file=None, sum_file=None, fmt=, dmin=-1, dmax=-1, depth_scale=, dir_path=): pcol = 4 tint = 9 plots = 0 ani_file = pmag.resolve_file_name(ani_file, dir_path) if not os.path.isfile(ani_file): print("Could not find rmag_...
returns matplotlib figure with anisotropy data plotted against depth available depth scales: 'sample_composite_depth', 'sample_core_depth', or 'age' (you must provide an age file to use this option)
def factor_cumulative_returns(factor_data, period, long_short=True, group_neutral=False, equal_weight=False, quantiles=None, groups=None): ...
Simulate a portfolio using the factor in input and returns the cumulative returns of the simulated portfolio Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha facto...
def get_chrom_for_transcript(self, transcript_id, hgnc_id): headers = {"content-type": "application/json"} self.attempt = 0 ext = "/overlap/id/{}?feature=gene".format(transcript_id) r = self.ensembl_request(ext, headers) for gene in json.loads...
obtain the sequence for a transcript from ensembl
def _state(self): state = {} required_keys = (, , , , ) try: for _ in range(self._state_retries): state.update(self._get_data()) except TypeError: ...
The internal state of the object. The api responses are not consistent so a retry is performed on every call with information updating the internally saved state refreshing the data. The info is cached for STATE_CACHING_SECONDS. :return: The current state of the toons' information stat...
def summary_by_datacenter(self): datacenters = collections.defaultdict(lambda: { : 0, : 0, : 0, : 0, : 0, }) for vlan in self.list_vlans(): name = utils.lookup(vlan, , , ) datacenters[name][] += 1 ...
Summary of the networks on the account, grouped by data center. The resultant dictionary is primarily useful for statistical purposes. It contains count information rather than raw data. If you want raw information, see the :func:`list_vlans` method instead. :returns: A dictionary keye...
def pwd(self, **kwargs): b_node = False node = 0 for key,val in kwargs.items(): if key == : b_node = True node = int(val) str_path = self.cwd() if b_node: l_path ...
Returns the cwd Optional kwargs: node = <node> If specified, return only the directory name at depth <node>.
def ls_command( endpoint_plus_path, recursive_depth_limit, recursive, long_output, show_hidden, filter_val, ): endpoint_id, path = endpoint_plus_path client = get_client() autoactivate(client, endpoint_id, if_expires_in=60) ls_params = {"show_hidden": int(sh...
Executor for `globus ls`
def _nama(self): hasil = self.nama if self.nomor: hasil += " [{}]".format(self.nomor) if self.kata_dasar: hasil = " » ".join(self.kata_dasar) + " » " + hasil return hasil
Mengembalikan representasi string untuk nama entri ini. :returns: String representasi nama entri :rtype: str
def calculate_auc_covar(auc_structure1, auc_structure2): actives1, decoys1 = splitter(auc_structure1) actives2, decoys2 = splitter(auc_structure2) fpf1 = [x[4] for x in actives1] fpf2 = [x[4] for x in actives2] covara = np.cov(fpf1,fpf2)[0][1] tpf1 = [x[5] for x in decoys1...
determine AUC covariance due to actives (covar_a) and decoys (covar_d) :param auc_structure1: list [(id, best_score, best_query, status, fpf, tpf), ...,] :param auc_structure2: list [(id, best_score, best_query, status, fpf, tpf), ...,] :return (covar_a, covar_d): tuple
def _read_bytes_from_framed_body(self, b): plaintext = b"" final_frame = False _LOGGER.debug("collecting %d bytes", b) while len(plaintext) < b and not final_frame: _LOGGER.debug("Reading frame") frame_data, final_frame = deserialize_frame( ...
Reads the requested number of bytes from a streaming framed message body. :param int b: Number of bytes to read :returns: Bytes read from source stream and decrypted :rtype: bytes
def format_string(self, fmat_string): try: return fmat_string.format(**vars(self)) except KeyError as e: raise ValueError( .format(repr(fmat_string), repr(e)))
Takes a string containing 0 or more {variables} and formats it according to this instance's attributes. :param fmat_string: A string, e.g. '{name}-foo.txt' :type fmat_string: ``str`` :return: The string formatted according to this instance. E.g. 'production-runtime-foo...
def for_web(self, data): rgba = self._prepare_array_for_png(data) data = ma.masked_where(rgba == self.nodata, rgba) return memory_file(data, self.profile()),
Convert data to web output. Parameters ---------- data : array Returns ------- web data : array
def persist(self, context): D = self._Document document = context.session[self.name] D.get_collection().replace_one(D.id == document.id, document, True)
Update or insert the session document into the configured collection
def preview(self, components=None, ask=0): ask = int(ask) self.init() component_order, plan_funcs = self.get_component_funcs(components=components) print( % (len(component_order), self.genv.host_string)) if component_order and plan_funcs: if self.verbose:...
Inspects differences between the last deployment and the current code state.
def dn(self, fraction, n=None): r if fraction == 1.0: fraction = 1.0 - epsilon if fraction < 0: raise ValueError() elif fraction == 0: if self.truncated: return self.d_min return 0.0 ...
r'''Computes the diameter at which a specified `fraction` of the distribution falls under. Utilizes a bounded solver to search for the desired diameter. Parameters ---------- fraction : float Fraction of the distribution which should be under the calculated ...
def _new(self, dx_hash, media_type=None, **kwargs): if media_type is not None: dx_hash["media"] = media_type resp = dxpy.api.file_new(dx_hash, **kwargs) self.set_ids(resp["id"], dx_hash["project"])
:param dx_hash: Standard hash populated in :func:`dxpy.bindings.DXDataObject.new()` containing attributes common to all data object classes. :type dx_hash: dict :param media_type: Internet Media Type :type media_type: string Creates a new remote file with media type *media_type*, if giv...
def pad(self, pad): tile = self.copy() tile.l -= pad tile.r += pad return tile
Pad this tile by an equal amount on each side as specified by pad >>> Tile(10).pad(2) Tile [-2, -2, -2] -> [12, 12, 12] ([14, 14, 14]) >>> Tile(10).pad([1,2,3]) Tile [-1, -2, -3] -> [11, 12, 13] ([12, 14, 16])
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_port_description(self, **kwargs): config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail output = ET.SubElement(get_lldp_neighbor_detail, "o...
Auto Generated Code
def verify2(self): output_key = hkdf_expand(, , self._shared) input_key = hkdf_expand(, , self._shared) log_binary(_LOGGER, , Output=output_key, Input=inpu...
Last verification step. The derived keys (output, input) are returned here.
def save(self): data = super().save() data[] = self.end_chars data[] = self.default_end return data
Convert to JSON. Returns ------- `dict` JSON data.
def TextWidget(*args, **kw): kw[] = str(kw[]) kw.pop(, None) return TextInput(*args,**kw)
Forces a parameter value to be text
def is_data_value(searchpath, searchtree, dtype = None, empty_is_false = False): if isinstance(searchpath, (str, unicode, int)): searchpath = [searchpath] if not isinstance(searchpath, (list, tuple)): return False for d in searchpath: if isinstance(searchtree, dict): ...
Follow searchpath through the datatree in searchtree and report if there exists a value of type dtype searchpath is a list of keys/indices If dtype is None check for any value you can also supply a tuple to dtype
def __apply_nested_option(self, option_name, field_names, set_operation): nested_fields = [name.split(, 1) for name in field_names if in name] nested_options = defaultdict(list) for parent, nested_names in nested_fields: nested_options[parent].append(neste...
Apply nested options to nested fields
def _postprocess_options(dbg, opts): ) that feed into the debugger (`dbg print_events = [] if opts.fntrace: print_events = [, , , ] if len(print_events): dbg.settings[] = frozenset(print_events) pass for setting in (, ,): dbg.settings[setting] = getattr(opts, set...
Handle options (`opts') that feed into the debugger (`dbg')
def add_definition_tags(self, tags, project, definition_id): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) if definition_id is not None: route_values[] = self._serialize.url(, definition_id, ) content = self._...
AddDefinitionTags. [Preview API] Adds multiple tags to a definition. :param [str] tags: The tags to add. :param str project: Project ID or project name :param int definition_id: The ID of the definition. :rtype: [str]
def collect_reponames(): reponames = [] try: with open(os.devnull) as devnull: remote_data = subprocess.check_output(["git","remote","-v","show"],stderr=devnull) branches = {} for line in remote_data.decode().split("\n"): if line.strip() == "": continue remote_match = re_mote.match(line) if...
Try to figure out a list of repos to consider by default from the contents of the working directory.
def remove_user(self, name, session=None): warnings.warn("remove_user is deprecated and will be removed in " "PyMongo 4.0. Use db.command with dropUser " "instead", DeprecationWarning, stacklevel=2) cmd = SON([("dropUser", name)]) if ...
**DEPRECATED**: Remove user `name` from this :class:`Database`. User `name` will no longer have permissions to access this :class:`Database`. .. note:: remove_user is deprecated and will be removed in PyMongo 4.0. Use the dropUser command instead:: db.command("dropUser",...
def render(self, name=None, template=None, context={}): Render Template meta from jinja2 templates. ' if isinstance(template, Template): _template = template else: _template = Template.objects.get(name=name) response = self.env.from_string( ...
Render Template meta from jinja2 templates.
def slew(self, value): if float(value) != self.filepos: pos = float(value) * self.filesize self.mlog.f.seek(int(pos)) self.find_message()
move to a given position in the file
def do_mode(self, target, msg, nick, send): mode_changes = irc.modes.parse_channel_modes(msg) with self.data_lock: for change in mode_changes: if change[1] == : self.voiced[target][change[2]] = True if change[0] == else False if c...
reop and handle guard violations.
def randomWalkFunction(requestContext, name, step=60): delta = timedelta(seconds=step) when = requestContext["startTime"] values = [] current = 0 while when < requestContext["endTime"]: values.append(current) current += random.random() - 0.5 when += delta return [Ti...
Short Alias: randomWalk() Returns a random walk starting at 0. This is great for testing when there is no real data in whisper. Example:: &target=randomWalk("The.time.series") This would create a series named "The.time.series" that contains points where x(t) == x(t-1)+random()-0.5, and x...
def unpause_topic(self, topic): nsq.assert_valid_topic_name(topic) return self._request(, , fields={: topic})
Resume message flow to channels of an existing, paused, topic.
def send_script_async(self, conn_id, data, progress_callback, callback): def _on_finished(_name, _retval, exception): if exception is not None: callback(conn_id, self.id, False, str(exception)) return callback(conn_id, self.id, True, None) ...
Asynchronously send a a script to this IOTile device Args: conn_id (int): A unique identifer that will refer to this connection data (string): the script to send to the device progress_callback (callable): A function to be called with status on our progress, called as: ...
def _apply_updates(self, gradients): if not hasattr(self, ): self.optimizers = \ {obj: AdaGradOptimizer(self.learning_rate) for obj in [, , , ]} self.W -= self.optimizers[].get_step(gradients[]) self.C -= self.optimizers[].get_step(gradients[...
Apply AdaGrad update to parameters. Parameters ---------- gradients Returns -------
def configure(self, width, height): self._imgwin_set = True self.set_window_size(width, height)
See :meth:`set_window_size`.
def merge_entities(self, from_entity_ids, to_entity_id, force=False, mount_point=DEFAULT_MOUNT_POINT): params = { : from_entity_ids, : to_entity_id, : force, } api_path = .format(mount_point=mount_point) return self._adapter.post( ...
Merge many entities into one entity. Supported methods: POST: /{mount_point}/entity/merge. Produces: 204 (empty body) :param from_entity_ids: Entity IDs which needs to get merged. :type from_entity_ids: array :param to_entity_id: Entity ID into which all the other entities ...
def execute_command(self, generator, write_concern, session): full_result = { "writeErrors": [], "writeConcernErrors": [], "nInserted": 0, "nUpserted": 0, "nMatched": 0, "nModified": 0, "nRemoved": 0, ...
Execute using write commands.
def OnCellFontSize(self, event): with undo.group(_("Font size")): self.grid.actions.set_attr("pointsize", event.size) self.grid.ForceRefresh() self.grid.update_attribute_toolbar() event.Skip()
Cell font size event handler
def history_json(self, nb=0): return [(i[0].isoformat(), i[1]) for i in self._history[-nb:]]
Return the history in ISO JSON format
def _writeBlock(block, blockID): with open("blockIDs.txt", "a") as fp: fp.write("blockID: " + str(blockID) + "\n") sentences = "" for sentence in block: sentences += sentence+"," fp.write("block sentences: "+sentences[:-1]+"\n") fp.write("\n")
writes the block to a file with the id
def _calc_dimension(self, dim_val, dim_max, font_dim): "Calculate final pos and size (auto, absolute in pixels & relativa)" if dim_val is None: return -1 elif isinstance(dim_val, int): return dim_val elif isinstance(dim_val, basestring): if d...
Calculate final pos and size (auto, absolute in pixels & relativa)
def upload(self): if self.upload_method == "setup": self.upload_by_setup() if self.upload_method == "twine": self.upload_by_twine() if self.upload_method == "gemfury": self.upload_by_gemfury()
upload via the method configured :return:
def move(src, dst): real_dst = dst if os.path.isdir(dst): if _samefile(src, dst): os.rename(src, dst) return real_dst = os.path.join(dst, _basename(src)) if os.path.exists(real_dst): raise Error("Destination path alread...
Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a d...
def _write_cdx_header(self): with open(self._cdx_filename, mode=, encoding=) as out_file: out_file.write(self.CDX_DELIMINATOR) out_file.write(self.CDX_DELIMINATOR.join(( , , , , , , , , , ))) ...
Write the CDX header. It writes the fields: 1. a: original URL 2. b: UNIX timestamp 3. m: MIME Type from the HTTP Content-type 4. s: response code 5. k: new style checksum 6. S: raw file record size 7. V: offset in raw file 8. g: filename of raw ...
def _secret_yaml(loader, node): fname = os.path.join(os.path.dirname(loader.name), "secrets.yaml") try: with open(fname, encoding="utf-8") as secret_file: secrets = YAML(typ="safe").load(secret_file) except FileNotFoundError: raise ValueError("Secrets file {} not found".for...
Load secrets and embed it into the configuration YAML.
def push_channel(self, content, channel, content_url=None): parameters = { : self.app_key, : self.app_secret, : channel } return self._push(content, , parameters, content_url)
Push a notification to a Pushed channel. Param: content -> content of Pushed notification message channel -> string identifying a Pushed channel content_url (optional) -> enrich message with URL Returns Shipment ID as string
def has_frames(self, destination): session = meta.Session() sel = select([model.frames_table.c.message_id]).where( model.frames_table.c.destination == destination) result = session.execute(sel) first = result.fetchone() return first is not None
Whether specified queue has any frames. @param destination: The queue name (destinationination). @type destination: C{str} @return: Whether there are any frames in the specified queue. @rtype: C{bool}
def move_top_cards(self, other, number=1): other.cards.append(reversed(self.cards[-number:]))
Move the top `number` of cards to the top of some `other` deck. By default only one card will be moved if `number` is not specified.
def set_onscreen_message(self, text, redraw=True): width, height = self.get_window_size() font = self.t_.get(, ) font_size = self.t_.get(, None) if font_size is None: font_size = self._calc_font_size(width) ht, wd = font_size, font_size ...
Called by a subclass to update the onscreen message. Parameters ---------- text : str The text to show in the display.
def by_geopoint(self, lat, long): header, content = self._http_request(self.BASE_URL, lat=lat, long=long) return json.loads(content)
Perform a Yelp Neighborhood API Search based on a geopoint. Args: lat - geopoint latitude long - geopoint longitude
def login(self, user=None, password=None, restrict_login=None): if self.api_key: raise ValueError("cannot login when using an API key") if user: self.user = user if password: self.password = password if not self.user: raise Value...
Attempt to log in using the given username and password. Subsequent method calls will use this username and password. Returns False if login fails, otherwise returns some kind of login info - typically either a numeric userid, or a dict of user info. If user is not set, the value of Bug...
def make_request(self, resource, params=None): if params is None: params = {} url = self.request_url(resource) params[] = r = self.session.get(url=url, params=params) r.raise_for_status() return r
Performs the API request. Most methods are a wrapper around this one.
def boottime(): global __boottime if __boottime is None: up = uptime() if up is None: return None if __boottime is None: _boottime_linux() if datetime is None: raise RuntimeError() return datetime.fromtimestamp(__boottime or time.time() - up)
Returns boot time if remotely possible, or None if not.
def set_params(self, deep=False, force=False, **parameters): param_names = self.get_params(deep=deep).keys() for parameter, value in parameters.items(): if (parameter in param_names or force or (hasattr(self, parameter) and parameter == parameter.stri...
sets an object's paramters Parameters ---------- deep : boolean, default: False when True, also sets non-user-facing paramters force : boolean, default: False when True, also sets parameters that the object does not already have **parameters :...
def read_line(self, sep=six.b()): start = 0 while not self._stream.closed: loc = self._buffer.find(sep, start) if loc >= 0: return self._pop(loc + len(sep)) else: start = len(self._buffer) self._buffer += self._stre...
Read the data stream until a given separator is found (default \n) :param sep: Separator to read until. Must by of the bytes type (str in python 2, bytes in python 3) :return: The str of the data read until sep
def by_median_household_income(self, lower=-1, upper=2 ** 31, zipcode_type=ZipcodeType.Standard, sort_by=SimpleZipcode.median_household_income.name, ...
Search zipcode information by median household income.
def on_left_click(self, event, grid, choices): row, col = event.GetRow(), event.GetCol() if col == 0 and self.grid.name != : default_val = self.grid.GetCellValue(row, col) msg = "Choose a new name for {}.\nThe new value will propagate throughout the contribution.".format...
creates popup menu when user clicks on the column if that column is in the list of choices that get a drop-down menu. allows user to edit the column, but only from available values
def get_engine(name): name = name.capitalize() + if name in globals(): return globals()[name] raise KeyError("engine does not exist" % name)
get an engine from string (engine class without Engine)
def register_extension_method(ext, base, *args, **kwargs): bound_method = create_bound_method(ext.plugin, base) setattr(base, ext.name.lstrip(), bound_method)
Register the given extension method as a public attribute of the given base. README: The expected protocol here is that the given extension method is an unbound function. It will be bound to the specified base as a method, and then set as a public attribute of that base.
def _viewdata_to_view(self, p_data): sorter = Sorter(p_data[], p_data[]) filters = [] if not p_data[]: filters.append(DependencyFilter(self.todolist)) filters.append(RelevanceFilter()) filters.append(HiddenTagFilter()) filters += get_filter_...
Converts a dictionary describing a view to an actual UIView instance.
def namespace(self, namespace): self._namespace = _ensure_unicode(namespace) if self._namespace is not None: self._namespace = self._namespace.strip()
Setter method; for a description see the getter method.
def _extract_model_params(self, defaults, **kwargs): obj = kwargs.pop(self.object_property_name, None) if obj is not None: kwargs[] = self.model._compute_hash(obj) lookup, params = super()._extract_model_params(defaults, **kwargs) if obj is not None: para...
this method allows django managers use `objects.get_or_create` and `objects.update_or_create` on a hashable object.
def add_line(self, line=, *, empty=False): max_page_size = self.max_size - self._prefix_len - 2 if len(line) > max_page_size: raise RuntimeError( % (max_page_size)) if self._count + len(line) + 1 > self.max_size: self.close_page() self._count += len(lin...
Adds a line to the current page. If the line exceeds the :attr:`max_size` then an exception is raised. Parameters ----------- line: :class:`str` The line to add. empty: :class:`bool` Indicates if another empty line should be added. Raise...
def create_js_pay_params(self, **package): pay_param, sign, sign_type = self._pay_sign_dict( package=self.create_js_pay_package(**package) ) pay_param[] = sign pay_param[] = sign_type for key in [, , ]: pay_param[key] = str(pay_param.pop...
签名 js 需要的参数 详情请参考 支付开发文档 :: wxclient.create_js_pay_params( body=标题, out_trade_no=本地订单号, total_fee=价格单位分, notify_url=通知url, spbill_create_ip=建议为支付人ip, ) :param package: 需要签名的的参数 :return: 支付需要的对象
def _on_bytes_read(self, num_bytes_read): self.actual_bytes_read += num_bytes_read if self.actual_bytes_read > self.bytes_to_read: raise TooLargeChunkDownloadError(self.actual_bytes_read, self.bytes_to_read, self.local_path) self.download_context.send_processed_message(num_b...
Record our progress so we can validate that we receive all the data :param num_bytes_read: int: number of bytes we received as part of one chunk
def _get_method_full_name(func): if hasattr(func, "__qualname__"): return func.__qualname__ module = inspect.getmodule(func) if module is None: return "?.%s" % getattr(func, "__name__", "?") for cls_name in dir(module): cls = getattr(module, cls_name) if not inspect.is...
Return fully qualified function name. This method will attempt to find "full name" of the given function object. This full name is either of the form "<class name>.<method name>" if the function is a class method, or "<module name>.<func name>" if it's a regular function. Thus, this is an attempt to back-p...
def check_argument_list(kernel_name, kernel_string, args): kernel_arguments = list() collected_errors = list() for iterator in re.finditer(kernel_name + "[ \n\t]*" + "\(", kernel_string): kernel_start = iterator.end() kernel_end = kernel_string.find(")", kernel_start) if kernel_...
raise an exception if a kernel arguments do not match host arguments
def _print(self, *data, **kw): sep = kw.pop(, ) end = kw.pop(, ) _ = kw.pop(, None) assert not kw, data = sep.join(map(str, data)) self._chan.write(data + end)
_print(self, *data, sep=' ', end='\n', file=None) Alternative 'print' function that prints back into the SSH channel.
def get_work_kind(self): slugs_to_kinds = {v:k for k,v in Work.KIND_SLUGS.items()} return slugs_to_kinds.get(self.kind_slug, None)
We'll have a kind_slug like 'movies'. We need to translate that into a work `kind` like 'movie'.
def writeToken(self): with os.fdopen(os.open(self.tokenFile, os.O_WRONLY | os.O_CREAT, 0o600), "w") as f: f.truncate() f.write(self.userId + "\n") f.write(self.tokens["skype"] + "\n") f.write(str(int(time.mktime(self.tokenExpiry["sky...
Store details of the current connection in the named file. This can be used by :meth:`readToken` to re-authenticate at a later time.
def strip(self, col: str): def remove_ws(row): val = str(row[col]) if " " in val.startswith(" "): row[col] = val.strip() return row try: self.df.apply(remove_ws) except Exception as e: self.err(e, "Can not remo...
Remove leading and trailing white spaces in a column's values :param col: name of the column :type col: str :example: ``ds.strip("mycol")``
def create_hitor_calibration(output_filename, plot_pixel_calibrations=False): logging.info(, output_filename) with AnalyzeRawData(raw_data_file=output_filename, create_pdf=True) as analyze_raw_data: analyze_raw_data.create_occupancy_hist = False analyze_raw_data.create_hit_table = ...
Generating HitOr calibration file (_calibration.h5) from raw data file and plotting of calibration data. Parameters ---------- output_filename : string Input raw data file name. plot_pixel_calibrations : bool, iterable If True, genearating additional pixel calibration plots. If l...
def set_dimensional_calibrations(self, dimensional_calibrations: typing.List[CalibrationModule.Calibration]) -> None: self.__data_item.set_dimensional_calibrations(dimensional_calibrations)
Set the dimensional calibrations. :param dimensional_calibrations: A list of calibrations, must match the dimensions of the data. .. versionadded:: 1.0 Scriptable: Yes
def pp_event(seq): if isinstance(seq, Event): return str(seq) rev_curses = dict((v, k) for k, v in CURSES_NAMES.items()) rev_curtsies = dict((v, k) for k, v in CURTSIES_NAMES.items()) if seq in rev_curses: seq = rev_curses[seq] elif seq in rev_curtsies: seq = rev_...
Returns pretty representation of an Event or keypress
def create_business_rules(self, hosts, services, hostgroups, servicegroups, macromodulations, timeperiods, running=False): cmdcall = getattr(self, , None) if cmdcall is None: return cmd = cmdcall.call ...
Create business rules if necessary (cmd contains bp_rule) :param hosts: Hosts object to look for objects :type hosts: alignak.objects.host.Hosts :param services: Services object to look for objects :type services: alignak.objects.service.Services :param running: flag used in eva...
def purge(gandi, email, background, force, alias): login, domain = email if alias: if not force: proceed = click.confirm( % (login, domain)) if not proceed: return result = gandi.mail.set_alias(domain, login, []) ...
Purge a mailbox.
def fetch(self, remote, branch, local_branch = None, force=False): pb = ProgressBar() pb.setup(self.name) if local_branch: branch = .join([branch, local_branch]) remote.fetch(branch, update_head_ok=True, force=force, progress=pb) print()
Pull a repository :param remote: git-remote instance :param branch: name of the branch to pull
def set_current_thumbnail(self, thumbnail): self.current_thumbnail = thumbnail self.figure_viewer.load_figure( thumbnail.canvas.fig, thumbnail.canvas.fmt) for thumbnail in self._thumbnails: thumbnail.highlight_canvas(thumbnail == self.current_thumbnail)
Set the currently selected thumbnail.
def dealias_image(alias): with Session() as session: try: result = session.Image.dealiasImage(alias) except Exception as e: print_error(e) sys.exit(1) if result[]: print("alias {0} removed.".format(alias)) else: print(r...
Remove an image alias.
def wrap(cls, private_key, algorithm): if not isinstance(private_key, byte_cls) and not isinstance(private_key, Asn1Value): raise TypeError(unwrap( , type_name(private_key) )) if algorithm == : if not isinstance(private_key, ...
Wraps a private key in a PrivateKeyInfo structure :param private_key: A byte string or Asn1Value object of the private key :param algorithm: A unicode string of "rsa", "dsa" or "ec" :return: A PrivateKeyInfo object
def find(cls, id=, slug=None): if not id and not slug: return None try: return cls.where(id=id, slug=slug).next() except StopIteration: raise PanoptesAPIException( "Could not find collection with slug=".format(slug) )
Similar to :py:meth:`.PanoptesObject.find`, but allows lookup by slug as well as ID. Examples:: collection_1234 = Collection.find(1234) my_collection = Collection.find(slug="example/my-collection")
def iresolve(self, *keys): for key in keys: missing = self.get_missing_deps(key) if missing: raise UnresolvableError("Missing dependencies for %s: %s" % (key, missing)) provider = self._providers.get(key) if not provider: ...
Iterates over resolved instances for given provider keys. :param keys: Provider keys :type keys: tuple :return: Iterator of resolved instances :rtype: generator