Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
361,000
def get_daily_rates(date_req: datetime.datetime = None, lang: str = ) -> Element: if lang not in [, ]: raise ValueError() base_url = const.CBRF_API_URLS[] if lang == \ else const.CBRF_API_URLS[] url = base_url + + utils.date_to_str(date_req) if date_req else base_url response =...
Getting currency for current day. see example: http://www.cbr.ru/scripts/Root.asp?PrtId=SXML :param date_req: :type date_req: datetime.datetime :param lang: language of API response ('eng' || 'rus') :type lang: str :return: :class: `Element <Element 'ValCurs'>` object :rtype: ElementTree....
361,001
def load(self): self._validate() self._logger.logging_load() self.encoding = get_file_encoding(self.source, self.encoding) if six.PY3: self._csv_reader = csv.reader( io.open(self.source, "r", encoding=self.encoding), delimiter=self.d...
Extract tabular data as |TableData| instances from a CSV file. |load_source_desc_file| :return: Loaded table data. |load_table_name_desc| =================== ======================================== Format specifier Value after the replacement ...
361,002
def init_huang(X, n_clusters, dissim, random_state): n_attrs = X.shape[1] centroids = np.empty((n_clusters, n_attrs), dtype=) for iattr in range(n_attrs): freq = defaultdict(int) for curattr in X[:, iattr]: freq[curattr] += 1 ...
Initialize centroids according to method by Huang [1997].
361,003
def dataSource(self, value): if isinstance(value, DataSource): self._dataSource = value else: raise TypeError("value must be a DataSource object")
sets the datasource object
361,004
def stripIEConditionals(contents, addHtmlIfMissing=True): allMatches = IE_CONDITIONAL_PATTERN.findall(contents) if not allMatches: return contents for match in allMatches: contents = contents.replace(match, ) if END_HTML.match(contents) and not START_HTML.match(contents): ...
stripIEConditionals - Strips Internet Explorer conditional statements. @param contents <str> - Contents String @param addHtmlIfMissing <bool> - Since these normally encompass the "html" element, optionally add it back if missing.
361,005
def _fake_openreferenceinstancepaths(self, namespace, **params): self._validate_namespace(namespace) self._validate_open_params(**params) params[] = params[] del params[] result = self._fake_referencenames(namespace, **params) objects = [] if result is...
Implements WBEM server responder for :meth:`~pywbem.WBEMConnection.OpenReferenceInstancePaths` with data from the instance repository.
361,006
def nhs_number_from_text_or_none(s: str) -> Optional[int]: funcname = "nhs_number_from_text_or_none: " if not s: log.debug(funcname + "incoming parameter was None") return None s = WHITESPACE_REGEX.sub("", s) if NON_NUMERIC_REGEX.search(s): log.debu...
Returns a validated NHS number (as an integer) from a string, or ``None`` if it is not valid. It's a 10-digit number, so note that database 32-bit INT values are insufficient; use BIGINT. Python will handle large integers happily. NHS number rules: http://www.datadictionary.nhs.uk/...
361,007
def append_row(self, index, value): if index in self._index: raise IndexError() self._index.append(index) self._data.append(value)
Appends a row of value to the end of the data. Be very careful with this function as for sorted Series it will not enforce sort order. Use this only for speed when needed, be careful. :param index: index :param value: value :return: nothing
361,008
def write(self, stream): topology = self.createTopology() def write_it(stream): transportOut = TMemoryBuffer() protocolOut = TBinaryProtocol.TBinaryProtocol(transportOut) topology.write(protocolOut) bytes = transportOut.getvalue() stre...
Writes the topology to a stream or file.
361,009
def astuple(obj, *, tuple_factory=tuple): if not _is_dataclass_instance(obj): raise TypeError("astuple() should be called on dataclass instances") return _astuple_inner(obj, tuple_factory)
Return the fields of a dataclass instance as a new tuple of field values. Example usage:: @dataclass class C: x: int y: int c = C(1, 2) assert astuple(c) == (1, 2) If given, 'tuple_factory' will be used instead of built-in tuple. The function applies recursively t...
361,010
def delete_many(self, filter, collation=None): with self._socket_for_writes() as sock_info: return DeleteResult(self._delete(sock_info, filter, True, collation=collation), self.write_concern.acknowledged)
Delete one or more documents matching the filter. >>> db.test.count({'x': 1}) 3 >>> result = db.test.delete_many({'x': 1}) >>> result.deleted_count 3 >>> db.test.count({'x': 1}) 0 :Parameters: - `filter`: A query that matches the ...
361,011
def add_core(self, x, y, p): if ((p < 0 or p > 17) or (x < self.base_x or x >= self.base_x + self.scale) or (y < self.base_y or y >= self.base_y + self.scale)): raise ValueError((x, y, p)) subregion = ((x >> self.shift) & 0x3) + 4*(...
Add a new core to the region tree. Raises ------ ValueError If the co-ordinate is not contained within this part of the tree or the core number is out of range. Returns ------- bool True if the specified core is to be loaded to all su...
361,012
def delete_timeline(self, scope_identifier, hub_name, plan_id, timeline_id): route_values = {} if scope_identifier is not None: route_values[] = self._serialize.url(, scope_identifier, ) if hub_name is not None: route_values[] = self._serialize.url(, hub_name, ) ...
DeleteTimeline. :param str scope_identifier: The project GUID to scope the request :param str hub_name: The name of the server hub: "build" for the Build server or "rm" for the Release Management server :param str plan_id: :param str timeline_id:
361,013
def construct_oauth_url(self): response = self._requester(requests.head, "{0}://{1}/".format(self.protocol, self.client.server), allow_redirects=False ) if response.is_redirect: ...
Constructs verifier OAuth URL
361,014
def _extract_id(self) -> str: match = re.match(self._VALID_URL, self.url) if match: return match.group() else: raise VideoIdNotMatchedError
Get video_id needed to obtain the real_url of the video. Raises: VideoIdNotMatchedError: If video_id is not matched with regular expression.
361,015
def from_date(datetime_date): return BusinessDate.from_ymd(datetime_date.year, datetime_date.month, datetime_date.day)
construct BusinessDate instance from datetime.date instance, raise ValueError exception if not possible :param datetime.date datetime_date: calendar day :return bool:
361,016
def unset_required_for(cls, sharable_fields): if in cls.base_fields and not in sharable_fields: cls.base_fields[].required = False if in cls.base_fields and not in sharable_fields: cls.base_fields[].required = False
Fields borrowed by `SharedGlossaryAdmin` to build its temporary change form, only are required if they are declared in `sharable_fields`. Otherwise just deactivate them.
361,017
def transform(self, matrix): cairo.cairo_transform(self._pointer, matrix._pointer) self._check_status()
Modifies the current transformation matrix (CTM) by applying :obj:`matrix` as an additional transformation. The new transformation of user space takes place after any existing transformation. :param matrix: A transformation :class:`Matrix` to be applied to the us...
361,018
def uint32_to_uint8(cls, img): return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))
Cast uint32 RGB image to 4 uint8 channels.
361,019
def findbeam_gravity(data, mask): data1 = data.copy() data1[mask == 0] = 0 x = np.arange(data1.shape[0]) y = np.arange(data1.shape[1]) onex = np.ones_like(x) oney = np.ones_like(y) nix = np.dot(x, data1) spamx = np.dot(onex, data...
Find beam center with the "gravity" method Inputs: data: scattering image mask: mask matrix Output: a vector of length 2 with the x (row) and y (column) coordinates of the origin, starting from 1
361,020
def add_reciprocal_link(self, target, weight): if not isinstance(target, list): target_list = [target] else: target_list = target for t in target_list: self.add_link(t, weight) t.add_link(self, weight)
Add links pointing in either direction between ``self`` and ``target``. This creates a ``Link`` from ``self`` to ``target`` and a ``Link`` from ``target`` to ``self`` of equal weight. If ``target`` is a list of ``Node`` 's, repeat this for each one. Args: target (Node or li...
361,021
def p_toc(self, toc): toc[0] = TableOfContent(toc[1], toc[2], []) self.toc = toc[0]
toc : HEADERSEC opttexts TOC opttexts
361,022
def groupselectfirst(table, key, presorted=False, buffersize=None, tempdir=None, cache=True): def _reducer(k, rows): return next(rows) return rowreduce(table, key, reducer=_reducer, presorted=presorted, buffersize=buffersize, tempdir=tempdir, cache=cache)
Group by the `key` field then return the first row within each group. E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar', 'baz'], ... ['A', 1, True], ... ['C', 7, False], ... ['B', 2, False], ... ['C', 9, True]] ...
361,023
def status(AuxiliaryStates_presence=0): a = TpPd(pd=0x3) b = MessageType(mesType=0x3d) c = Cause() d = CallState() packet = a / b / c / d if AuxiliaryStates_presence is 1: e = AuxiliaryStatesHdr(ieiAS=0x24, eightBitAS=0x0) packet = packet / e return packet
STATUS Section 9.3.27
361,024
def write_bytes(self, bytes, append=False): if append: mode = else: mode = with self.open(mode) as f: f.write(bytes)
Open this file and write the given bytes to it. Default behavior is to overwrite any existing file. Call ``p.write_bytes(bytes, append=True)`` to append instead.
361,025
def walkfolder(toppath, pred): for entry in scandir.scandir(toppath): if not entry.is_dir() or not pred(entry.name): continue yield entry.path for p in walkfolder(entry.path, pred): yield p
walk folder if pred(foldername) is True :type toppath: str :type pred: function(str) => bool
361,026
def make_ujson_response(obj, status_code=200): json_encoded = ujson.encode(obj, ensure_ascii=False, double_precision=-1) resp = make_response(json_encoded) resp.mimetype = resp.content_type = resp.status_code = status_code return resp
Encodes the given *obj* to json and wraps it in a response. :return: A Flask response.
361,027
def strip_ids(ids, ids_to_strip): ids = list(ids) while ids and ids[-1] in ids_to_strip: ids.pop() return ids
Strip ids_to_strip from the end ids.
361,028
def clone(self, _, scene): if self._name is not None: for effect in scene.effects: if isinstance(effect, Frame): if effect._name == self._name: effect.data = self.data for layout in self._l...
Create a clone of this Frame into a new Screen. :param _: ignored. :param scene: The new Scene object to clone into.
361,029
def dendrogram(tree): plot_data = { "x": [], "y": [], "o": [], "b": [], } for idx, (i, d) in enumerate(zip(tree["icoord"], tree["dcoord"])): plot_data["x"].extend(map(lambda x: -x, d)) plot_data["y"].extend(map(lambda x: -x, i)) plot_data["o"...
Plot a simple square dendrogram using Altair. Parameters ---------- tree : `dict` returned by `scipy.cluster.hierarchy.dendrogram` Contains, at a minimum, 'icoord', 'dcoord', and 'leaves' keys. Scipy does all the work of determining where the lines in the tree should go. All we have to do is draw t...
361,030
def created_at(self): if self._created_at: return self._created_at elif not self.abstract: return self.read_meta()._created_at raise EmptyDocumentException()
:return: When the document was created :rtype: :py:class:`datetime.datetime`
361,031
def set_model(self, m): self._model = m self.new_root.emit(QtCore.QModelIndex()) self.model_changed(m)
Set the model for the level :param m: the model that the level should use :type m: QtCore.QAbstractItemModel :returns: None :rtype: None :raises: None
361,032
def _copy_params(self): cls = type(self) src_name_attrs = [(x, getattr(cls, x)) for x in dir(cls)] src_params = list(filter(lambda nameAttr: isinstance(nameAttr[1], Param), src_name_attrs)) for name, param in src_params: setattr(self, name, param._copy_new_parent(sel...
Copy all params defined on the class to current object.
361,033
def signup(self, project_name, email): uri = data = { "project_name": project_name, "email": email, } post_body = json.dumps(data) resp, body = self.post(uri, body=post_body) self.expected_success(200, resp.status) body = json.lo...
Signup for a new project.
361,034
def fval(self, instance): try: val = instance.__dict__[self.instance_field_name] except KeyError as e: val = None return val
return the raw value that this property is holding internally for instance
361,035
def persist_config(run, session, cfg): from benchbuild.utils import schema as s for cfg_elem in cfg: session.add( s.Config(name=cfg_elem, value=cfg[cfg_elem], run_id=run.id))
Persist the configuration in as key-value pairs. Args: run: The run we attach the config to. session: The db transaction we belong to. cfg: The configuration we want to persist.
361,036
def check_base_required_attributes(self, dataset): test_ctx = TestCtx(BaseCheck.HIGH, ) conventions = getattr(dataset, , ) feature_type = getattr(dataset, , ) accepted_conventions = [, ] dataset_conventions = conventions.replace(, ).split() for accepte...
Check the global required and highly recommended attributes for 2.0 templates. These go an extra step besides just checking that they exist. :param netCDF4.Dataset dataset: An open netCDF dataset :Conventions = "CF-1.6, ACDD-1.3" ; //............................... REQUIRED - Always try to use...
361,037
def nextpow2(value): if value >= 1: return 2**np.ceil(np.log2(value)).astype(int) elif value > 0: return 1 elif value == 0: return 0 else: raise ValueError()
Compute the nearest power of two greater or equal to the input value
361,038
def extract_path_ext(path, default_ext=None): ext = None _, dotext = os.path.splitext(path) if dotext: ext = dotext[1:] if not ext and default_ext: ext = default_ext if not ext: raise ValueError(.format(path)) return ext
Extract file extension (without dot) from `path` or return `default_ext` if path does not contain a valid extension.
361,039
def create_app_id(self, app_id, policies, display_name=None, mount_point=, **kwargs): if isinstance(policies, (list, set, tuple)): policies = .join(policies) params = { : policies } if display_name: param...
POST /auth/<mount point>/map/app-id/<app_id> :param app_id: :type app_id: :param policies: :type policies: :param display_name: :type display_name: :param mount_point: :type mount_point: :param kwargs: :type kwargs: :return: ...
361,040
def add_profile(self, namespace, key, value, force=False): try: entry = dax.Profile(namespace, key, value) self._dax_node.addProfile(entry) except dax.DuplicateError: if force: self._dax_node.removeProfile(entry) ...
Add profile information to this node at the DAX level
361,041
def _notebook_dir_changed(self, name, old, new): if os.path.exists(new) and not os.path.isdir(new): raise TraitError("notebook dir %r is not a directory" % new) if not os.path.exists(new): self.log.info("Creating notebook dir %s", new) try: os...
do a bit of validation of the notebook dir
361,042
def build_list_params(self, params, items, label): for i in xrange(1, len(items)+1): if isinstance(items[i-1], dict): for k, v in items[i-1].iteritems(): if isinstance(v, dict): for kk, vv in v.iteritems(): ...
Items is a list of dictionaries or strings:: [ { 'Protocol' : 'HTTP', 'LoadBalancerPort' : '80', 'InstancePort' : '80' }, .. ] etc. or:: ['us-east-1b',...]
361,043
def import_context(target_zip): context_path = tasks.get_context_path() with zipfile.ZipFile(target_zip) as unzipped_data: with open(context_path, ) as context: context.write(unzipped_data.read())
Overwrite old context.json, use context.json from target_zip :param target_zip: :return:
361,044
def _getdata_by_idx(data, idx): shuffle_data = [] for k, v in data: if (isinstance(v, h5py.Dataset) if h5py else False): shuffle_data.append((k, v)) elif isinstance(v, CSRNDArray): shuffle_data.append((k, sparse_array(v.asscipy()[idx], v.context))) else: ...
Shuffle the data.
361,045
def setup_logfile_raw(self, logfile, mode=): self.logfile_raw = open(logfile, mode=mode)
start logging raw bytes to the given logfile, without timestamps
361,046
def get_treasury_yield(start=None, end=None, period=): if start is None: start = if end is None: end = _1_bday_ago() treasury = web.DataReader("DGS3{}".format(period), "fred", start, end) treasury = treasury.ffill() return treasury
Load treasury yields from FRED. Parameters ---------- start : date, optional Earliest date to fetch data for. Defaults to earliest date available. end : date, optional Latest date to fetch data for. Defaults to latest date available. period : {'1MO', '3MO', '6MO', 1'...
361,047
def do_metric_name_list(mc, args): fields = {} if args.dimensions: fields[] = utils.format_dimensions_query(args.dimensions) if args.limit: fields[] = args.limit if args.offset: fields[] = args.offset if args.tenant_id: fields[] = args.tenant_id try: ...
List names of metrics.
361,048
def check_response(res): try: res.raise_for_status() except Exception as exc: % list(err_info.keys())) exc.args += (err_msg,) raise exc
Check HTTP response and raise exception if response is not OK.
361,049
def get_html(self): if self.__htmltree is not None: return self.__htmltree else: self.__make_tree() return self.__htmltree
Generates if need be and returns a simpler html document with text
361,050
def get_temperature_interval(self): intervals = ({ -20: 1, -19: 1, -18: 1, -17: 1, -16: 1, -15: 1, -14: 2, -13: 2, -12: 2, -11: 2, -10: 2, -9: 3, -8: 3, -7: 3, -6: 3, -5: 3, -4: 4, -3: 4, -2: 4, -1: 4, 0: 4, 1: 5, 2: 5, 3: 5, 4: 5, 5: 5, 6: 6, 7: 6, 8: 6,...
Appoints the corresponding temperature interval to each temperature in the temperature vector.
361,051
def book_car(intent_request): slots = intent_request[][] pickup_city = slots[] pickup_date = slots[] return_date = slots[] driver_age = slots[] car_type = slots[] confirmation_status = intent_request[][] session_attributes = intent_request[] last_confirmed_reservation = try_ex(l...
Performs dialog management and fulfillment for booking a car. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of sessionAttributes to pass information that can be used to guide conversation
361,052
def fit(self, min_ndata_factor=3, max_poly_order_factor=5, min_poly_order=2): warnings.simplefilter(, np.RankWarning) get_rms = lambda x, y: np.sqrt(np.sum((np.array(x)-np.array(y))**2)/len(x)) e_v = [(i, j) for i, j in zip(self.energies, self.volumes)] ndata = len(e_...
Fit the input data to the 'numerical eos', the equation of state employed in the quasiharmonic Debye model described in the paper: 10.1103/PhysRevB.90.174107. credits: Cormac Toher Args: min_ndata_factor (int): parameter that controls the minimum number of d...
361,053
def colRowIsOnSciencePixel(self, col, row, padding=DEFAULT_PADDING): if col < 12. - padding or col > 1111 + padding: return False if row < 20 - padding or row > 1043 + padding: return False return True
Is col row on a science pixel? Ranges taken from Fig 25 or Instrument Handbook (p50) Padding allows for the fact that distortion means the results from getColRowWithinChannel can be off by a bit. Setting padding > 0 means that objects that are computed to lie a small amount off...
361,054
def current_user(self): if self.session: try: response = self.session.get(self.entry_points.get()) if response.status_code in (200, 201): admin_href=response.json().get() request = SMCRequest(href=admin_href) ...
.. versionadded:: 0.6.0 Requires SMC version >= 6.4 Return the currently logged on API Client user element. :raises UnsupportedEntryPoint: Current user is only supported with SMC version >= 6.4 :rtype: Element
361,055
def open(self, name, mode=): return self.get_storage(name).open(name, mode)
Retrieves the specified file from storage. :param name: file name :type name: str :param mode: mode to open the file with :type mode: str :rtype: :class:`~django:django.core.files.File`
361,056
def advth(step): rbot, rtop = misc.get_rbounds(step) rmean = 0.5 * (rbot + rtop) rad = step.rprof[].values + rbot radio = step.timeinfo[] if rbot != 0: th_adv = -(rtop**3 - rad**3) / rmean**2 / 3 else: th_adv = rad - rtop th_adv *= radio th_adv += step.timeinfo[] ...
Theoretical advection. This compute the theoretical profile of total advection as function of radius. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance. Returns: tuple of :class:`numpy.array` and None: the theoretical advection. The sec...
361,057
def current_vm(self): try: _, _, _, _, vm = self._callstack[-1] return vm except IndexError: return None
current vm
361,058
def process_instrs(queue, stack, body, context): next_instr = queue.popleft while queue: newcontext = _process_instr(next_instr(), queue, stack, body, context) if newcontext is not None: context = newcontext
Process instructions from the instruction queue.
361,059
def message_box(type, title, message, icon=None, buttons=QMessageBox.Ok, custom_buttons=None): LOGGER.debug("> Launching messagebox().") LOGGER.debug("> Message type: .".format(type)) LOGGER.debug("> Title: .".format(title)) LOGGER.debug("> Message: .".format(message)) message_box = QMessageB...
Provides a fast GUI message box. :param title: Current message title. :type title: unicode :param message: Message. :type message: unicode :param icon: Custom icon. :type icon: QConstant :param buttons: Standard buttons. :type buttons: QConstant :param custom_buttons: Custom buttons...
361,060
def get_palette(samples, options, return_mask=False, kmeans_iter=40): if not options.quiet: print() bg_color = get_bg_color(samples, 6) fg_mask = get_fg_mask(bg_color, samples, options) centers, _ = kmeans(samples[fg_mask].astype(np.float32), options.num_colors-...
Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels.
361,061
def revoke(self): if self.access_token is None: raise InvalidInvocation("no token available to revoke") self._authenticator.revoke_token(self.access_token, "access_token") self._clear_access_token()
Revoke the current Authorization.
361,062
def __vCmdConnectCameras(self, args): if len(args) >= 1: self.WirelessPort = args[0] print ("Connecting to Cameras on %s" % self.WirelessPort) self.__vRegisterCameras()
ToDo: Validate the argument as a valid port
361,063
def handleEntity(self, ctxt): if ctxt is None: ctxt__o = None else: ctxt__o = ctxt._o libxml2mod.xmlHandleEntity(ctxt__o, self._o)
Default handling of defined entities, when should we define a new input stream ? When do we just handle that as a set of chars ? OBSOLETE: to be removed at some point.
361,064
def glob_wildcards(pattern: str, files: Optional[List[str]] = None ) -> Dict[str, Union[List[Any], List[str]]]: pattern = os.path.normpath(pattern) if sys.platform == : pattern = pattern.replace(, ) first_wildcard = re.search("{[^{]", pattern) dirname = os.path.di...
Glob the values of the wildcards by matching the given pattern to the filesystem. Returns a named tuple with a list of values for each wildcard.
361,065
def to_xml(self, f=None): if not f: from tempfile import TemporaryFile f = TemporaryFile() print >> f, print >> f, % self.name for item in self: print >> f, % item.name for k in item: print >> f, % k ...
Get this domain as an XML DOM Document :param f: Optional File to dump directly to :type f: File or Stream :return: File object where the XML has been dumped to :rtype: file
361,066
def refresh(self): if self.isHidden(): if self.editor is not None: self.clear_matches() return state = self.editor is not None for widget in self.widgets: widget.setEnabled(state) if state: self.find()
Refresh widget
361,067
def post_event_display_settings(self, id, **data): return self.post("/events/{0}/display_settings/".format(id), data=data)
POST /events/:id/display_settings/ Updates the display settings for an event.
361,068
def close(self): " Close pipe fds. " os.close(self._r) os.close(self._w) self._r = None self._w = None
Close pipe fds.
361,069
def _theorem6p3(): pruning_set3 = set() def _prune3(x, as_list, b): for a in as_list: key = (tuple(x), a, b) if key in pruning_set3: return True return False def _explored3(x, a, as_list): for b in as_list: prunable = (tupl...
See Theorem 6.3 in paper. Prunes (s,b) when (s,a) is explored, b (almost) simplicial in (s,a), and a (almost) simplicial in (s,b)
361,070
def get_event_teams_attendees(self, id, team_id, **data): return self.get("/events/{0}/teams/{0}/attendees/".format(id,team_id), data=data)
GET /events/:id/teams/:team_id/attendees/ Returns :format:`attendees` for a single :format:`teams`.
361,071
def add_secondary_linked_file(self, file_path, relpath=None, mimetype=None, time_origin=None, assoc_with=None): if mimetype is None: mimetype = self.MIMES[file_path.split()[-1]] self.linked_file_descriptors.append({ : file_path, : relpat...
Add a secondary linked file. :param str file_path: Path of the file. :param str relpath: Relative path of the file. :param str mimetype: Mimetype of the file, if ``None`` it tries to guess it according to the file extension which currently only works for wav, mpg, mpeg a...
361,072
def get_proof(self, index): if not self.tree[]: return None current_row_index = len(self.tree[]) - 1 if index < 0 or index > len(self.tree[][current_row_index]) - 1: return None proof = [] for current_level in range(current_row_inde...
Returns the proof for a leaf at the given index as an array of merkle siblings in hex format :param index: :return:
361,073
def _connect(self): while True: if self._closing: break try: kwargs = {} if self.source_ip or self.source_port: if tornado.version_info >= (4, 5): ...
Try to connect for the rest of time!
361,074
def toplevel_packages(): packages = set(easy.options.setup.packages) for pkg in list(packages): packages -= set(p for p in packages if str(p).startswith(pkg + )) return list(sorted(packages))
Get package list, without sub-packages.
361,075
def add_yaml_file_content_to_database( self, filepath, deleteFile=False ): self.log.debug( ) import codecs try: self.log.debug("attempting to open the file %s" % (filepath,)) readFile = codecs.open(filepath, encoding=, mod...
*given a file to a yaml file, add yaml file content to database* **Key Arguments:** - ``filepath`` -- the path to the yaml file - ``deleteFile`` -- delete the yaml file when its content has been added to the database. Default *False* **Return:** - None **Us...
361,076
def get_distribute_alterations_metadata(self): metadata = dict(self._mdata[]) metadata.update({: self._my_map[]}) return Metadata(**metadata)
Gets the metadata for the distribute alterations rights flag. return: (osid.Metadata) - metadata for the distribution rights fields *compliance: mandatory -- This method must be implemented.*
361,077
def create_server(cloud, **kwargs): if cloud == : _create_server_ec2(**kwargs) elif cloud == : _create_server_rackspace(**kwargs) elif cloud == : _create_server_gce(**kwargs) else: raise ValueError("Unknown cloud type: {}".format(cloud))
Create a new instance
361,078
def computeA(self, j, timeSeries): seasonLength = self.get_parameter("seasonLength") A_j = 0 for i in range(seasonLength): A_j += timeSeries[(seasonLength * (j)) + i][1] return A_j / seasonLength
Calculates A_j. Aj is the average value of x in the jth cycle of your data :return: A_j :rtype: numeric
361,079
def remove_inconsistent_edges(graph: BELGraph) -> None: for u, v in get_inconsistent_edges(graph): edges = [(u, v, k) for k in graph[u][v]] graph.remove_edges_from(edges)
Remove all edges between node pairs with inconsistent edges. This is the all-or-nothing approach. It would be better to do more careful investigation of the evidences during curation.
361,080
def timeshift_isc(data, pairwise=False, summary_statistic=, n_shifts=1000, tolerate_nans=True, random_state=None): data, n_TRs, n_voxels, n_subjects = _check_timeseries_input(data) observed = isc(data, pairwise=pairwise, summary_statistic=summary_statistic,...
Circular time-shift randomization for one-sample ISC test For each voxel or ROI, compute the actual ISC and p-values from a null distribution of ISCs where response time series are first circularly shifted by random intervals. If pairwise, apply time-shift randomization to each subjects and compute pai...
361,081
def get_capture_dimensions(capture): width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) return width, height
Get the dimensions of a capture
361,082
def _ref_has_region_assembled_twice(nucmer_hits, ref_seq, threshold): coords = AssemblyCompare.nucmer_hits_to_ref_coords(nucmer_hits) covered = [] for coords_list in coords.values(): covered.extend(coords_list) covered.sort() if len(covered) <= 1: ...
Returns true iff there is a part of the reference that is assembled more than once (ie covered by >1 nucmer hit). Needs a minimum proportin of the ref to be assembled more than once, determined by threshold. nucmer_hits = hits made by self._parse_nucmer_coords_file.
361,083
def delete_fit(self, fit, specimen=None): if specimen == None: for spec in self.pmag_results_data[]: if fit in self.pmag_results_data[][spec]: specimen = spec break if specimen not in self.pmag_results_data[]: retur...
removes fit from GUI results data Parameters ---------- fit : fit to remove specimen : specimen of fit to remove, if not provided and set to None then the function will find the specimen itself
361,084
def matchingFilePaths(targetfilename, directory, targetFileExtension=None, selector=None): targetFilePaths = list() targetfilename = os.path.splitext(targetfilename)[0] targetFileExtension = targetFileExtension.replace(, ) matchExtensions = False if targetFileExtension is Non...
Search for files in all subfolders of specified directory, return filepaths of all matching instances. :param targetfilename: filename to search for, only the string before the last "." is used for filename matching. Ignored if a selector function is specified. :param directory: search dire...
361,085
def addGraphic(self, layerName, geometry, symbol): allowed_geomtypes = [, , , ] if not (geometry.type.lower() in allowed_geomtypes): return False, layerName geom = _unicode_convert(json.loads(geometry.JSON)) geomType = self.__look_up_geom(geometry.type.lower()) ...
loads a geometry (ArcPy Geometry Object) into Graphic Layer
361,086
def gmail_email(self, from_, to, msg): logging.debug() smtpConn = smtplib.SMTP(, 587) smtpConn.ehlo() smtpConn.starttls() login_response = smtpConn.login(self._credentials[], self._credentials[]) if isinstance(msg, email.message.Message...
Send an email from your `gmail`_ account. .. _gmail: https://mail.google.com/ msg can either be: * A string, in which case: * At the first newline (\\n) the string will be split into subject and body * If no newline is present, the enti...
361,087
def get_triplet_tuple(a: BaseEntity, b: BaseEntity, c: BaseEntity) -> Tuple[str, str, str, str, str, str]: return a.as_bel(), a.sha512, b.as_bel(), b.sha512, c.as_bel(), c.sha512
Get the triple as a tuple of BEL/hashes.
361,088
def get_all_intervals(self): ints = sorted(self.get_intervals(True)) if self.tier_type == : if not ints: ints.append((self.xmin, self.xmax, )) else: if ints[0][0] > self.xmin: ints.insert(0, (self.xmin, ints[0][0], )) ...
Returns the true list of intervals including the empty intervals.
361,089
def setEditorData(self, editor, index): value = self.get_value(index) if isinstance(editor, QLineEdit): if is_binary_string(value): try: value = to_text_string(value, ) except: pass if not i...
Overriding method setEditorData Model --> Editor
361,090
def next_except_jump(self, start): if self.code[start] == self.opc.DUP_TOP: except_match = self.first_instr(start, len(self.code), self.opc.PJIF) if except_match: jmp = self.prev[self.get_target(except_match)] if self.version < ...
Return the next jump that was generated by an except SomeException: construct in a try...except...else clause or None if not found.
361,091
def run_spider(self, target_url, context_name=None, user_name=None): self.logger.debug(.format(target_url)) context_id, user_id = self._get_context_and_user_ids(context_name, user_name) if user_id: self.logger.debug(.format(context_id, user_id)) scan_id = self....
Run spider against a URL.
361,092
def collect_cmd(self, args, ret): from dvc.command.daemon import CmdDaemonAnalytics assert isinstance(ret, int) or ret is None if ret is not None: self.info[self.PARAM_CMD_RETURN_CODE] = ret if args is not None and hasattr(args, "func"): assert args.fu...
Collect analytics info from a CLI command.
361,093
def apply_async(self, args=None, kwargs=None, **options): if self.is_previous_task_processing(*args, **kwargs): message = % self.name logger.info(message) return self.AsyncResult(options.get() or str(uuid4())) return super(BackgroundTask, self)....
Do not run background task if previous task is uncompleted
361,094
def _password(self, password): with self.lock: self.send( % password, error_check=True)
Authenticates with the IRC server. NOTE: Method will not raise an exception, if the password is wrong. It will just fail.. Required arguments: * password - Password to send.
361,095
def close(self): if self._transport is None: return self._transport.close() self._transport = None if self._agent is not None: self._agent.close() self._agent = None
Close this SSHClient and its underlying `.Transport`. .. warning:: Failure to do this may, in some situations, cause your Python interpreter to hang at shutdown (often due to race conditions). It's good practice to `close` your client objects anytime you're done ...
361,096
def And(cls, *requirements): return cls(*requirements, op=operator.and_, until=False)
Short cut helper to construct a combinator that uses :meth:`operator.and_` to reduce requirement results and stops evaluating on the first False. This is also exported at the module level as ``And``
361,097
def imap_connect(self): self.mailbox = imaplib.IMAP4_SSL(self.imap_string, self.port) self.mailbox.login(self.uname, self.pwd) self.mailbox.select()
Connect to the IMAP mailbox.
361,098
def _support_diag_dump(self): cfg_block = [] pconn = InsightsConnection(self.config) logger.info(, get_nvr()) reg_check = registration_check(pconn) cfg_block.append() for key in reg_check: cfg_block.append(key + + str(reg_check[key])) ...
Collect log info for debug
361,099
def define_selector(by, value, el_class): el = el_class selector = by if isinstance(value, six.string_types): selector = (by, value) elif value is not None: el = value if el is None: el = elements.PageElement return el, selector
:param by: :param value: :param el_class: :rtype: tuple[type, str|tuple[str, str]] :return: