INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Performs passed - in comparison op between every element in the passed - in array and other and returns an array of booleans. | def compare(array, other, op, ty_str):
"""
Performs passed-in comparison op between every element in the passed-in
array and other, and returns an array of booleans.
Args:
array (WeldObject / Numpy.ndarray): Input array
other (WeldObject / Numpy.ndarray): Second input array
op (... |
Returns a new array - of - arrays with each array truncated starting at index start for length characters. | def slice(array, start, size, ty):
"""
Returns a new array-of-arrays with each array truncated, starting at
index `start` for `length` characters.
Args:
array (WeldObject / Numpy.ndarray): Input array
start (int): starting index
size (int): length to truncate at
ty (Weld... |
Checks if given string is contained in each string in the array. Output is a vec of booleans. | def contains(array, ty, string):
"""
Checks if given string is contained in each string in the array.
Output is a vec of booleans.
Args:
array (WeldObject / Numpy.ndarray): Input array
start (int): starting index
size (int): length to truncate at
ty (WeldType): Type of e... |
Computes a join on two tables | def join(expr1, expr2, d1_keys, d2_keys, keys_type, d1_vals, df1_vals_ty, d2_vals, df2_vals_ty):
"""
Computes a join on two tables
"""
weld_obj = WeldObject(encoder_, decoder_)
df1_var = weld_obj.update(expr1)
if isinstance(expr1, WeldObject):
df1_var = expr1.obj_id
weld_obj.... |
Constructs a pivot table where the index_index and columns_index are used as keys and the value_index is used as the value which is aggregated. | def pivot_table(expr, value_index, value_ty, index_index, index_ty, columns_index, columns_ty, aggfunc):
"""
Constructs a pivot table where the index_index and columns_index are used as keys and the value_index is used as the value which is aggregated.
"""
weld_obj = WeldObject(encoder_, decoder_)
... |
Groups the given columns by the corresponding grouping column value and aggregate by summing values. | def groupby_size(columns, column_tys, grouping_columns, grouping_column_tys):
"""
Groups the given columns by the corresponding grouping column
value, and aggregate by summing values.
Args:
columns (List<WeldObject>): List of columns as WeldObjects
column_tys (List<str>): List of each c... |
Groups the given columns by the corresponding grouping column value and aggregate by summing values. | def groupby_sort(columns, column_tys, grouping_columns, grouping_column_tys, key_index, ascending):
"""
Groups the given columns by the corresponding grouping column
value, and aggregate by summing values.
Args:
columns (List<WeldObject>): List of columns as WeldObjects
column_tys (List... |
Groups the given columns by the corresponding grouping column value and aggregate by summing values. | def flatten_group(expr, column_tys, grouping_column_tys):
"""
Groups the given columns by the corresponding grouping column
value, and aggregate by summing values.
Args:
columns (List<WeldObject>): List of columns as WeldObjects
column_tys (List<str>): List of each column data ty
... |
Groups the given columns by the corresponding grouping column value and aggregate by summing values. | def grouped_slice(expr, type, start, size):
"""
Groups the given columns by the corresponding grouping column
value, and aggregate by summing values.
Args:
columns (List<WeldObject>): List of columns as WeldObjects
column_tys (List<str>): List of each column data ty
grouping_col... |
Get column corresponding to passed - in index from ptr returned by groupBySum. | def get_column(columns, column_tys, index):
"""
Get column corresponding to passed-in index from ptr returned
by groupBySum.
Args:
columns (List<WeldObject>): List of columns as WeldObjects
column_tys (List<str>): List of each column data ty
index (int): index of selected column... |
Computes the dot product between a matrix and a vector. TODO: Make this more generic | def dot(matrix, vector):
"""
Computes the dot product between a matrix and a vector.
TODO: Make this more generic
Args:
matrix (TYPE): Description
vector (TYPE): Description
"""
matrix_weld_type = None
vector_weld_type = None
if isinstance(matrix, LazyOpResult):
... |
Computes a per - element exponent of the passed - in vector. | def exp(vector):
"""
Computes a per-element exponent of the passed-in vector.
Args:
vector (TYPE): Description
"""
weld_type = None
if isinstance(vector, LazyOpResult):
weld_type = vector.weld_type
vector = vector.expr
elif isinstance(vector, np.ndarray):
wel... |
Summary | def sum(self):
"""Summary
Returns:
TYPE: Description
"""
return NumpyArrayWeld(
numpy_weld_impl.aggr(
self.expr,
"+",
0,
self.weld_type
),
self.weld_type,
0
... |
Wrapper around weldarray - first create np. array and then convert to weldarray. | def array(arr, *args, **kwargs):
'''
Wrapper around weldarray - first create np.array and then convert to
weldarray.
'''
return weldarray(np.array(arr, *args, **kwargs)) |
Summary | def py_to_weld_type(self, obj):
"""Summary
Args:
obj (TYPE): Description
Returns:
TYPE: Description
Raises:
Exception: Description
"""
if isinstance(obj, np.ndarray):
dtype = str(obj.dtype)
if dtype == 'int16'... |
Converts Python object to Weld object. | def encode(self, obj):
"""Converts Python object to Weld object.
Args:
obj: Python object that needs to be converted to Weld format
Returns:
Weld formatted object
"""
if isinstance(obj, np.ndarray):
if obj.ndim == 1 and obj.dtype == 'int16':
... |
Converts Weld object to Python object. | def decode(self, obj, restype, raw_ptr=False):
"""Converts Weld object to Python object.
Args:
obj: Result of Weld computation that needs to be decoded
restype: Type of Weld computation result
raw_ptr: Boolean indicating whether obj needs to be extracted
... |
Tries to remove temp files by filename wildcard path. | def cleanup(temp_name):
''' Tries to remove temp files by filename wildcard path. '''
for filename in iglob(temp_name + '*' if temp_name else temp_name):
try:
os.remove(filename)
except OSError:
pass |
Returns LooseVersion object of the Tesseract version | def get_tesseract_version():
'''
Returns LooseVersion object of the Tesseract version
'''
try:
return LooseVersion(
subprocess.check_output(
[tesseract_cmd, '--version'], stderr=subprocess.STDOUT
).decode('utf-8').split()[1].lstrip(string.printable[10:])
... |
Returns the result of a Tesseract OCR run on the provided image to string | def image_to_string(image,
lang=None,
config='',
nice=0,
output_type=Output.STRING):
'''
Returns the result of a Tesseract OCR run on the provided image to string
'''
args = [image, 'txt', lang, config, nice]
return {
... |
Returns the result of a Tesseract OCR run on the provided image to pdf/ hocr | def image_to_pdf_or_hocr(image,
lang=None,
config='',
nice=0,
extension='pdf'):
'''
Returns the result of a Tesseract OCR run on the provided image to pdf/hocr
'''
if extension not in {'pdf', 'hocr'}:
raise ValueErr... |
Returns string containing box boundaries confidences and other information. Requires Tesseract 3. 05 + | def image_to_data(image,
lang=None,
config='',
nice=0,
output_type=Output.STRING):
'''
Returns string containing box boundaries, confidences,
and other information. Requires Tesseract 3.05+
'''
if get_tesseract_version() < '3.0... |
Returns string containing the orientation and script detection ( OSD ) | def image_to_osd(image,
lang='osd',
config='',
nice=0,
output_type=Output.STRING):
'''
Returns string containing the orientation and script detection (OSD)
'''
config = '{}-psm 0 {}'.format(
'' if get_tesseract_version() < '3.05... |
This function parses and validates a WebSocket URI. | def parse_uri(uri: str) -> WebSocketURI:
"""
This function parses and validates a WebSocket URI.
If the URI is valid, it returns a :class:`WebSocketURI`.
Otherwise it raises an :exc:`~websockets.exceptions.InvalidURI` exception.
"""
parsed = urllib.parse.urlparse(uri)
try:
assert ... |
Convert a string or byte - like object to an opcode and a bytes - like object. | def prepare_data(data: Data) -> Tuple[int, bytes]:
"""
Convert a string or byte-like object to an opcode and a bytes-like object.
This function is designed for data frames.
If ``data`` is a :class:`str`, return ``OP_TEXT`` and a :class:`bytes`
object encoding ``data`` in UTF-8.
If ``data`` is... |
Convert a string or byte - like object to bytes. | def encode_data(data: Data) -> bytes:
"""
Convert a string or byte-like object to bytes.
This function is designed for ping and pon g frames.
If ``data`` is a :class:`str`, return a :class:`bytes` object encoding
``data`` in UTF-8.
If ``data`` is a bytes-like object, return a :class:`bytes` o... |
Parse the data in a close frame. | def parse_close(data: bytes) -> Tuple[int, str]:
"""
Parse the data in a close frame.
Return ``(code, reason)`` when ``code`` is an :class:`int` and ``reason``
a :class:`str`.
Raise :exc:`~websockets.exceptions.WebSocketProtocolError` or
:exc:`UnicodeDecodeError` if the data is invalid.
"... |
Serialize the data for a close frame. | def serialize_close(code: int, reason: str) -> bytes:
"""
Serialize the data for a close frame.
This is the reverse of :func:`parse_close`.
"""
check_close(code)
return struct.pack("!H", code) + reason.encode("utf-8") |
Read a WebSocket frame and return a: class: Frame object. | async def read(
cls,
reader: Callable[[int], Awaitable[bytes]],
*,
mask: bool,
max_size: Optional[int] = None,
extensions: Optional[Sequence["websockets.extensions.base.Extension"]] = None,
) -> "Frame":
"""
Read a WebSocket frame and return a :class:`... |
Write a WebSocket frame. | def write(
frame,
writer: Callable[[bytes], Any],
*,
mask: bool,
extensions: Optional[Sequence["websockets.extensions.base.Extension"]] = None,
) -> None:
"""
Write a WebSocket frame.
``frame`` is the :class:`Frame` object to write.
``writer`... |
Check that this frame contains acceptable values. | def check(frame) -> None:
"""
Check that this frame contains acceptable values.
Raise :exc:`~websockets.exceptions.WebSocketProtocolError` if this
frame contains incorrect values.
"""
# The first parameter is called `frame` rather than `self`,
# but it's the ins... |
Read an HTTP/ 1. 1 GET request from stream. | async def read_request(stream: asyncio.StreamReader) -> Tuple[str, "Headers"]:
"""
Read an HTTP/1.1 GET request from ``stream``.
``stream`` is an :class:`~asyncio.StreamReader`.
Return ``(path, headers)`` where ``path`` is a :class:`str` and
``headers`` is a :class:`Headers` instance.
``path`... |
Read an HTTP/ 1. 1 response from stream. | async def read_response(stream: asyncio.StreamReader) -> Tuple[int, str, "Headers"]:
"""
Read an HTTP/1.1 response from ``stream``.
``stream`` is an :class:`~asyncio.StreamReader`.
Return ``(status_code, reason, headers)`` where ``status_code`` is an
:class:`int`, ``reason`` is a :class:`str`, and... |
Read HTTP headers from stream. | async def read_headers(stream: asyncio.StreamReader) -> "Headers":
"""
Read HTTP headers from ``stream``.
``stream`` is an :class:`~asyncio.StreamReader`.
Return a :class:`Headers` instance
Non-ASCII characters are represented with surrogate escapes.
"""
# https://tools.ietf.org/html/rfc... |
Read a single line from stream. | async def read_line(stream: asyncio.StreamReader) -> bytes:
"""
Read a single line from ``stream``.
``stream`` is an :class:`~asyncio.StreamReader`.
Return :class:`bytes` without CRLF.
"""
# Security: this is bounded by the StreamReader's limit (default = 32 KiB).
line = await stream.read... |
Return the ( possibly empty ) list of all values for a header. | def get_all(self, key: str) -> List[str]:
"""
Return the (possibly empty) list of all values for a header.
"""
return self._dict.get(key.lower(), []) |
Return the next character from header at the given position. | def peek_ahead(header: str, pos: int) -> Optional[str]:
"""
Return the next character from ``header`` at the given position.
Return ``None`` at the end of ``header``.
We never need to peek more than one character ahead.
"""
return None if pos == len(header) else header[pos] |
Parse optional whitespace from header at the given position. | def parse_OWS(header: str, pos: int) -> int:
"""
Parse optional whitespace from ``header`` at the given position.
Return the new position.
The whitespace itself isn't returned because it isn't significant.
"""
# There's always a match, possibly empty, whose content doesn't matter.
match =... |
Parse a token from header at the given position. | def parse_token(header: str, pos: int, header_name: str) -> Tuple[str, int]:
"""
Parse a token from ``header`` at the given position.
Return the token value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
"""
match = _token_re.match(header, pos... |
Parse a quoted string from header at the given position. | def parse_quoted_string(header: str, pos: int, header_name: str) -> Tuple[str, int]:
"""
Parse a quoted string from ``header`` at the given position.
Return the unquoted value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
"""
match = _quoted_... |
Parse a comma - separated list from header at the given position. | def parse_list(
parse_item: Callable[[str, int, str], Tuple[T, int]],
header: str,
pos: int,
header_name: str,
) -> List[T]:
"""
Parse a comma-separated list from ``header`` at the given position.
This is appropriate for parsing values with the following grammar:
1#item
``pars... |
Parse a Connection option from header at the given position. | def parse_connection_option(
header: str, pos: int, header_name: str
) -> Tuple[ConnectionOption, int]:
"""
Parse a Connection option from ``header`` at the given position.
Return the protocol value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
... |
Parse an Upgrade protocol from header at the given position. | def parse_upgrade_protocol(
header: str, pos: int, header_name: str
) -> Tuple[UpgradeProtocol, int]:
"""
Parse an Upgrade protocol from ``header`` at the given position.
Return the protocol value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
... |
Parse a single extension parameter from header at the given position. | def parse_extension_item_param(
header: str, pos: int, header_name: str
) -> Tuple[ExtensionParameter, int]:
"""
Parse a single extension parameter from ``header`` at the given position.
Return a ``(name, value)`` pair and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` o... |
Parse an extension definition from header at the given position. | def parse_extension_item(
header: str, pos: int, header_name: str
) -> Tuple[ExtensionHeader, int]:
"""
Parse an extension definition from ``header`` at the given position.
Return an ``(extension name, parameters)`` pair, where ``parameters`` is a
list of ``(name, value)`` pairs, and the new positi... |
Build an extension definition. | def build_extension_item(name: str, parameters: List[ExtensionParameter]) -> str:
"""
Build an extension definition.
This is the reverse of :func:`parse_extension_item`.
"""
return "; ".join(
[name]
+ [
# Quoted strings aren't necessary because values are always tokens.... |
Unparse a Sec - WebSocket - Extensions header. | def build_extension(extensions: Sequence[ExtensionHeader]) -> str:
"""
Unparse a ``Sec-WebSocket-Extensions`` header.
This is the reverse of :func:`parse_extension`.
"""
return ", ".join(
build_extension_item(name, parameters) for name, parameters in extensions
) |
Parse a subprotocol from header at the given position. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 ping. | 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... |
This coroutine sends a pong. | 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
... |
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. | 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 ). | 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. | 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. | 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. | 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. | 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 | 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. | 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. | 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. | 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)] |
plot distribution | def plot_dist_normal(s, mu, sigma):
"""
plot distribution
"""
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 30, normed=True)
plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) \
* np.exp( - (bins - mu)**2 / (2 * sigma**2) ), \
linewidth = 2, color = 'r')
... |
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 | 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] |
Return a df with predictions and confidence interval | def _predict(self, fit, df):
"""
Return a df with predictions and confidence interval
Notes
-----
The df will contain the following columns:
- 'predicted': the model output
- 'interval_u', 'interval_l': upper and lower confidence bounds.
The result will ... |
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. | 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. | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.