docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Export all transcripts from the database Args: adapter(scout.adapter.MongoAdapter) build(str) Yields: transcript(scout.models.Transcript)
def export_transcripts(adapter, build='37'): LOG.info("Exporting all transcripts") for tx_obj in adapter.transcripts(build=build): yield tx_obj
615,434
Parse metadata for a gene panel For historical reasons it is possible to include all information about a gene panel in the header of a panel file. This function parses the header. Args: panel_lines(iterable(str)) Returns: panel_info(dict): Dictionary with panel information
def get_panel_info(panel_lines=None, panel_id=None, institute=None, version=None, date=None, display_name=None): panel_info = { 'panel_id': panel_id, 'institute': institute, 'version': version, 'date': date, 'display_name': display_name, } if ...
615,452
Parse a file with genes and return the hgnc ids Args: gene_lines(iterable(str)): Stream with genes Returns: genes(list(dict)): Dictionaries with relevant gene info
def parse_genes(gene_lines): genes = [] header = [] hgnc_identifiers = set() delimiter = '\t' # This can be '\t' or ';' delimiters = ['\t', ' ', ';'] # There are files that have '#' to indicate headers # There are some files that start with a header line without # any special s...
615,454
Parse the panel info and return a gene panel Args: path(str): Path to panel file institute(str): Name of institute that owns the panel panel_id(str): Panel id date(datetime.datetime): Date of creation version(float) full_name(str): Option ...
def parse_gene_panel(path, institute='cust000', panel_id='test', panel_type='clinical', date=datetime.now(), version=1.0, display_name=None, genes = None): LOG.info("Parsing gene panel %s", panel_id) gene_panel = {} gene_panel['path'] = path gene_panel['type'] = panel_type ...
615,455
Parse a panel app formated gene Args: app_gene(dict): Dict with panel app info hgnc_map(dict): Map from hgnc_symbol to hgnc_id Returns: gene_info(dict): Scout infromation
def parse_panel_app_gene(app_gene, hgnc_map): gene_info = {} confidence_level = app_gene['LevelOfConfidence'] # Return empty gene if not confident gene if not confidence_level == 'HighEvidence': return gene_info hgnc_symbol = app_gene['GeneSymbol'] # Returns a set of hgnc ids ...
615,456
Parse a PanelApp panel Args: panel_info(dict) hgnc_map(dict): Map from symbol to hgnc ids institute(str) panel_type(str) Returns: gene_panel(dict)
def parse_panel_app_panel(panel_info, hgnc_map, institute='cust000', panel_type='clinical'): date_format = "%Y-%m-%dT%H:%M:%S.%f" gene_panel = {} gene_panel['version'] = float(panel_info['version']) gene_panel['date'] = get_date(panel_info['Created'][:-1], date_format=date_format) gene_pan...
615,457
Return all genes that should be included in the OMIM-AUTO panel Return the hgnc symbols Genes that have at least one 'established' or 'provisional' phenotype connection are included in the gene panel Args: genemap2_lines(iterable) mim2gene_lines(iterable) alias_genes(di...
def get_omim_panel_genes(genemap2_lines, mim2gene_lines, alias_genes): parsed_genes = get_mim_genes(genemap2_lines, mim2gene_lines) STATUS_TO_ADD = set(['established', 'provisional']) for hgnc_symbol in parsed_genes: try: gene = parsed_genes[hgnc_symbol] keep =...
615,458
Parse the conservation predictors Args: variant(dict): A variant dictionary Returns: conservations(dict): A dictionary with the conservations
def parse_conservations(variant): conservations = {} conservations['gerp'] = parse_conservation( variant, 'dbNSFP_GERP___RS' ) conservations['phast'] = parse_conservation( ...
615,469
Get the conservation prediction Args: variant(dict): A variant dictionary info_key(str) Returns: conservations(list): List of censervation terms
def parse_conservation(variant, info_key): raw_score = variant.INFO.get(info_key) conservations = [] if raw_score: if isinstance(raw_score, numbers.Number): raw_score = (raw_score,) for score in raw_score: if score >= CONSERVATION[info_key]['conserved_min']: ...
615,470
Returns cases with phenotype If phenotypes are provided search for only those Args: adapter(adapter.MongoAdapter) institute_id(str): an institute _id slice_query(str): query to filter cases to obtain statistics for. Returns: data(dict): Dictionary with relevant inform...
def get_dashboard_info(adapter, institute_id=None, slice_query=None): LOG.debug("General query with institute_id {}.".format(institute_id)) # if institute_id == 'None' or None, all cases and general stats will be returned if institute_id == 'None': institute_id = None # If a slice_query ...
615,472
Return general information about cases Args: adapter(adapter.MongoAdapter) institute_id(str) slice_query(str): Query to filter cases to obtain statistics for. Returns: general(dict)
def get_general_case_info(adapter, institute_id=None, slice_query=None): general = {} # Potentially sensitive slice queries are assumed allowed if we have got this far name_query = slice_query cases = adapter.cases(owner=institute_id, name_query=name_query) phenotype_cases = 0 causative_...
615,473
Return the information about case groups Args: store(adapter.MongoAdapter) total_cases(int): Total number of cases slice_query(str): Query to filter cases to obtain statistics for. Returns: cases(dict):
def get_case_groups(adapter, total_cases, institute_id=None, slice_query=None): # Create a group with all cases in the database cases = [{'status': 'all', 'count': total_cases, 'percent': 1}] # Group the cases based on their status pipeline = [] group = {'$group' : {'_id': '$status', 'count': {...
615,474
Return information about analysis types. Group cases based on analysis type for the individuals. Args: adapter(adapter.MongoAdapter) total_cases(int): Total number of cases institute_id(str) slice_query(str): Query to filter cases to obtain statistics for. Returns: ...
def get_analysis_types(adapter, total_cases, institute_id=None, slice_query=None): # Group cases based on analysis type of the individuals query = {} subquery = {} if institute_id and slice_query: subquery = adapter.cases(owner=institute_id, name_query=slice_query, ...
615,475
Add a hpo object Arguments: hpo_obj(dict)
def load_hpo_term(self, hpo_obj): LOG.debug("Loading hpo term %s into database", hpo_obj['_id']) try: self.hpo_term_collection.insert_one(hpo_obj) except DuplicateKeyError as err: raise IntegrityError("Hpo term %s already exists in database".format(hpo_obj['_id']...
615,489
Add a hpo object Arguments: hpo_bulk(list(scout.models.HpoTerm)) Returns: result: pymongo bulkwrite result
def load_hpo_bulk(self, hpo_bulk): LOG.debug("Loading hpo bulk") try: result = self.hpo_term_collection.insert_many(hpo_bulk) except (DuplicateKeyError, BulkWriteError) as err: raise IntegrityError(err) return result
615,490
Fetch a hpo term Args: hpo_id(str) Returns: hpo_obj(dict)
def hpo_term(self, hpo_id): LOG.debug("Fetching hpo term %s", hpo_id) return self.hpo_term_collection.find_one({'_id': hpo_id})
615,491
Return all HPO terms If a query is sent hpo_terms will try to match with regex on term or description. Args: query(str): Part of a hpoterm or description hpo_term(str): Search for a specific hpo term limit(int): the number of desired results Returns...
def hpo_terms(self, query=None, hpo_term=None, text=None, limit=None): query_dict = {} search_term = None if query: query_dict = {'$or': [ {'hpo_id': {'$regex': query, '$options':'i'}}, {'description': {'$regex': query,...
615,492
Return a disease term Checks if the identifier is a disease number or a id Args: disease_identifier(str) Returns: disease_obj(dict)
def disease_term(self, disease_identifier): query = {} try: disease_identifier = int(disease_identifier) query['disease_nr'] = disease_identifier except ValueError: query['_id'] = disease_identifier return self.disease_term_collection.find_on...
615,493
Return all disease terms that overlaps a gene If no gene, return all disease terms Args: hgnc_id(int) Returns: iterable(dict): A list with all disease terms that match
def disease_terms(self, hgnc_id=None): query = {} if hgnc_id: LOG.debug("Fetching all diseases for gene %s", hgnc_id) query['genes'] = hgnc_id else: LOG.info("Fetching all disease terms") return list(self.disease_term_collection.find(query))
615,494
Load a disease term into the database Args: disease_obj(dict)
def load_disease_term(self, disease_obj): LOG.debug("Loading disease term %s into database", disease_obj['_id']) try: self.disease_term_collection.insert_one(disease_obj) except DuplicateKeyError as err: raise IntegrityError("Disease term %s already exists in dat...
615,495
Generate a sorted list with namedtuples of hpogenes Each namedtuple of the list looks like (hgnc_id, count) Args: hpo_terms(iterable(str)) Returns: hpo_genes(list(HpoGene))
def generate_hpo_gene_list(self, *hpo_terms): genes = {} for term in hpo_terms: hpo_obj = self.hpo_term(term) if hpo_obj: for hgnc_id in hpo_obj['genes']: if hgnc_id in genes: genes[hgnc_id] += 1 ...
615,496
Create a complete graph from the list of node ids. Args: node_ids: a list of node ids Returns: An undirected graph (as a networkx.Graph)
def _create_complete_graph(node_ids): g = nx.Graph() g.add_nodes_from(node_ids) for (i, j) in combinations(node_ids, 2): g.add_edge(i, j) return g
615,696
Estimate a CPDAG from the skeleton graph and separation sets returned by the estimate_skeleton() function. Args: skel_graph: A skeleton graph (an undirected networkx.Graph). sep_set: An 2D-array of separation set. The contents look like something like below. sep_set[...
def estimate_cpdag(skel_graph, sep_set): dag = skel_graph.to_directed() node_ids = skel_graph.nodes() for (i, j) in combinations(node_ids, 2): adj_i = set(dag.successors(i)) if j in adj_i: continue adj_j = set(dag.successors(j)) if i in adj_j: con...
615,698
Plot frequency spectrum of a given file Args: t (int): integration number to plot (0 -> len(data)) logged (bool): Plot in linear (False) or dB units (True) if_id (int): IF identification (if multiple IF signals in file) c: color for line kwargs: keywo...
def plot_spectrum(self, t=0, f_start=None, f_stop=None, logged=False, if_id=0, c=None, **kwargs): if self.header[b'nbits'] <=2: logged = False t='all' ax = plt.gca() plot_f, plot_data = self.grab_data(f_start, f_stop, if_id) #Using accending frequency f...
615,711
Plot frequency spectrum of a given file Args: logged (bool): Plot in linear (False) or dB units (True) if_id (int): IF identification (if multiple IF signals in file) c: color for line kwargs: keyword args to be passed to matplotlib plot()
def plot_spectrum_min_max(self, t=0, f_start=None, f_stop=None, logged=False, if_id=0, c=None, **kwargs): ax = plt.gca() plot_f, plot_data = self.grab_data(f_start, f_stop, if_id) #Using accending frequency for all plots. if self.header[b'foff'] < 0: plot_data = pl...
615,712
Plot waterfall of data Args: f_start (float): start frequency, in MHz f_stop (float): stop frequency, in MHz logged (bool): Plot in linear (False) or dB units (True), cb (bool): for plotting the colorbar kwargs: keyword args to be passed to matplotlib...
def plot_waterfall(self, f_start=None, f_stop=None, if_id=0, logged=True, cb=True, MJD_time=False, **kwargs): plot_f, plot_data = self.grab_data(f_start, f_stop, if_id) #Using accending frequency for all plots. if self.header[b'foff'] < 0: plot_data = plot_data[..., ::-1] ...
615,713
Plot the time series. Args: f_start (float): start frequency, in MHz f_stop (float): stop frequency, in MHz logged (bool): Plot in linear (False) or dB units (True), kwargs: keyword args to be passed to matplotlib imshow()
def plot_time_series(self, f_start=None, f_stop=None, if_id=0, logged=True, orientation='h', MJD_time=False, **kwargs): ax = plt.gca() plot_f, plot_data = self.grab_data(f_start, f_stop, if_id) if logged and self.header[b'nbits'] >= 8: plot_data = db(plot_data) #S...
615,714
Plot kurtosis Args: f_start (float): start frequency, in MHz f_stop (float): stop frequency, in MHz kwargs: keyword args to be passed to matplotlib imshow()
def plot_kurtosis(self, f_start=None, f_stop=None, if_id=0, **kwargs): ax = plt.gca() plot_f, plot_data = self.grab_data(f_start, f_stop, if_id) #Using accending frequency for all plots. if self.header[b'foff'] < 0: plot_data = plot_data[..., ::-1] # Reverse data ...
615,715
Write data to blimpy file. Args: filename_out (str): Name of output file
def write_to_filterbank(self, filename_out): print("[Filterbank] Warning: Non-standard function to write in filterbank (.fil) format. Please use Waterfall.") n_bytes = int(self.header[b'nbits'] / 8) with open(filename_out, "wb") as fileh: fileh.write(generate_sigproc_head...
615,717
Write data to HDF5 file. Args: filename_out (str): Name of output file
def write_to_hdf5(self, filename_out, *args, **kwargs): print("[Filterbank] Warning: Non-standard function to write in HDF5 (.h5) format. Please use Waterfall.") if not HAS_HDF5: raise RuntimeError("h5py package required for HDF5 output.") with h5py.File(filename_out, 'w'...
615,718
Rebin data by averaging bins together Args: d (np.array): data n_x (int): number of bins in x dir to rebin into one n_y (int): number of bins in y dir to rebin into one Returns: d: rebinned data with shape (n_x, n_y)
def rebin(d, n_x, n_y=None): if d.ndim == 2: if n_y is None: n_y = 1 if n_x is None: n_x = 1 d = d[:int(d.shape[0] // n_x) * n_x, :int(d.shape[1] // n_y) * n_y] d = d.reshape((d.shape[0] // n_x, n_x, d.shape[1] // n_y, n_y)) d = d.mean(axis=3) ...
615,730
Making sure the selection if time and frequency are within the file limits. Args: init (bool): If call during __init__
def _setup_selection_range(self, f_start=None, f_stop=None, t_start=None, t_stop=None, init=False): # This avoids resetting values if init is True: if t_start is None: t_start = self.t_begin if t_stop is None: t_stop = self.t_end ...
615,745
Constructor. Args: filename (str): filename of blimpy file. f_start (float): start frequency, in MHz f_stop (float): stop frequency, in MHz t_start (int): start time bin t_stop (int): stop time bin
def __init__(self, filename, f_start=None, f_stop=None, t_start=None, t_stop=None, load_data=True, max_load=1.): super(H5Reader, self).__init__() if filename and os.path.isfile(filename) and h5py.is_hdf5(filename): #These values may be modified once code for multi_beam and multi_s...
615,756
Constructor. Args: filename (str): filename of blimpy file. f_start (float): start frequency, in MHz f_stop (float): stop frequency, in MHz t_start (int): start time bin t_stop (int): stop time bin
def __init__(self, filename,f_start=None, f_stop=None,t_start=None, t_stop=None, load_data=True, max_load=1.): super(FilReader, self).__init__() self.header_keywords_types = sigproc.header_keyword_types if filename and os.path.isfile(filename): self.filename = filename ...
615,761
Read blimpy header and return a Python dictionary of key:value pairs Args: filename (str): name of file to open Optional args: return_idxs (bool): Default False. If true, returns the file offset indexes for values Returns: Py...
def read_header(self, return_idxs=False): self.header = sigproc.read_header(self.filename, return_idxs=return_idxs) return self.header
615,762
Write data to .fil file. It check the file size then decides how to write the file. Args: filename_out (str): Name of output file
def write_to_fil(self, filename_out, *args, **kwargs): #For timing how long it takes to write a file. t0 = time.time() #Update header self.__update_header() if self.container.isheavy(): self.__write_to_fil_heavy(filename_out) else: self...
615,773
Write data to .fil file. Args: filename_out (str): Name of output file
def __write_to_fil_heavy(self, filename_out, *args, **kwargs): #Note that a chunk is not a blob!! chunk_dim = self.__get_chunk_dimensions() blob_dim = self.__get_blob_dimensions(chunk_dim) n_blobs = self.container.calc_n_blobs(blob_dim) #Write header of .fil file ...
615,774
Write data to .fil file. Args: filename_out (str): Name of output file
def __write_to_fil_light(self, filename_out, *args, **kwargs): n_bytes = self.header[b'nbits'] / 8 with open(filename_out, "wb") as fileh: fileh.write(generate_sigproc_header(self)) #generate_sigproc_header comes from sigproc.py j = self.data if n_bytes == ...
615,775
Write data to HDF5 file. It check the file size then decides how to write the file. Args: filename_out (str): Name of output file
def write_to_hdf5(self, filename_out, *args, **kwargs): #For timing how long it takes to write a file. t0 = time.time() #Update header self.__update_header() if self.container.isheavy(): self.__write_to_hdf5_heavy(filename_out) else: se...
615,776
Write data to HDF5 file. Args: filename_out (str): Name of output file
def __write_to_hdf5_heavy(self, filename_out, *args, **kwargs): block_size = 0 #Note that a chunk is not a blob!! chunk_dim = self.__get_chunk_dimensions() blob_dim = self.__get_blob_dimensions(chunk_dim) n_blobs = self.container.calc_n_blobs(blob_dim) with h5...
615,777
Write data to HDF5 file in one go. Args: filename_out (str): Name of output file
def __write_to_hdf5_light(self, filename_out, *args, **kwargs): block_size = 0 with h5py.File(filename_out, 'w') as h5: h5.attrs[b'CLASS'] = b'FILTERBANK' h5.attrs[b'VERSION'] = b'1.0' if HAS_BITSHUFFLE: bs_compression = bitshuffle.h5.H5...
615,778
Extract a portion of data by frequency range. Args: f_start (float): start frequency in MHz f_stop (float): stop frequency in MHz if_id (int): IF input identification (req. when multiple IFs in file) Returns: (freqs, data) (np.arrays): frequency axis in ...
def grab_data(self, f_start=None, f_stop=None,t_start=None, t_stop=None, if_id=0): self.freqs = self.populate_freqs() self.timestamps = self.populate_timestamps() if f_start is None: f_start = self.freqs[0] if f_stop is None: f_stop = self.freqs[-1] ...
615,781
Return the length of the blimpy header, in bytes Args: filename (str): name of file to open Returns: idx_end (int): length of header, in bytes
def len_header(filename): with open(filename, 'rb') as f: header_sub_count = 0 eoh_found = False while not eoh_found: header_sub = f.read(512) header_sub_count += 1 if b'HEADER_END' in header_sub: idx_end = header_sub.index(b'HEADER_E...
615,811
Read blimpy header and return a Python dictionary of key:value pairs Args: filename (str): name of file to open Optional args: return_idxs (bool): Default False. If true, returns the file offset indexes for values returns
def read_header(filename, return_idxs=False): with open(filename, 'rb') as fh: header_dict = {} header_idxs = {} # Check this is a blimpy file keyword, value, idx = read_next_header_keyword(fh) try: assert keyword == b'HEADER_START' except Assertion...
615,814
Generate a serialized string for a sigproc keyword:value pair If value=None, just the keyword will be written with no payload. Data type is inferred by keyword name (via a lookup table) Args: keyword (str): Keyword to write value (None, float, str, double or angle): value to write to file ...
def to_sigproc_keyword(keyword, value=None): keyword = bytes(keyword) if value is None: return np.int32(len(keyword)).tostring() + keyword else: dtype = header_keyword_types[keyword] dtype_to_type = {b'<l' : np.int32, b'str' : str, ...
615,817
Generate a serialzed sigproc header which can be written to disk. Args: f (Filterbank object): Filterbank object for which to generate header Returns: header_str (str): Serialized string corresponding to header
def generate_sigproc_header(f): header_string = b'' header_string += to_sigproc_keyword(b'HEADER_START') for keyword in f.header.keys(): if keyword == b'src_raj': header_string += to_sigproc_keyword(b'src_raj') + to_sigproc_angle(f.header[b'src_raj']) elif keyword == b'sr...
615,818
Sign the message prior to sending the message. Args: msg (dict): The message to sign and relay.
def consume(self, msg): msg['body'] = crypto.sign(msg['body'], **self.hub.config) super(SigningRelayConsumer, self).consume(msg)
615,834
Checks that the sender is allowed to emit messages for the given topic. Args: topic (str): The message topic the ``signer`` used when sending the message. signer (str): The Common Name of the certificate used to sign the message. Returns: bool: True if the policy defined in the setting...
def validate_policy(topic, signer, routing_policy, nitpicky=False): if topic in routing_policy: # If so.. is the signer one of those permitted senders? if signer in routing_policy[topic]: # We are good. The signer of this message is explicitly # whitelisted to send on t...
615,911
Create a validator that checks if a setting is either None or a given type. Args: t: The type to assert. Returns: callable: A callable that will validate a setting for that type.
def _validate_none_or_type(t): def _validate(setting): if setting is not None and not isinstance(setting, t): raise ValueError('"{}" is not "{}"'.format(setting, t)) return setting return _validate
615,918
Load the configuration either from the config file, or from the given settings. Args: settings (dict): If given, the settings are pulled from this dictionary. Otherwise, the config file is used.
def load_config(self, settings=None): self._load_defaults() if settings: self.update(settings) else: config_paths = _get_config_files() for p in config_paths: conf = _process_config_file([p]) self.update(conf) s...
615,930
Internal method used for GET requests Args: url (str): URL to fetch Returns: Individual URL request's response Raises: HTTPError: If HTTP request failed.
def _get_sync(self, url): response = self.session.get(url) if response.status_code == requests.codes.ok: return response.json() else: raise HTTPError
617,724
Asynchronous internal method used for GET requests Args: url (str): URL to fetch session (obj): aiohttp client session for async loop Returns: data (obj): Individual URL request's response corountine
async def _get_async(self, url, session): data = None async with session.get(url) as resp: if resp.status == 200: data = await resp.json() return data
617,725
Asynchronous internal method used to request multiple URLs Args: urls (list): URLs to fetch Returns: responses (obj): All URL requests' response coroutines
async def _async_loop(self, urls): results = [] async with aiohttp.ClientSession( connector=aiohttp.TCPConnector(ssl=False) ) as session: for url in urls: result = asyncio.ensure_future(self._get_async(url, session)) results.append...
617,726
Asynchronous event loop execution Args: urls (list): URLs to fetch Returns: results (obj): All URL requests' responses
def _run_async(self, urls): loop = asyncio.get_event_loop() results = loop.run_until_complete(self._async_loop(urls)) return results
617,727
Given a list of item ids, return all the Item objects Args: item_ids (obj): List of item IDs to query item_type (str): (optional) Item type to filter results with Returns: List of `Item` objects for given item IDs and given item type
def get_items_by_ids(self, item_ids, item_type=None): urls = [urljoin(self.item_url, F"{i}.json") for i in item_ids] result = self._run_async(urls=urls) items = [Item(r) for r in result if r] if item_type: return [item for item in items if item.item_type == item_type...
617,730
Returns list of item ids of current top stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to represent all objects in raw json. Returns: `list` object containing ids of top stories.
def top_stories(self, raw=False, limit=None): top_stories = self._get_stories('topstories', limit) if raw: top_stories = [story.raw for story in top_stories] return top_stories
617,733
Returns list of item ids of current new stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. Returns: `list` object containing ids of new stories.
def new_stories(self, raw=False, limit=None): new_stories = self._get_stories('newstories', limit) if raw: new_stories = [story.raw for story in new_stories] return new_stories
617,734
Returns list of item ids of latest Ask HN stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. Returns: `list` object containing ids of Ask HN stories.
def ask_stories(self, raw=False, limit=None): ask_stories = self._get_stories('askstories', limit) if raw: ask_stories = [story.raw for story in ask_stories] return ask_stories
617,735
Returns list of item ids of latest Show HN stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. Returns: `list` object containing ids of Show HN storie...
def show_stories(self, raw=False, limit=None): show_stories = self._get_stories('showstories', limit) if raw: show_stories = [story.raw for story in show_stories] return show_stories
617,736
Returns list of item ids of latest Job stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. Returns: `list` object containing ids of Job stories.
def job_stories(self, raw=False, limit=None): job_stories = self._get_stories('jobstories', limit) if raw: job_stories = [story.raw for story in job_stories] return job_stories
617,737
The current largest item id Fetches data from URL: https://hacker-news.firebaseio.com/v0/maxitem.json Args: expand (bool): Flag to indicate whether to transform all IDs into objects. Returns: `int` if successful.
def get_max_item(self, expand=False): url = urljoin(self.base_url, 'maxitem.json') response = self._get_sync(url) if expand: return self.get_item(response) else: return response
617,739
Computes a http status code and message `CheckResponse` The return value a tuple (code, message, api_key_is_bad) where code: is the http status code message: is the message to return api_key_is_bad: indicates that a given api_key is bad Args: check_response (:class:`endpoints_management.ge...
def convert_response(check_response, project_id): if not check_response or not check_response.checkErrors: return _IS_OK # only check the first error for now, as per ESP theError = check_response.checkErrors[0] error_tuple = _CHECK_ERROR_CONVERSION.get(theError.code, _IS_UNKNOWN) if er...
617,780
Obtains a signature for an operation in a `CheckRequest` Args: op (:class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): an operation used in a `CheckRequest` Returns: string: a secure hash generated from the operation
def sign(check_request): if not isinstance(check_request, sc_messages.CheckRequest): raise ValueError(u'Invalid request') op = check_request.operation if op is None or op.operationName is None or op.consumerId is None: logging.error(u'Bad %s: not initialized => not signed', check_reques...
617,781
Adds the response from sending to `req` to this instance's cache. Args: req (`ServicecontrolServicesCheckRequest`): the request resp (CheckResponse): the response from sending the request
def add_response(self, req, resp): if self._cache is None: return signature = sign(req.checkRequest) with self._cache as c: now = self._timer() quota_scale = 0 # WIP item = c.get(signature) if item is None: c[s...
617,787
Compares two timestamps. ``a`` and ``b`` must be the same type, in addition to normal representations of timestamps that order naturally, they can be rfc3339 formatted strings. Args: a (string|object): a timestamp b (string|object): another timestamp Returns: int: -1 if a < b, 0...
def compare(a, b): a_is_text = isinstance(a, basestring) b_is_text = isinstance(b, basestring) if type(a) != type(b) and not (a_is_text and b_is_text): _logger.error(u'Cannot compare %s to %s, types differ %s!=%s', a, b, type(a), type(b)) raise ValueError(u'cannot ...
617,794
Constructor. If kinds is not specifed, all operations will be merged assuming they are of Kind ``DEFAULT_KIND`` Args: initial_op ( :class:`endpoints_management.gen.servicecontrol_v1_messages.Operation`): the initial version of the operation kin...
def __init__(self, initial_op, kinds=None): assert isinstance(initial_op, sc_messages.Operation) if kinds is None: kinds = {} self._kinds = kinds self._metric_values_by_name_then_sign = collections.defaultdict(dict) our_op = encoding.CopyProtoMessage(initial_...
617,799
Combines `other_op` with the operation held by this aggregator. N.B. It merges the operations log entries and metric values, but makes the assumption the operation is consistent. It's the callers responsibility to ensure consistency Args: other_op ( class:`endp...
def add(self, other_op): self._op.logEntries.extend(other_op.logEntries) self._merge_timestamps(other_op) self._merge_metric_values(other_op)
617,801
Creates a new instance of distribution with exponential buckets Args: num_finite_buckets (int): initializes number of finite buckets growth_factor (float): initializes the growth factor scale (float): initializes the scale Return: :class:`endpoints_management.gen.servicecontrol_v1_...
def create_exponential(num_finite_buckets, growth_factor, scale): if num_finite_buckets <= 0: raise ValueError(_BAD_NUM_FINITE_BUCKETS) if growth_factor <= 1.0: raise ValueError(_BAD_FLOAT_ARG % (u'growth factor', 1.0)) if scale <= 0.0: raise ValueError(_BAD_FLOAT_ARG % (u'scale...
617,804
Creates a new instance of distribution with linear buckets. Args: num_finite_buckets (int): initializes number of finite buckets width (float): initializes the width of each bucket offset (float): initializes the offset Return: :class:`endpoints_management.gen.servicecontrol_v1_mes...
def create_linear(num_finite_buckets, width, offset): if num_finite_buckets <= 0: raise ValueError(_BAD_NUM_FINITE_BUCKETS) if width <= 0.0: raise ValueError(_BAD_FLOAT_ARG % (u'width', 0.0)) return sc_messages.Distribution( bucketCounts=[0] * (num_finite_buckets + 2), l...
617,805
Creates a new instance of distribution with explicit buckets. bounds is an iterable of ordered floats that define the explicit buckets Args: bounds (iterable[float]): initializes the bounds Return: :class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution` Raises: ...
def create_explicit(bounds): safe_bounds = sorted(float(x) for x in bounds) if len(safe_bounds) != len(set(safe_bounds)): raise ValueError(u'Detected two elements of bounds that are the same') return sc_messages.Distribution( bucketCounts=[0] * (len(safe_bounds) + 1), explicitBu...
617,806
Adds `a_float` to `dist`, updating its existing buckets. Args: a_float (float): a new value dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`): the Distribution being updated Raises: ValueError: if `dist` does not have known bucket options defined ...
def add_sample(a_float, dist): dist_type, _ = _detect_bucket_option(dist) if dist_type == u'exponentialBuckets': _update_general_statistics(a_float, dist) _update_exponential_bucket_count(a_float, dist) elif dist_type == u'linearBuckets': _update_general_statistics(a_float, dist...
617,807
Determines whether two `Distributions` are nearly equal. Args: a_dist (:class:`Distribution`): an instance b_dist (:class:`Distribution`): another instance Return: boolean: `True` if the two instances are approximately equal, otherwise False
def _buckets_nearly_equal(a_dist, b_dist): a_type, a_buckets = _detect_bucket_option(a_dist) b_type, b_buckets = _detect_bucket_option(b_dist) if a_type != b_type: return False elif a_type == u'linearBuckets': return _linear_buckets_nearly_equal(a_buckets, b_buckets) elif a_type...
617,814
Adds a_float to distribution, updating the statistics fields. Args: a_float (float): a new value dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`): the Distribution being updated
def _update_general_statistics(a_float, dist): if not dist.count: dist.count = 1 dist.maximum = a_float dist.minimum = a_float dist.mean = a_float dist.sumOfSquaredDeviation = 0 else: old_count = dist.count old_mean = dist.mean new_mean = ((ol...
617,815
Adds `a_float` to `dist`, updating its exponential buckets. Args: a_float (float): a new value dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`): the Distribution being updated Raises: ValueError: if `dist` does not already have exponential buckets defi...
def _update_exponential_bucket_count(a_float, dist): buckets = dist.exponentialBuckets if buckets is None: raise ValueError(_BAD_UNSET_BUCKETS % (u'exponential buckets')) bucket_counts = dist.bucketCounts num_finite_buckets = buckets.numFiniteBuckets if len(bucket_counts) < num_finite_b...
617,816
Adds `a_float` to `dist`, updating the its linear buckets. Args: a_float (float): a new value dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`): the Distribution being updated Raises: ValueError: if `dist` does not already have linear buckets defined ...
def _update_linear_bucket_count(a_float, dist): buckets = dist.linearBuckets if buckets is None: raise ValueError(_BAD_UNSET_BUCKETS % (u'linear buckets')) bucket_counts = dist.bucketCounts num_finite_buckets = buckets.numFiniteBuckets if len(bucket_counts) < num_finite_buckets + 2: ...
617,817
Adds `a_float` to `dist`, updating its explicit buckets. Args: a_float (float): a new value dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`): the Distribution being updated Raises: ValueError: if `dist` does not already have explict buckets defined ...
def _update_explicit_bucket_count(a_float, dist): buckets = dist.explicitBuckets if buckets is None: raise ValueError(_BAD_UNSET_BUCKETS % (u'explicit buckets')) bucket_counts = dist.bucketCounts bounds = buckets.bounds if len(bucket_counts) < len(bounds) + 1: raise ValueError(_...
617,818
Determine if an instance of `Money` is valid. Args: money (:class:`endpoints_management.gen.servicecontrol_v1_messages.Money`): the instance to test Raises: ValueError: if the money instance is invalid
def check_valid(money): if not isinstance(money, sc_messages.Money): raise ValueError(u'Inputs should be of type %s' % (sc_messages.Money,)) currency = money.currencyCode if not currency or len(currency) != 3: raise ValueError(_MSG_3_LETTERS_LONG) units = money.units nanos = mon...
617,825
Determines the amount sign of a money instance Args: money (:class:`endpoints_management.gen.servicecontrol_v1_messages.Money`): the instance to test Return: int: 1, 0 or -1
def _sign_of(money): units = money.units nanos = money.nanos if units: if units > 0: return 1 elif units < 0: return -1 if nanos: if nanos > 0: return 1 elif nanos < 0: return -1 return 0
617,828
Verifies that the required claims exist. Args: jwt_claims: the JWT claims to be verified. Raises: UnauthenticatedException: if some claim doesn't exist.
def _verify_required_claims_exist(jwt_claims): for claim_name in [u"aud", u"exp", u"iss", u"sub"]: if claim_name not in jwt_claims: raise suppliers.UnauthenticatedException(u'Missing "%s" claim' % claim_name)
617,830
Construct an instance of AuthTokenDecoder. Args: issuers_to_provider_ids: a dictionary mapping from issuers to provider IDs defined in the service configuration. jwks_supplier: an instance of JwksSupplier that supplies JWKS based on issuer. cache_capacity: ...
def __init__(self, issuers_to_provider_ids, jwks_supplier, cache_capacity=200): self._issuers_to_provider_ids = issuers_to_provider_ids self._jwks_supplier = jwks_supplier arguments = {u"capacity": cache_capacity} expiration_time = datetime.timedelta(minutes=5) self._ca...
617,831
Converts a datetime_func to a timestamp_func. Args: datetime_func (callable[[datatime]]): a func that returns the current time Returns: time_func (callable[[timestamp]): a func that returns the timestamp from the epoch
def to_cache_timer(datetime_func): if datetime_func is None: datetime_func = datetime.utcnow def _timer(): return (datetime_func() - datetime(1970, 1, 1)).total_seconds() return _timer
617,836
Constructor. Args: maxsize (int): the maximum number of entries in the queue ttl (int): the ttl for entries added to the cache out_deque :class:`collections.deque`: a `deque` in which to add items that expire from the cache **kw: the other keyword args suppor...
def __init__(self, maxsize, ttl, out_deque=None, **kw): super(DequeOutTTLCache, self).__init__(maxsize, ttl, **kw) if out_deque is None: out_deque = collections.deque() elif not isinstance(out_deque, collections.deque): raise ValueError(u'out_deque should be a co...
617,839
Constructor. Args: maxsize (int): the maximum number of entries in the queue out_deque :class:`collections.deque`: a `deque` in which to add items that expire from the cache **kw: the other keyword args supported by constructor to :class:`cachetools.LRUCach...
def __init__(self, maxsize, out_deque=None, **kw): super(DequeOutLRUCache, self).__init__(maxsize, **kw) if out_deque is None: out_deque = collections.deque() elif not isinstance(out_deque, collections.deque): raise ValueError(u'out_deque should be collections.de...
617,842
Constructs a new metric value. This acts as an alternate to MetricValue constructor which simplifies specification of labels. Rather than having to create a MetricValue.Labels instance, all that's necessary to specify the required string. Args: labels (dict([string, [string]]): **kw: ...
def create(labels=None, **kw): if labels is not None: kw[u'labels'] = encoding.PyValueToMessage(MetricValue.LabelsValue, labels) return MetricValue(**kw)
617,866
Merges `prior` and `latest` Args: metric_kind (:class:`MetricKind`): indicates the kind of metrics being merged prior (:class:`MetricValue`): an prior instance of the metric latest (:class:`MetricValue`: the latest instance of the metric
def merge(metric_kind, prior, latest): prior_type, _ = _detect_value(prior) latest_type, _ = _detect_value(latest) if prior_type != latest_type: _logger.warn(u'Metric values are not compatible: %s, %s', prior, latest) raise ValueError(u'Incompatible delta metric val...
617,867
Adds ``mv`` to ``a_hash`` Args: a_hash (`Hash`): the secure hash, e.g created by hashlib.md5 mv (:class:`MetricValue`): the instance to add to the hash
def update_hash(a_hash, mv): if mv.labels: signing.add_dict_to_hash(a_hash, encoding.MessageToPyValue(mv.labels)) money_value = mv.get_assigned_value(u'moneyValue') if money_value is not None: a_hash.update(b'\x00') a_hash.update(money_value.currencyCode.encode('utf-8'))
617,868
Obtains a signature for a `MetricValue` Args: mv (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricValue`): a MetricValue that's part of an operation Returns: string: a unique signature for that operation
def sign(mv): md5 = hashlib.md5() update_hash(md5, mv) return md5.digest()
617,869
Supplies the `jwks_uri` for the given issuer. Args: issuer: the issuer. Returns: The `jwks_uri` that is either statically configured or retrieved via OpenId discovery. None is returned when the issuer is unknown or the OpenId discovery fails.
def supply(self, issuer): issuer_uri_config = self._issuer_uri_configs.get(issuer) if not issuer_uri_config: # The issuer is unknown. return jwks_uri = issuer_uri_config.jwks_uri if jwks_uri: # When jwks_uri is set, return it directly. ...
617,878
Constructs an instance of JwksSupplier. Args: key_uri_supplier: a KeyUriSupplier instance that returns the `jwks_uri` based on the given issuer.
def __init__(self, key_uri_supplier): self._key_uri_supplier = key_uri_supplier self._jwks_cache = cache.make_region().configure( u"dogpile.cache.memory", expiration_time=datetime.timedelta(minutes=5))
617,879
Supplies the `Json Web Key Set` for the given issuer. Args: issuer: the issuer. Returns: The successfully retrieved Json Web Key Set. None is returned if the issuer is unknown or the retrieval process fails. Raises: UnauthenticatedException: When this...
def supply(self, issuer): def _retrieve_jwks(): jwks_uri = self._key_uri_supplier.supply(issuer) if not jwks_uri: raise UnauthenticatedException(u"Cannot find the `jwks_uri` for issuer " u"%s: either th...
617,880
Create an instance of IsserUriConfig. Args: open_id_valid: indicates whether the corresponding issuer is valid for OpenId discovery. jwks_uri: is the saved jwks_uri. Its value can be None if the OpenId discovery process has not begun or has already failed.
def __init__(self, open_id_valid, jwks_uri): self._open_id_valid = open_id_valid self._jwks_uri = jwks_uri
617,881
Constructor. update_label_func is used when updating a label in an `Operation` from a `ReportRequestInfo`. Args: label_name (str): the name of the label descriptor value_type (:class:`ValueType`): the `value type` of the described metric kind (:class:`Kind`): t...
def __init__(self, label_name, value_type, kind, update_label_func): self.label_name = label_name self.kind = kind self.update_label_func = update_label_func self.value_type = value_type
617,892
Determines if a given label descriptor matches this enum instance Args: desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`): the instance to test Return: `True` if desc is supported, otherwise `False`
def matches(self, desc): desc_value_type = desc.valueType or ValueType.STRING # default not parsed return (self.label_name == desc.key and self.value_type == desc_value_type)
617,893
Updates a dictionary of labels using the assigned update_op_func Args: info (:class:`endpoints_management.control.report_request.Info`): the info instance to update labels (dict[string[string]]): the labels dictionary Return: `True` if desc is supported, ...
def do_labels_update(self, info, labels): if self.update_label_func: self.update_label_func(self.label_name, info, labels)
617,894
Determines if the given label descriptor is supported. Args: desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`): the label descriptor to test Return: `True` if desc is supported, otherwise `False`
def is_supported(cls, desc): for l in cls: if l.matches(desc): return True return False
617,895
Constructor. Args: service (:class:`endpoints_management.gen.servicemanagement_v1_messages.Service`): a service instance
def __init__(self, service): if not isinstance(service, sm_messages.Service): raise ValueError(u'service should be an instance of Service') if not service.name: raise ValueError(u'Bad service: the name is missing') self._service = service # the service that pro...
617,905
Initializes an LruBackend. Args: options: a dictionary that contains configuration options.
def __init__(self, options): capacity = options[u"capacity"] if u"capacity" in options else 200 self._cache = pylru.lrucache(capacity)
617,926
Create an instance of :class:`google.auth.tokens.Authenticator`. Args: a_service (:class:`endpoints_management.gen.servicemanagement_v1_messages.Service`): a service instance
def _create_authenticator(a_service): if not isinstance(a_service, sm_messages.Service): raise ValueError(u"service is None or not an instance of Service") authentication = a_service.authentication if not authentication: _logger.info(u"authentication is not configured in service, " ...
617,939
Initializes a new Middleware instance. Args: application: the wrapped wsgi application a_service (:class:`endpoints_management.gen.servicemanagement_v1_messages.Service`): a service instance
def __init__(self, application, a_service): if not isinstance(a_service, sm_messages.Service): raise ValueError(u"service is None or not an instance of Service") self._application = application self._service = a_service method_registry, reporting_rules = self._conf...
617,947
Initializes a new Middleware instance. Args: application: the wrapped wsgi application project_id: the project_id thats providing service control support control_client: the service control client instance next_operation_id (func): produces the next operation ...
def __init__(self, application, project_id, control_client, next_operation_id=_next_operation_uuid, timer=datetime.utcnow): self._application = application self._project_id = project_id self._control_cl...
617,950