INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Parse a subprotocol from ``header`` at the given position. Return the subprotocol value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
def parse_subprotocol_item( header: str, pos: int, header_name: str ) -> Tuple[Subprotocol, int]: """ Parse a subprotocol from ``header`` at the given position. Return the subprotocol value and the new position. Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. """ ...
Build an Authorization header for HTTP Basic Auth.
def build_basic_auth(username: str, password: str) -> str: """ Build an Authorization header for HTTP Basic Auth. """ # https://tools.ietf.org/html/rfc7617#section-2 assert ":" not in username user_pass = f"{username}:{password}" basic_credentials = base64.b64encode(user_pass.encode()).deco...
Similar to :func:`serve()`, but for listening on Unix sockets. This function calls the event loop's :meth:`~asyncio.AbstractEventLoop.create_unix_server` method. It is only available on Unix. It's useful for deploying a server behind a reverse proxy such as nginx.
def unix_serve( ws_handler: Callable[[WebSocketServerProtocol, str], Awaitable[Any]], path: str, **kwargs: Any, ) -> Serve: """ Similar to :func:`serve()`, but for listening on Unix sockets. This function calls the event loop's :meth:`~asyncio.AbstractEventLoop.create_unix_server` method. ...
Register connection and initialize a task to handle it.
def connection_made(self, transport: asyncio.BaseTransport) -> None: """ Register connection and initialize a task to handle it. """ super().connection_made(transport) # Register the connection with the server before creating the handler # task. Registering at the beginn...
Handle the lifecycle of a WebSocket connection. Since this method doesn't have a caller able to handle exceptions, it attemps to log relevant ones and guarantees that the TCP connection is closed before exiting.
async def handler(self) -> None: """ Handle the lifecycle of a WebSocket connection. Since this method doesn't have a caller able to handle exceptions, it attemps to log relevant ones and guarantees that the TCP connection is closed before exiting. """ try: ...
Read request line and headers from the HTTP request. Raise :exc:`~websockets.exceptions.InvalidMessage` if the HTTP message is malformed or isn't an HTTP/1.1 GET request. Don't attempt to read the request body because WebSocket handshake requests don't have one. If the request contains...
async def read_http_request(self) -> Tuple[str, Headers]: """ Read request line and headers from the HTTP request. Raise :exc:`~websockets.exceptions.InvalidMessage` if the HTTP message is malformed or isn't an HTTP/1.1 GET request. Don't attempt to read the request body becaus...
Write status line and headers to the HTTP response. This coroutine is also able to write a response body.
def write_http_response( self, status: http.HTTPStatus, headers: Headers, body: Optional[bytes] = None ) -> None: """ Write status line and headers to the HTTP response. This coroutine is also able to write a response body. """ self.response_headers = headers ...
Intercept the HTTP request and return an HTTP response if needed. ``request_headers`` is a :class:`~websockets.http.Headers` instance. If this method returns ``None``, the WebSocket handshake continues. If it returns a status code, headers and a response body, that HTTP response is sen...
def process_request( self, path: str, request_headers: Headers ) -> Union[Optional[HTTPResponse], Awaitable[Optional[HTTPResponse]]]: """ Intercept the HTTP request and return an HTTP response if needed. ``request_headers`` is a :class:`~websockets.http.Headers` instance. I...
Handle the Origin HTTP request header. Raise :exc:`~websockets.exceptions.InvalidOrigin` if the origin isn't acceptable.
def process_origin( headers: Headers, origins: Optional[Sequence[Optional[Origin]]] = None ) -> Optional[Origin]: """ Handle the Origin HTTP request header. Raise :exc:`~websockets.exceptions.InvalidOrigin` if the origin isn't acceptable. """ # "The user age...
Handle the Sec-WebSocket-Extensions HTTP request header. Accept or reject each extension proposed in the client request. Negotiate parameters for accepted extensions. Return the Sec-WebSocket-Extensions HTTP response header and the list of accepted extensions. Raise :exc:`~web...
def process_extensions( headers: Headers, available_extensions: Optional[Sequence[ServerExtensionFactory]], ) -> Tuple[Optional[str], List[Extension]]: """ Handle the Sec-WebSocket-Extensions HTTP request header. Accept or reject each extension proposed in the client request...
Handle the Sec-WebSocket-Protocol HTTP request header. Return Sec-WebSocket-Protocol HTTP response header, which is the same as the selected subprotocol.
def process_subprotocol( self, headers: Headers, available_subprotocols: Optional[Sequence[Subprotocol]] ) -> Optional[Subprotocol]: """ Handle the Sec-WebSocket-Protocol HTTP request header. Return Sec-WebSocket-Protocol HTTP response header, which is the same as the select...
Pick a subprotocol among those offered by the client. If several subprotocols are supported by the client and the server, the default implementation selects the preferred subprotocols by giving equal value to the priorities of the client and the server. If no subprotocols are supported...
def select_subprotocol( self, client_subprotocols: Sequence[Subprotocol], server_subprotocols: Sequence[Subprotocol], ) -> Optional[Subprotocol]: """ Pick a subprotocol among those offered by the client. If several subprotocols are supported by the client and the ser...
Perform the server side of the opening handshake. If provided, ``origins`` is a list of acceptable HTTP Origin values. Include ``None`` if the lack of an origin is acceptable. If provided, ``available_extensions`` is a list of supported extensions in the order in which they should be u...
async def handshake( self, origins: Optional[Sequence[Optional[Origin]]] = None, available_extensions: Optional[Sequence[ServerExtensionFactory]] = None, available_subprotocols: Optional[Sequence[Subprotocol]] = None, extra_headers: Optional[HeadersLikeOrCallable] = None, ) -...
Tell whether the server is accepting new connections or shutting down.
def is_serving(self) -> bool: """ Tell whether the server is accepting new connections or shutting down. """ try: # Python ≥ 3.7 return self.server.is_serving() # type: ignore except AttributeError: # pragma: no cover # Python < 3.7 ...
Close the server and terminate connections with close code 1001. This method is idempotent.
def close(self) -> None: """ Close the server and terminate connections with close code 1001. This method is idempotent. """ if self.close_task is None: self.close_task = self.loop.create_task(self._close())
Implementation of :meth:`close`. This calls :meth:`~asyncio.Server.close` on the underlying :class:`~asyncio.Server` object to stop accepting new connections and then closes open connections with close code 1001.
async def _close(self) -> None: """ Implementation of :meth:`close`. This calls :meth:`~asyncio.Server.close` on the underlying :class:`~asyncio.Server` object to stop accepting new connections and then closes open connections with close code 1001. """ # Stop ac...
Write request line and headers to the HTTP request.
def write_http_request(self, path: str, headers: Headers) -> None: """ Write request line and headers to the HTTP request. """ self.path = path self.request_headers = headers logger.debug("%s > GET %s HTTP/1.1", self.side, path) logger.debug("%s > %r", self.side...
Read status line and headers from the HTTP response. Raise :exc:`~websockets.exceptions.InvalidMessage` if the HTTP message is malformed or isn't an HTTP/1.1 GET request. Don't attempt to read the response body because WebSocket handshake responses don't have one. If the response conta...
async def read_http_response(self) -> Tuple[int, Headers]: """ Read status line and headers from the HTTP response. Raise :exc:`~websockets.exceptions.InvalidMessage` if the HTTP message is malformed or isn't an HTTP/1.1 GET request. Don't attempt to read the response body beca...
Handle the Sec-WebSocket-Extensions HTTP response header. Check that each extension is supported, as well as its parameters. Return the list of accepted extensions. Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the connection. :rfc:`6455` leaves the rules up t...
def process_extensions( headers: Headers, available_extensions: Optional[Sequence[ClientExtensionFactory]], ) -> List[Extension]: """ Handle the Sec-WebSocket-Extensions HTTP response header. Check that each extension is supported, as well as its parameters. Return ...
Handle the Sec-WebSocket-Protocol HTTP response header. Check that it contains exactly one supported subprotocol. Return the selected subprotocol.
def process_subprotocol( headers: Headers, available_subprotocols: Optional[Sequence[Subprotocol]] ) -> Optional[Subprotocol]: """ Handle the Sec-WebSocket-Protocol HTTP response header. Check that it contains exactly one supported subprotocol. Return the selected subprotoc...
Perform the client side of the opening handshake. If provided, ``origin`` sets the Origin HTTP header. If provided, ``available_extensions`` is a list of supported extensions in the order in which they should be used. If provided, ``available_subprotocols`` is a list of supported ...
async def handshake( self, wsuri: WebSocketURI, origin: Optional[Origin] = None, available_extensions: Optional[Sequence[ClientExtensionFactory]] = None, available_subprotocols: Optional[Sequence[Subprotocol]] = None, extra_headers: Optional[HeadersLike] = None, ) -> ...
Callback when the TCP connection is established. Record references to the stream reader and the stream writer to avoid using private attributes ``_stream_reader`` and ``_stream_writer`` of :class:`~asyncio.StreamReaderProtocol`.
def client_connected( self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter ) -> None: """ Callback when the TCP connection is established. Record references to the stream reader and the stream writer to avoid using private attributes ``_stream_reader`` and ``_str...
Callback when the WebSocket opening handshake completes. Enter the OPEN state and start the data transfer phase.
def connection_open(self) -> None: """ Callback when the WebSocket opening handshake completes. Enter the OPEN state and start the data transfer phase. """ # 4.1. The WebSocket Connection is Established. assert self.state is State.CONNECTING self.state = State.O...
This property is ``True`` when the connection is usable. It may be used to detect disconnections but this is discouraged per the EAFP_ principle. When ``open`` is ``False``, using the connection raises a :exc:`~websockets.exceptions.ConnectionClosed` exception. .. _EAFP: https://docs.p...
def open(self) -> bool: """ This property is ``True`` when the connection is usable. It may be used to detect disconnections but this is discouraged per the EAFP_ principle. When ``open`` is ``False``, using the connection raises a :exc:`~websockets.exceptions.ConnectionClosed` ...
This coroutine receives the next message. It returns a :class:`str` for a text frame and :class:`bytes` for a binary frame. When the end of the message stream is reached, :meth:`recv` raises :exc:`~websockets.exceptions.ConnectionClosed`. This can happen after a normal connecti...
async def recv(self) -> Data: """ This coroutine receives the next message. It returns a :class:`str` for a text frame and :class:`bytes` for a binary frame. When the end of the message stream is reached, :meth:`recv` raises :exc:`~websockets.exceptions.ConnectionClosed...
This coroutine sends a message. It sends a string (:class:`str`) as a text frame and a bytes-like object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) as a binary frame. It also accepts an iterable or an asynchronous iterator of strings or bytes-like objects. Eac...
async def send( self, message: Union[Data, Iterable[Data], AsyncIterable[Data]] ) -> None: """ This coroutine sends a message. It sends a string (:class:`str`) as a text frame and a bytes-like object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) as a b...
This coroutine performs the closing handshake. It waits for the other end to complete the handshake and for the TCP connection to terminate. As a consequence, there's no need to await :meth:`wait_closed`; :meth:`close` already does it. :meth:`close` is idempotent: it doesn't do anythin...
async def close(self, code: int = 1000, reason: str = "") -> None: """ This coroutine performs the closing handshake. It waits for the other end to complete the handshake and for the TCP connection to terminate. As a consequence, there's no need to await :meth:`wait_closed`; :me...
This coroutine sends a pong. An unsolicited pong may serve as a unidirectional heartbeat. The content may be overridden with the optional ``data`` argument which must be a string (which will be encoded to UTF-8) or a bytes-like object.
async def pong(self, data: bytes = b"") -> None: """ This coroutine sends a pong. An unsolicited pong may serve as a unidirectional heartbeat. The content may be overridden with the optional ``data`` argument which must be a string (which will be encoded to UTF-8) or a ...
This coroutine sends a ping. It returns a :class:`~asyncio.Future` which will be completed when the corresponding pong is received and which you may ignore if you don't want to wait. A ping may serve as a keepalive or as a check that the remote endpoint received all messages up...
async def ping(self, data: Optional[bytes] = None) -> Awaitable[None]: """ This coroutine sends a ping. It returns a :class:`~asyncio.Future` which will be completed when the corresponding pong is received and which you may ignore if you don't want to wait. A ping may s...
Given a list of mapping items (in the form described by the parse_mapping_file method) and a header line, write each row to the given input file with fields separated by tabs. :type mapFNH: file or str :param mapFNH: Either the full path to the map file or an open file handle :type items: list :pa...
def write_map_file(mapFNH, items, header): """ Given a list of mapping items (in the form described by the parse_mapping_file method) and a header line, write each row to the given input file with fields separated by tabs. :type mapFNH: file or str :param mapFNH: Either the full path to the map fil...
Greengenes provides a file each OTU a full taxonomic designation. This method parses that file into a map with (key,val) = (OTU, taxonomy). :type idtaxFNH: file or str :param idtaxFNH: Either the full path to the map file or an open file handle :rtype: dict :return: A map associating each OTU ID w...
def parse_taxonomy_table(idtaxFNH): """ Greengenes provides a file each OTU a full taxonomic designation. This method parses that file into a map with (key,val) = (OTU, taxonomy). :type idtaxFNH: file or str :param idtaxFNH: Either the full path to the map file or an open file handle :rtype: d...
Return either the full or truncated version of a QIIME-formatted taxonomy string. :type p: str :param p: A QIIME-formatted taxonomy string: k__Foo; p__Bar; ... :type level: str :param level: The different level of identification are kingdom (k), phylum (p), class (c),order (o), famil...
def split_phylogeny(p, level="s"): """ Return either the full or truncated version of a QIIME-formatted taxonomy string. :type p: str :param p: A QIIME-formatted taxonomy string: k__Foo; p__Bar; ... :type level: str :param level: The different level of identification are kingdom (k), phylum (p...
Check to make sure the supplied directory path does not exist, if so, create it. The method catches OSError exceptions and returns a descriptive message instead of re-raising the error. :type d: str :param d: It is the full path to a directory. :return: Does not return anything, but creates a dire...
def ensure_dir(d): """ Check to make sure the supplied directory path does not exist, if so, create it. The method catches OSError exceptions and returns a descriptive message instead of re-raising the error. :type d: str :param d: It is the full path to a directory. :return: Does not retu...
Takes either a file path or an open file handle, checks validity and returns an open file handle or raises an appropriate Exception. :type fnh: str :param fnh: It is the full path to a file, or open file handle :type mode: str :param mode: The way in which this file will be used, for example to re...
def file_handle(fnh, mode="rU"): """ Takes either a file path or an open file handle, checks validity and returns an open file handle or raises an appropriate Exception. :type fnh: str :param fnh: It is the full path to a file, or open file handle :type mode: str :param mode: The way in wh...
Find the user specified categories in the map and create a dictionary to contain the relevant data for each type within the categories. Multiple categories will have their types combined such that each possible combination will have its own entry in the dictionary. :type imap: dict :param imap: The...
def gather_categories(imap, header, categories=None): """ Find the user specified categories in the map and create a dictionary to contain the relevant data for each type within the categories. Multiple categories will have their types combined such that each possible combination will have its own entry...
Parses the unifrac results file into a dictionary :type unifracFN: str :param unifracFN: The path to the unifrac results file :rtype: dict :return: A dictionary with keys: 'pcd' (principle coordinates data) which is a dictionary of the data keyed by sample ID, 'eigvals' (eigenvalues), and...
def parse_unifrac(unifracFN): """ Parses the unifrac results file into a dictionary :type unifracFN: str :param unifracFN: The path to the unifrac results file :rtype: dict :return: A dictionary with keys: 'pcd' (principle coordinates data) which is a dictionary of the data keyed ...
Function to parse data from older version of unifrac file obtained from Qiime version 1.8 and earlier. :type unifrac: dict :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after stripping whitespace characters.
def parse_unifrac_v1_8(unifrac, file_data): """ Function to parse data from older version of unifrac file obtained from Qiime version 1.8 and earlier. :type unifrac: dict :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after...
Function to parse data from newer version of unifrac file obtained from Qiime version 1.9 and later. :type unifracFN: str :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after stripping whitespace characters.
def parse_unifrac_v1_9(unifrac, file_data): """ Function to parse data from newer version of unifrac file obtained from Qiime version 1.9 and later. :type unifracFN: str :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after ...
Determine color-category mapping. If color_column was specified, then map the category names to color values. Otherwise, use the palettable colors to automatically generate a set of colors for the group values. :type sample_map: dict :param unifracFN: Map associating each line of the mapping file with ...
def color_mapping(sample_map, header, group_column, color_column=None): """ Determine color-category mapping. If color_column was specified, then map the category names to color values. Otherwise, use the palettable colors to automatically generate a set of colors for the group values. :type sample...
The first argument is assumed to be the ``key`` for routing.
def _route(self, attr, args, kwargs, **fkwargs): """ The first argument is assumed to be the ``key`` for routing. """ key = get_key(args, kwargs) found = self._hash.get_node(key) if not found and len(self._down_connections) > 0: raise self.HostListExhausted...
The first argument is assumed to be the ``key`` for routing.
def _route(self, attr, args, kwargs, **fkwargs): """ The first argument is assumed to be the ``key`` for routing. """ key = get_key(args, kwargs) return [crc32(str(key)) % len(self.cluster)]
return reverse completment of read
def rev_c(read): """ return reverse completment of read """ rc = [] rc_nucs = {'A':'T', 'T':'A', 'G':'C', 'C':'G', 'N':'N'} for base in read: rc.extend(rc_nucs[base.upper()]) return rc[::-1]
randomly shuffle genome
def shuffle_genome(genome, cat, fraction = float(100), plot = True, \ alpha = 0.1, beta = 100000, \ min_length = 1000, max_length = 200000): """ randomly shuffle genome """ header = '>randomized_%s' % (genome.name) sequence = list(''.join([i[1] for i in parse_fasta(genome)])) len...
Find the best model (fit) and create self.list_of_fits and self.fit
def _do_analysis_no_cross_validation(self): """ Find the best model (fit) and create self.list_of_fits and self.fit """ # first model is just the mean response_term = [Term([LookupFactor(self.y)])] model_terms = [Term([])] # empty term is the intercept all_model_...
Find the best model (fit) based on cross-valiation (leave one out)
def _do_analysis_cross_validation(self): """ Find the best model (fit) based on cross-valiation (leave one out) """ assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints" # initialization: first model is the mean, but com...
If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignificant parameters p_max : float ...
def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignif...
Return the best fit, based on rsquared
def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1]
Return the best fit, based on Akaike information criterion
def find_best_akaike(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.aic) return res[0]
Return the best fit, based on Akaike information criterion
def find_best_bic(list_of_fits): """Return the best fit, based on Akaike information criterion""" res = sorted(list_of_fits, key=lambda x: x.bic) return res[0]
Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but the result depends on the following attributes ...
def add_prediction(self): """ Add predictions and confidence interval to self.df self.df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. Parameters ---------- None, but t...
Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visualize them differently. Parameters ---------- model ...
def plot(self, model=True, bar_chart=True, **kwargs): """ Plot measurements and predictions. By default, use self._fit and self.df, but both can be overruled by the arguments df and fit This function will detect if the data has been used for the modelling or not and will visuali...
Return a string representation of a patsy ModelDesc object
def _modeldesc_to_dict(self, md): """Return a string representation of a patsy ModelDesc object""" d = {'lhs_termlist': [md.lhs_termlist[0].factors[0].name()]} rhs_termlist = [] # add other terms, if any for term in md.rhs_termlist[:]: if len(term.factors) == 0: ...
Return a string representation of a patsy ModelDesc object
def _modeldesc_from_dict(self, d): """Return a string representation of a patsy ModelDesc object""" lhs_termlist = [Term([LookupFactor(d['lhs_termlist'][0])])] rhs_termlist = [] for name in d['rhs_termlist']: if name == '': rhs_termlist.append(Term([])) ...
Calculate the relative abundance of each OTUID in a Sample. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: list :param sampleIDs: A list of sample id's from BIOM format OTU table. :rtype: dict :return: Returns a keyed on SampleIDs, and the values are dictionaries k...
def relative_abundance(biomf, sampleIDs=None): """ Calculate the relative abundance of each OTUID in a Sample. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: list :param sampleIDs: A list of sample id's from BIOM format OTU table. :rtype: dict :return: Retu...
Calculate the mean OTU abundance percentage. :type ra: Dict :param ra: 'ra' refers to a dictionary keyed on SampleIDs, and the values are dictionaries keyed on OTUID's and their values represent the relative abundance of that OTUID in that SampleID. 'ra' is the output of ...
def mean_otu_pct_abundance(ra, otuIDs): """ Calculate the mean OTU abundance percentage. :type ra: Dict :param ra: 'ra' refers to a dictionary keyed on SampleIDs, and the values are dictionaries keyed on OTUID's and their values represent the relative abundance of that OTU...
Calculate the mean relative abundance percentage. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: list :param sampleIDs: A list of sample id's from BIOM format OTU table. :param transform: Mathematical function which is used to transform smax to another ...
def MRA(biomf, sampleIDs=None, transform=None): """ Calculate the mean relative abundance percentage. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: list :param sampleIDs: A list of sample id's from BIOM format OTU table. :param transform: Mathematical function...
Calculate the total number of sequences in each OTU or SampleID. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: List :param sampleIDs: A list of column id's from BIOM format OTU table. By default, the list has been set to None. :type sample_abd: B...
def raw_abundance(biomf, sampleIDs=None, sample_abd=True): """ Calculate the total number of sequences in each OTU or SampleID. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: List :param sampleIDs: A list of column id's from BIOM format OTU table. By default, the ...
Function to transform the total abundance calculation for each sample ID to another format based on user given transformation function. :type biomf: A BIOM file. :param biomf: OTU table format. :param fn: Mathematical function which is used to transform smax to another format. By defaul...
def transform_raw_abundance(biomf, fn=math.log10, sampleIDs=None, sample_abd=True): """ Function to transform the total abundance calculation for each sample ID to another format based on user given transformation function. :type biomf: A BIOM file. :param biomf: OTU table format. :param fn: M...
Takes the proportion data from relative_abundance() and applies the variance stabilizing arcsine square root transformation: X = sin^{-1} \sqrt p
def arcsine_sqrt_transform(rel_abd): """ Takes the proportion data from relative_abundance() and applies the variance stabilizing arcsine square root transformation: X = sin^{-1} \sqrt p """ arcsint = lambda p: math.asin(math.sqrt(p)) return {col_id: {row_id: arcsint(rel_abd[col_id][row_id]...
find and replace elements in lookup within file
def f2lookup(f, lookup): """ find and replace elements in lookup within file """ lookup = {i: r for i, r in [l.strip().split('\t')[0:2] for l in lookup]} for line in f: line = line.strip().split() for i, w in enumerate(line): if w in lookup: line[i] = look...
Compute the Mann-Whitney U test for unequal group sample sizes.
def print_MannWhitneyU(div_calc): """ Compute the Mann-Whitney U test for unequal group sample sizes. """ try: x = div_calc.values()[0].values() y = div_calc.values()[1].values() except: return "Error setting up input arrays for Mann-Whitney U Test. Skipping "\ ...
Given a dictionary of diversity calculations (keyed by method) write out the data to a file.
def write_diversity_metrics(data, sample_ids, fp=None): """ Given a dictionary of diversity calculations (keyed by method) write out the data to a file. """ if fp is None: fp = "./diversity_data.txt" with open(fp, "w") as outf: out = csv.writer(outf, delimiter="\t") out....
Compute the Kruskal-Wallis H-test for independent samples. A typical rule is that each group must have at least 5 measurements.
def print_KruskalWallisH(div_calc): """ Compute the Kruskal-Wallis H-test for independent samples. A typical rule is that each group must have at least 5 measurements. """ calc = defaultdict(list) try: for k1, v1 in div_calc.iteritems(): for k2, v2 in v1.iteritems(): ...
Parses the given options passed in at the command line.
def handle_program_options(): """Parses the given options passed in at the command line.""" parser = argparse.ArgumentParser(description="Calculate the alpha diversity\ of a set of samples using one or more \ metrics and output a kernal d...
make blast db
def blastdb(fasta, maxfile = 10000000): """ make blast db """ db = fasta.rsplit('.', 1)[0] type = check_type(fasta) if type == 'nucl': type = ['nhr', type] else: type = ['phr', type] if os.path.exists('%s.%s' % (db, type[0])) is False \ and os.path.exists('%s....
make usearch db
def usearchdb(fasta, alignment = 'local', usearch_loc = 'usearch'): """ make usearch db """ if '.udb' in fasta: print('# ... database found: %s' % (fasta), file=sys.stderr) return fasta type = check_type(fasta) db = '%s.%s.udb' % (fasta.rsplit('.', 1)[0], type) if os.path.exi...
run phmmer
def phmmer(query, db, type, out, threads = '4', evalue = '0.01'): """ run phmmer """ if os.path.exists(out) is False: print('# ... running phmmer with %s as query and %s as database' % (query, db)) os.system('phmmer -o %s.ph1 --tblout %s.ph2 --acc --noali --notextw -E %s --cpu %s %s %s' ...
run blast
def blast(query, db, type, out, threads = '4', maxtargets = '100', megablast = False): """ run blast """ if os.path.exists(out) is False: db = blastdb(db) # make the database file, if necessary print('# ... running blast with %s as query and %s as database' % (query, db)) if typ...
run usearch
def usearch5(query, db, type, out, threads = '4', evalue = '100', alignment = 'local'): """ run usearch """ if os.path.exists(out) is False: print('# ... running usearch with %s as query and %s as database' % (query, db)) if type[1] == 'nucl': threads = '' else: ...
run usearch
def usearch(query, db, type, out, threads = '6', evalue = '100', alignment = 'local', max_hits = 100, cluster = False): """ run usearch """ if 'usearch64' in os.environ: usearch_loc = os.environ['usearch64'] else: usearch_loc = 'usearch' if os.path.exists(out) is False: d...
run
def run(self): """run""" if self.callback: log.info(("{} - using callback={}") .format(self.name, self.callback)) self.callback(name=self.response_name, task_queue=self.task_queue, ...
Pretty print.
def _pp(dict_data): """Pretty print.""" for key, val in dict_data.items(): # pylint: disable=superfluous-parens print('{0:<11}: {1}'.format(key, val))
Print licenses. :param argparse.Namespace params: parameter :param bootstrap_py.classifier.Classifiers metadata: package metadata
def print_licences(params, metadata): """Print licenses. :param argparse.Namespace params: parameter :param bootstrap_py.classifier.Classifiers metadata: package metadata """ if hasattr(params, 'licenses'): if params.licenses: _pp(metadata.licenses_desc()) sys.exit(0)
Check repository existence. :param argparse.Namespace params: parameters
def check_repository_existence(params): """Check repository existence. :param argparse.Namespace params: parameters """ repodir = os.path.join(params.outdir, params.name) if os.path.isdir(repodir): raise Conflict( 'Package repository "{0}" has already exists.'.format(repodir))
Generate package repository. :param argparse.Namespace params: parameters
def generate_package(params): """Generate package repository. :param argparse.Namespace params: parameters """ pkg_data = package.PackageData(params) pkg_tree = package.PackageTree(pkg_data) pkg_tree.generate() pkg_tree.move() VCS(os.path.join(pkg_tree.outdir, pkg_tree.name), pkg_tree.p...
print single reads to stderr
def print_single(line, rev): """ print single reads to stderr """ if rev is True: seq = rc(['', line[9]])[1] qual = line[10][::-1] else: seq = line[9] qual = line[10] fq = ['@%s' % line[0], seq, '+%s' % line[0], qual] print('\n'.join(fq), file = sys.stderr)
convert sam to fastq
def sam2fastq(sam, singles = False, force = False): """ convert sam to fastq """ L, R = None, None for line in sam: if line.startswith('@') is True: continue line = line.strip().split() bit = [True if i == '1' else False \ for i in bin(int(line[1])...
sort sam file
def sort_sam(sam, sort): """ sort sam file """ tempdir = '%s/' % (os.path.abspath(sam).rsplit('/', 1)[0]) if sort is True: mapping = '%s.sorted.sam' % (sam.rsplit('.', 1)[0]) if sam != '-': if os.path.exists(mapping) is False: os.system("\ ...
randomly subset sam file
def sub_sam(sam, percent, sort = True, sbuffer = False): """ randomly subset sam file """ mapping = sort_sam(sam, sort) pool = [1 for i in range(0, percent)] + [0 for i in range(0, 100 - percent)] c = cycle([1, 2]) for line in mapping: line = line.strip().split() if line[0].s...
convert fq to fa
def fq2fa(fq): """ convert fq to fa """ c = cycle([1, 2, 3, 4]) for line in fq: n = next(c) if n == 1: seq = ['>%s' % (line.strip().split('@', 1)[1])] if n == 2: seq.append(line.strip()) yield seq
find and replace elements in lookup within file
def f2lookup(f, lookup): """ find and replace elements in lookup within file """ lookup = {i: r for i, r in [l.strip().split('\t')[0:2] for l in lookup]} for line in f: line = line.strip() for find, replace in list(lookup.items()): line = line.replace(find, replace) yield line
Converts the returned value of wrapped function to the type of the first arg or to the type specified by a kwarg key return_type's value.
def change_return_type(f): """ Converts the returned value of wrapped function to the type of the first arg or to the type specified by a kwarg key return_type's value. """ @wraps(f) def wrapper(*args, **kwargs): if kwargs.has_key('return_type'): return_type = kwargs['return_...
Converts all args to 'set' type via self.setify function.
def convert_args_to_sets(f): """ Converts all args to 'set' type via self.setify function. """ @wraps(f) def wrapper(*args, **kwargs): args = (setify(x) for x in args) return f(*args, **kwargs) return wrapper
Makes class properties accessible to self.__class__ (i hope) to via creation of an '_accessible_<property>' attr.
def accessible(f): """ Makes class properties accessible to self.__class__ (i hope) to via creation of an '_accessible_<property>' attr. """ @wraps(f) def wrapper(*args, **kwargs): print 'KWARGS= ', kwargs setattr(args[0], kwargs['name'], args[1]) print "property: ", str(geta...
Tokenize a string (passed as argument or read from stdin) segments [--profile=PATH/TO/PROFILE] tokenize [STRING]
def tokenize(args): """ Tokenize a string (passed as argument or read from stdin) segments [--profile=PATH/TO/PROFILE] tokenize [STRING] """ if args.profile and not Path(args.profile).exists(): # pragma: no cover raise ParserError('--profile must be a path for an existing file') _write...
Mengambil semua teks dalam sup label HTML (tanpa anak-anaknya). :param sup: BeautifulSoup dari suatu label HTML :type sup: BeautifulSoup :returns: String semua teks dalam sup label HTML :rtype: str
def ambil_teks_dalam_label(sup): """Mengambil semua teks dalam sup label HTML (tanpa anak-anaknya). :param sup: BeautifulSoup dari suatu label HTML :type sup: BeautifulSoup :returns: String semua teks dalam sup label HTML :rtype: str """ return ''.join(i.strip() for i in sup.find_all(text=T...
Membuat objek-objek entri dari laman yang diambil. :param laman: Laman respons yang dikembalikan oleh KBBI daring. :type laman: Response
def _init_entri(self, laman): """Membuat objek-objek entri dari laman yang diambil. :param laman: Laman respons yang dikembalikan oleh KBBI daring. :type laman: Response """ sup = BeautifulSoup(laman.text, 'html.parser') estr = '' for label in sup.find('hr').nex...
Memproses kata dasar yang ada dalam nama entri. :param dasar: ResultSet untuk label HTML dengan class="rootword" :type dasar: ResultSet
def _init_kata_dasar(self, dasar): """Memproses kata dasar yang ada dalam nama entri. :param dasar: ResultSet untuk label HTML dengan class="rootword" :type dasar: ResultSet """ for tiap in dasar: kata = tiap.find('a') dasar_no = kata.find('sup') ...
Mengembalikan hasil serialisasi objek Entri ini. :returns: Dictionary hasil serialisasi :rtype: dict
def serialisasi(self): """Mengembalikan hasil serialisasi objek Entri ini. :returns: Dictionary hasil serialisasi :rtype: dict """ return { "nama": self.nama, "nomor": self.nomor, "kata_dasar": self.kata_dasar, "pelafalan": self.p...
Mengembalikan representasi string untuk semua makna entri ini. :returns: String representasi makna-makna :rtype: str
def _makna(self): """Mengembalikan representasi string untuk semua makna entri ini. :returns: String representasi makna-makna :rtype: str """ if len(self.makna) > 1: return '\n'.join( str(i) + ". " + str(makna) for i, makna in enumera...
Mengembalikan representasi string untuk nama entri ini. :returns: String representasi nama entri :rtype: str
def _nama(self): """Mengembalikan representasi string untuk nama entri ini. :returns: String representasi nama entri :rtype: str """ hasil = self.nama if self.nomor: hasil += " [{}]".format(self.nomor) if self.kata_dasar: hasil = " » ".jo...
Mengembalikan representasi string untuk varian entri ini. Dapat digunakan untuk "Varian" maupun "Bentuk tidak baku". :param varian: List bentuk tidak baku atau varian :type varian: list :returns: String representasi varian atau bentuk tidak baku :rtype: str
def _varian(self, varian): """Mengembalikan representasi string untuk varian entri ini. Dapat digunakan untuk "Varian" maupun "Bentuk tidak baku". :param varian: List bentuk tidak baku atau varian :type varian: list :returns: String representasi varian atau bentuk tidak baku ...
Memproses kelas kata yang ada dalam makna. :param makna_label: BeautifulSoup untuk makna yang ingin diproses. :type makna_label: BeautifulSoup
def _init_kelas(self, makna_label): """Memproses kelas kata yang ada dalam makna. :param makna_label: BeautifulSoup untuk makna yang ingin diproses. :type makna_label: BeautifulSoup """ kelas = makna_label.find(color='red') lain = makna_label.find(color='darkgreen') ...
Memproses contoh yang ada dalam makna. :param makna_label: BeautifulSoup untuk makna yang ingin diproses. :type makna_label: BeautifulSoup
def _init_contoh(self, makna_label): """Memproses contoh yang ada dalam makna. :param makna_label: BeautifulSoup untuk makna yang ingin diproses. :type makna_label: BeautifulSoup """ indeks = makna_label.text.find(': ') if indeks != -1: contoh = makna_label....
Mengembalikan hasil serialisasi objek Makna ini. :returns: Dictionary hasil serialisasi :rtype: dict
def serialisasi(self): """Mengembalikan hasil serialisasi objek Makna ini. :returns: Dictionary hasil serialisasi :rtype: dict """ return { "kelas": self.kelas, "submakna": self.submakna, "info": self.info, "contoh": self.contoh ...
send_tcp_message Send a ``TCP`` message to port 80 by default.
def send_tcp_message(): """send_tcp_message Send a ``TCP`` message to port 80 by default. """ need_response = os.getenv("NEED_RESPONSE", "0") == "1" msg = os.getenv( "MSG", "testing msg time={} - {}".format( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:...
Build sphinx documentation. :rtype: int :return: subprocess.call return code :param `bootstrap_py.control.PackageData` pkg_data: package meta data :param str projectdir: project root directory
def build_sphinx(pkg_data, projectdir): """Build sphinx documentation. :rtype: int :return: subprocess.call return code :param `bootstrap_py.control.PackageData` pkg_data: package meta data :param str projectdir: project root directory """ try: version, _minor_version = pkg_data.ve...
A decorator which ensures that once a method has been marked as resolved (via Class.__resolved)) will then propagate the attribute (function) call upstream.
def promise_method(func): """ A decorator which ensures that once a method has been marked as resolved (via Class.__resolved)) will then propagate the attribute (function) call upstream. """ name = func.__name__ @wraps(func) def wrapped(self, *args, **kwargs): cls_name = type(se...
make bowtie db
def bowtiedb(fa, keepDB): """ make bowtie db """ btdir = '%s/bt2' % (os.getcwd()) # make directory for if not os.path.exists(btdir): os.mkdir(btdir) btdb = '%s/%s' % (btdir, fa.rsplit('/', 1)[-1]) if keepDB is True: if os.path.exists('%s.1.bt2' % (btdb)): retu...
generate bowtie2 command
def bowtie(sam, btd, f, r, u, opt, no_shrink, threads): """ generate bowtie2 command """ bt2 = 'bowtie2 -x %s -p %s ' % (btd, threads) if f is not False: bt2 += '-1 %s -2 %s ' % (f, r) if u is not False: bt2 += '-U %s ' % (u) bt2 += opt if no_shrink is False: if f...