Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
371,500
def _fetch_all(cls, api_key, endpoint=None, offset=0, limit=25, **kwargs): output = [] qp = kwargs.copy() limit = max(1, min(100, limit)) maximum = kwargs.get() qp[] = min(limit, maximum) if maximum is not None else limit qp[] = offset more, total = None,...
Call `self._fetch_page` for as many pages as exist. TODO: should be extended to do async page fetches if API allows it via exposing total value. Returns a list of `cls` instances.
371,501
def random(cls, length, bit_prob=.5): assert isinstance(length, int) and length >= 0 assert isinstance(bit_prob, (int, float)) and 0 <= bit_prob <= 1 bits = numpy.random.choice( [False, True], size=(length,), p=[1-bit_prob, bit_prob] ) ...
Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=.1) Arguments: length: An int...
371,502
def to_wire_dict (self): return dict(valid=self.valid, extern=self.extern[0], result=self.result, warnings=self.warnings[:], name=self.name or u"", title=self.get_title(), parent_url=self.parent_url or u"", base_ref=self.base_ref or ...
Return a simplified transport object for logging and caching. The transport object must contain these attributes: - url_data.valid: bool Indicates if URL is valid - url_data.result: unicode Result string - url_data.warnings: list of tuples (tag, warning message) ...
371,503
def _read(self, stream, text, byte_order): dtype = self.dtype(byte_order) if text: self._read_txt(stream) elif _can_mmap(stream) and not self._have_list: num_bytes = self.count * dtype.itemsize offset = stream.tell() ...
Read the actual data from a PLY file.
371,504
def free(self, connection): LOGGER.debug(, self.id, id(connection)) try: self.connection_handle(connection).free() except KeyError: raise ConnectionNotFoundError(self.id, id(connection)) if self.idle_connections == list(self.connections.values()): ...
Free the connection from use by the session that was using it. :param connection: The connection to free :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError
371,505
def get_gcd(a, b): "Return greatest common divisor for a and b." while a: a, b = b % a, a return b
Return greatest common divisor for a and b.
371,506
def _next_page(self): if self._last_page_seen: raise StopIteration new, self._last_page_seen = self.conn.query_multiple(self.object_type, self._next_page_index, self.url_params, self.query_params) self._next_page_i...
Fetch the next page of the query.
371,507
def list_instances(self): resp = self.instance_admin_client.list_instances(self.project_path) instances = [Instance.from_pb(instance, self) for instance in resp.instances] return instances, resp.failed_locations
List instances owned by the project. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_list_instances] :end-before: [END bigtable_list_instances] :rtype: tuple :returns: (instances, failed_locations), where 'instances' is li...
371,508
def search(self, CorpNum, DType, SDate, EDate, State, ItemCode, Page, PerPage, Order, UserID=None, QString=None): if DType == None or DType == : raise PopbillException(-99999999, "μΌμžμœ ν˜•μ΄ μž…λ ₯λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.") if SDate == None or SDate == : raise PopbillException(-9999999...
λͺ©λ‘ 쑰회 args CorpNum : νŒλΉŒνšŒμ› μ‚¬μ—…μžλ²ˆν˜Έ DType : μΌμžμœ ν˜•, R-λ“±λ‘μΌμ‹œ, W-μž‘μ„±μΌμž, I-λ°œν–‰μΌμ‹œ 쀑 택 1 SDate : μ‹œμž‘μΌμž, ν‘œμ‹œν˜•μ‹(yyyyMMdd) EDate : μ’…λ£ŒμΌμž, ν‘œμ‹œν˜•μ‹(yyyyMMdd) State : μƒνƒœμ½”λ“œ, 2,3번째 μžλ¦¬μ— μ™€μΌλ“œμΉ΄λ“œ(*) μ‚¬μš©κ°€λŠ₯ ItemCode : λͺ…μ„Έμ„œ μ’…λ₯˜μ½”λ“œ λ°°μ—΄, 121-λͺ…μ„Έμ„œ, 1...
371,509
def _MergeEntities(self, a, b): def _MergeAgencyId(a_agency_id, b_agency_id): a_agency_id = a_agency_id or None b_agency_id = b_agency_id or None return self._MergeIdentical(a_agency_id, b_agency_id) scheme = {: _MergeAgencyId, : self._MergeIdentical, ...
Merges two agencies. To be merged, they are required to have the same id, name, url and timezone. The remaining language attribute is taken from the new agency. Args: a: The first agency. b: The second agency. Returns: The merged agency. Raises: MergeError: The agencies c...
371,510
def hide_defaults(self): for k in list(self.fields.keys()): if k in self.default_fields: if self.default_fields[k] == self.fields[k]: del(self.fields[k]) self.payload.hide_defaults()
Removes fields' values that are the same as default values.
371,511
def command(self, outfile, configfile, pix): params = dict(script=self.config[][], config=configfile, outfile=outfile, nside=self.nside_likelihood, pix=pix, verbose= if self.verbose else ) cmd = %params return cmd
Generate the command for running the likelihood scan.
371,512
def find_and_modify(self, query=None, update=None): update = update or {} for document in self.find(query=query): document.update(update) self.update(document)
Finds documents in this collection that match a given query and updates them
371,513
async def write_message_data(self, data: bytes, timeout: NumType = None) -> None: data = LINE_ENDINGS_REGEX.sub(b"\r\n", data) data = PERIOD_REGEX.sub(b"..", data) if not data.endswith(b"\r\n"): data += b"\r\n" data += b".\r\n" await self.write_and_drain(dat...
Encode and write email message data. Automatically quotes lines beginning with a period per RFC821. Lone \\\\r and \\\\n characters are converted to \\\\r\\\\n characters.
371,514
def get_node_values( self, feature=None, show_root=False, show_tips=False, ): ndict = self.get_node_dict(return_internal=True, return_nodes=True) nodes = [ndict[i] for i in range(self.nnodes)[::-1]] if feature: v...
Returns node values from tree object in node plot order. To modify values you must modify the .treenode object directly by setting new 'features'. For example for node in ttree.treenode.traverse(): node.add_feature("PP", 100) By default node and tip values are hidden (set t...
371,515
def get_fun(returner, fun): * returners = salt.loader.returners(__opts__, __salt__) return returners[.format(returner)](fun)
Return info about last time fun was called on each minion CLI Example: .. code-block:: bash salt '*' ret.get_fun mysql network.interfaces
371,516
def fingerprint(channel_samples: list, Fs: int = DEFAULT_FS, wsize: int = DEFAULT_WINDOW_SIZE, wratio: Union[int, float] = DEFAULT_OVERLAP_RATIO, fan_value: int = DEFAULT_FAN_VALUE, amp_min: Union[int, float] = DEFAULT_AMP_MIN)-> Iterator[tuple]: ...
FFT the channel, log transform output, find local maxima, then return locally sensitive hashes. #
371,517
def set_classifier_interface_params(spec, features, class_labels, model_accessor_for_class_labels, output_features = None): features = _fm.process_or_validate_features(features) if class_labels is None: raise ValueError("List of class labels must be provided.") n_classes = len(cl...
Common utilities to set the regression interface params.
371,518
def enable_asynchronous(self): def is_monkey_patched(): try: from gevent import monkey, socket except ImportError: return False if hasattr(monkey, "saved"): return "socket" in monkey.saved return gevent.soc...
Check if socket have been monkey patched by gevent
371,519
def get_extra_path(name): helper_name, _, key = name.partition(".") helper = path_helpers.get(helper_name) if not helper: raise ValueError("Helper not found.".format(helper)) if name not in path_cache: extra_paths = helper.extra_paths() path_cache.update(extra_paths) ...
:param name: name in format helper.path_name sip.default_sip_dir
371,520
def handleOACK(self, pkt): if len(pkt.options.keys()) > 0: if pkt.match_options(self.context.options): log.info("Successful negotiation of options") self.context.options = pkt.options for key in self.context.options: ...
This method handles an OACK from the server, syncing any accepted options.
371,521
def set_path(self, path): if os.path.isabs(path): path = os.path.normpath(os.path.join(self.cwd, path)) self.path = path self.relative = os.path.relpath(self.path, self.base)
Set the path of the file.
371,522
def snippets(self): return [strip_suffix(f, ) for f in self._stripped_files if self._snippets_pattern.match(f)]
Get all snippets in this DAP
371,523
def download(self, overwrite=True): if overwrite or not os.path.exists(self.file_path): _, f = tempfile.mkstemp() try: urlretrieve(self.DOWNLOAD_URL, f) extract_csv(f, self.file_path) finally: os.remove(f)
Download the zipcodes CSV file. If ``overwrite`` is set to False, the file won't be downloaded if it already exists.
371,524
def render(self, progress, width=None, status=None): current_pct = int(progress * 100 + 0.1) return RenderResult(rendered="%3d%%" % current_pct, next_progress=(current_pct + 1) / 100)
Render the widget.
371,525
def set_stream_stats(self, rx_ports=None, tx_ports=None, start_offset=40, sequence_checking=True, data_integrity=True, timestamp=True): if not rx_ports: rx_ports = self.ports.values() if not tx_ports: tx_ports = {} for port in self....
Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX pgs. If empty set for all ports. :type ports: list[ixexplorer.ixe_port.IxePort] :param tx_ports: list of streams to set TX pgs. If empty set for all streams. :type tx_ports: dict[ixexplorer.ixe_por...
371,526
def output_is_valid(self, process_data): if self.METADATA["data_type"] == "raster": return ( is_numpy_or_masked_array(process_data) or is_numpy_or_masked_array_with_tags(process_data) ) elif self.METADATA["data_type"] == "vector": ...
Check whether process output is allowed with output driver. Parameters ---------- process_data : raw process output Returns ------- True or False
371,527
def fraction(value, allow_empty = False, minimum = None, maximum = None, **kwargs): try: value = _numeric_coercion(value, coercion_function = fractions.Fraction, allow_empty = allow_e...
Validate that ``value`` is a :class:`Fraction <python:fractions.Fraction>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is :obj:`None <python:None>`. If ``False``, raises a :class:`EmptyValueError <validator_collection.error...
371,528
def normalize_cjk_fullwidth_ascii(seq: str) -> str: def convert(char: str) -> str: code_point = ord(char) if not 0xFF01 <= code_point <= 0xFF5E: return char return chr(code_point - 0xFEE0) return .join(map(convert, seq))
Conver fullwith ASCII to halfwidth ASCII. See https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms
371,529
def guess_payload_class(self, payload): under_layer = self.underlayer tzsp_header = None while under_layer: if isinstance(under_layer, TZSP): tzsp_header = under_layer break under_layer = under_layer.underlayer if tzsp_h...
the type of the payload encapsulation is given be the outer TZSP layers attribute encapsulation_protocol # noqa: E501
371,530
def _set_static_ip(name, session, vm_): ipv4_cidr = ipv4_gw = if in vm_.keys(): log.debug() ipv4_gw = vm_[] if in vm_.keys(): log.debug() ipv4_cidr = vm_[] log.debug() set_vm_ip(name, ipv4_cidr, ipv4_gw, session, None)
Set static IP during create() if defined
371,531
def _check_chn_type(channels, available_channels): chn_list_standardized = [] devices = list(available_channels.keys()) for dev_nbr, device in enumerate(devices): if channels is not None: sub_unit = channels[dev_nbr] for channel in sub_unit: ...
Function used for checking weather the elements in "channels" input are coincident with the available channels. ---------- Parameters ---------- channels : list [[mac_address_1_channel_1 <int>, mac_address_1_channel_2 <int>...], [mac_address_2_channel_1 <int>...]...] Fro...
371,532
def get_suggested_repositories(self): if self.suggested_repositories is None: repository_set = list() for term_count in range(5, 2, -1): query = self.__get_query_for_repos(term_count=term_count) repository_set.extend(self.__get_repos_...
Method to procure suggested repositories for the user. :return: Iterator to procure suggested repositories for the user.
371,533
def get_instruments(self, name=None): if name: return self.get_instruments_by_name(name) return sorted( self._instruments.items(), key=lambda s: s[0].lower())
:returns: sorted list of (mount, instrument)
371,534
def load_vocab(vocab_file): vocab = collections.OrderedDict() index = 0 with io.open(vocab_file, ) as reader: while True: token = reader.readline() if not token: break token = token.strip() vocab[token] = index index +=...
Loads a vocabulary file into a dictionary.
371,535
def find_npolfile(flist,detector,filters): npolfile = None for f in flist: fdet = fits.getval(f, , memmap=False) if fdet == detector: filt1 = fits.getval(f, , memmap=False) filt2 = fits.getval(f, , memmap=False) fdate = fits.getval(f, , memmap=False) ...
Search a list of files for one that matches the configuration of detector and filters used.
371,536
def import_eit_fzj(self, filename, configfile, correction_file=None, timestep=None, **kwargs): df_emd, dummy1, dummy2 = eit_fzj.read_3p_data( filename, configfile, **kwargs ) if correction_file is not None: ...
EIT data import for FZJ Medusa systems
371,537
def strip_metadata(report): report[] = report[][] report[] = report[][] report[] = report[][] report.pop() return report
Duplicates org_name, org_email and report_id into JSON root and removes report_metadata key to bring it more inline with Elastic output.
371,538
def take_function_register(self, rtype = SharedData.TYPES.NO_TYPE): reg = SharedData.FUNCTION_REGISTER if reg not in self.free_registers: self.error("function register already taken") self.free_registers.remove(reg) self.used_registers.append(reg) self...
Reserves register for function return value and sets its type
371,539
def merge_validator_config(configs): bind_network = None bind_component = None bind_consensus = None endpoint = None peering = None seeds = None peers = None network_public_key = None network_private_key = None scheduler = None permissions = None roles = None ope...
Given a list of ValidatorConfig objects, merges them into a single ValidatorConfig, giving priority in the order of the configs (first has highest priority).
371,540
def split_input(cls, mapper_spec): shard_count = mapper_spec.shard_count query_spec = cls._get_query_spec(mapper_spec) if not property_range.should_shard_by_property_range(query_spec.filters): return super(DatastoreInputReader, cls).split_input(mapper_spec) ...
Inherit docs.
371,541
def generate_random_128bit_string(): t = int(time.time()) lower_96 = random.getrandbits(96) return .format((t << 96) | lower_96)
Returns a 128 bit UTF-8 encoded string. Follows the same conventions as generate_random_64bit_string(). The upper 32 bits are the current time in epoch seconds, and the lower 96 bits are random. This allows for AWS X-Ray `interop <https://github.com/openzipkin/zipkin/issues/1754>`_ :returns: 32-ch...
371,542
def get_auth(): import getpass from requests.auth import HTTPDigestAuth input_func = input try: input_func = raw_input except NameError: pass uname = input_func("MODSCAG Username:") pw = getpass.getpass("MODSCAG Password:") auth = HTTPDigestAuth(uname, pw) ...
Get authorization token for https
371,543
def exclude(*what): cls, attrs = _split_what(what) def exclude_(attribute, value): return value.__class__ not in cls and attribute not in attrs return exclude_
Blacklist *what*. :param what: What to blacklist. :type what: :class:`list` of classes or :class:`attr.Attribute`\\ s. :rtype: :class:`callable`
371,544
def as_action_description(self): description = { self.name: { : self.href_prefix + self.href, : self.time_requested, : self.status, }, } if self.input is not None: description[self.name][] = self.input ...
Get the action description. Returns a dictionary describing the action.
371,545
def is_dn(s): if s == : return True rm = DN_REGEX.match(s) return rm is not None and rm.group(0) == s
Return True if s is a LDAP DN.
371,546
def _residual_soil(self): return self.catchment.descriptors.bfihost \ + 1.3 * (0.01 * self.catchment.descriptors.sprhost) \ - 0.987
Methodology source: FEH, Vol. 3, p. 14
371,547
def decode(message): try: data = json.loads(message.payload.decode("utf-8")) except ValueError as e: raise InvalidEventException( % (message.payload, str(e))) timestamp = datetime.now(pytz.timezone("UTC")) return Message(data, timestamp)
Convert a generic JSON message * The entire message is converted to JSON and treated as the message data * The timestamp of the message is the time that the message is RECEIVED
371,548
def setup_admin_on_rest_handlers(admin, admin_handler): add_route = admin.router.add_route add_static = admin.router.add_static static_folder = str(PROJ_ROOT / ) a = admin_handler add_route(, , a.index_page, name=) add_route(, , a.token, name=) add_static(, path=static_folder, name=) ...
Initialize routes.
371,549
def plot_2(data, *args): df_all = pd.DataFrame(data) df_params = nonconstant_parameters(data) x = [df_all[][0]] y = [df_all[][0]] params = [df_params.loc[0]] for i in range(len(df_all)): if df_all[][i] > y[-1]: x.append(df_all[][i]) y.append(df_all[][i]) ...
Plot 2. Running best score (scatter plot)
371,550
def get_insight(self, project_key, insight_id, **kwargs): try: project_owner, project_id = parse_dataset_key(project_key) return self._insights_api.get_insight(project_owner, project_id, ...
Retrieve an insight :param project_key: Project identifier, in the form of projectOwner/projectid :type project_key: str :param insight_id: Insight unique identifier. :type insight_id: str :returns: Insight definition, with all attributes :rtype: object :...
371,551
def find_files(sequencepath): files = sorted(glob(os.path.join(sequencepath, ))) return files
Use glob to find all FASTA files in the provided sequence path. NOTE: FASTA files must have an extension such as .fasta, .fa, or .fas. Extensions of .fsa, .tfa, ect. are not currently supported :param sequencepath: path of folder containing FASTA genomes :return: list of FASTA files
371,552
def create_shipping_address(self, shipping_address): url = urljoin(self._url, ) return shipping_address.post(url)
Creates a shipping address on an existing account. If you are creating an account, you can embed the shipping addresses with the request
371,553
def datetime(self): index = self.data.index.remove_unused_levels() return pd.to_datetime(index.levels[0])
εˆ†ι’ŸηΊΏη»“ζž„θΏ”ε›ždatetime ζ—₯ηΊΏη»“ζž„θΏ”ε›ždate
371,554
def get_dir_backup(): args = parser.parse_args() s3_get_dir_backup( args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name, args.s3_folder, args.zip_backups_dir, args.project)
retrieves directory backup
371,555
def get_neutron_endpoint(cls, json_resp): catalog = json_resp.get(, {}).get(, []) match = neutron_endpoint = None for entry in catalog: if entry[] == match or in entry[]: valid_endpoints = {} for ep in entry[]: i...
Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service Sends a CRITICAL service check when none are found registered in the Catalog
371,556
def redirect(self, pid): if not (self.is_registered() or self.is_redirected()): raise PIDInvalidAction("Persistent identifier is not registered.") try: with db.session.begin_nested(): if self.is_redirected(): r = Redirect.query.get(se...
Redirect persistent identifier to another persistent identifier. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` where redirect the PID. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not registered or is not already redirecting to another ...
371,557
def artist(self, spotify_id): route = Route(, , spotify_id=spotify_id) return self.request(route)
Get a spotify artist by their ID. Parameters ---------- spotify_id : str The spotify_id to search by.
371,558
def ast_scan_file(filename, re_fallback=True): try: with io.open(filename, ) as fp: try: root = ast.parse(fp.read(), filename=filename) except (SyntaxError, IndentationError): if re_fallback: log.debug() ret...
Scans a file for imports using AST. In addition to normal imports, try to get imports via `__import__` or `import_module` calls. The AST parser should be able to resolve simple variable assignments in cases where these functions are called with variables instead of strings.
371,559
def delete_bond(self, n, m): self.remove_edge(n, m) self.flush_cache()
implementation of bond removing
371,560
def write(self, file): w = Writer(**self.info) w.write(file, self.rows)
Write the image to the open file object. See `.save()` if you have a filename. In general, you can only call this method once; after it has been called the first time the PNG image is written, the source data will have been streamed, and cannot be streamed again.
371,561
def set_default_content_type(application, content_type, encoding=None): settings = get_settings(application, force_instance=True) settings.default_content_type = content_type settings.default_encoding = encoding
Store the default content type for an application. :param tornado.web.Application application: the application to modify :param str content_type: the content type to default to :param str|None encoding: encoding to use when one is unspecified
371,562
def get_bin(self): return _convert(self._ip_dec, notation=IP_BIN, inotation=IP_DEC, _check=False, _isnm=self._isnm)
Return the binary notation of the address/netmask.
371,563
def user_data(self, access_token, *args, **kwargs): return self.get_json(self.USER_INFO_URL, method="POST", headers=self._get_headers(access_token))
Loads user data from service
371,564
def delete_glossary( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): if "delete_glossary" not in self._inner_api_calls: self._inner_api_calls[ "...
Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns NOT\_FOUND, if the glossary doesn't exist. Example: >>> from google.cloud import translate_v3beta1 >>> >>> client = translate_v3beta1.TranslationServiceClient() ...
371,565
def gen_batches(iterable, batch_size): abcdefghijklabcdefghijkl def batches_thunk(): return iter_batches(iterable, batch_size) try: length = len(iterable) except TypeError: return batches_thunk() num_batches = (length - 1) // batch_size + 1 return SizedGenerator(batches...
Returns a generator object that yields batches from `iterable`. See `iter_batches` for more details and caveats. Note that `iter_batches` returns an iterator, which never supports `len()`, `gen_batches` returns an iterable which supports `len()` if and only if `iterable` does. This *may* be an iterator...
371,566
def authenticate(self, _=None): acceptance_wait_time = self.opts[] acceptance_wait_time_max = self.opts[] channel = salt.transport.client.ReqChannel.factory(self.opts, crypt=) if not acceptance_wait_time_max: acceptance_wait_time_max = acceptance_wait_time ...
Authenticate with the master, this method breaks the functional paradigm, it will update the master information from a fresh sign in, signing in can occur as often as needed to keep up with the revolving master AES key. :rtype: Crypticle :returns: A crypticle used for encryption...
371,567
def direct_messages_sent(self, since_id=None, max_id=None, count=None, include_entities=None, page=None): params = {} set_str_param(params, , since_id) set_str_param(params, , max_id) set_int_param(params, , count) set_int_param(params, , pag...
Gets the 20 most recent direct messages sent by the authenticating user. https://dev.twitter.com/docs/api/1.1/get/direct_messages/sent :param str since_id: Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the numb...
371,568
def get_or_load_name(self, type_, id_, method): name = self.get_name(type_, id_) if name is not None: defer.returnValue(name) instance = yield method(id_) if instance is None: defer.returnValue(None) self.put_name(type_, id_, instance.name) ...
read-through cache for a type of object's name. If we don't have a cached name for this type/id, then we will query the live Koji server and store the value before returning. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :param method: function to call if this ...
371,569
def _special_method_cache(method, cache_wrapper): name = method.__name__ special_names = , if name not in special_names: return wrapper_name = + name def proxy(self, *args, **kwargs): if wrapper_name not in vars(self): bound = types.MethodType(method, self) cache = cache_wrapper(bound) setattr(s...
Because Python treats special methods differently, it's not possible to use instance attributes to implement the cached methods. Instead, install the wrapper method under a different name and return a simple proxy to that wrapper. https://github.com/jaraco/jaraco.functools/issues/5
371,570
def parse_ppi_graph(path: str, min_edge_weight: float = 0.0) -> Graph: logger.info("In parse_ppi_graph()") graph = igraph.read(os.path.expanduser(path), format="ncol", directed=False, names=True) graph.delete_edges(graph.es.select(weight_lt=min_edge_weight)) graph.delete_vertices(graph.vs.select(_d...
Build an undirected graph of gene interactions from edgelist file. :param str path: The path to the edgelist file :param float min_edge_weight: Cutoff to keep/remove the edges, default is 0, but could also be 0.63. :return Graph: Protein-protein interaction graph
371,571
def async_alert(self, alert_msg: str, new_prompt: Optional[str] = None) -> None: if not (vt100_support and self.use_rawinput): return import shutil import colorama.ansi as ansi from colorama import Cursor cursor_input_offset = last_prompt...
Display an important message to the user while they are at the prompt in between commands. To the user it appears as if an alert message is printed above the prompt and their current input text and cursor location is left alone. IMPORTANT: This function will not print an alert unless it can acq...
371,572
def contract(self, process): print(, process) print(self.name, , self.parent) return self.parent
this contracts the current node to its parent and then either caclulates the params and values if all child data exists, OR uses the default parent data. (In real terms it returns the parent and recalculates) TODO = processes need to be recalculated
371,573
def update( self, kb_id, update_kb, custom_headers=None, raw=False, **operation_config): url = self.update.metadata[] path_format_arguments = { : self._serialize.url("self.config.endpoint", self.config.endpoint, , skip_quote=True), : self._serialize....
Asynchronous operation to modify a knowledgebase. :param kb_id: Knowledgebase id. :type kb_id: str :param update_kb: Post body of the request. :type update_kb: ~azure.cognitiveservices.knowledge.qnamaker.models.UpdateKbOperationDTO :param dict custom_headers: headers th...
371,574
def set_alpha_value(self, value): if isinstance(value, float) is False: raise TypeError("The type of __alpha_value must be float.") self.__alpha_value = value
setter Learning rate.
371,575
def health_check(self): api_response = result = .format(self._resource_name) try: health_check_flow = RunCommandFlow(self.cli_handler, self._logger) health_check_flow.execute_flow() result += except Exception as e: self._logger...
Verify that device is accessible over CLI by sending ENTER for cli session
371,576
def _process_cache(self, d, path=()): for k, v in d.iteritems(): if not isinstance(v, dict): self.metrics.append((path + (k,), v)) else: self._process_cache(v, path + (k,))
Recusively walk a nested recon cache dict to obtain path/values
371,577
def parse_item(self, location: str, item_type: Type[T], item_name_for_log: str = None, file_mapping_conf: FileMappingConfiguration = None, options: Dict[str, Dict[str, Any]] = None) -> T: item_name_for_log = item_name_for_log or check_var(item_name_for_log, var_typ...
Main method to parse an item of type item_type :param location: :param item_type: :param item_name_for_log: :param file_mapping_conf: :param options: :return:
371,578
def _build(self, inputs): shape_inputs = inputs.get_shape().as_list() rank = len(shape_inputs) max_dim = np.max(self._dims) + 1 if rank < max_dim: raise ValueError("Rank of inputs must be at least {}.".format(max_dim)) full_begin = [0] * rank full_size = [-1] * rank ...
Connects the SliceByDim module into the graph. Args: inputs: `Tensor` to slice. Its rank must be greater than the maximum dimension specified in `dims` (plus one as python is 0 indexed). Returns: The sliced tensor. Raises: ValueError: If `inputs` tensor has insufficient rank.
371,579
def summarize_entity_person(person): ret = [] value = person.get("name") if not value: return False ret.append(value) prop = "courtesyName" value = json_get_first_item(person, prop) if value == u"不详": value = "" if value: ret.append(u.format(value)) val...
assume person entity using cnschma person vocabulary, http://cnschema.org/Person
371,580
def fit_interval_censoring( self, lower_bound, upper_bound, event_observed=None, timeline=None, label=None, alpha=None, ci_labels=None, show_progress=False, entry=None, weights=None, ): check_nans_or_infs(lowe...
Fit the model to an interval censored dataset. Parameters ---------- lower_bound: an array, or pd.Series length n, the start of the period the subject experienced the event in. upper_bound: an array, or pd.Series length n, the end of the period the subject experience...
371,581
def _connectionLost(self, reason): log.info(, self, reason) self.proto = None for tReq in self.requests.values(): tReq.sent = False if self._dDown: self._dDown.callback(None) elif self.requests: self._connect()
Called when the protocol connection is lost - Log the disconnection. - Mark any outstanding requests as unsent so they will be sent when a new connection is made. - If closing the broker client, mark completion of that process. :param reason: Failure that indicate...
371,582
def fit_allele_specific_predictors( self, n_models, architecture_hyperparameters_list, allele, peptides, affinities, inequalities=None, train_rounds=None, models_dir_for_save=None, verbose=0, ...
Fit one or more allele specific predictors for a single allele using one or more neural network architectures. The new predictors are saved in the Class1AffinityPredictor instance and will be used on subsequent calls to `predict`. Parameters ---------- n...
371,583
def _convert_file_records(self, file_records): for record in file_records: type_ = self.guess_type(record[], allow_directory=False) if type_ == : yield self._notebook_model_from_db(record, False) elif type_ == : yield self._file_model_...
Apply _notebook_model_from_db or _file_model_from_db to each entry in file_records, depending on the result of `guess_type`.
371,584
def update_assessment_taken(self, assessment_taken_form): collection = JSONClientValidated(, collection=, runtime=self._runtime) if not isinstance(assessment_taken_form, ABCAssessmentTakenForm): ...
Updates an existing assessment taken. arg: assessment_taken_form (osid.assessment.AssessmentTakenForm): the form containing the elements to be updated raise: IllegalState - ``assessment_taken_form`` already used in an update transaction raise:...
371,585
def _actionsFreqs(self,*args,**kwargs): acfs= self._actionsFreqsAngles(*args,**kwargs) return (acfs[0],acfs[1],acfs[2],acfs[3],acfs[4],acfs[5])
NAME: actionsFreqs (_actionsFreqs) PURPOSE: evaluate the actions and frequencies (jr,lz,jz,Omegar,Omegaphi,Omegaz) INPUT: Either: a) R,vR,vT,z,vz[,phi]: 1) floats: phase-space value for single object (phi is optional) (each can be a Quantit...
371,586
def monkeycache(apis): if isinstance(type(apis), type(None)) or apis is None: return {} verbs = set() cache = {} cache[] = apis[] cache[] = [] apilist = apis[] if apilist is None: print("[monkeycache] Server response issue, no apis found") for api in apilist: ...
Feed this a dictionary of api bananas, it spits out processed cache
371,587
def nt2codon_rep(ntseq): nt2num = {: 0, : 1, : 2, : 3, : 0, : 1, : 2, : 3} codon_rep = return .join([codon_rep[nt2num[ntseq[i]] + 4*nt2num[ntseq[i+1]] + 16*nt2num[ntseq[i+2]]] for i in range(0, len(ntseq), 3) if i+2 < len(ntseq)])
Represent nucleotide sequence by sequence of codon symbols. 'Translates' the nucleotide sequence into a symbolic representation of 'amino acids' where each codon gets its own unique character symbol. These characters should be reserved only for representing the 64 individual codons --- note that this...
371,588
def id(self, id): if id is None: raise ValueError("Invalid value for `id`, must not be `None`") if len(id) > 255: raise ValueError("Invalid value for `id`, length must be less than `255`") self._id = id
Sets the id of this Shift. UUID for this object :param id: The id of this Shift. :type: str
371,589
def toarray(vari): if isinstance(vari, Poly): shape = vari.shape out = numpy.asarray( [{} for _ in range(numpy.prod(shape))], dtype=object ) core = vari.A.copy() for key in core.keys(): core[key] = core[key].flatten() for...
Convert polynomial array into a numpy.asarray of polynomials. Args: vari (Poly, numpy.ndarray): Input data. Returns: (numpy.ndarray): A numpy array with ``Q.shape==A.shape``. Examples: >>> poly = cp.prange(3) >>> print(poly) [1, q0, q0^2] ...
371,590
def __on_download_progress_update(self, blocknum, blocksize, totalsize): if not self.__show_download_progress: return readsofar = blocknum * blocksize if totalsize > 0: s = "\r%s / %s" % (size(readsofar), size(totalsize)) sys.stdout.write(s) ...
Prints some download progress information :param blocknum: :param blocksize: :param totalsize: :return:
371,591
def create_equipamento_roteiro(self): return EquipamentoRoteiro( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of equipamento_roteiro services facade.
371,592
def get_times_modified(self): times_modified = self.conn.client.get(self.times_modified_key) if times_modified is None: return 0 return int(times_modified)
:returns: The total number of times increment_times_modified has been called for this resource by all processes. :rtype: int
371,593
def faces_to_path(mesh, face_ids=None, **kwargs): if face_ids is None: edges = mesh.edges_sorted else: edges = mesh.edges_sorted.reshape( (-1, 6))[face_ids].reshape((-1, 2)) unique_edges = grouping.group_rows( edges, require_count=1) kwargs.upd...
Given a mesh and face indices find the outline edges and turn them into a Path3D. Parameters --------- mesh : trimesh.Trimesh Triangulated surface in 3D face_ids : (n,) int Indexes referencing mesh.faces Returns --------- kwargs : dict Kwargs for Path3D constructor
371,594
def mkrngs(self): bbool = bool_2_indices(self.bkg) if bbool is not None: self.bkgrng = self.Time[bbool] else: self.bkgrng = [[np.nan, np.nan]] sbool = bool_2_indices(self.sig) if sbool is not None: self.sigrng = self.Time[sbool] ...
Transform boolean arrays into list of limit pairs. Gets Time limits of signal/background boolean arrays and stores them as sigrng and bkgrng arrays. These arrays can be saved by 'save_ranges' in the analyse object.
371,595
def unvectorize_args(fn): @wraps(fn) def new_fn(*args): return fn(np.asarray(args)) return new_fn
See Also -------- revrand.utils.decorators.vectorize_args Examples -------- The Rosenbrock function is commonly used as a performance test problem for optimization algorithms. It and its derivatives are included in `scipy.optimize` and is implemented as expected by the family of opti...
371,596
def get_count(self, unique_identifier, metric, start_date=None, end_date=None, **kwargs): result = None if start_date and end_date: start_date, end_date = (start_date, end_date,) if start_date < end_date else (end_date, start_date,) start_date = start_date if hasattr(st...
Gets the count for the ``metric`` for ``unique_identifier``. You can specify a ``start_date`` and an ``end_date``, to only get metrics within that time range. :param unique_identifier: Unique string indetifying the object this metric is for :param metric: A unique name for the metric you want t...
371,597
def start(self, labels=None): if labels is None: labels = self.dfltlbl if not isinstance(labels, (list, tuple)): labels = [labels,] t = timer() for lbl in labels: if lbl not in self.td: ...
Start specified timer(s). Parameters ---------- labels : string or list, optional (default None) Specify the label(s) of the timer(s) to be started. If it is ``None``, start the default timer with label specified by the ``dfltlbl`` parameter of :meth:`__init__`.
371,598
def split_semicolon(line, maxsplit=None): r split_line = line.split() split_line_size = len(split_line) if maxsplit is None or maxsplit < 0: maxsplit = split_line_size else: i += 1 return split_line
r"""Split a line on semicolons characters but not on the escaped semicolons :param line: line to split :type line: str :param maxsplit: maximal number of split (if None, no limit) :type maxsplit: None | int :return: split line :rtype: list >>> split_semicolon('a,b;c;;g') ['a,b', 'c', '...
371,599
def _convert_unsigned(data, fmt): num = len(data) return struct.unpack( "{}{}".format(num, fmt.upper()).encode("utf-8"), struct.pack("{}{}".format(num, fmt).encode("utf-8"), *data) )
Convert data from signed to unsigned in bulk.