Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
349,600
def effective_value(self): raw_value = self.actual if raw_value is None: raw_value = self.def_val return self._normalize(raw_value)
Read/write |float| representing normalized adjustment value for this adjustment. Actual values are a large-ish integer expressed in shape coordinates, nominally between 0 and 100,000. The effective value is normalized to a corresponding value nominally between 0.0 and 1.0. Intuitively th...
349,601
def working_dir(val, **kwargs): try: is_abs = os.path.isabs(val) except AttributeError: is_abs = False if not is_abs: raise SaltInvocationError({0}\.format(val)) return val
Must be an absolute path
349,602
def validate(self, input): self._serializer(input) if self._extraValidator is not None: self._extraValidator(input)
Validate the given input value against this L{Field} definition. @param input: An input value supposedly serializable by this L{Field}. @raises ValidationError: If the value is not serializable or fails to be validated by the additional validator.
349,603
def _sam_to_soft_clipped(self, sam): if sam.is_unmapped: raise Error() if sam.cigar is None or len(sam.cigar) == 0: return False, False return (sam.cigar[0][0] == 4, sam.cigar[-1][0] == 4)
Returns tuple of whether or not the left and right end of the mapped read in the sam record is soft-clipped
349,604
def send_offset_commit_request(self, group, payloads=None, fail_on_error=True, callback=None, group_generation_id=-1, consumer_id=): group = _coerce_consumer_group(group) encoder = partial(K...
Send a list of OffsetCommitRequests to the Kafka broker for the given consumer group. Args: group (str): The consumer group to which to commit the offsets payloads ([OffsetCommitRequest]): List of topic, partition, offsets to commit. fail_on_error (bool): Wheth...
349,605
def gen_lines(self, block, indent): prefix1 = indent + self.PS1 prefix2 = indent + self.PS2 prefix = prefix1 for line in block: if line.startswith(prefix): yield line[len(prefix):] elif line == prefix.rstrip() + u"\n": yiel...
Generates lines as expected by tokenize from a list of lines. This strips the first len(indent + self.PS1) characters off each line.
349,606
def p_type_def_4(t): id = t[2] body = t[3] lineno = t.lineno(1) if id_unique(id, , lineno): name_dict[id] = union_info(id, body, lineno)
type_def : UNION ID union_body SEMI
349,607
def add(self, full_name, repetition_type, type): base_name = self.element.name simple_name = relative_field(full_name, base_name) path = split_field(simple_name) output = self if len(path) == 0: return output._add_one(, full_name, repetition_type, type) ...
:param full_name: dot delimited path to the property (use dot (".") for none) :param repetition_type: one of OPTIONAL or NESTED (REQUIRED is not possible) :param json_type: the json type to store :return:
349,608
def print_page(text): color_re = re.compile(r"\[(?P<color>[FB]G_[A-Z_]+|NORMAL)\]") width = max([len(strip_colors(x)) for x in text.splitlines()]) print("\n" + hbar(width)) for line in text.splitlines(): if line == "[HBAR]": print(hbar(width)) continue ...
Format the text and prints it on stdout. Text is formatted by adding a ASCII frame around it and coloring the text. Colors can be added to text using color tags, for example: My [FG_BLUE]blue[NORMAL] text. My [BG_BLUE]blue background[NORMAL] text.
349,609
def _allocate_output(self, windows, shape): missing_value = self.missing_value outputs = self.outputs if outputs is not NotSpecified: out = recarray( shape, formats=[self.dtype.str] * len(outputs), names=outputs, ) ...
Allocate an output array whose rows should be passed to `self.compute`. The resulting array must have a shape of ``shape``. If we have standard outputs (i.e. self.outputs is NotSpecified), the default is an empty ndarray whose dtype is ``self.dtype``. If we have an outputs tuple, the ...
349,610
def _parse_single_request_trap_errors(cls, request_data): try: method, params, request_id = cls._parse_single_request(request_data) return method, params, request_id, None except errors.RPCFault as ex: return None, None, ex.request_id, ex
Traps exceptions generated by __parse_single_request and converts them into values of request_id and error in the returned tuple. :Returns: (method_name, params_object, request_id, error) Where: - method_name is a str (or None when error is set) -...
349,611
def tran(inimage,outimage,direction=,x=None,y=None, coords=None, coordfile=None,colnames=None,separator=None, precision=6, output=None,verbose=True): single_coord = False if coords is not None and coordfile is None: coordfile = coords warnings.simplefilter(,Deprecation...
Primary interface to perform coordinate transformations in pixel coordinates between 2 images using STWCS and full distortion models read from each image's header.
349,612
def removeAxis(self, axis): if not isinstance(axis, XChartAxis): axis = self.axis(nativestring(axis)) try: self._axes.remove(axis) except ValueError: pass
Removes an axis from this chart either by direct reference or by name. :param axis | <projexui.widgets.XChartAxis> || <str>
349,613
def isInteractive(): if sys.stdout.isatty() and os.name != : try: import threading except ImportError: return False else: return True else: return False
A basic check of if the program is running in interactive mode
349,614
def get_resource_path(venv, package=None, resource=None): * _verify_safe_py_code(package, resource) bin_path = _verify_virtualenv(venv) ret = __salt__[]( bin_path, "print(pkg_resources.resource_filename(, ))".format( ...
Return the path to a package resource installed inside a virtualenv .. versionadded:: 2015.5.0 venv Path to the virtualenv package Name of the package in which the resource resides .. versionadded:: 2016.3.0 resource Name of the resource of which the path is to be re...
349,615
def sumSeriesWithWildcards(requestContext, seriesList, *positions): newSeries = {} newNames = list() for series in seriesList: newname = .join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name....
Call sumSeries after inserting wildcards at the given position(s). Example:: &target=sumSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1) This would be the equivalent of:: &target=sumSeries(host.*.cpu-user.value)&target=sumSeries( ...
349,616
def update(self, friendly_name=values.unset, customer_name=values.unset, street=values.unset, city=values.unset, region=values.unset, postal_code=values.unset, emergency_enabled=values.unset, auto_correct_address=values.unset): data = values.of({ ...
Update the AddressInstance :param unicode friendly_name: A string to describe the resource :param unicode customer_name: The name to associate with the address :param unicode street: The number and street address of the address :param unicode city: The city of the address :param...
349,617
def predict(self, n_periods=10, exogenous=None, return_conf_int=False, alpha=0.05): check_is_fitted(self, ) if not isinstance(n_periods, (int, long)): raise TypeError("n_periods must be an int or a long") exogenous = self._check_exog(exogenous) ...
Forecast future values Generate predictions (forecasts) ``n_periods`` in the future. Note that if ``exogenous`` variables were used in the model fit, they will be expected for the predict procedure and will fail otherwise. Parameters ---------- n_periods : int, optional...
349,618
def strip_column_names(cols, keep_paren_contents=True): new_cols = [ _strip_column_name(col, keep_paren_contents=keep_paren_contents) for col in cols] if len(new_cols) != len(set(new_cols)): warn_str = warn_str += warnings.warn(warn_str, Warning) pr...
Utility script for renaming pandas columns to patsy-friendly names. Revised names have been: - stripped of all punctuation and whitespace (converted to text or `_`) - converted to lower case Takes a list of column names, returns a dict mapping names to revised names. If there are any ...
349,619
def load_targets(self): ldap_services = [] if self.ldap: ldap_services = self.search.get_services(ports=[389], up=True) self.ldap_strings = ["ldap://{}".format(service.address) for service in ldap_services] self.services = self.search.get_services(tags=[]) s...
load_targets will load the services with smb signing disabled and if ldap is enabled the services with the ldap port open.
349,620
def create_from_table(cls, tab_e): convert_sed_cols(tab_e) try: emin = np.array(tab_e[].to(u.MeV)) emax = np.array(tab_e[].to(u.MeV)) except: emin = np.array(tab_e[]) emax = np.array(tab_e[]) ne = len(emin) try: ...
Parameters ---------- tab_e : `~astropy.table.Table` EBOUNDS table.
349,621
def wrap_parser_error(self, data, renderer_context): response = renderer_context.get("response", None) status_code = response and response.status_code if status_code != 400: raise WrapperNotApplicable() if list(data.keys()) != []: raise WrapperNotAppli...
Convert parser errors to the JSON API Error format Parser errors have a status code of 400, like field errors, but have the same native format as generic errors. Also, the detail message is often specific to the input, so the error is listed as a 'detail' rather than a 'title'.
349,622
def getQuotes(symbols): yahoo-financegooglefinanceAAPLIndexNASDAQLastTradeWithCurrency129.09LastTradeDateTime2015-03-02T16:04:29ZLastTradePrice129.09Yield1.46LastTradeTime4:04PM ESTLastTradeDateTimeLongMar 2, 4:04PM ESTDividend0.47StockSymbolAAPLID22144AAPLGOOGIndexNASDAQLastTradeWithCurrency129.09LastTradeDateTime...
get real-time quotes (index, last trade price, last trade time, etc) for stocks, using google api: http://finance.google.com/finance/info?client=ig&q=symbols Unlike python package 'yahoo-finance' (15 min delay), There is no delay for NYSE and NASDAQ stocks in 'googlefinance' package. example: quotes = get...
349,623
def exec_create(self, container, cmd, stdout=True, stderr=True, stdin=False, tty=False, privileged=False, user=, environment=None, workdir=None, detach_keys=None): if environment is not None and utils.version_lt(self._version, ): raise errors.Invalid...
Sets up an exec instance in a running container. Args: container (str): Target container where exec instance will be created cmd (str or list): Command to be executed stdout (bool): Attach to stdout. Default: ``True`` stderr (bool): Attach to stde...
349,624
def clear(self): self.points = [] self.vectors = [] self.point_style = [] self.annotations = []
Resets Bloch sphere data sets to empty.
349,625
def ssl_context(self, verify=True, cert_reqs=None, check_hostname=False, certfile=None, keyfile=None, cafile=None, capath=None, cadata=None, **kw): assert ssl, cafile = cafile or DEFAULT_CA_BUNDLE_PATH if verify is True: cert_reqs = ...
Create a SSL context object. This method should not be called by from user code
349,626
def long_press(self, x: int, y: int, duration: int = 1000) -> None: self._execute(, self.device_sn, , , , str(x), str(y), str(x), str(y), str(duration))
Simulate finger long press somewhere. (1000ms = 1s)
349,627
def last_continuous_indexes_slice(ol,value): length = ol.__len__() end = None slice = [] for i in range(length-1,-1,-1): if(ol[i]==value): end = i break else: pass if(end == None): return(None) else: slice.append(end) ...
from elist.elist import * ol = [1,"a","a",2,3,"a",4,"a","a","a",5] last_continuous_indexes_slice(ol,"a")
349,628
def visualize(self, format=): import ibis.expr.visualize as viz path = viz.draw(viz.to_graph(self), format=format) webbrowser.open(.format(os.path.abspath(path)))
Visualize an expression in the browser as an SVG image. Parameters ---------- format : str, optional Defaults to ``'svg'``. Some additional formats are ``'jpeg'`` and ``'png'``. These are specified by the ``graphviz`` Python library. Notes --...
349,629
def read(self, link): with contextlib.closing(self.open(link)) as fp: return fp.read()
Return the binary content associated with the link. :param link: The :class:`Link` to read.
349,630
def OrEvent(*events): or_event = threading.Event() def changed(): bools = [event_i.is_set() for event_i in events] if any(bools): or_event.set() else: or_event.clear() for event_i in events: orify(event_i, changed) ...
Parameters ---------- events : list(threading.Event) List of events. Returns ------- threading.Event Event that is set when **at least one** of the events in :data:`events` is set.
349,631
def set_bio_assembly_trans(self, bio_assembly_index, input_chain_indices, input_transform): this_bioass = None for bioass in self.bio_assembly: if bioass[] == str(bio_assembly_index): this_bioass = bioass break if not this_bioass: ...
Set the Bioassembly transformation information. A single bioassembly can have multiple transforms, :param bio_assembly_index: the integer index of the bioassembly :param input_chain_indices: the list of integer indices for the chains of this bioassembly :param input_transformation: the list of d...
349,632
def find_usedby(self, depslock_file_path, property_validate=True): if depslock_file_path is None: self._raw = [self._params] self._raw[0][] = None self._raw[0][] = None else: self._raw = [x for x in self._downloader.common_parser.iter_packages_par...
Find all dependencies by package :param depslock_file_path: :param property_validate: for `root` packages we need check property, bad if we find packages from `lock` file, we can skip validate part :return:
349,633
def createNetwork(self, data, headers=None, query_params=None, content_type="application/json"): uri = self.client.base_url + "/network" return self.client.post(uri, data, headers, query_params, content_type)
Create a new network It is method for POST /network
349,634
def copy(self, key): copy = Set(key=key, db=self.db) copy.clear() copy |= self return copy
Copy the set to another key and return the new Set. WARNING: If the key exists, it overwrites it.
349,635
def DeregisterPlugin(cls, plugin_class): name = getattr( plugin_class, , plugin_class.__name__) name = name.lower() if name not in cls._plugins: raise KeyError( .format(name)) del cls._plugins[name] if name in cls._file_system_plugins: del cls._file_system_plugin...
Deregisters an preprocess plugin class. Args: plugin_class (type): preprocess plugin class. Raises: KeyError: if plugin class is not set for the corresponding name. TypeError: if the source type of the plugin class is not supported.
349,636
def _get_snmp(self, oid): if self.snmp_version in ["v1", "v2c"]: return self._get_snmpv2c(oid) else: return self._get_snmpv3(oid)
Wrapper for generic SNMP call.
349,637
def filter_tasks(self, filter_dict): query_args = taskw.utils.encode_query(filter_dict, self.get_version()) return self._get_task_objects( , *query_args )
Return a filtered list of tasks from taskwarrior. Filter dict should be a dictionary mapping filter constraints with their values. For example, to return only pending tasks, you could use:: {'status': 'pending'} Or, to return tasks that have the word "Abjad" in their desc...
349,638
def _set_selinux_context(self): chcon_command_exists() if self.selinux_context: logger.debug("setting SELinux context of %s to %s", self.path, self.selinux_context) run_cmd(["chcon", self.selinux_context, self.path]) if any([self.selinux_user, self.selin...
Set SELinux context or fields using chcon program. Raises CommandDoesNotExistException if the command is not present on the system. :return: None
349,639
def _create_placeholders(self): self.input_data = tf.placeholder( tf.int32, [self.batch_size, self.num_steps]) self.input_labels = tf.placeholder( tf.int32, [self.batch_size, self.num_steps])
Create the computational graph's placeholders.
349,640
def log_likelihood_bits(eval_data, predictions, scores, learner=): return (np.array(scores) / np.log(2.0)).tolist()
Return the log likelihood of each correct output in base 2 (bits), computed from the scores in `scores` (which should be in base e, nats). >>> bits = log_likelihood_bits(None, None, [np.log(0.5), np.log(0.125), np.log(0.25)]) >>> [round(b) for b in bits] [-1.0, -3.0, -2.0]
349,641
def end_episode(self): self.evaluation_buffer.reset_local_buffers() for agent_id in self.cumulative_rewards: self.cumulative_rewards[agent_id] = 0 for agent_id in self.episode_steps: self.episode_steps[agent_id] = 0
A signal that the Episode has ended. The buffer must be reset. Get only called when the academy resets.
349,642
def request_host(request): url = request.get_full_url() parse_result = compat.urlparse.urlparse(url) scheme, host, port = parse_result.scheme, parse_result.hostname, parse_result.port try: port = int(port) except ValueError: pass if host == "": host = request.get_hea...
Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison.
349,643
def hwvtep_activate_hwvtep(self, **kwargs): name = kwargs.pop() name_args = dict(name=name) method_name = method_class = self._brocade_tunnels gw_attr = getattr(method_class, method_name) config = gw_attr(**name_args) output = self._callback(config) ...
Activate the hwvtep Args: name (str): overlay_gateway name callback (function): A function executed upon completion of the method. Returns: Return value of `callback`. Raises: None
349,644
def check_log(logfile, exited=, successful=, exists=True): if not os.path.exists(logfile): return not exists if exited in open(logfile).read(): return elif successful in open(logfile).read(): return else: return
Often logfile doesn't exist because the job hasn't begun to run. It is unclear what you want to do in that case... Parameters ---------- logfile : str String with path to logfile exists : bool Is the logfile required to exist exited : str String in logfile used to dete...
349,645
def create_user_deliveryserver(self, domainid, data): return self.api_call( ENDPOINTS[][], dict(domainid=domainid), body=data)
Create a user delivery server
349,646
def washburn(target, surface_tension=, contact_angle=, diameter=): r network = target.project.network phase = target.project.find_phase(target) element, sigma, theta = _get_key_props(phase=phase, diameter=diameter, ...
r""" Computes the capillary entry pressure assuming the throat in a cylindrical tube. Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides access to other ne...
349,647
def spin_first(f, self, *args, **kwargs): self.spin() return f(self, *args, **kwargs)
Call spin() to sync state prior to calling the method.
349,648
def SRU_Compute_CPU(activation_type, d, bidirectional=False, scale_x=1): def sru_compute_cpu(u, x, bias, init=None, mask_h=None): bidir = 2 if bidirectional else 1 length = x.size(0) if x.dim() == 3 else 1 batch = x.size(-2) k = u.size(-1) // d // bidir if mask_h is No...
CPU version of the core SRU computation. Has the same interface as SRU_Compute_GPU() but is a regular Python function instead of a torch.autograd.Function because we don't implement backward() explicitly.
349,649
def save_hash(self, repo: str, branch: str, git_repo: Repo): if self.single_pull: repo_id = self.repo_id(repo) self._current_hashes[repo_id][branch] = git_repo.head.object.hexsha
If ``single_pull`` is enabled, saves the current git hash of the specified repository/branch combination, to indicate that it shouldn't be pull again.
349,650
def fetch_module(self, module): tm = int(time.time()) datestamp = datetime.utcfromtimestamp(tm).isoformat() filename = "lime-{0}-{1}.ko".format(datestamp, module[]) url = "{0}/{1}".format(self.url, module[]) logger.info("downloading {0} as {1}".format(url, filename)) ...
Download and verify kernel module :type module: str :param module: kernel module path
349,651
def declared_symbols(self): return self.local_declared_symbols | ( self.parent.declared_symbols if self.parent else set())
Return all local symbols here, and also of the parents
349,652
def logs_sidecars_experiments(experiment_name: str, experiment_uuid: str, job_uuid: str, log_lines: Optional[Union[str, Iterable[str]]]) -> None: handle_experiment_job_log(experiment_name=experiment_name, ...
Signal handling for sidecars logs.
349,653
def add_label_work_count(self): self._logger.info() def add_label_text_count(df): work_maxima = df.groupby(constants.WORK_FIELDNAME, sort=False).any() df.loc[:, constants.LABEL_WORK_COUNT_FIELDNAME] = work_maxima[ con...
Adds to each result row a count of the number of works within the label contain that n-gram. This counts works that have at least one witness carrying the n-gram. This correctly handles cases where an n-gram has only zero counts for a given work (possible with zero-fill followe...
349,654
def load(self, filename): try: with open(filename, ) as fp: self.counters = cPickle.load(fp) except: logging.debug("can't load counter from file: %s", filename) return False return True
Load counters to file
349,655
def xcom_push( self, key, value, execution_date=None): if execution_date and execution_date < self.execution_date: raise ValueError( .format( self.execution_date, execution_date)) ...
Make an XCom available for tasks to pull. :param key: A key for the XCom :type key: str :param value: A value for the XCom. The value is pickled and stored in the database. :type value: any pickleable object :param execution_date: if provided, the XCom will not be vi...
349,656
def _get_object_as_soft(self): soft = [] if self.database is not None: soft.append(self.database._get_object_as_soft()) soft += ["^%s = %s" % (self.geotype, self.name), self._get_metadata_as_string()] for gsm in itervalues(self.gsms): sof...
Get object as SOFT formatted string.
349,657
def update_product_set( self, product_set, location=None, product_set_id=None, update_mask=None, project_id=None, retry=None, timeout=None, metadata=None, ): client = self.get_conn() product_set = self.product_set_name_...
For the documentation see: :class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionProductSetUpdateOperator`
349,658
def WalkTree(top, getChildren: Callable = None, getFirstChild: Callable = None, getNextSibling: Callable = None, yieldCondition: Callable = None, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF): if maxDepth <= 0: return depth = 0 if getChildren: if includeTop: if not y...
Walk a tree not using recursive algorithm. top: a tree node. getChildren: function(treeNode) -> list. getNextSibling: function(treeNode) -> treeNode. getNextSibling: function(treeNode) -> treeNode. yieldCondition: function(treeNode, depth) -> bool. includeTop: bool, if True yield top first. ...
349,659
def context_changed(self, context): self._image.set_cmap(context[]) self._image.set_clim(context[], context[]) self._image.set_interpolation(context[]) self._update_indicators(context) self._set_view_limits() if self._model.index_direction is not SliceDirection...
:type context: dict
349,660
def dataframe(self): if self._dataframe is None: try: import pandas as pd except ImportError: raise RuntimeError( pip install datadotworld[pandas]\) self._dataframe = pd.DataFrame.from_records(self....
Build and cache a dataframe from query results
349,661
def BivariateGaussian(x, y, mu_x, mu_y, sig_x, sig_y, rho): exponent = - 1 / (2 * (1 - rho**2)) exponent *= (x - mu_x)**2 / sig_x**2 + (y - mu_y)**2 / sig_y**2 \ - 2 * rho * (x - mu_x) * (y - mu_y) / (sig_x * sig_y) return sympy.exp(exponent) / (2 * sympy.pi * sig_x * sig_y * sympy.sqrt...
Bivariate Gaussian pdf. :param x: :class:`symfit.core.argument.Variable` :param y: :class:`symfit.core.argument.Variable` :param mu_x: :class:`symfit.core.argument.Parameter` for the mean of `x` :param mu_y: :class:`symfit.core.argument.Parameter` for the mean of `y` :param sig_x: :class:`symfit.co...
349,662
def ae(actual, predicted): return np.abs(np.array(actual)-np.array(predicted))
Computes the absolute error. This function computes the absolute error between two numbers, or for element between a pair of lists or numpy arrays. Parameters ---------- actual : int, float, list of numbers, numpy array The ground truth value predicted : same type as actual ...
349,663
def pgettext(self, context, string, domain=None, **variables): t = self.get_translations(domain) return t.upgettext(context, string) % variables
Like :meth:`gettext` but with a context.
349,664
def factored_joint_mvn(distributions): graph_parents = [tensor for distribution in distributions for tensor in distribution._graph_parents] with tf.compat.v1.name_scope(, values=graph_parents): dtype = tf.debugging.assert_same_float_dtype(distributions) broadcas...
Combine MultivariateNormals into a factored joint distribution. Given a list of multivariate normal distributions `dist[i] = Normal(loc[i], scale[i])`, construct the joint distribution given by concatenating independent samples from these distributions. This is multivariate normal with mean vector given by...
349,665
def inspect_node_neighborhood(nlinks, msinds, node_msindex): node_neighbor_edges = get_neighborhood_edes(nlinks, node_msindex) node_neighbor_seeds = np.zeros_like(msinds, dtype=np.int8) for neighboor_ind in np.unique(node_neighbor_edges[:, :2].ravel()): node_neighbor_ind = np.w...
Get information about one node in graph :param nlinks: neighboorhood edges :param msinds: indexes in 3d image :param node_msindex: int, multiscale index of selected voxel :return: node_neighboor_edges_and_weights, node_neighboor_seeds
349,666
def avail_sizes(call=None): if call == : raise SaltCloudSystemExit( ) conn = get_conn() data = conn.list_role_sizes() ret = {} for item in data.role_sizes: ret[item.name] = object_to_dict(item) return ret
Return a list of sizes from Azure
349,667
def get_nanopubstore_start_dt(url: str): hostname = urllib.parse.urlsplit(url)[1] start_dates_doc = state_mgmt.get(start_dates_doc_key) if start_dates_doc and start_dates_doc.get("start_dates"): date = [ dt["start_dt"] for dt in start_dates_doc["start_dates"] ...
Get last start_dt recorded for getting new nanopub ID's
349,668
def _submit( self, metric_name, message, send_histograms_buckets=True, send_monotonic_counter=False, custom_tags=None, hostname=None, ): if message.type < len(self.METRIC_TYPES): for metric in message.metric: custom...
For each metric in the message, report it as a gauge with all labels as tags except if a labels dict is passed, in which case keys are label names we'll extract and corresponding values are tag names we'll use (eg: {'node': 'node'}). Histograms generate a set of values instead of a unique metri...
349,669
def sync_balancer_files(self): def sync(): for balancer in self.configurables[Balancer].values(): balancer.sync_file(self.configurables[Cluster].values()) self.work_pool.submit(sync)
Syncs the config files for each present Balancer instance. Submits the work to sync each file as a work pool job.
349,670
def message_callback_add(self, sub, callback): if callback is None or sub is None: raise ValueError("sub and callback must both be defined.") self._callback_mutex.acquire() for i in range(0, len(self.on_message_filtered)): if self.on_message_filtered[i][0] == su...
Register a message callback for a specific topic. Messages that match 'sub' will be passed to 'callback'. Any non-matching messages will be passed to the default on_message callback. Call multiple times with different 'sub' to define multiple topic specific callbacks. ...
349,671
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.
349,672
def uniq(objs): done = set() for obj in objs: if obj in done: continue done.add(obj) yield obj return
Eliminates duplicated elements.
349,673
def parse_condition(self, condition): if isinstance(condition, bytes): sql = " where {}".format(condition) elif isinstance(condition, dict): conditions = [] for k, v in condition.iteritems(): if isinstance(v, unicode): v = ...
.. :py:method:: parse the condition, support string and dictonary
349,674
def add_rotating_file_handler(logger=None, file_path="out.log", level=logging.INFO, log_format=log_formats.easy_read, max_bytes=10*sizes.mb, backup_count=5, **handler_kwargs): if not isinstan...
Adds a rotating file handler to the specified logger. :param logger: logging name or object to modify, defaults to root logger :param file_path: path to file to log to :param level: logging level to set handler at :param log_format: log formatter :param max_bytes: Max file size in bytes before rota...
349,675
def open(cls, dbfile, encoding=None, fieldnames_lower=True, case_sensitive=True): if not case_sensitive: if isinstance(dbfile, string_types): dbfile = pick_name(dbfile, listdir(path.dirname(dbfile))) with open(dbfile, ) as f: yield cls(f, encoding=encodi...
Context manager. Allows opening a .dbf file. .. code-block:: with Dbf.open('some.dbf') as dbf: ... :param str|unicode|file dbfile: .dbf filepath or a file-like object. :param str|unicode encoding: Encoding used by DB. This will be used if there's no en...
349,676
def remove_named_query(self, alias, afterwards=None): if self.ro: raise DatabaseROError() self.writequeue.append((, afterwards, + alias, ))
remove a named query from the notmuch database. :param alias: name of shortcut :type alias: str :param afterwards: callback to trigger after adding the alias :type afterwards: callable or None
349,677
def connect_head_namespaced_pod_proxy(self, name, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.connect_head_namespaced_pod_proxy_with_http_info(name, namespace, **kwargs) else: (data) = self.connect_head_namespaced_pod_proxy_with_http_info(n...
connect HEAD requests to proxy of Pod This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_head_namespaced_pod_proxy(name, namespace, async_req=True) >>> result = thread.get() :param as...
349,678
def find_common_beginning(string_list, boundary_char = None): common= if len(string_list) > 1: shortestLen = min([len(el) for el in string_list]) for idx in range(shortestLen): chars = [s[idx] for s in string_list] if chars.count(chars[0]) != ...
Given a list of strings, finds finds the longest string that is common to the *beginning* of all strings in the list. boundary_char defines a boundary that must be preserved, so that the common string removed must end with this char.
349,679
def __delete_file(self, file): for file_node in self.__script_editor.model.get_file_nodes(file, self.__script_editor.model.root_node): self.__script_editor.unregister_node_path(file_node) self.__delete_path(file) if self.__script_editor.model.is_authoring_node(file_...
Deletes given file. :param file: File to delete. :type file: unicode
349,680
def _estimate_bkg_rms(self, xmin, xmax, ymin, ymax): data = self.global_data.data_pix[ymin:ymax, xmin:xmax] pixels = np.extract(np.isfinite(data), data).ravel() if len(pixels) < 4: bkg, rms = np.NaN, np.NaN else: pixels.sort() p25 = pixels[int...
Estimate the background noise mean and RMS. The mean is estimated as the median of data. The RMS is estimated as the IQR of data / 1.34896. Parameters ---------- xmin, xmax, ymin, ymax : int The bounding region over which the bkg/rms will be calculated. Retu...
349,681
def _create_subset_file(in_file, het_region_bed, work_dir, data): cnv_regions = shared.get_base_cnv_regions(data, work_dir) region_bed = bedutils.intersect_two(het_region_bed, cnv_regions, work_dir, data) out_file = os.path.join(work_dir, "%s-origsubset.bcf" % utils.splitext_plus(os.path.basename(in_fi...
Subset the VCF to a set of pre-calculated smaller regions.
349,682
def rate_limited(max_per_second): min_interval = 1.0 / float(max_per_second) def decorate(func): last_time_called = [0.0] rate_lock = threading.Lock() def rate_limited_function(*args, **kargs): try: rate_lock.acquire(True) elapsed = ti...
This decorator limits how often a method can get called in a second. If the limit is exceeded, the call will be held in a queue until enough time has passed. Useful when trying to avoid overloading a system with rapid calls.
349,683
def send_iq_and_wait_for_reply(self, iq, *, timeout=None): warnings.warn( r"send_iq_and_wait_for_reply is deprecated and will be removed in" r" 1.0", DeprecationWarning, stacklevel=1, ) return (yield from...
Send an IQ stanza `iq` and wait for the response. If `timeout` is not :data:`None`, it must be the time in seconds for which to wait for a response. If the response is a ``"result"`` IQ, the value of the :attr:`~aioxmpp.IQ.payload` attribute is returned. Otherwise, the exception...
349,684
def write_to_file(self): bt = BatchFile(self.batch_name_value, self.p_values, self.x_value, self.y_value, self.g_value, self.s_value, self.z_value, self.wavelength_values, self.verbose_value, self.phytoplankton_path, self.bottom_path, self.nb_cpu, self.exec...
This function calls "gui_batch.py" with inputs values to write the batch file.
349,685
def iter_object_acl(root): for obj in iter_object_graph(root): for ace in parse_acl(getattr(obj, , ())): yield ace
Child-first discovery of ACEs for an object. Walks the ACL graph via ``__acl_bases__`` and yields the ACEs parsed from ``__acl__`` on each object.
349,686
def _GetDecodedStreamSize(self): self._file_object.seek(0, os.SEEK_SET) self._decoder = self._GetDecoder() self._decoded_data = b encoded_data_offset = 0 encoded_data_size = self._file_object.get_size() decoded_stream_size = 0 while encoded_data_offset < encoded_data_size: read...
Retrieves the decoded stream size. Returns: int: decoded stream size.
349,687
def sort_request(request: Dict[str, Any]) -> OrderedDict: sort_order = ["jsonrpc", "method", "params", "id"] return OrderedDict(sorted(request.items(), key=lambda k: sort_order.index(k[0])))
Sort a JSON-RPC request dict. This has no effect other than making the request nicer to read. >>> json.dumps(sort_request( ... {'id': 2, 'params': [2, 3], 'method': 'add', 'jsonrpc': '2.0'})) '{"jsonrpc": "2.0", "method": "add", "params": [2, 3], "id": 2}' Args: request: J...
349,688
def _normalize_entity(value): if ndb is not None and isinstance(value, ndb.Model): return None if getattr(value, "_populate_internal_entity", None): return value._populate_internal_entity() return value
Return an entity from an entity or model instance.
349,689
def angledependentabsorption_errorprop(twotheta, dtwotheta, transmission, dtransmission): return (angledependentabsorption(twotheta, transmission), _calc_angledependentabsorption_error(twotheta, dtwotheta, transmission, dtransmission))
Correction for angle-dependent absorption of the sample with error propagation Inputs: twotheta: matrix of two-theta values dtwotheta: matrix of absolute error of two-theta values transmission: the transmission of the sample (I_after/I_before, or exp(-mu*d)) dtransmissio...
349,690
def create_hist(self, evclass, evtype, xsep, energy, ctheta, fill_sep=False, fill_evtype=False): nevt = len(evclass) ebin = utils.val_to_bin(self._energy_bins, energy) scale = self._psf_scale[ebin] vals = [energy, ctheta] bins = [self._energy_bins, ...
Load into a histogram.
349,691
def process(self, value, tag=None): content = Content(tag=tag, value=value) result = Core.process(self, content) return result
Process (marshal) the tag with the specified value using the optional type information. @param value: The value (content) of the XML node. @type value: (L{Object}|any) @param tag: The (optional) tag name for the value. The default is value.__class__.__name__ @type ta...
349,692
def show_rules(cls, *names, attr=None): from qnet.printing import srepr try: if attr is None: attr = cls._rules_attr() rules = getattr(cls, attr) except TypeError: rules = {} for (name, rule) in rules.items(): if le...
Print algebraic rules used by :class:`create` Print a summary of the algebraic rules with the given names, or all rules if not names a given. Args: names (str): Names of rules to show attr (None or str): Name of the class attribute from which to get the ...
349,693
def reset(project, user): d = Project.path(project, user) + "output" if os.path.isdir(d): shutil.rmtree(d) os.makedirs(d) else: raise flask.abort(404) if os.path.exists(Project.path(project, user) + ".done"): os.unlink(Project.path...
Reset system, delete all output files and prepare for a new run
349,694
def get_instance(self, payload): return FeedbackInstance( self._version, payload, account_sid=self._solution[], message_sid=self._solution[], )
Build an instance of FeedbackInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance
349,695
def sha1(s): h = hashlib.new() h.update(s) return h.hexdigest()
Returns a sha1 of the given string
349,696
def _update_kind_map(cls): cls._kind_map[cls._class_name()] = cls class_key = cls._class_key() if class_key: cls._class_map[tuple(class_key)] = cls
Override; called by Model._fix_up_properties(). Update the kind map as well as the class map, except for PolyModel itself (its class key is empty). Note that the kind map will contain entries for all classes in a PolyModel hierarchy; they all have the same kind, but different class names. PolyModel c...
349,697
def encode(self, data: mx.sym.Symbol, data_length: mx.sym.Symbol, seq_len: int) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, int]: embedding = mx.sym.swapaxes(data=self.sym, dim1=1, dim2=3) embedding = mx.sym.swapaxes(data=embedding, dim...
Encodes data given sequence lengths of individual examples and maximum sequence length. :param data: Ignored. Assume that the input is the image. :param data_length: Vector with sequence lengths. :param seq_len: Maximum sequence length. :return: Encoded versions of input data data, data...
349,698
def _set_details(self, content): try: self.details = str(content) except UnicodeEncodeError: if sys.version_info < (3, 0): self.details = unicode(content) else: logging.error( ...
Sets the `details` field. Args: content: the content to extract details from.
349,699
def admin_tools_render_dashboard_module(context, module): module.init_with_context(context) context.update({ : module.template, : module, : reverse( % get_admin_site_name(context)), }) return context
Template tag that renders a given dashboard module, it takes a ``DashboardModule`` instance as first parameter.