Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
300
def marker(self, marker_name=None, label=None, color=None, retina=False): if marker_name is None: raise ValidationError( "marker_name is a required argument" ) marker_name = self._validate_marker_name(marker_name) ...
Returns a single marker image without any background map. Parameters ---------- marker_name : str The marker's shape and size. label : str, optional The marker's alphanumeric label. Options are a through z, 0 through 99, or the ...
301
def logical_xor(self, other): return self.operation(other, lambda x, y: int(bool(x) ^ bool(y)))
logical_xor(t) = self(t) ^ other(t).
302
def process_raw_file(self, raw_file_name, field_names): dist_vals = [] group_dat = [] events = [] with open(raw_file_name) as csvfile: reader = csv.DictReader(csvfile, fieldnames = field_names) for num_lines, row in enumerate(re...
takes the filename to be read and uses the maps setup on class instantiation to process the file. This is a top level function and uses self.maps which should be the column descriptions (in order).
303
def gmres_mgs(A, b, x0=None, tol=1e-5, restrt=None, maxiter=None, xtype=None, M=None, callback=None, residuals=None, reorth=False): A, M, x, b, postprocess = make_system(A, M, x0, b) dimen = A.shape[0] import warnings warnings.filterwarnings(, module=) if not hasa...
Generalized Minimum Residual Method (GMRES) based on MGS. GMRES iteratively refines the initial solution guess to the system Ax = b Modified Gram-Schmidt version Parameters ---------- A : array, matrix, sparse matrix, LinearOperator n x n, linear system to solve b : array, matrix ...
304
def logout(config): state = read(config.configfile) if state.get("BUGZILLA"): remove(config.configfile, "BUGZILLA") success_out("Forgotten") else: error_out("No stored Bugzilla credentials")
Remove and forget your Bugzilla credentials
305
def flatten(l, types=(list, )): if not isinstance(l, types): return l return list(flattened_iterator(l, types))
Given a list/tuple that potentially contains nested lists/tuples of arbitrary nesting, flatten into a single dimension. In other words, turn [(5, 6, [8, 3]), 2, [2, 1, (3, 4)]] into [5, 6, 8, 3, 2, 2, 1, 3, 4] This is safe to call on something not a list/tuple - the original input is returned as a list
306
def Percentile(pmf, percentage): p = percentage / 100.0 total = 0 for val, prob in pmf.Items(): total += prob if total >= p: return val
Computes a percentile of a given Pmf. percentage: float 0-100
307
def detect_version(env, cc): cc = env.subst(cc) if not cc: return None version = None pipe = SCons.Action._subproc(env, SCons.Util.CLVar(cc) + [], stdin = , stderr = , stdout = subprocess...
Return the version of the GNU compiler, or None if it is not a GNU compiler.
308
def calculate_lvgd_voltage_current_stats(nw): nw.control_circuit_breakers(mode=) nodes_idx = 0 nodes_dict = {} branches_idx = 0 branches_dict = {} for mv_district in nw.mv_grid_districts(): for LA in mv_district.lv_load_areas(): if not LA.is_aggregated: ...
LV Voltage and Current Statistics for an arbitrary network Note ---- Aggregated Load Areas are excluded. Parameters ---------- nw: :any:`list` of NetworkDing0 The MV grid(s) to be studied Returns ------- pandas.DataFrame nodes_df : Dataframe containing voltage, res...
309
def jco_from_pestpp_runstorage(rnj_filename,pst_filename): header_dtype = np.dtype([("n_runs",np.int64),("run_size",np.int64),("p_name_size",np.int64), ("o_name_size",np.int64)]) pst = pyemu.Pst(pst_filename) par = pst.parameter_data log_pars = set(par.loc[par.partrans=="log...
read pars and obs from a pest++ serialized run storage file (e.g., .rnj) and return pyemu.Jco. This can then be passed to Jco.to_binary or Jco.to_coo, etc., to write jco file in a subsequent step to avoid memory resource issues associated with very large problems. Parameters ---------- rnj_filena...
310
def find_file_regex(root_dir,re_expression,return_abs_path = True,search_sub_directories = True): compiled = re.compile(re_expression) result = [] for dirpath, dirnames, files in os.walk(root_dir) : for file in files : if compiled.match(file): ...
Finds all the files with the specified root directory with the name matching the regex expression. Args : root_dir : The root directory. re_expression : The regex expression. return_abs_path : If set to true, returns the absolute path of th...
311
def regression(): Command("touch", DIR.project.joinpath("pathquery", "__init__.py").abspath()).run() storybook = _storybook({}).only_uninherited() Command("touch", DIR.project.joinpath("pathquery", "__init__.py").abspath()).run() storybook.with_params(**{"python version": "3...
Run regression testing - lint and then run all tests.
312
def check_dataset(dataset): if isinstance(dataset, numpy.ndarray) and not len(dataset.shape) == 4: check_dataset_shape(dataset) check_dataset_range(dataset) else: for i, d in enumerate(dataset): if not isinstance(d, numpy.ndarray): raise ValueError( ...
Confirm shape (3 colors x rows x cols) and values [0 to 255] are OK.
313
def get(self, sid): return FaxMediaContext(self._version, fax_sid=self._solution[], sid=sid, )
Constructs a FaxMediaContext :param sid: The unique string that identifies the resource to fetch :returns: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext :rtype: twilio.rest.fax.v1.fax.fax_media.FaxMediaContext
314
def create_bv_bitmap(dot_product_vector: str, dot_product_bias: str) -> Dict[str, str]: n_bits = len(dot_product_vector) bit_map = {} for bit_val in range(2 ** n_bits): bit_map[np.binary_repr(bit_val, width=n_bits)] = str( (int(utils.bitwise_dot_product(np.binary_repr(bit_val, width...
This function creates a map from bitstring to function value for a boolean formula :math:`f` with a dot product vector :math:`a` and a dot product bias :math:`b` .. math:: f:\\{0,1\\}^n\\rightarrow \\{0,1\\} \\mathbf{x}\\rightarrow \\mathbf{a}\\cdot\\mathbf{x}+b\\pmod{2} ...
315
def _node_add_with_peer_list(self, child_self, child_other): parent_self = child_self.getparent() s_node = self.device.get_schema_node(child_self) if child_other.get(operation_tag) != and \ child_other.get(operation_tag) != and \ s_node.get() == and \ ...
_node_add_with_peer_list Low-level api: Apply delta child_other to child_self when child_self is the peer of child_other. Element child_self and child_other are list nodes. Element child_self will be modified during the process. RFC6020 section 7.8.6 is a reference of this method. ...
316
def evaluate_scpd_xml(url): try: res = requests.get(url, timeout=2) except requests.exceptions.RequestException as err: _LOGGER.error( "When trying to request %s the following error occurred: %s", url, err) raise ConnectionError if res.status_code =...
Get and evaluate SCPD XML to identified URLs. Returns dictionary with keys "host", "modelName", "friendlyName" and "presentationURL" if a Denon AVR device was found and "False" if not.
317
def delete_rich_menu(self, rich_menu_id, timeout=None): self._delete( .format(rich_menu_id=rich_menu_id), timeout=timeout )
Call delete rich menu API. https://developers.line.me/en/docs/messaging-api/reference/#delete-rich-menu :param str rich_menu_id: ID of an uploaded rich menu :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a (conne...
318
def deactivate(self): LOGGER.debug("> Deactivating Component.".format(self.__class__.__name__)) self.__engine = None self.__settings = None self.__settings_section = None self.__script_editor = None self.activated = False return True
Deactivates the Component. :return: Method success. :rtype: bool
319
def adduser(username, uid=None, system=False, no_login=True, no_password=False, group=False, gecos=None, **kwargs): return _format_cmd(, username, __system=bool(system), __uid=uid, __group=bool(group), __gid=uid, no_login=(no_login, _NO_CREATE_HOME, _NO_LOGIN), __d...
Formats an ``adduser`` command. :param username: User name. :type username: unicode | str :param uid: Optional user id to use. :type uid: long | int :param system: Create a system user account. :type system: bool :param no_login: Disable the login for this user. Not compatible with CentOS. ...
320
def transaction(self): self._depth -= 1 raise except: self._depth -= 1 if self._depth == 0: self.mdr.rollback() raise if self._depth == 0: ...
Sets up a context where all the statements within it are ran within a single database transaction. For internal use only.
321
def slides(self): sldIdLst = self._element.get_or_add_sldIdLst() self.part.rename_slide_parts([sldId.rId for sldId in sldIdLst]) return Slides(sldIdLst, self)
|Slides| object containing the slides in this presentation.
322
def job_conf(self, job_id): path = .format(jobid=job_id) return self.request(path)
A job configuration resource contains information about the job configuration for this job. :param str job_id: The job id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response`
323
def get_agg_data(cls, obj, category=None): paths = [] if isinstance(obj, Graph): obj = obj.edgepaths kdims = list(obj.kdims) vdims = list(obj.vdims) dims = obj.dimensions()[:2] if isinstance(obj, Path): glyph = for p in obj.sp...
Reduces any Overlay or NdOverlay of Elements into a single xarray Dataset that can be aggregated.
324
def list_spiders(self, project): url = self._build_url(constants.LIST_SPIDERS_ENDPOINT) params = {: project} json = self.client.get(url, params=params, timeout=self.timeout) return json[]
Lists all known spiders for a specific project. First class, maps to Scrapyd's list spiders endpoint.
325
def retry(func, exception_type, quit_event): while True: if quit_event.is_set(): raise StopIteration try: return func() except exception_type: pass
Run the function, retrying when the specified exception_type occurs. Poll quit_event on each iteration, to be responsive to an external exit request.
326
def eigh(a, eigvec=True, rcond=None): a = numpy.asarray(a) if a.dtype != object: val, vec = numpy.linalg.eigh(a) return (val, vec) if eigvec else val amean = gvar.mean(a) if amean.ndim != 2 or amean.shape[0] != amean.shape[1]: raise ValueError( + str(a.shape)) if rcond i...
Eigenvalues and eigenvectors of symmetric matrix ``a``. Args: a: Two-dimensional, square Hermitian matrix/array of numbers and/or :class:`gvar.GVar`\s. Array elements must be real-valued if `gvar.GVar`\s are involved (i.e., symmetric matrix). eigvec (bool): If ``...
327
def store_records_for_package(self, entry_point, records): pkg_module_records = self._dist_to_package_module_map(entry_point) pkg_module_records.extend(records)
Store the records in a way that permit lookup by package
328
def get_params(self, deep=False): attrs = self.__dict__ for attr in self._include: attrs[attr] = getattr(self, attr) if deep is True: return attrs return dict([(k,v) for k,v in list(attrs.items()) \ if (k[0] != ) \ ...
returns a dict of all of the object's user-facing parameters Parameters ---------- deep : boolean, default: False when True, also gets non-user-facing paramters Returns ------- dict
329
def fetch_existing_token_of_user(self, client_id, grant_type, user_id): token_data = self.fetchone(self.fetch_existing_token_of_user_query, client_id, grant_type, user_id) if token_data is None: raise AccessTokenNotFound scopes = self._fe...
Retrieve an access token issued to a client and user for a specific grant. :param client_id: The identifier of a client as a `str`. :param grant_type: The type of grant. :param user_id: The identifier of the user the access token has been issued to. :ret...
330
def parse_uniprot_txt_file(infile): uniprot_metadata_dict = {} metadata = old_parse_uniprot_txt_file(infile) metadata_keys = list(metadata.keys()) if metadata_keys: metadata_key = metadata_keys[0] else: return uniprot_metadata_dict uniprot_metadata_dict[] = len(str(metada...
Parse a raw UniProt metadata file and return a dictionary. Args: infile: Path to metadata file Returns: dict: Metadata dictionary
331
def splitEkmDate(dateint): date_str = str(dateint) dt = namedtuple(, [, , , , , , ]) if len(date_str) != 14: dt.yy = dt.mm = dt.dd = dt.weekday = dt.hh = dt.minutes = dt.ss = 0 return dt dt.yy = int(date_str[0:2]) dt.mm = int(date_str[2:4]) ...
Break out a date from Omnimeter read. Note a corrupt date will raise an exception when you convert it to int to hand to this method. Args: dateint (int): Omnimeter datetime as int. Returns: tuple: Named tuple which breaks out as followws: ========...
332
def rsa_base64_decrypt(self, cipher, b64=True): with open(self.key_file) as fp: key_ = RSA.importKey(fp.read()) _cip = PKCS1_v1_5.new(key_) cipher = base64.b64decode(cipher) if b64 else cipher plain = _cip.decrypt(cipher, Random.new().read(15 + SHA.digest...
先base64 解码 再rsa 解密数据
333
def clearAdvancedActions( self ): self._advancedMap.clear() margins = list(self.getContentsMargins()) margins[2] = 0 self.setContentsMargins(*margins)
Clears out the advanced action map.
334
def select_if(df, fun): def _filter_f(col): try: return fun(df[col]) except: return False cols = list(filter(_filter_f, df.columns)) return df[cols]
Selects columns where fun(ction) is true Args: fun: a function that will be applied to columns
335
def forecast(stl, fc_func, steps=10, seasonal=False, **fc_func_kwargs): forecast_array = np.array([]) trend_array = stl.trend for step in range(steps): pred = fc_func(np.append(trend_array, forecast_array), **fc_func_kwargs) forecast_array = ...
Forecast the given decomposition ``stl`` forward by ``steps`` steps using the forecasting function ``fc_func``, optionally including the calculated seasonality. This is an additive model, Y[t] = T[t] + S[t] + e[t] Args: stl (a modified statsmodels.tsa.seasonal.DecomposeResult): STL decomposi...
336
def all(self): url = "{url_base}/resource/{pid}/files/".format(url_base=self.hs.url_base, pid=self.pid) r = self.hs._request(, url) return r
:return: array of file objects (200 status code)
337
def make_jira_blueprint( base_url, consumer_key=None, rsa_key=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, storage=None, ): if rsa_key and os.path.isfile(rsa_key): with open(rsa_key) as f: rsa_key = f...
Make a blueprint for authenticating with JIRA using OAuth 1. This requires a consumer key and RSA key for the JIRA application link. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables :envvar:`JIRA_OAUTH_CONSUMER_KEY` and :e...
338
def deletePartials(self): if self.dryrun: self._client.listPartials() else: self._client.deletePartials()
Delete any old partial uploads/downloads in path.
339
def items(iterable): if hasattr(iterable, ): return (p for p in iterable.iteritems()) elif hasattr(iterable, ): return (p for p in iterable.items()) else: return (p for p in enumerate(iterable))
Iterates over the items of a sequence. If the sequence supports the dictionary protocol (iteritems/items) then we use that. Otherwise we use the enumerate built-in function.
340
def get_part_name(self, undefined=""): return _undefined_pattern( "".join(self.get_subfields("245", "n")), lambda x: x.strip() == "", undefined )
Args: undefined (optional): Argument, which will be returned if the `part_name` record is not found. Returns: str: Name of the part of the series. or `undefined` if `part_name`\ is not found.
341
def register_phonon_task(self, *args, **kwargs): kwargs["task_class"] = PhononTask return self.register_task(*args, **kwargs)
Register a phonon task.
342
def get_default_saver(max_to_keep: int=3) -> tf.train.Saver: return tf.train.Saver(max_to_keep=max_to_keep)
Creates Tensorflow Saver object with 3 recent checkpoints to keep. :param max_to_keep: Maximum number of recent checkpoints to keep, defaults to 3
343
def generate_stimfunction(onsets, event_durations, total_time, weights=[1], timing_file=None, temporal_resolution=100.0, ): if timing_file is not Non...
Return the function for the timecourse events When do stimuli onset, how long for and to what extent should you resolve the fMRI time course. There are two ways to create this, either by supplying onset, duration and weight information or by supplying a timing file (in the three column format used by F...
344
def to_text(self, tree, force_root=False): self.extract_tag_metadata(tree) text = [] attributes = [] comments = [] blocks = [] if not (self.ignores.match(tree) if self.ignores else None): capture = self.captures.match(tree) if self.cap...
Extract text from tags. Skip any selectors specified and include attributes if specified. Ignored tags will not have their attributes scanned either.
345
def find_analyses(ar_or_sample): bc = api.get_tool(CATALOG_ANALYSIS_REQUEST_LISTING) ar = bc(portal_type=, id=ar_or_sample) if len(ar) == 0: ar = bc(portal_type=, getClientSampleID=ar_or_sample) if len(ar) == 1: obj = ar[0].getObject() analyses = obj.getAnalyses(full_objects...
This function is used to find keywords that are not on the analysis but keywords that are on the interim fields. This function and is is_keyword function should probably be in resultsimport.py or somewhere central where it can be used by other instrument interfaces.
346
def match_similar(base, items): finds = list(find_similar(base, items)) if finds: return max(finds, key=base.similarity) return None
Get the most similar matching item from a list of items. @param base: base item to locate best match @param items: list of items for comparison @return: most similar matching item or None
347
def dcounts(self): print("WARNING: Distinct value count for all tables can take a long time...", file=sys.stderr) sys.stderr.flush() data = [] for t in self.tables(): for c in t.columns(): data.append([t.name(), c.name(), c.dcount(), t.size(), c.dcou...
:return: a data frame with names and distinct counts and fractions for all columns in the database
348
def select_unrectified_slitlet(image2d, islitlet, csu_bar_slit_center, params, parmodel, maskonly): if image2d.shape != (EMIR_NAXIS2, EMIR_NAXIS1): raise ValueError("NAXIS1, NAXIS2 unexpected for EMIR detector") image2d_output = np.zeros_like(image2d) ...
Returns image with the indicated slitlet (zero anywhere else). Parameters ---------- image2d : numpy array Initial image from which the slitlet data will be extracted. islitlet : int Slitlet number. csu_bar_slit_center : float CSU bar slit center. params : :class:`~lmfit...
349
def CreateJarBuilder(env): try: java_jar = env[][] except KeyError: fs = SCons.Node.FS.get_default_fs() jar_com = SCons.Action.Action(, ) java_jar = SCons.Builder.Builder(action = jar_com, suffix = , ...
The Jar builder expects a list of class files which it can package into a jar file. The jar tool provides an interface for passing other types of java files such as .java, directories or swig interfaces and will build them to class files in which it can package into the jar.
350
def _init_data_map(self): if self._data_map is not None: return if self._xml_tree is None: agis_root = ARCGIS_ROOTS[0] else: agis_root = get_element_name(self._xml_tree) if agis_root not in ARCGIS_ROOTS: raise Inva...
OVERRIDDEN: Initialize required FGDC data map with XPATHS and specialized functions
351
def printBoundingBox(self): print ("Bounding Latitude: ") print (self.startlatitude) print (self.endlatitude) print ("Bounding Longitude: ") print (self.startlongitude) print (self.endlongitude)
Print the bounding box that this DEM covers
352
def Send(self, url, opname, pyobj, nsdict={}, soapaction=None, chain=None, **kw): url = url or self.url cookies = None if chain is not None: cookies = chain.flow.cookies d = {} d.update(self.nsdict) d.update(nsdict) ...
Returns a ProcessingChain which needs to be passed to Receive if Send is being called consecutively.
353
def __delete_action(self, revision): delete_response = yield self.collection.delete(revision.get("master_id")) if delete_response.get("n") == 0: raise DocumentRevisionDeleteFailed()
Handle a delete action to a partiular master id via the revision. :param dict revision: :return:
354
def columnSchema(self): if self._columnSchema is None: ctx = SparkContext._active_spark_context jschema = ctx._jvm.org.apache.spark.ml.image.ImageSchema.columnSchema() self._columnSchema = _parse_datatype_json_string(jschema.json()) return self._columnSchema
Returns the schema for the image column. :return: a :class:`StructType` for image column, ``struct<origin:string, height:int, width:int, nChannels:int, mode:int, data:binary>``. .. versionadded:: 2.4.0
355
def update(self, unique_name=values.unset, default_ttl=values.unset, callback_url=values.unset, geo_match_level=values.unset, number_selection_behavior=values.unset, intercept_callback_url=values.unset, out_of_session_callback_url=values.unset, ...
Update the ServiceInstance :param unicode unique_name: An application-defined string that uniquely identifies the resource :param unicode default_ttl: Default TTL for a Session, in seconds :param unicode callback_url: The URL we should call when the interaction status changes :param Ser...
356
def get_lazystring_encoder(app): from speaklater import _LazyString class JSONEncoder(app.json_encoder): def default(self, o): if isinstance(o, _LazyString): return text_type(o) return super(JSONEncoder, self).default(o) return JSONEncoder
Return a JSONEncoder for handling lazy strings from Babel. Installed on Flask application by default by :class:`InvenioI18N`.
357
def clear(self, exclude=None): if exclude is None: self.cache = {} else: self.cache = {k: v for k, v in self.cache.items() if k in exclude}
Remove all elements in the cache.
358
def on_message(self, message): msg = tornado.escape.json_decode(message) if msg[] == : if self.application.verbose: print(msg[]) self.config = list(yaml.load_all(msg[])) if len(self.config) > 1: error = if...
Receiving a message from the websocket, parse, and act accordingly.
359
def cleanup_dead_jobs(): from .models import WooeyJob inspect = celery_app.control.inspect() active_tasks = {task[] for worker, tasks in six.iteritems(inspect.active()) for task in tasks} active_jobs = WooeyJob.objects.filter(status=WooeyJob.RUNNING) to_disable = set() for job i...
This cleans up jobs that have been marked as ran, but are not queue'd in celery. It is meant to cleanup jobs that have been lost due to a server crash or some other reason a job is in limbo.
360
def partial_fit(self, X, y=None, classes=None, **fit_params): if not self.initialized_: self.initialize() self.notify(, X=X, y=y) try: self.fit_loop(X, y, **fit_params) except KeyboardInterrupt: pass self.notify(, X=X, y=y) re...
Fit the module. If the module is initialized, it is not re-initialized, which means that this method should be used if you want to continue training a model (warm start). Parameters ---------- X : input data, compatible with skorch.dataset.Dataset By default, ...
361
def compute_number_edges(function): n = 0 for node in function.nodes: n += len(node.sons) return n
Compute the number of edges of the CFG Args: function (core.declarations.function.Function) Returns: int
362
def reversed(self): return Arc(self.end, self.radius, self.rotation, self.large_arc, not self.sweep, self.start)
returns a copy of the Arc object with its orientation reversed.
363
def resolve_identifier(self, name, expected_type=None): name = str(name) if name in self._known_identifiers: obj = self._known_identifiers[name] if expected_type is not None and not isinstance(obj, expected_type): raise UnresolvedIdentifierError(u"Ident...
Resolve an identifier to an object. There is a single namespace for identifiers so the user also should pass an expected type that will be checked against what the identifier actually resolves to so that there are no surprises. Args: name (str): The name that we want to res...
364
def log_event(self, text, timestamp=None): try: text = text.encode("mbcs") except LookupError: text = text.encode("ascii") comment = b"Added by python-can" marker = b"python-can" data = GLOBAL_MARKER_STRUCT.pack( 0, 0xFFFF...
Add an arbitrary message to the log file as a global marker. :param str text: The group name of the marker. :param float timestamp: Absolute timestamp in Unix timestamp format. If not given, the marker will be placed along the last message.
365
def dict_dot(d, k, val=None, default=None): if val is None and k == : return d def set_default(dict_or_model, key, default_value): if isinstance(dict_or_model, models.Model): if not hasattr(dict_or_model, key): setattr(dict_or_model, key, default_value)...
Get or set value using a dot-notation key in a multilevel dict.
366
def q12d_local(vertices, lame, mu): M = lame + 2*mu R_11 = np.matrix([[2, -2, -1, 1], [-2, 2, 1, -1], [-1, 1, 2, -2], [1, -1, -2, 2]]) / 6.0 R_12 = np.matrix([[1, 1, -1, -1], [-1, -1, 1, 1], ...
Local stiffness matrix for two dimensional elasticity on a square element. Parameters ---------- lame : Float Lame's first parameter mu : Float shear modulus See Also -------- linear_elasticity Notes ----- Vertices should be listed in counter-clockwise order:: ...
367
def write_calculations_to_csv(funcs, states, columns, path, headers, out_name, metaids=[], extension=".xls"): if not isinstance(funcs, list): funcs = [funcs] * len(headers) if not isinstance(states, list): states = [states] * len(headers) if not isinstanc...
Writes each output of the given functions on the given states and data columns to a new column in the specified output file. Note: Column 0 is time. The first data column is column 1. :param funcs: A function or list of functions which will be applied in order to the data. If only one function is given it...
368
def diagonal_line(xi=None, yi=None, *, ax=None, c=None, ls=None, lw=None, zorder=3): if ax is None: ax = plt.gca() if xi is None: xi = ax.get_xlim() if yi is None: yi = ax.get_ylim() if c is None: c = matplotlib.rcParams["grid.color"] if ls is None: ...
Plot a diagonal line. Parameters ---------- xi : 1D array-like (optional) The x axis points. If None, taken from axis limits. Default is None. yi : 1D array-like The y axis points. If None, taken from axis limits. Default is None. ax : axis (optional) Axis to plot on. If non...
369
def notify( self, force_notify=None, use_email=None, use_sms=None, email_body_template=None, **kwargs, ): email_sent = None sms_sent = None use_email = use_email or getattr(settings, "EMAIL_ENABLED", False) use_sms = use_sms or...
Notify / send an email and/or SMS. Main entry point. This notification class (me) knows from whom and to whom the notifications will be sent. See signals and kwargs are: * history_instance * instance * user
370
def trace(): def fget(self): return self._options.get(, None) def fset(self, value): self._options[] = value return locals()
Enables and disables request tracing.
371
def parse_acl(acl_string): if not acl_string: return [ALLOW_ALL] aces_list = acl_string.replace(, ).split() aces_list = [ace.strip().split(, 2) for ace in aces_list if ace] aces_list = [(a, b, c.split()) for a, b, c in aces_list] result_acl = [] for action_str, princ_str, perms in...
Parse raw string :acl_string: of RAML-defined ACLs. If :acl_string: is blank or None, all permissions are given. Values of ACL action and principal are parsed using `actions` and `special_principals` maps and are looked up after `strip()` and `lower()`. ACEs in :acl_string: may be separated by new...
372
def orcid_uri_to_orcid(value): "Strip the uri schema from the start of ORCID URL strings" if value is None: return value replace_values = [, ] for replace_value in replace_values: value = value.replace(replace_value, ) return value
Strip the uri schema from the start of ORCID URL strings
373
def __iter_read_spectrum_meta(self): mz_group = int_group = None slist = None elem_iterator = self.iterparse(self.filename, events=("start", "end")) if sys.version_info > (3,): _, self.root = next(elem_iterator) else: _, self.root = elem_iterator...
This method should only be called by __init__. Reads the data formats, coordinates and offsets from the .imzML file and initializes the respective attributes. While traversing the XML tree, the per-spectrum metadata is pruned, i.e. the <spectrumList> element(s) are left behind empty. Supported ...
374
def delete_eventtype(self, test_type_str=None): if test_type_str: answer = test_type_str, True else: answer = QInputDialog.getText(self, , s name to delete') if answer[1]: self.annot.remove_event_type(answer[0...
Action: create dialog to delete event type.
375
def introspect_access_token(self, access_token_value): if access_token_value not in self.access_tokens: raise InvalidAccessToken(.format(access_token_value)) authz_info = self.access_tokens[access_token_value] introspection = {: authz_info[] >= int(time.time())} ...
Returns authorization data associated with the access token. See <a href="https://tools.ietf.org/html/rfc7662">"Token Introspection", Section 2.2</a>.
376
def _reload(self): ConfigModel = apps.get_model() cache = {} data = dict( ConfigModel.objects .all() .values_list(, )) for form_class in self._registry: empty_form = form_class() cach...
Gets every registered form's field value.\ If a field name is found in the db, it will load it from there.\ Otherwise, the initial value from the field form is used
377
def open(self): try: self.project.open_main(self.filename) except UnicodeDecodeError: with open(self.filename, ) as openfile: encoding = get_encoding(openfile.read()) try: self.project.open_main(self.filename, encoding) ...
Open the subtitle file into an Aeidon project.
378
def from_gpx(gpx_segment): points = [] for point in gpx_segment.points: points.append(Point.from_gpx(point)) return Segment(points)
Creates a segment from a GPX format. No preprocessing is done. Arguments: gpx_segment (:obj:`gpxpy.GPXTrackSegment`) Return: :obj:`Segment`
379
def get_options(self): args = self.parse_options(self.args) if args: self.directory = args[0] if self.develop: self.skiptag = True if not self.develop: self.develop = self.defaults.develop if not self.develop: self.infofl...
Process the command line.
380
def _get_mean(self, vs30, mag, rrup, imt, scale_fac): C_HR, C_BC, C_SR, SC = self._extract_coeffs(imt) rrup = self._clip_distances(rrup) f0 = self._compute_f0_factor(rrup) f1 = self._compute_f1_factor(rrup) f2 = self._compute_f2_factor(rrup) pga_bc = self._get...
Compute and return mean
381
def plot_forest( data, kind="forestplot", model_names=None, var_names=None, combined=False, credible_interval=0.94, rope=None, quartiles=True, ess=False, r_hat=False, colors="cycle", textsize=None, linewidth=None, markersize=None, ridgeplot_alpha=None, rid...
Forest plot to compare credible intervals from a number of distributions. Generates a forest plot of 100*(credible_interval)% credible intervals from a trace or list of traces. Parameters ---------- data : obj or list[obj] Any object that can be converted to an az.InferenceData object ...
382
def _timeout_thread(self, remain): time.sleep(remain) if not self._ended: self._ended = True self._release_all()
Timeout before releasing every thing, if nothing was returned
383
def raise_if(self, exception, message, *args, **kwargs): if issubclass(exception, self.minimum_defect): raise exception(*args, **kwargs) warn(message, SyntaxWarning, *args, **kwargs)
If current exception has smaller priority than minimum, subclass of this class only warns user, otherwise normal exception will be raised.
384
def k8s_ports_to_metadata_ports(k8s_ports): ports = [] for k8s_port in k8s_ports: if k8s_port.protocol is not None: ports.append("%s/%s" % (k8s_port.port, k8s_port.protocol.lower())) else: ports.append(str(k8s_port.port)) return ports
:param k8s_ports: list of V1ServicePort :return: list of str, list of exposed ports, example: - ['1234/tcp', '8080/udp']
385
def set_widgets(self): self.parent.step_fc_agglayer_from_canvas.\ list_compatible_canvas_layers() lst_wdg = self.parent.step_fc_agglayer_from_canvas.lstCanvasAggLayers if lst_wdg.count(): self.rbAggLayerFromCanvas.setText(tr( ...
Set widgets on the Aggregation Layer Origin Type tab.
386
def summary(self): if self.hasSummary: if self.numClasses <= 2: return BinaryLogisticRegressionTrainingSummary(super(LogisticRegressionModel, self).summary) else: return Logistic...
Gets summary (e.g. accuracy/precision/recall, objective history, total iterations) of model trained on the training set. An exception is thrown if `trainingSummary is None`.
387
def set_creator(self, value: Union[Literal, Identifier, str], lang: str= None): self.metadata.add(key=DC.creator, value=value, lang=lang)
Set the DC Creator literal value :param value: Value of the creator node :param lang: Language in which the value is
388
def get_clan(self, tag: crtag, timeout: int=None): url = self.api.CLAN + + tag return self._get_model(url, FullClan, timeout=timeout)
Get inforamtion about a clan Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV timeout: Optional[int] = None Custom timeout that overwrites Client.timeout
389
def CSWAP(control, target_1, target_2): qubits = [unpack_qubit(q) for q in (control, target_1, target_2)] return Gate(name="CSWAP", params=[], qubits=qubits)
Produces a controlled-SWAP gate. This gate conditionally swaps the state of two qubits:: CSWAP = [[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], ...
390
def whitelisted(argument=None): def is_whitelisted(remote_ip, whitelist): user_ip = ipaddr.IPv4Address(remote_ip) if any([user_ip in ipaddr.IPv4Network(entry) for entry in whitelist]): return True return False if type(argument) is types...
Decorates a method requiring that the requesting IP address is whitelisted. Requires a whitelist value as a list in the Application.settings dictionary. IP addresses can be an individual IP address or a subnet. Examples: ['10.0.0.0/8','192.168.1.0/24', '1.2.3.4/32'] :param list argument: L...
391
def insertDataset(self, businput): if not ("primary_ds_name" in businput and "dataset" in businput and "dataset_access_type" in businput and "processed_ds_name" in businput ): dbsExceptionHandler(, "business/DBSDataset/insertDataset must have dataset,\ datas...
input dictionary must have the following keys: dataset, primary_ds_name(name), processed_ds(name), data_tier(name), acquisition_era(name), processing_version It may have following keys: physics_group(name), xtcrosssection, creation_date, create_by, last_modification_date, last_m...
392
def _get_model(vehicle): model = vehicle[] model = model.replace(vehicle[], ) model = model.replace(vehicle[], ) return model.strip().split()[0]
Clean the model field. Best guess.
393
def mkdir(self, path, parents=True, mode=0o755, raise_if_exists=False): if not parents or raise_if_exists: warnings.warn() permission = int(oct(mode)[2:]) self.client.makedirs(path, permission=permission)
Has no returnvalue (just like WebHDFS)
394
def cur_time(typ=, tz=DEFAULT_TZ, trading=True, cal=): dt = pd.Timestamp(, tz=tz) if typ == : if trading: return trade_day(dt=dt, cal=cal).strftime() else: return dt.strftime() if typ == : return dt.strftime() if typ == : return dt.strftime() if typ == : return dt return ...
Current time Args: typ: one of ['date', 'time', 'time_path', 'raw', ''] tz: timezone trading: check if current date is trading day cal: trading calendar Returns: relevant current time or date Examples: >>> cur_dt = pd.Timestamp('now') >>> cur_time(t...
395
def _worker_queue_scheduled_tasks(self): queues = set(self._filter_queues(self.connection.smembers( self._key(SCHEDULED)))) now = time.time() for queue in queues: self._did_work = True
Helper method that takes due tasks from the SCHEDULED queue and puts them in the QUEUED queue for execution. This should be called periodically.
396
def insertTopLevelItem( self, index, item ): self.treeWidget().insertTopLevelItem(index, item) if self.updatesEnabled(): try: item.sync(recursive = True) except AttributeError: pass
Inserts the inputed item at the given index in the tree. :param index | <int> item | <XGanttWidgetItem>
397
def make_symbols(symbols, *args): if (hasattr(symbols, ) and not any(symbols)) \ or (isinstance(symbols, (list, tuple, Mapping)) and not symbols): return [] if isinstance(symbols, basestring): return [s.upper().strip() for s in (symbols.split(...
Return a list of uppercase strings like "GOOG", "$SPX, "XOM"... Arguments: symbols (str or list of str): list of market ticker symbols to normalize If `symbols` is a str a get_symbols_from_list() call is used to retrieve the list of symbols Returns: list of str: list of cananical ticker sy...
398
def win_menu_select_item(title, *items, **kwargs): text = kwargs.get("text", "") if not (0 < len(items) < 8): raise ValueError("accepted none item or number of items exceed eight") f_items = [LPCWSTR(item) for item in items] for i in xrange(8 - len(f_items)): f_items.append(LPCWSTR(...
Usage: win_menu_select_item("[CLASS:Notepad]", "", u"文件(&F)", u"退出(&X)") :param title: :param text: :param items: :return:
399
def handle_no_start_state(self): start_state = self.get_start_state(set_final_outcome=True) while not start_state: execution_signal = state_machine_execution_engine.handle_execution_mode(self) if execution_signal is StateMachineExecutionStatus.STOPPED: ...
Handles the situation, when no start state exists during execution The method waits, until a transition is created. It then checks again for an existing start state and waits again, if this is not the case. It returns the None state if the the state machine was stopped.