Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
370,700
def sf01(arr): s = arr.shape return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])
swap and then flatten axes 0 and 1
370,701
def propose_unif(self): while True: u = self.ell.sample(rstate=self.rstate) if unitcheck(u, self.nonperiodic): break return u, self.ell.axes
Propose a new live point by sampling *uniformly* within the ellipsoid.
370,702
def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True): evals_result = {} self.classes_ = list(np.unique(y)) self.n_classes_ = len(self.classes_) if self.n_classes_ > 2: sel...
Fit gradient boosting classifier Parameters ---------- X : array_like Feature matrix y : array_like Labels sample_weight : array_like Weight for each instance eval_set : list, optional A list of (X, y) pairs to use as a val...
370,703
def read_sql( sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None, ): _, _, _, kwargs = inspect.getargvalues(inspect.currentframe()) return DataFrame(query_compiler=BaseFactory.read_sql(**kwargs))
Read SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name. con: SQLAlchemy connectable (engine/connection) or database string URI or DBAPI2 connection (fallback mode) index_col: Column(s) to...
370,704
def bgr2rgb(self): new_data = cv2.cvtColor(self.raw_data, cv2.COLOR_BGR2RGB) return ColorImage(new_data, frame=self.frame, encoding=)
Converts data using the cv conversion.
370,705
def customData( self, key, default = None ): return self._customData.get(nativestring(key), default)
Return the custom data that is stored on this node for the \ given key, returning the default parameter if none was found. :param key <str> :param default <variant> :return <variant>
370,706
def read_wait_cell(self): table_state = self.bt_table.read_row( TABLE_STATE, filter_=bigtable_row_filters.ColumnRangeFilter( METADATA, WAIT_CELL, WAIT_CELL)) if table_state is None: utils.dbg( ) return None ...
Read the value of the cell holding the 'wait' value, Returns the int value of whatever it has, or None if the cell doesn't exist.
370,707
def set_header(self, msg): self.s.move(1, 0) self.overwrite_line(msg, attr=curses.A_NORMAL)
Set second head line text
370,708
def create(context, name): result = tag.create(context, name=name) utils.format_output(result, context.format)
create(context, name) Create a tag. >>> dcictl tag-create [OPTIONS] :param string name: Name of the tag [required]
370,709
def dist_calc_matrix(surf, cortex, labels, exceptions = [, ], verbose = True): cortex_vertices, cortex_triangles = surf_keep_cortex(surf, cortex) label_list = sd.load.get_freesurfer_label(labels, verbose = False) rs = np.where([a not in exceptions for a in label_list])[0] rois = [label_list[...
Calculate exact geodesic distance along cortical surface from set of source nodes. "labels" specifies the freesurfer label file to use. All values will be used other than those specified in "exceptions" (default: 'Unknown' and 'Medial_Wall'). returns: dist_mat: symmetrical nxn matrix of minimum dista...
370,710
def raw_value(self): if self.parent_setting is not None: return self.parent_setting.raw_value[self.full_name] else: return getattr(settings, self.full_name)
Property to return the variable defined in ``django.conf.settings``. Returns: object: the variable defined in ``django.conf.settings``. Raises: AttributeError: if the variable is missing. KeyError: if the item is missing from nested setting.
370,711
def _build_row(self, row, parent, align, border): tr = etree.SubElement(parent, ) tag = if parent.tag == : tag = cells = self._split_row(row, border) for i, a in enumerate(align): c = etree.SubElement(tr, tag) ...
Given a row of text, build table cells.
370,712
def _convert_md_type(self, type_to_convert: str): if type_to_convert in FILTER_TYPES: return FILTER_TYPES.get(type_to_convert) elif type_to_convert in FILTER_TYPES.values(): return [k for k, v in FILTER_TYPES.items() if v == type_to_convert][0] else: ...
Metadata types are not consistent in Isogeo API. A vector dataset is defined as vector-dataset in query filter but as vectorDataset in resource (metadata) details. see: https://github.com/isogeo/isogeo-api-py-minsdk/issues/29
370,713
def create(cls, interface_id, address=None, network_value=None, nodeid=1, **kw): data = {: address, : False, : False, : False, : False, : False, : False, : network_value, ...
:param int interface_id: interface id :param str address: address of this interface :param str network_value: network of this interface in cidr x.x.x.x/24 :param int nodeid: if a cluster, identifies which node this is for :rtype: dict
370,714
def get_scanner_param_mandatory(self, param): assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return False return entry.get()
Returns if a scanner parameter is mandatory.
370,715
def search_subscriptions(self, **kwargs): params = [(key, kwargs[key]) for key in sorted(kwargs.keys())] url = "/notification/v1/subscription?{}".format( urlencode(params, doseq=True)) response = NWS_DAO().getURL(url, self._read_headers) if response.status != 200: ...
Search for all subscriptions by parameters
370,716
def check(text): err = "pinker.latin" msg = "Use English. is the preferred form." list = [ ["other things being equal", ["ceteris paribus"]], ["among other things", ["inter alia"]], ["in and of itself", ["simpliciter"]], ["havin...
Suggest the preferred forms.
370,717
def BSR_Get_Row(A, i): blocksize = A.blocksize[0] BlockIndx = int(i/blocksize) rowstart = A.indptr[BlockIndx] rowend = A.indptr[BlockIndx+1] localRowIndx = i % blocksize indys = A.data[rowstart:rowend, localRowIndx, :].nonzero() z = A.data[rowstart:rowend, localRowIndx, :][indys[0...
Return row i in BSR matrix A. Only nonzero entries are returned Parameters ---------- A : bsr_matrix Input matrix i : int Row number Returns ------- z : array Actual nonzero values for row i colindx Array of column indices for the nonzeros of row i ...
370,718
def get_t_factor(t1, t2): t_factor = None if t1 is not None and t2 is not None and t1 != t2: dt = t2 - t1 year = timedelta(days=365.25) t_factor = abs(dt.total_seconds() / year.total_seconds()) return t_factor
Time difference between two datetimes, expressed as decimal year
370,719
def CheckCondition(condition, check_object): try: of = objectfilter.Parser(condition).Parse() compiled_filter = of.Compile(objectfilter.BaseFilterImplementation) return compiled_filter.Matches(check_object) except objectfilter.Error as e: raise ConditionError(e)
Check if a condition matches an object. Args: condition: A string condition e.g. "os == 'Windows'" check_object: Object to validate, e.g. an rdf_client.KnowledgeBase() Returns: True or False depending on whether the condition matches. Raises: ConditionError: If condition is bad.
370,720
def print_all(self, out=sys.stdout): THREAD_FUNC_NAME_LEN = 25 THREAD_NAME_LEN = 13 THREAD_ID_LEN = 15 THREAD_SCHED_CNT_LEN = 10 out.write(CRLF) out.write("name tid ttot scnt") out.write(CRLF) for stat in self: ...
Prints all of the thread profiler results to a given file. (stdout by default)
370,721
def decimal_field_data(field, **kwargs): min_value = 0 max_value = 10 from django.core.validators import MinValueValidator, MaxValueValidator for elem in field.validators: if isinstance(elem, MinValueValidator): min_value = elem.limit_value if isinstance(elem, MaxValueV...
Return random value for DecimalField >>> result = any_form_field(forms.DecimalField(max_value=100, min_value=11, max_digits=4, decimal_places = 2)) >>> type(result) <type 'str'> >>> from decimal import Decimal >>> Decimal(result) >= 11, Decimal(result) <= Decimal('99.99') (True, True)
370,722
def raw_sign(message, secret): digest = hmac.new(secret, message, hashlib.sha256).digest() return base64.b64encode(digest)
Sign a message.
370,723
def get_history_tags(self, exp, rep=0): history = self.get_history(exp, rep, ) return history.keys()
returns all available tags (logging keys) of the given experiment repetition. Note: Technically, each repetition could have different tags, therefore the rep number can be passed in as parameter, even though usually all repetitions have the same tags. The ...
370,724
def gen_zonal_stats( vectors, raster, layer=0, band=1, nodata=None, affine=None, stats=None, all_touched=False, categorical=False, category_map=None, add_stats=None, zone_func=None, raster_out=False, prefix=None, ...
Zonal statistics of raster values aggregated to vector geometries. Parameters ---------- vectors: path to an vector source or geo-like python objects raster: ndarray or path to a GDAL raster source If ndarray is passed, the ``affine`` kwarg is required. layer: int or string, optional ...
370,725
def batch( self, owner, action=None, attribute_write_type=None, halt_on_error=False, playbook_triggers_enabled=None, ): from .tcex_ti_batch import TcExBatch return TcExBatch( self, owner, action, attribute_write_type, halt_on_erro...
Return instance of Batch
370,726
def list_(env=None, user=None): cmd = _create_conda_cmd(, args=[], env=env, user=user) ret = _execcmd(cmd, user=user) if ret[] == 0: pkg_list = json.loads(ret[]) packages = {} for pkg in pkg_list: pkg_info = pkg.split() name, version, build = .join(pkg_in...
List the installed packages on an environment Returns ------- Dictionary: {package: {version: 1.0.0, build: 1 } ... }
370,727
def construct_all(templates, **unbound_var_values): def _merge_dicts(src, dst): for k, v in six.iteritems(src): if dst.get(k, v) != v: raise ValueError( % (k, v, dst[k])) else: dst[k] = v all_unbound_vars = {} context = {} for x in templates: i...
Constructs all the given templates in a single pass without redundancy. This is useful when the templates have a common substructure and you want the smallest possible graph. Args: templates: A sequence of templates. **unbound_var_values: The unbound_var values to replace. Returns: A list of resul...
370,728
def async_func(self, function): @wraps(function) def wrapped(*args, **kwargs): return self.submit(function, *args, **kwargs) return wrapped
Decorator for let a normal function return the NewFuture
370,729
def within_bounding_box(self, limits): is_valid = np.logical_and( self.catalogue.data[] >= limits[0], np.logical_and(self.catalogue.data[] <= limits[2], np.logical_and( self.catalogue.data[] >= limits[1], ...
Selects the earthquakes within a bounding box. :parameter limits: A list or a numpy array with four elements in the following order: - min x (longitude) - min y (latitude) - max x (longitude) - max y (latitude) :returns: ...
370,730
def read_rle_bit_packed_hybrid(file_obj, width, length=None): debug_logging = logger.isEnabledFor(logging.DEBUG) io_obj = file_obj if length is None: length = read_plain_int32(file_obj, 1)[0] raw_bytes = file_obj.read(length) if raw_bytes == b: return None io...
Read values from `fo` using the rel/bit-packed hybrid encoding. If length is not specified, then a 32-bit int is read first to grab the length of the encoded data.
370,731
def tyn_calus_scaling(target, DABo, To, mu_o, viscosity=, temperature=): r Ti = target[temperature] mu_i = target[viscosity] value = DABo*(Ti/To)*(mu_o/mu_i) return value
r""" Uses Tyn_Calus model to adjust a diffusion coeffciient for liquids from reference conditions to conditions of interest Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and al...
370,732
def recache(i): o=i.get(,) r=ck.access({:, :ck.cfg[]}) if r[]>0: return r l=r[] cru={} cri={} for ps in [0,1]: for q in l: if ps==0 or (ps==1 and q.get(,)!=): ruoa=q[] muoa=q[] duoa=q[]...
Input: {} Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 }
370,733
def get_default_config_help(self): config = super(TSDBHandler, self).get_default_config_help() config.update({ : , : , : , : , : , : , : , : , : , : True, : True,...
Returns the help text for the configuration options for this handler
370,734
def insertBulkBlock(self, blockDump): frst = True if (blockDump[][0][][0]).get() == None: frst = False redFlag = False if frst == True: eventCT = (fl.get() == None for f in blockDump[] for fl in f[]) else: ...
API to insert a bulk block :param blockDump: Output of the block dump command, example can be found in https://svnweb.cern.ch/trac/CMSDMWM/browser/DBS/trunk/Client/tests/dbsclient_t/unittests/blockdump.dict :type blockDump: dict
370,735
def _set_loam_show_debug_information(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=loam_show_debug_information.loam_show_debug_information, is_container=, presence=False, yang_name="loam-show-debug-information", rest_name="loam-show-debug-informatio...
Setter method for loam_show_debug_information, mapped from YANG variable /loam_show_debug_state/loam_show_debug_information (container) If this variable is read-only (config: false) in the source YANG file, then _set_loam_show_debug_information is considered as a private method. Backends looking to populate...
370,736
def get_kernel_spec(self, kernel_name): try: return super(EnvironmentKernelSpecManager, self).get_kernel_spec(kernel_name) except (NoSuchKernel, FileNotFoundError): venv_kernel_name = kernel_name.lower() specs = self.get_all_kernel_sp...
Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name is not found.
370,737
def touch(self, filepath): if self.is_ssh(filepath): self._check_ssh() remotepath = self._get_remote(filepath) stdin, stdout, stderr = self.ssh.exec_command("touch {}".format(remotepath)) stdin.close() else: os.system("touch {}".format...
Touches the specified file so that its modified time changes.
370,738
def _warn_if_not_at_expected_pos(self, expected_pos, end_of, start_of): diff = expected_pos - self.stream.tell() if diff != 0: logger.warning( "There are {} bytes between {} and {}".format(diff, end_of, start_of) )
Helper function to warn about unknown bytes found in the file
370,739
def get_cso_dataframe(self): assert self.jco is not None assert self.pst is not None weights = self.pst.observation_data.loc[self.jco.to_dataframe().index,"weight"].copy().values cso = np.diag(np.sqrt((self.qhalfx.x.dot(self.qhalfx.x.T))))/(float(self.pst.npar-1)) cso_df...
get a dataframe of composite observation sensitivity, as returned by PEST in the seo file. Note that this formulation deviates slightly from the PEST documentation in that the values are divided by (npar-1) rather than by (npar). The equation is cso_j = ((Q^1/2*J*J^T*Q^1/2)^1/2)_jj/(NP...
370,740
def daemons(self): for attr in dir(self): field = getattr(self, attr) if isinstance(field, Daemon): yield field
List of daemons for this module
370,741
def _create_packet(self, request): data_len = struct.pack(, len(request)) packet = b + data_len + request def ord23(x): if not isinstance(x, int): return ord(x) else: return x logger.debug(, packet) logger.debug(...
Create a formatted packet from a request. :type request: str :param request: Formatted zabbix request :rtype: str :return: Data packet for zabbix
370,742
def validate(self, value): val = super(SlavesValue, self).validate(value) slaves = val.replace(" ", "") slaves = filter(None, slaves.split()) slaves = [x.split(":") for x in slaves] res = list() for x in slaves: self._validate_ip(x[0]) if...
Accepts: str, unicode Returns: list of tuples in the format (ip, port)
370,743
def stmt_lambda_proc(self, inputstring, **kwargs): regexes = [] for i in range(len(self.stmt_lambdas)): name = self.stmt_lambda_name(i) regex = compile_regex(r"\b%s\b" % (name,)) regexes.append(regex) out = [] for line in inputstring.splitline...
Add statement lambda definitions.
370,744
def play_song(self, song, tempo=120, delay=0.05): if tempo <= 0: raise ValueError( % tempo) if delay < 0: raise ValueError( % delay) delay_ms = int(delay * 1000) meas_duration_ms = 60000 / tempo * 4 def beep_args(note, value): ...
Plays a song provided as a list of tuples containing the note name and its value using music conventional notation instead of numerical values for frequency and duration. It supports symbolic notes (e.g. ``A4``, ``D#3``, ``Gb5``) and durations (e.g. ``q``, ``h``). For an exhaustive lis...
370,745
async def logs( self, service_id: str, *, details: bool = False, follow: bool = False, stdout: bool = False, stderr: bool = False, since: int = 0, timestamps: bool = False, is_tty: bool = False, tail: str = "all" ) -> Union[str,...
Retrieve logs of the given service Args: details: show service context and extra details provided to logs follow: return the logs as a stream. stdout: return logs from stdout stderr: return logs from stderr since: return logs since this time, as a UNI...
370,746
def min_geodetic_distance(a, b): if isinstance(a, tuple): a = spherical_to_cartesian(a[0].flatten(), a[1].flatten()) if isinstance(b, tuple): b = spherical_to_cartesian(b[0].flatten(), b[1].flatten()) return cdist(a, b).min(axis=0)
Compute the minimum distance between first mesh and each point of the second mesh when both are defined on the earth surface. :param a: a pair of (lons, lats) or an array of cartesian coordinates :param b: a pair of (lons, lats) or an array of cartesian coordinates
370,747
def webify(v: Any, preserve_newlines: bool = True) -> str: nl = "<br>" if preserve_newlines else " " if v is None: return "" if not isinstance(v, str): v = str(v) return cgi.escape(v).replace("\n", nl).replace("\\n", nl)
Converts a value into an HTML-safe ``str`` (formerly, in Python 2: ``unicode``). Converts value ``v`` to a string; escapes it to be safe in HTML format (escaping ampersands, replacing newlines with ``<br>``, etc.). Returns ``""`` for blank input.
370,748
def calmarnorm(sharpe, T, tau = 1.0): return calmar(sharpe,tau)/calmar(sharpe,T)
Multiplicator for normalizing calmar ratio to period tau
370,749
def set_exit_handler(self): signal.signal(signal.SIGINT, self.manage_signal) signal.signal(signal.SIGTERM, self.manage_signal) signal.signal(signal.SIGHUP, self.manage_signal) signal.signal(signal.SIGQUIT, self.manage_signal)
Set the signal handler to manage_signal (defined in this class) Only set handlers for signal.SIGTERM, signal.SIGINT, signal.SIGUSR1, signal.SIGUSR2 :return: None
370,750
def format_name(format, name, target_type, prop_set): if __debug__: from ..build.property_set import PropertySet assert is_iterable_typed(format, basestring) assert isinstance(name, basestring) assert isinstance(target_type, basestring) assert isinstance(prop_set, Proper...
Given a target, as given to a custom tag rule, returns a string formatted according to the passed format. Format is a list of properties that is represented in the result. For each element of format the corresponding target information is obtained and added to the result string. For all, but the...
370,751
def loadStructuredPoints(filename): reader = vtk.vtkStructuredPointsReader() reader.SetFileName(filename) reader.Update() gf = vtk.vtkImageDataGeometryFilter() gf.SetInputConnection(reader.GetOutputPort()) gf.Update() return Actor(gf.GetOutput())
Load a ``vtkStructuredPoints`` object from file and return an ``Actor(vtkActor)`` object. .. hint:: |readStructuredPoints| |readStructuredPoints.py|_
370,752
def addSibling(self, elem): if elem is None: elem__o = None else: elem__o = elem._o ret = libxml2mod.xmlAddSibling(self._o, elem__o) if ret is None:raise treeError() __tmp = xmlNode(_obj=ret) return __tmp
Add a new element @elem to the list of siblings of @cur merging adjacent TEXT nodes (@elem may be freed) If the new element was already inserted in a document it is first unlinked from its existing context.
370,753
def _get_compute_func(self, nmr_samples, thinning, return_output): cl_func = + ( if return_output else ) + if return_output: cl_func += + str(thinning) + + str(thinning) + + str(thinning) + + str(self._nmr_params) + + str(thinning) + + str(nmr_samples) + cl_func += ...
Get the MCMC algorithm as a computable function. Args: nmr_samples (int): the number of samples we will draw thinning (int): the thinning factor we want to use return_output (boolean): if the kernel should return output Returns: mot.lib.cl_function.CLFun...
370,754
def buildlist(self, enabled): choice = [] for item in self.data: choice.append((item, False)) for item in enabled: choice.append((item, True)) items = [(tag, tag, sta) for (tag, sta) in choice] code, self.tags = self.d.buildlist( text=...
Run dialog buildlist
370,755
def nsamples_to_hourminsec(x, pos): h, m, s = hourminsec(x/16.0) return .format(h, m, s)
Convert axes labels to experiment duration in hours/minutes/seconds Notes ----- Matplotlib FuncFormatter function https://matplotlib.org/examples/pylab_examples/custom_ticker1.html
370,756
def create_ospf_profile(): OSPFDomainSetting.create(name=, abr_type=) ospf_domain = OSPFDomainSetting() ospf_profile = OSPFProfile.create(name=, domain_settings_ref=ospf_domain.href) print(ospf_profile)
An OSPF Profile contains administrative distance and redistribution settings. An OSPF Profile is applied at the engine level. When creating an OSPF Profile, you must reference a OSPFDomainSetting. An OSPFDomainSetting holds the settings of the area border router (ABR) type, throttle timer settings, ...
370,757
def to_wire(self, name, file, compress=None, origin=None, override_rdclass=None, want_shuffle=True): if not override_rdclass is None: rdclass = override_rdclass want_shuffle = False else: rdclass = self.rdclass file.seek(0, 2) ...
Convert the rdataset to wire format. @param name: The owner name of the RRset that will be emitted @type name: dns.name.Name object @param file: The file to which the wire format data will be appended @type file: file @param compress: The compression table to use; the default is...
370,758
def add_parameter(self, field_name, param_name, param_value): try: self.fields[field_name][][param_name] = param_value except Exception as ex: raise ScriptFieldsError("Error adding parameter %s with value %s :%s" % (param_name, param_value, ex)) return self
Add a parameter to a field into script_fields The ScriptFields object will be returned, so calls to this can be chained.
370,759
def sendtoaddress(self, recv_addr, amount, comment=""): return self.req("sendtoaddress", [recv_addr, amount, comment])
send ammount to address, with optional comment. Returns txid. sendtoaddress(ADDRESS, AMMOUNT, COMMENT)
370,760
def summary(self): res = ("nlive: {:d}\n" "niter: {:d}\n" "ncall: {:d}\n" "eff(%): {:6.3f}\n" "logz: {:6.3f} +/- {:6.3f}" .format(self.nlive, self.niter, sum(self.ncall), self.eff, self.logz[-1], self.log...
Return a formatted string giving a quick summary of the results.
370,761
def get_distribution_path(venv, distribution): * _verify_safe_py_code(distribution) bin_path = _verify_virtualenv(venv) ret = __salt__[]( bin_path, "print(pkg_resources.get_distribution().location)".format( distribution ) ) if ret[] != 0...
Return the path to a distribution installed inside a virtualenv .. versionadded:: 2016.3.0 venv Path to the virtualenv. distribution Name of the distribution. Note, all non-alphanumeric characters will be converted to dashes. CLI Example: .. code-block:: bash sal...
370,762
def _choice_getter(self): def get_group_member_element(obj): return obj.first_child_found_in(*self._member_nsptagnames) get_group_member_element.__doc__ = ( ) return get_group_member_element
Return a function object suitable for the "get" side of the property descriptor.
370,763
def UpdateAcqEraEndDate(self, acquisition_era_name ="", end_date=0): if acquisition_era_name =="" or end_date==0: dbsExceptionHandler(, "acquisition_era_name and end_date are required") conn = self.dbi.connection() tran = conn.begin() try: self.acqud.exec...
Input dictionary has to have the following keys: acquisition_era_name, end_date.
370,764
def get_repo_parent(path): if is_repo(path): return Local(path) elif not os.path.isdir(path): _rel = while path and path != : if is_repo(path): return Local(path) else: _rel = os.path.join(os.path.basename(path), _r...
Returns parent repo or input path if none found. :return: grit.Local or path
370,765
def send_invoice_email(self, invoice_id, email_dict): return self._create_post_request( resource=INVOICES, billomat_id=invoice_id, send_data=email_dict, command=EMAIL, )
Sends an invoice by email If you want to send your email to more than one persons do: 'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}} :param invoice_id: the invoice id :param email_dict: the email dict :return dict
370,766
def _make_connect(module, args, kwargs): return functools.partial(module.connect, *args, **kwargs)
Returns a function capable of making connections with a particular driver given the supplied credentials.
370,767
def _print_stats(self, env, stats): def _format_time(mins): mins = int(mins) if mins < MINS_IN_HOUR: time_str = .format(mins) else: hours = mins // MINS_IN_HOUR mins %= MINS_IN_HOUR if mi...
Prints statistic information using io stream. `env` ``Environment`` object. `stats` Tuple of task stats for each date.
370,768
def register(self, prefix, viewset, base_name=None): if base_name is None: base_name = prefix super(DynamicRouter, self).register(prefix, viewset, base_name) prefix_parts = prefix.split() if len(prefix_parts) > 1: prefix = prefix_parts[0] en...
Add any registered route into a global API directory. If the prefix includes a path separator, store the URL in the directory under the first path segment. Otherwise, store it as-is. For example, if there are two registered prefixes, 'v1/users' and 'groups', `directory` will lo...
370,769
def furthest_from_root(self): best = (self.root,0); d = dict() for node in self.traverse_preorder(): if node.edge_length is None: d[node] = 0 else: d[node] = node.edge_length if not node.is_root(): d[node] += d[...
Return the ``Node`` that is furthest from the root and the corresponding distance. Edges with no length will be considered to have a length of 0 Returns: ``tuple``: First value is the furthest ``Node`` from the root, and second value is the corresponding distance
370,770
def uint64(self, val): try: self.msg += [pack("!Q", val)] except struct.error: raise ValueError("Expected uint64") return self
append a frame containing a uint64
370,771
def add_lat_lon(self, lat, lon, precision=1e7): self._ef["GPS"][piexif.GPSIFD.GPSLatitudeRef] = "N" if lat > 0 else "S" self._ef["GPS"][piexif.GPSIFD.GPSLongitudeRef] = "E" if lon > 0 else "W" self._ef["GPS"][piexif.GPSIFD.GPSLongitude] = decimal_to_dms( abs(lon), int(precis...
Add lat, lon to gps (lat, lon in float).
370,772
def _list_objects(self, client_kwargs, path, max_request_entries): client_kwargs = client_kwargs.copy() if max_request_entries: client_kwargs[] = max_request_entries while True: with _handle_client_error(): response = self.client.list_objects_v2(...
Lists objects. args: client_kwargs (dict): Client arguments. path (str): Path relative to current locator. max_request_entries (int): If specified, maximum entries returned by request. Returns: generator of tuple: object name str, object ...
370,773
def acquire_read(self): self.monitor.acquire() while self.rwlock < 0 or self.writers_waiting: self.readers_ok.wait() self.rwlock += 1 self.monitor.release()
Acquire a read lock. Several threads can hold this typeof lock. It is exclusive with write locks.
370,774
def _set_disable_res(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=disable_res.disable_res, is_container=, presence=False, yang_name="disable-res", rest_name="disable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, registe...
Setter method for disable_res, mapped from YANG variable /ha/process_restart/disable_res (container) If this variable is read-only (config: false) in the source YANG file, then _set_disable_res is considered as a private method. Backends looking to populate this variable should do so via calling thisObj...
370,775
def connections_from_graph(env, G, edge_data=False): if not issubclass(G.__class__, (Graph, DiGraph)): raise TypeError("Graph structure must be derived from Networkxget_agentsenv' must have get_agents.") addrs = env.get_agents(addr=True) if len(addrs) != len(G): raise ValueError("The n...
Create connections for agents in the given environment from the given NetworkX graph structure. :param env: Environment where the agents live. The environment should be derived from :class:`~creamas.core.environment.Environment`, :class:`~creamas.mp.MultiEnvironment` or :class:`...
370,776
def SubtractFromBalance(self, assetId, fixed8_val): found = False for key, balance in self.Balances.items(): if key == assetId: self.Balances[assetId] = self.Balances[assetId] - fixed8_val found = True if not found: self.Balances[a...
Subtract amount to the specified balance. Args: assetId (UInt256): fixed8_val (Fixed8): amount to add.
370,777
def load(self, graphic): for prop in graphic.properties(): key = prop.name() value = prop.value() if key == : value = projex.wikitext.render(value.strip()) self.setProperty(key, value) for at...
Loads information for this item from the xml data. :param graphic | <XWalkthroughItem>
370,778
def continue_oauth(self, oauth_callback_data=None): self.response_qs = oauth_callback_data if not self.response_qs: webbrowser.open(self.redirect) self.response_qs = input("Callback URL: ") response_qs = self.response_qs.split(b)[-1] ...
Continuation of OAuth procedure. Method must be explicitly called in order to complete OAuth. This allows external entities, e.g. websites, to provide tokens through callback URLs directly. :param oauth_callback_data: The callback URL received to a Web app :type oauth_callback_data: bytes ...
370,779
def search_archives(query): _assert_obj_type(query, name="query", obj_type=DBArchive) return _get_handler().search_objects(query)
Return list of :class:`.DBArchive` which match all properties that are set (``not None``) using AND operator to all of them. Example: result = storage_handler.search_publications( DBArchive(isbn="azgabash") ) Args: query (obj): :class:`.DBArchive` with `some` of the pro...
370,780
def write_to_socket(self, frame_data): self._wr_lock.acquire() try: total_bytes_written = 0 bytes_to_send = len(frame_data) while total_bytes_written < bytes_to_send: try: if not self.socket: raise s...
Write data to the socket. :param str frame_data: :return:
370,781
def add_listener_policy(self, json_data): env = boto3.session.Session(profile_name=self.env, region_name=self.region) elbclient = env.client() stickiness = {} elb_settings = self.properties[] if elb_settings.get(): ports = elb_settings[] ...
Attaches listerner policies to an ELB Args: json_data (json): return data from ELB upsert
370,782
def _to_dict_fixed_width_arrays(self, var_len_str=True): self.strings_to_categoricals() obs_rec, uns_obs = df_to_records_fixed_width(self._obs, var_len_str) var_rec, uns_var = df_to_records_fixed_width(self._var, var_len_str) layers = self.layers.as_dict() d = { ...
A dict of arrays that stores data and annotation. It is sufficient for reconstructing the object.
370,783
def more(value1, value2): number1 = FloatConverter.to_nullable_float(value1) number2 = FloatConverter.to_nullable_float(value2) if number1 == None or number2 == None: return False return number1 > number2
Checks if first value is greater than the second one. The operation can be performed over numbers or strings. :param value1: the first value to compare :param value2: the second value to compare :return: true if the first value is greater than second and false otherwise.
370,784
def popular(self, **kwargs): path = self._get_path() response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the list of popular movies on The Movie Database. This list refreshes every day. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. Returns: A dict representation of the JSON returned from the A...
370,785
def trunk_update(request, trunk_id, old_trunk, new_trunk): LOG.debug("trunk_update(): trunk_id=%s", trunk_id) def dict2frozenset(d): return frozenset(d.items()) updatable_props = (, , ) prop_diff = { k: new_trunk[k] for k in updatable...
Handle update to a trunk in (at most) three neutron calls. The JavaScript side should know only about the old and new state of a trunk. However it should not know anything about how the old and new are meant to be diffed and sent to neutron. We handle that here. This code was adapted from Heat, see: h...
370,786
def usearch_cluster_error_correction( fasta_filepath, output_filepath=None, output_uc_filepath=None, percent_id_err=0.97, sizein=True, sizeout=True, w=64, slots=16769023, maxrejects=64, log_name="usearch_cluster_err_corrected.log", ...
Cluster for err. correction at percent_id_err, output consensus fasta fasta_filepath = input fasta file, generally a dereplicated fasta output_filepath = output error corrected fasta filepath percent_id_err = minimum identity percent. sizein = not defined in usearch helpstring sizeout = not defined...
370,787
async def _auth_handler_post_get_auth(self): s __call__ returning a dict to update the requestd response object to calculate auth details from. ' if isinstance(self.auth, PostResponseAuth): if self.history_objects: authable_resp = self.history...
If the user supplied auth does rely on a response (is a PostResponseAuth object) then we call the auth's __call__ returning a dict to update the request's headers with, as long as there is an appropriate 401'd response object to calculate auth details from.
370,788
def get_subsamples(data, samples, force): subsamples = [] for sample in samples: if not force: if sample.stats.state >= 5: print(.format(sample.name)) elif not sample.stats.clusters_hidepth: print(\ .format(sample.name, int(sample.stats.c...
Apply state, ncluster, and force filters to select samples to be run.
370,789
def tvBrowserHazard_selection_changed(self): (is_compatible, desc) = self.get_layer_description_from_browser( ) self.lblDescribeBrowserHazLayer.setText(desc) self.lblDescribeBrowserHazLayer.setEnabled(is_compatible) self.parent.pbnNext.setEnabled(is_compatible)
Update layer description label.
370,790
def appendAnchor(self, name=None, position=None, color=None, anchor=None): identifier = None if anchor is not None: anchor = normalizers.normalizeAnchor(anchor) if name is None: name = anchor.name if position is None: position ...
Append an anchor to this glyph. >>> anchor = glyph.appendAnchor("top", (10, 20)) This will return a :class:`BaseAnchor` object representing the new anchor in the glyph. ``name`` indicated the name to be assigned to the anchor. It must be a :ref:`type-string` or ``None``. ``...
370,791
def get_definition_properties(self, project, definition_id, filter=None): 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, ) que...
GetDefinitionProperties. [Preview API] Gets properties for a definition. :param str project: Project ID or project name :param int definition_id: The ID of the definition. :param [str] filter: A comma-delimited list of properties. If specified, filters to these specific properties. ...
370,792
def OpenServerEndpoint(self, path, verify_cb=lambda x: True, data=None, params=None, headers=None, method="GET", timeout=None): tries = ...
Search through all the base URLs to connect to one that works. This is a thin wrapper around requests.request() so most parameters are documented there. Args: path: The URL path to access in this endpoint. verify_cb: A callback which should return True if the response is reasonable. Th...
370,793
def x_plus(self, dx=None): if dx is None: self.x += self.dx else: self.x = self.x + dx
Mutable x addition. Defaults to set delta value.
370,794
def getManager(self, force=False): manager = self.session.get(self.getSessionKey()) if (manager is not None and (manager.forURL(self.url) or force)): return manager else: return None
Extract the YadisServiceManager for this object's URL and suffix from the session. @param force: True if the manager should be returned regardless of whether it's a manager for self.url. @return: The current YadisServiceManager, if it's for this URL, or else None
370,795
def remove_father(self, father): self._fathers = [x for x in self._fathers if x.node_id != father.node_id]
Remove the father node. Do nothing if the node is not a father Args: fathers: list of fathers to add
370,796
def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): 10.0.0.0/8192.168.0.0/168.8.8.8 ret = { : name, : False, : , : {} } if not isinstance(connection_auth, dict): ...
.. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual netw...
370,797
def setup_suspend(self): self.frame_calling = None self.frame_stop = None self.frame_return = None self.frame_suspend = True self.pending_stop = True self.enable_tracing() return
Setup debugger to "suspend" execution
370,798
def prune_cached(values): import os config_path = os.path.expanduser() file_path = os.path.join(config_path, ) if not os.path.isfile(file_path): return values cached = [x.strip() for x in open(file_path, ).readlines()] output = list() for item in values: hashed = hash_va...
Remove the items that have already been cached.
370,799
def _unary_op(name, doc="unary operator"): def _(self): jc = getattr(self._jc, name)() return Column(jc) _.__doc__ = doc return _
Create a method for given unary operator