Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def poll(self): if self._subprocess is not None: self._subprocess.poll() time.sleep(self._beaver_config.get('subprocess_poll_sleep'))
[ "Poll attached subprocess until it is available" ]
Please provide a description of the function:def close(self): if self._subprocess is not None: os.killpg(self._subprocess.pid, signal.SIGTERM) self._subprocess = None
[ "Close child subprocess" ]
Please provide a description of the function:def callback(self, filename, lines, **kwargs): timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] for line in lines: try: import warnings ...
[ "publishes lines one by one to the given topic" ]
Please provide a description of the function:def _to_unicode(self, data, encoding, errors='strict'): '''Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases''' # strip Byte Order Mark (if present) if (len(data) >= 4) and (data[:2] == '\...
[]
Please provide a description of the function:def callback(self, filename, lines, **kwargs): timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] for line in lines: try: import warnings ...
[ "publishes lines one by one to the given topic" ]
Please provide a description of the function:def reconnect(self): try: self.conn.close() except Exception,e: self.logger.warn(e) self.createConnection() return True
[ "Allows reconnection from when a handled\n TransportException is thrown" ]
Please provide a description of the function:def _check_connections(self): for server in self._servers: if self._is_reachable(server): server['down_until'] = 0 else: server['down_until'] = time.time() + 5
[ "Checks if all configured redis servers are reachable" ]
Please provide a description of the function:def _is_reachable(self, server): try: server['redis'].ping() return True except UserWarning: self._logger.warn('Cannot reach redis server: ' + server['url']) except Exception: self._logger.warn...
[ "Checks if the given redis server is reachable" ]
Please provide a description of the function:def invalidate(self): super(RedisTransport, self).invalidate() for server in self._servers: server['redis'].connection_pool.disconnect() return False
[ "Invalidates the current transport and disconnects all redis connections" ]
Please provide a description of the function:def callback(self, filename, lines, **kwargs): self._logger.debug('Redis transport called') timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] namespaces = self._beaver_c...
[ "Sends log lines to redis servers" ]
Please provide a description of the function:def _get_next_server(self): current_try = 0 max_tries = len(self._servers) while current_try < max_tries: server_index = self._raise_server_index() server = self._servers[server_index] down_until = serve...
[ "Returns a valid redis server or raises a TransportException" ]
Please provide a description of the function:def _raise_server_index(self): self._current_server_index = (self._current_server_index + 1) % len(self._servers) return self._current_server_index
[ "Round robin magic: Raises the current redis server index and returns it" ]
Please provide a description of the function:def valid(self): valid_servers = 0 for server in self._servers: if server['down_until'] <= time.time(): valid_servers += 1 return valid_servers > 0
[ "Returns whether or not the transport can send data to any redis server" ]
Please provide a description of the function:def callback(self, filename, lines, **kwargs): timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] for line in lines: try: import warnings ...
[ "publishes lines one by one to the given topic" ]
Please provide a description of the function:def format(self, filename, line, timestamp, **kwargs): line = unicode(line.encode("utf-8"), "utf-8", errors="ignore") formatter = self._beaver_config.get_field('format', filename) if formatter not in self._formatters: formatter = ...
[ "Returns a formatted log line" ]
Please provide a description of the function:def get_timestamp(self, **kwargs): timestamp = kwargs.get('timestamp') if not timestamp: now = datetime.datetime.utcnow() timestamp = now.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (now.microsecond / 1000) + "Z" return...
[ "Retrieves the timestamp for a given set of data" ]
Please provide a description of the function:def _make_executable(path): os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
[ "Make the file at path executable." ]
Please provide a description of the function:def build_parser(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Required args parser.add_argument("--in_path", "-i", required=True, ...
[ "Build argument parser." ]
Please provide a description of the function:def subset_main(args): # Read in each of the command line arguments rid = _read_arg(args.rid) cid = _read_arg(args.cid) exclude_rid = _read_arg(args.exclude_rid) exclude_cid = _read_arg(args.exclude_cid) # If GCT, use subset_gctoo if args.i...
[ " Separate method from main() in order to make testing easier and to\n enable command-line access. " ]
Please provide a description of the function:def _read_arg(arg): # If arg is None, just return it back if arg is None: arg_out = arg else: # If len(arg) == 1 and arg[0] is a valid filepath, read it as a grp file if len(arg) == 1 and os.path.exists(arg[0]): arg_out ...
[ "\n If arg is a list with 1 element that corresponds to a valid file path, use\n set_io.grp to read the grp file. Otherwise, check that arg is a list of strings.\n\n Args:\n arg (list or None)\n\n Returns:\n arg_out (list or None)\n " ]
Please provide a description of the function:def fast_cov(x, y=None, destination=None): validate_inputs(x, y, destination) if y is None: y = x if destination is None: destination = numpy.zeros((x.shape[1], y.shape[1])) mean_x = numpy.mean(x, axis=0) mean_y = numpy.mean(y, axi...
[ "calculate the covariance matrix for the columns of x (MxN), or optionally, the covariance matrix between the\n columns of x and and the columns of y (MxP). (In the language of statistics, the columns are variables, the rows\n are observations).\n\n Args:\n x (numpy array-like) MxN in shape\n ...
Please provide a description of the function:def read(file_path): # Read in file actual_file_path = os.path.expanduser(file_path) with open(actual_file_path, 'r') as f: lines = f.readlines() # Create GMT object gmt = [] # Iterate over each line for line_num, line in en...
[ " Read a gmt file at the path specified by file_path.\n\n Args:\n file_path (string): path to gmt file\n\n Returns:\n gmt (GMT object): list of dicts, where each dict corresponds to one\n line of the GMT file\n\n " ]
Please provide a description of the function:def verify_gmt_integrity(gmt): # Verify that set ids are unique set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt] assert len(set(set_ids)) == len(set_ids), ( "Set identifiers should be unique. set_ids: {}".format(set_ids))
[ " Make sure that set ids are unique.\n\n Args:\n gmt (GMT object): list of dicts\n\n Returns:\n None\n\n " ]
Please provide a description of the function:def write(gmt, out_path): with open(out_path, 'w') as f: for _, each_dict in enumerate(gmt): f.write(each_dict[SET_IDENTIFIER_FIELD] + '\t') f.write(each_dict[SET_DESC_FIELD] + '\t') f.write('\t'.join([str(entry) for entry...
[ " Write a GMT to a text file.\n\n Args:\n gmt (GMT object): list of dicts\n out_path (string): output path\n\n Returns:\n None\n\n " ]
Please provide a description of the function:def diff_gctoo(gctoo, plate_control=True, group_field='pert_type', group_val='ctl_vehicle', diff_method="robust_z", upper_diff_thresh=10, lower_diff_thresh=-10): ''' Converts a matrix of values (e.g. gene expression, viability, etc.) into a matrix of d...
[]
Please provide a description of the function:def parse(gctx_file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False): full_path = os.path.expanduser(gctx_file_path) # Verify that the path exists if not os.pat...
[ "\n Primary method of script. Reads in path to a gctx file and parses into GCToo object.\n\n Input:\n Mandatory:\n - gctx_file_path (str): full path to gctx file you want to parse.\n\n Optional:\n - convert_neg_666 (bool): whether to convert -666 values to numpy.nan or not\n ...
Please provide a description of the function:def check_and_order_id_inputs(rid, ridx, cid, cidx, row_meta_df, col_meta_df): (row_type, row_ids) = check_id_idx_exclusivity(rid, ridx) (col_type, col_ids) = check_id_idx_exclusivity(cid, cidx) row_ids = check_and_convert_ids(row_type, row_ids, row_meta_df...
[ "\n Makes sure that (if entered) id inputs entered are of one type (string id or index)\n Input:\n - rid (list or None): if not None, a list of rids\n - ridx (list or None): if not None, a list of indexes\n - cid (list or None): if not None, a list of cids\n - cidx (list or None): ...
Please provide a description of the function:def check_id_idx_exclusivity(id, idx): if (id is not None and idx is not None): msg = ("'id' and 'idx' fields can't both not be None," + " please specify subset in only one of these fields") logger.error(msg) raise Exception("p...
[ "\n Makes sure user didn't provide both ids and idx values to subset by.\n\n Input:\n - id (list or None): if not None, a list of string id names\n - idx (list or None): if not None, a list of integer id indexes\n\n Output:\n - a tuple: first element is subset type, second is subset co...
Please provide a description of the function:def get_ordered_idx(id_type, id_list, meta_df): if meta_df is not None: if id_type is None: id_list = range(0, len(list(meta_df.index))) elif id_type == "id": lookup = {x: i for (i,x) in enumerate(meta_df.index)} i...
[ "\n Gets index values corresponding to ids to subset and orders them.\n Input:\n - id_type (str): either \"id\", \"idx\" or None\n - id_list (list): either a list of indexes or id names\n Output:\n - a sorted list of indexes to subset a dimension by\n " ]
Please provide a description of the function:def parse_metadata_df(dim, meta_group, convert_neg_666): # read values from hdf5 & make a DataFrame header_values = {} array_index = 0 for k in meta_group.keys(): curr_dset = meta_group[k] temp_array = np.empty(curr_dset.shape, dtype=curr...
[ "\n Reads in all metadata from .gctx file to pandas DataFrame\n with proper GCToo specifications.\n Input:\n - dim (str): Dimension of metadata; either \"row\" or \"column\"\n - meta_group (HDF5 group): Group from which to read metadata values\n - convert_neg_666 (bool): whether to con...
Please provide a description of the function:def replace_666(meta_df, convert_neg_666): if convert_neg_666: out_df = meta_df.replace([-666, "-666", -666.0], np.nan) else: out_df = meta_df.replace([-666, -666.0], "-666") return out_df
[ " Replace -666, -666.0, and optionally \"-666\".\n Args:\n meta_df (pandas df):\n convert_neg_666 (bool):\n Returns:\n out_df (pandas df): updated meta_df\n " ]
Please provide a description of the function:def set_metadata_index_and_column_names(dim, meta_df): if dim == "row": meta_df.index.name = "rid" meta_df.columns.name = "rhd" elif dim == "col": meta_df.index.name = "cid" meta_df.columns.name = "chd"
[ "\n Sets index and column names to GCTX convention.\n Input:\n - dim (str): Dimension of metadata to read. Must be either \"row\" or \"col\"\n - meta_df (pandas.DataFrame): data frame corresponding to metadata fields\n of dimension specified.\n Output:\n None\n " ]
Please provide a description of the function:def parse_data_df(data_dset, ridx, cidx, row_meta, col_meta): if len(ridx) == len(row_meta.index) and len(cidx) == len(col_meta.index): # no subset data_array = np.empty(data_dset.shape, dtype=np.float32) data_dset.read_direct(data_array) da...
[ "\n Parses in data_df from hdf5, subsetting if specified.\n\n Input:\n -data_dset (h5py dset): HDF5 dataset from which to read data_df\n -ridx (list): list of indexes to subset from data_df\n (may be all of them if no subsetting)\n -cidx (list): list of indexes to subset from d...
Please provide a description of the function:def get_column_metadata(gctx_file_path, convert_neg_666=True): full_path = os.path.expanduser(gctx_file_path) # open file gctx_file = h5py.File(full_path, "r") col_dset = gctx_file[col_meta_group_node] col_meta = parse_metadata_df("col", col_dset, co...
[ "\n Opens .gctx file and returns only column metadata\n\n Input:\n Mandatory:\n - gctx_file_path (str): full path to gctx file you want to parse.\n\n Optional:\n - convert_neg_666 (bool): whether to convert -666 values to num\n\n Output:\n - col_meta (pandas DataFrame): a...
Please provide a description of the function:def get_row_metadata(gctx_file_path, convert_neg_666=True): full_path = os.path.expanduser(gctx_file_path) # open file gctx_file = h5py.File(full_path, "r") row_dset = gctx_file[row_meta_group_node] row_meta = parse_metadata_df("row", row_dset, conve...
[ "\n Opens .gctx file and returns only row metadata\n\n Input:\n Mandatory:\n - gctx_file_path (str): full path to gctx file you want to parse.\n\n Optional:\n - convert_neg_666 (bool): whether to convert -666 values to num\n\n Output:\n - row_meta (pandas DataFrame): a Da...
Please provide a description of the function:def multi_index_df_to_component_dfs(multi_index_df, rid="rid", cid="cid"): # Id level of the multiindex will become the index rids = list(multi_index_df.index.get_level_values(rid)) cids = list(multi_index_df.columns.get_level_values(cid)) # It's possi...
[ " Convert a multi-index df into 3 component dfs. " ]
Please provide a description of the function:def check_df(self, df): if isinstance(df, pd.DataFrame): if not df.index.is_unique: repeats = df.index[df.index.duplicated()].values msg = "Index values must be unique but aren't. The following entries appear more ...
[ "\n Verifies that df is a pandas DataFrame instance and\n that its index and column values are unique.\n " ]
Please provide a description of the function:def id_match_check(self, data_df, meta_df, dim): if dim == "row": if len(data_df.index) == len(meta_df.index) and set(data_df.index) == set(meta_df.index): return True else: msg = ("The rids are inconsi...
[ "\n Verifies that id values match between:\n - row case: index of data_df & index of row metadata\n - col case: columns of data_df & index of column metadata\n " ]
Please provide a description of the function:def assemble_multi_index_df(self): #prepare row index self.logger.debug("Row metadata shape: {}".format(self.row_metadata_df.shape)) self.logger.debug("Is empty? {}".format(self.row_metadata_df.empty)) row_copy = pd.DataFrame(self.row...
[ "Assembles three component dataframes into a multiindex dataframe.\n Sets the result to self.multi_index_df.\n IMPORTANT: Cross-section (\"xs\") is the best command for selecting\n data. Be sure to use the flag \"drop_level=False\" with this command,\n or else the dataframe that is retur...
Please provide a description of the function:def parse(file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False): assert sum([row_meta_only, col_meta_only]) <= 1, ( "row_meta_only and col_meta_only cannot both b...
[ "\n The main method.\n\n Args:\n - file_path (string): full path to gct(x) file you want to parse\n - convert_neg_666 (bool): whether to convert -666 values to numpy.nan\n (see Note below for more details). Default = False.\n - rid (list of strings): list of row ids to specific...
Please provide a description of the function:def are_genes_in_api(my_clue_api_client, gene_symbols): if len(gene_symbols) > 0: query_gene_symbols = gene_symbols if type(gene_symbols) is list else list(gene_symbols) query_result = my_clue_api_client.run_filter_query(resource_name, {...
[ "determine if genes are present in the API\n\n Args:\n my_clue_api_client:\n gene_symbols: collection of gene symbols to query the API with\n\n Returns: set of the found gene symbols\n\n " ]
Please provide a description of the function:def write(gctoo, out_fname, data_null="NaN", metadata_null="-666", filler_null="-666", data_float_format="%.4f"): # Create handle for output file if not out_fname.endswith(".gct"): out_fname += ".gct" f = open(out_fname, "w") # Write first two l...
[ "Write a gctoo object to a gct file.\n\n Args:\n gctoo (gctoo object)\n out_fname (string): filename for output gct file\n data_null (string): how to represent missing values in the data (default = \"NaN\")\n metadata_null (string): how to represent missing values in the metadata (def...
Please provide a description of the function:def write_version_and_dims(version, dims, f): f.write(("#" + version + "\n")) f.write((dims[0] + "\t" + dims[1] + "\t" + dims[2] + "\t" + dims[3] + "\n"))
[ "Write first two lines of gct file.\n\n Args:\n version (string): 1.3 by default\n dims (list of strings): length = 4\n f (file handle): handle of output file\n Returns:\n nothing\n " ]
Please provide a description of the function:def write_top_half(f, row_metadata_df, col_metadata_df, metadata_null, filler_null): # Initialize the top half of the gct including the third line size_of_top_half_df = (1 + col_metadata_df.shape[1], 1 + row_metadata_df.shape[1] + col_...
[ " Write the top half of the gct file: top-left filler values, row metadata\n headers, and top-right column metadata.\n\n Args:\n f (file handle): handle for output file\n row_metadata_df (pandas df)\n col_metadata_df (pandas df)\n metadata_null (string): how to represent missing va...
Please provide a description of the function:def write_bottom_half(f, row_metadata_df, data_df, data_null, data_float_format, metadata_null): # create the left side of the bottom half of the gct (for the row metadata) size_of_left_bottom_half_df = (row_metadata_df.shape[0], 1 ...
[ " Write the bottom half of the gct file: row metadata and data.\n\n Args:\n f (file handle): handle for output file\n row_metadata_df (pandas df)\n data_df (pandas df)\n data_null (string): how to represent missing values in the data\n metadata_null (string): how to represent m...
Please provide a description of the function:def append_dims_and_file_extension(fname, data_df): # If there's no .gct at the end of output file name, add the dims and .gct if not fname.endswith(".gct"): out_fname = '{0}_n{1}x{2}.gct'.format(fname, data_df.shape[1], data_df.shape[0]) return ...
[ "Append dimensions and file extension to output filename.\n N.B. Dimensions are cols x rows.\n\n Args:\n fname (string): output filename\n data_df (pandas df)\n Returns:\n out_fname (string): output filename with matrix dims and .gct appended\n " ]
Please provide a description of the function:def robust_zscore(mat, ctrl_mat=None, min_mad=0.1): ''' Robustly z-score a pandas df along the rows. Args: mat (pandas df): Matrix of data that z-scoring will be applied to ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs ...
[]
Please provide a description of the function:def gct2gctx_main(args): in_gctoo = parse_gct.parse(args.filename, convert_neg_666=False) if args.output_filepath is None: basename = os.path.basename(args.filename) out_name = os.path.splitext(basename)[0] + ".gctx" else: out_name ...
[ " Separate from main() in order to make command-line tool. ", " If annotations are supplied, parse table and set metadata_df " ]
Please provide a description of the function:def parse(file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False): if file_path.endswith(".gct"): out = parse_gct.parse(file_path, convert_neg_666=convert_neg_666, ...
[ "\n Identifies whether file_path corresponds to a .gct or .gctx file and calls the\n correct corresponding parse method.\n\n Input:\n Mandatory:\n - gct(x)_file_path (str): full path to gct(x) file you want to parse.\n\n Optional:\n - convert_neg_666 (bool): whether to convert -...
Please provide a description of the function:def get_upper_triangle(correlation_matrix): ''' Extract upper triangle from a square matrix. Negative values are set to 0. Args: correlation_matrix (pandas df): Correlations between all replicates Returns: upper_tri_df (pandas df): Upper triangle ex...
[]
Please provide a description of the function:def calculate_weights(correlation_matrix, min_wt): ''' Calculate a weight for each profile based on its correlation to other replicates. Negative correlations are clipped to 0, and weights are clipped to be min_wt at the least. Args: correlation_matrix (...
[]
Please provide a description of the function:def agg_wt_avg(mat, min_wt = 0.01, corr_metric='spearman'): ''' Aggregate a set of replicate profiles into a single signature using a weighted average. Args: mat (pandas df): a matrix of replicate profiles, where the columns are samples and the rows ...
[]
Please provide a description of the function:def concat_main(args): # Get files directly if args.input_filepaths is not None: files = args.input_filepaths # Or find them else: files = get_file_list(args.file_wildcard) # No files found if len(files) == 0: ...
[ " Separate method from main() in order to make testing easier and to\n enable command-line access. " ]
Please provide a description of the function:def get_file_list(wildcard): files = glob.glob(os.path.expanduser(wildcard)) return files
[ " Search for files to be concatenated. Currently very basic, but could\n expand to be more sophisticated.\n\n Args:\n wildcard (regular expression string)\n\n Returns:\n files (list of full file paths)\n\n " ]
Please provide a description of the function:def hstack(gctoos, remove_all_metadata_fields=False, error_report_file=None, fields_to_remove=[], reset_ids=False): # Separate each gctoo into its component dfs row_meta_dfs = [] col_meta_dfs = [] data_dfs = [] srcs = [] for g in gctoos: ...
[ " Horizontally concatenate gctoos.\n\n Args:\n gctoos (list of gctoo objects)\n remove_all_metadata_fields (bool): ignore/strip all common metadata when combining gctoos\n error_report_file (string): path to write file containing error report indicating \n problems that occurred...
Please provide a description of the function:def assemble_common_meta(common_meta_dfs, fields_to_remove, sources, remove_all_metadata_fields, error_report_file): all_meta_df, all_meta_df_with_dups = build_common_all_meta_df(common_meta_dfs, fields_to_remove, remove_all_metadata_fields) if not all_meta_df....
[ " Assemble the common metadata dfs together. Both indices are sorted.\n Fields that are not in all the dfs are dropped.\n\n Args:\n common_meta_dfs (list of pandas dfs)\n fields_to_remove (list of strings): fields to be removed from the\n common metadata because they don't agree acros...
Please provide a description of the function:def build_common_all_meta_df(common_meta_dfs, fields_to_remove, remove_all_metadata_fields): if remove_all_metadata_fields: trimmed_common_meta_dfs = [pd.DataFrame(index=df.index) for df in common_meta_dfs] else: shared_column_headers = sorted(s...
[ "\n concatenate the entries in common_meta_dfs, removing columns selectively (fields_to_remove) or entirely (\n remove_all_metadata_fields=True; in this case, effectively just merges all the indexes in common_meta_dfs).\n\n Returns 2 dataframes (in a tuple): the first has duplicates removed, the s...
Please provide a description of the function:def assemble_concatenated_meta(concated_meta_dfs, remove_all_metadata_fields): # Concatenate the concated_meta_dfs if remove_all_metadata_fields: for df in concated_meta_dfs: df.drop(df.columns, axis=1, inplace=True) all_concated_meta_df...
[ " Assemble the concatenated metadata dfs together. For example,\n if horizontally concatenating, the concatenated metadata dfs are the\n column metadata dfs. Both indices are sorted.\n\n Args:\n concated_meta_dfs (list of pandas dfs)\n\n Returns:\n all_concated_meta_df_sorted (pandas df)\n...
Please provide a description of the function:def assemble_data(data_dfs, concat_direction): if concat_direction == "horiz": # Concatenate the data_dfs horizontally all_data_df = pd.concat(data_dfs, axis=1) # Sanity check: the number of columns in all_data_df should # correspond...
[ " Assemble the data dfs together. Both indices are sorted.\n\n Args:\n data_dfs (list of pandas dfs)\n concat_direction (string): 'horiz' or 'vert'\n\n Returns:\n all_data_df_sorted (pandas df)\n\n " ]
Please provide a description of the function:def do_reset_ids(concatenated_meta_df, data_df, concat_direction): if concat_direction == "horiz": # Make sure cids agree between data_df and concatenated_meta_df assert concatenated_meta_df.index.equals(data_df.columns), ( "cids in conc...
[ " Reset ids in concatenated metadata and data dfs to unique integers and\n save the old ids in a metadata column.\n\n Note that the dataframes are modified in-place.\n\n Args:\n concatenated_meta_df (pandas df)\n data_df (pandas df)\n concat_direction (string): 'horiz' or 'vert'\n\n ...
Please provide a description of the function:def reset_ids_in_meta_df(meta_df): # Record original index name, and then change it so that the column that it # becomes will be appropriately named original_index_name = meta_df.index.name meta_df.index.name = "old_id" # Reset index meta_df.re...
[ " Meta_df is modified inplace. " ]
Please provide a description of the function:def subset_gctoo(gctoo, row_bool=None, col_bool=None, rid=None, cid=None, ridx=None, cidx=None, exclude_rid=None, exclude_cid=None): assert sum([(rid is not None), (row_bool is not None), (ridx is not None)]) <= 1, ( "Only one of rid, row_boo...
[ " Extract a subset of data from a GCToo object in a variety of ways.\n The order of rows and columns will be preserved.\n\n Args:\n gctoo (GCToo object)\n row_bool (list of bools): length must equal gctoo.data_df.shape[0]\n col_bool (list of bools): length must equal gctoo.data_df.shape[1...
Please provide a description of the function:def get_rows_to_keep(gctoo, rid=None, row_bool=None, ridx=None, exclude_rid=None): # Use rid if provided if rid is not None: assert type(rid) == list, "rid must be a list. rid: {}".format(rid) rows_to_keep = [gctoo_row for gctoo_row in gctoo.dat...
[ " Figure out based on the possible row inputs which rows to keep.\n\n Args:\n gctoo (GCToo object):\n rid (list of strings):\n row_bool (boolean array):\n ridx (list of integers):\n exclude_rid (list of strings):\n\n Returns:\n rows_to_keep (list of strings): row ids ...
Please provide a description of the function:def get_cols_to_keep(gctoo, cid=None, col_bool=None, cidx=None, exclude_cid=None): # Use cid if provided if cid is not None: assert type(cid) == list, "cid must be a list. cid: {}".format(cid) cols_to_keep = [gctoo_col for gctoo_col in gctoo.da...
[ " Figure out based on the possible columns inputs which columns to keep.\n\n Args:\n gctoo (GCToo object):\n cid (list of strings):\n col_bool (boolean array):\n cidx (list of integers):\n exclude_cid (list of strings):\n\n Returns:\n cols_to_keep (list of strings): c...
Please provide a description of the function:def read(in_path): assert os.path.exists(in_path), "The following GRP file can't be found. in_path: {}".format(in_path) with open(in_path, "r") as f: lines = f.readlines() # need the second conditional to ignore comment lines grp = [line...
[ " Read a grp file at the path specified by in_path.\n\n Args:\n in_path (string): path to GRP file\n\n Returns:\n grp (list)\n\n " ]
Please provide a description of the function:def write(grp, out_path): with open(out_path, "w") as f: for x in grp: f.write(str(x) + "\n")
[ " Write a GRP to a text file.\n\n Args:\n grp (list): GRP object to write to new-line delimited text file\n out_path (string): output path\n\n Returns:\n None\n\n " ]
Please provide a description of the function:def fast_corr(x, y=None, destination=None): if y is None: y = x r = fast_cov.fast_cov(x, y, destination) std_x = numpy.std(x, axis=0, ddof=1) std_y = numpy.std(y, axis=0, ddof=1) numpy.divide(r, std_x[:, numpy.newaxis], out=r) numpy.di...
[ "calculate the pearson correlation matrix for the columns of x (with dimensions MxN), or optionally, the pearson correlaton matrix\n between x and y (with dimensions OxP). If destination is provided, put the results there. \n In the language of statistics the columns are the variables and the rows are the o...
Please provide a description of the function:def make_specified_size_gctoo(og_gctoo, num_entries, dim): assert dim in ["row", "col"], "dim specified must be either 'row' or 'col'" dim_index = 0 if "row" == dim else 1 assert num_entries <= og_gctoo.data_df.shape[dim_index], ("number of entries must be ...
[ "\n\tSubsets a GCToo instance along either rows or columns to obtain a specified size.\n\n\tInput:\n\t\t- og_gctoo (GCToo): a GCToo instance \n\t\t- num_entries (int): the number of entries to keep\n\t\t- dim (str): the dimension along which to subset. Must be \"row\" or \"col\"\n\n\tOutput:\n\t\t- new_gctoo (GCToo...
Please provide a description of the function:def run_filter_query(self, resource_name, filter_clause): url = self.base_url + "/" + resource_name params = {"filter":json.dumps(filter_clause)} r = requests.get(url, headers=self.headers, params=params) logger.debug("requests.get r...
[ "run a query (get) against the CLUE api, using the API and user key fields of self and the fitler_clause provided\n\n Args:\n resource_name: str - name of the resource / collection to query - e.g. genes, perts, cells etc.\n filter_clause: dictionary - contains filter to pass to API to; ...
Please provide a description of the function:def write(gctoo_object, out_file_name, convert_back_to_neg_666=True, gzip_compression_level=6, max_chunk_kb=1024, matrix_dtype=numpy.float32): # make sure out file has a .gctx suffix gctx_out_name = add_gctx_to_out_name(out_file_name) # open an hdf5 fil...
[ "\n\tWrites a GCToo instance to specified file.\n\n\tInput:\n\t\t- gctoo_object (GCToo): A GCToo instance.\n\t\t- out_file_name (str): file name to write gctoo_object to.\n - convert_back_to_neg_666 (bool): whether to convert np.NAN in metadata back to \"-666\"\n - gzip_compression_level (int, default...
Please provide a description of the function:def write_src(hdf5_out, gctoo_object, out_file_name): if gctoo_object.src == None: hdf5_out.attrs[src_attr] = out_file_name else: hdf5_out.attrs[src_attr] = gctoo_object.src
[ "\n\tWrites src as attribute of gctx out file. \n\n\tInput:\n\t\t- hdf5_out (h5py): hdf5 file to write to \n\t\t- gctoo_object (GCToo): GCToo instance to be written to .gctx\n\t\t- out_file_name (str): name of hdf5 out file. \n\t" ]
Please provide a description of the function:def calculate_elem_per_kb(max_chunk_kb, matrix_dtype): if matrix_dtype == numpy.float32: return (max_chunk_kb * 8)/32 elif matrix_dtype == numpy.float64: return (max_chunk_kb * 8)/64 else: msg = "Invalid matrix_dtype: {}; only numpy.f...
[ "\n Calculates the number of elem per kb depending on the max chunk size set. \n\n Input: \n - max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy\n - matrix_dtype (numpy dtype, default=numpy.float32): Storage data type for data matrix. \n Currently ne...
Please provide a description of the function:def set_data_matrix_chunk_size(df_shape, max_chunk_kb, elem_per_kb): row_chunk_size = min(df_shape[0], 1000) col_chunk_size = min(((max_chunk_kb*elem_per_kb)//row_chunk_size), df_shape[1]) return (row_chunk_size, col_chunk_size)
[ "\n Sets chunk size to use for writing data matrix. \n Note. Calculation used here is for compatibility with cmapM and cmapR. \n\n Input:\n - df_shape (tuple): shape of input data_df. \n - max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy\n - elem_per...
Please provide a description of the function:def write_metadata(hdf5_out, dim, metadata_df, convert_back_to_neg_666, gzip_compression): if dim == "col": hdf5_out.create_group(col_meta_group_node) metadata_node_name = col_meta_group_node elif dim == "row": hdf5_out.create_group(row_m...
[ "\n\tWrites either column or row metadata to proper node of gctx out (hdf5) file.\n\n\tInput:\n\t\t- hdf5_out (h5py): open hdf5 file to write to\n\t\t- dim (str; must be \"row\" or \"col\"): dimension of metadata to write to \n\t\t- metadata_df (pandas DataFrame): metadata DataFrame to write to file \n\t\t- convert...
Please provide a description of the function:def create_lazy_user(self): user_class = self.model.get_user_class() username = self.generate_username(user_class) user = user_class.objects.create_user(username, '') self.create(user=user) return user, username
[ " Create a lazy user. Returns a 2-tuple of the underlying User\n object (which may be of a custom class), and the username.\n " ]
Please provide a description of the function:def convert(self, form): if not is_lazy_user(form.instance): raise NotLazyError('You cannot convert a non-lazy user') user = form.save() # We need to remove the LazyUser instance assocated with the # newly-converted user...
[ " Convert a lazy user to a non-lazy one. The form passed\n in is expected to be a ModelForm instance, bound to the user\n to be converted.\n\n The converted ``User`` object is returned.\n\n Raises a TypeError if the user is not lazy.\n " ]
Please provide a description of the function:def generate_username(self, user_class): m = getattr(user_class, 'generate_username', None) if m: return m() else: max_length = user_class._meta.get_field( self.username_field).max_length re...
[ " Generate a new username for a user\n " ]
Please provide a description of the function:def convert(request, form_class=None, redirect_field_name='redirect_to', anonymous_redirect=settings.LOGIN_URL, template_name='lazysignup/convert.html', ajax_template_name='lazysignup/convert_ajax.html'): redirect_to =...
[ " Convert a temporary user to a real one. Reject users who don't\n appear to be temporary users (ie. they have a usable password)\n " ]
Please provide a description of the function:def is_lazy_user(user): # Anonymous users are not lazy. if user.is_anonymous: return False # Check the user backend. If the lazy signup backend # authenticated them, then the user is lazy. backend = getattr(user, 'backend', None) if bac...
[ " Return True if the passed user is a lazy user. " ]
Please provide a description of the function:def add(queue_name, payload=None, content_type=None, source=None, task_id=None, build_id=None, release_id=None, run_id=None): if task_id: task = WorkQueue.query.filter_by(task_id=task_id).first() if task: return task.task_id e...
[ "Adds a work item to a queue.\n\n Args:\n queue_name: Name of the queue to add the work item to.\n payload: Optional. Payload that describes the work to do as a string.\n If not a string and content_type is not provided, then this\n function assumes the payload is a JSON-able ...
Please provide a description of the function:def _task_to_dict(task): payload = task.payload if payload and task.content_type == 'application/json': payload = json.loads(payload) return dict( task_id=task.task_id, queue_name=task.queue_name, eta=_datetime_to_epoch_secon...
[ "Converts a WorkQueue to a JSON-able dictionary." ]
Please provide a description of the function:def lease(queue_name, owner, count=1, timeout_seconds=60): now = datetime.datetime.utcnow() query = ( WorkQueue.query .filter_by(queue_name=queue_name, status=WorkQueue.LIVE) .filter(WorkQueue.eta <= now) .order_by(WorkQueue.eta) ...
[ "Leases a work item from a queue, usually the oldest task available.\n\n Args:\n queue_name: Name of the queue to lease work from.\n owner: Who or what is leasing the task.\n count: Lease up to this many tasks. Return value will never have more\n than this many items present.\n ...
Please provide a description of the function:def _get_task_with_policy(queue_name, task_id, owner): now = datetime.datetime.utcnow() task = ( WorkQueue.query .filter_by(queue_name=queue_name, task_id=task_id) .with_lockmode('update') .first()) if not task: raise ...
[ "Fetches the specified task and enforces ownership policy.\n\n Args:\n queue_name: Name of the queue the work item is on.\n task_id: ID of the task that is finished.\n owner: Who or what has the current lease on the task.\n\n Returns:\n The valid WorkQueue task that is currently ow...
Please provide a description of the function:def heartbeat(queue_name, task_id, owner, message, index): task = _get_task_with_policy(queue_name, task_id, owner) if task.heartbeat_number > index: return False task.heartbeat = message task.heartbeat_number = index # Extend the lease by ...
[ "Sets the heartbeat status of the task and extends its lease.\n\n The task's lease is extended by the same amount as its last lease to\n ensure that any operations following the heartbeat will still hold the\n lock for the original lock period.\n\n Args:\n queue_name: Name of the queue the work i...
Please provide a description of the function:def finish(queue_name, task_id, owner, error=False): task = _get_task_with_policy(queue_name, task_id, owner) if not task.status == WorkQueue.LIVE: logging.warning('Finishing already dead task. queue=%r, task_id=%r, ' 'owner=%r, ...
[ "Marks a work item on a queue as finished.\n\n Args:\n queue_name: Name of the queue the work item is on.\n task_id: ID of the task that is finished.\n owner: Who or what has the current lease on the task.\n error: Defaults to false. True if this task's final state is an error.\n\n ...
Please provide a description of the function:def _query(queue_name=None, build_id=None, release_id=None, run_id=None, count=None): assert queue_name or build_id or release_id or run_id q = WorkQueue.query if queue_name: q = q.filter_by(queue_name=queue_name) if build_id: ...
[ "Queries for work items based on their criteria.\n\n Args:\n queue_name: Optional queue name to restrict to.\n build_id: Optional build ID to restrict to.\n release_id: Optional release ID to restrict to.\n run_id: Optional run ID to restrict to.\n count: How many tasks to fetc...
Please provide a description of the function:def query(**kwargs): count = kwargs.get('count', None) task_list = _query(**kwargs) task_dict_list = [_task_to_dict(task) for task in task_list] if count == 1: if not task_dict_list: return None else: return task_...
[ "Queries for work items based on their criteria.\n\n Args:\n queue_name: Optional queue name to restrict to.\n build_id: Optional build ID to restrict to.\n release_id: Optional release ID to restrict to.\n run_id: Optional run ID to restrict to.\n count: How many tasks to fetc...
Please provide a description of the function:def cancel(**kwargs): task_list = _query(**kwargs) for task in task_list: task.status = WorkQueue.CANCELED task.finished = datetime.datetime.utcnow() db.session.add(task) return len(task_list)
[ "Cancels work items based on their criteria.\n\n Args:\n **kwargs: Same parameters as the query() method.\n\n Returns:\n The number of tasks that were canceled.\n " ]
Please provide a description of the function:def handle_add(queue_name): source = request.form.get('source', request.remote_addr, type=str) try: task_id = work_queue.add( queue_name, payload=request.form.get('payload', type=str), content_type=request.form.get('co...
[ "Adds a task to a queue." ]
Please provide a description of the function:def handle_lease(queue_name): owner = request.form.get('owner', request.remote_addr, type=str) try: task_list = work_queue.lease( queue_name, owner, request.form.get('count', 1, type=int), request.form.get(...
[ "Leases a task from a queue." ]
Please provide a description of the function:def handle_heartbeat(queue_name): task_id = request.form.get('task_id', type=str) message = request.form.get('message', type=str) index = request.form.get('index', type=int) try: work_queue.heartbeat( queue_name, task_id, ...
[ "Updates the heartbeat message for a task." ]
Please provide a description of the function:def handle_finish(queue_name): task_id = request.form.get('task_id', type=str) owner = request.form.get('owner', request.remote_addr, type=str) error = request.form.get('error', type=str) is not None try: work_queue.finish(queue_name, task_id, ow...
[ "Marks a task on a queue as finished." ]
Please provide a description of the function:def view_all_work_queues(): count_list = list( db.session.query( work_queue.WorkQueue.queue_name, work_queue.WorkQueue.status, func.count(work_queue.WorkQueue.task_id)) .group_by(work_queue.WorkQueue.queue_name, ...
[ "Page for viewing the index of all active work queues." ]
Please provide a description of the function:def manage_work_queue(queue_name): modify_form = forms.ModifyWorkQueueTaskForm() if modify_form.validate_on_submit(): primary_key = (modify_form.task_id.data, queue_name) task = work_queue.WorkQueue.query.get(primary_key) if task: ...
[ "Page for viewing the contents of a work queue." ]
Please provide a description of the function:def retryable_transaction(attempts=3, exceptions=(OperationalError,)): assert len(exceptions) > 0 assert attempts > 0 def wrapper(f): @functools.wraps(f) def wrapped(*args, **kwargs): for i in xrange(attempts): tr...
[ "Decorator retries a function when expected exceptions are raised." ]
Please provide a description of the function:def jsonify_assert(asserted, message, status_code=400): if asserted: return try: raise AssertionError(message) except AssertionError, e: stack = traceback.extract_stack() stack.pop() logging.error('Assertion failed: %s...
[ "Asserts something is true, aborts the request if not." ]
Please provide a description of the function:def jsonify_error(message_or_exception, status_code=400): if isinstance(message_or_exception, Exception): message = '%s: %s' % ( message_or_exception.__class__.__name__, message_or_exception) else: message = message_or_exception ...
[ "Returns a JSON payload that indicates the request had an error." ]
Please provide a description of the function:def ignore_exceptions(f): @functools.wraps(f) def wrapped(*args, **kwargs): try: return f(*args, **kwargs) except: logging.exception("Ignoring exception in %r", f) return wrapped
[ "Decorator catches and ignores any exceptions raised by this function." ]
Please provide a description of the function:def timesince(when): if not when: return '' now = datetime.datetime.utcnow() if now > when: diff = now - when suffix = 'ago' else: diff = when - now suffix = 'from now' periods = ( (diff.days / 365, '...
[ "Returns string representing \"time since\" or \"time until\".\n\n Examples:\n 3 days ago, 5 hours ago, 3 minutes from now, 5 hours from now, now.\n " ]
Please provide a description of the function:def human_uuid(): return base64.b32encode( hashlib.sha1(uuid.uuid4().bytes).digest()).lower().strip('=')
[ "Returns a good UUID for using as a human readable string." ]