repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
moonso/vcf_parser | vcf_parser/parser.py | cli | python | def cli(variant_file, vep, split):
from datetime import datetime
from pprint import pprint as pp
if variant_file == '-':
my_parser = VCFParser(fsock=sys.stdin, split_variants=split)
else:
my_parser = VCFParser(infile = variant_file, split_variants=split)
start = datetime.now()
nr... | Parses a vcf file.\n
\n
Usage:\n
parser infile.vcf\n
If pipe:\n
parser - | train | https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/parser.py#L284-L305 | [
"def print_header(self):\n \"\"\"Returns a list with the header lines if proper format\"\"\"\n lines_to_print = []\n lines_to_print.append('##fileformat='+self.fileformat)\n if self.filedate:\n lines_to_print.append('##fileformat='+self.fileformat)\n\n for filt in self.filter_dict:\n li... | #!/usr/bin/env python
# encoding: utf-8
"""
vcf_parser.py
Parse a vcf file.
Includes a header class for storing information about the headers.
Create variant objects and a dictionary with individuals that have a dictionary with genotypes for each variant.
Thanks to PyVCF for heaader parser and more...:
Copyright (... |
moonso/vcf_parser | vcf_parser/parser.py | VCFParser.add_variant | python | def add_variant(self, chrom, pos, rs_id, ref, alt, qual, filt, info, form=None, genotypes=[]):
variant_info = [chrom, pos, rs_id, ref, alt, qual, filt, info]
if form:
variant_info.append(form)
for individual in genotypes:
variant_info.append(individual)
v... | Add a variant to the parser.
This function is for building a vcf. It takes the relevant parameters
and make a vcf variant in the proper format. | train | https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/parser.py#L173-L202 | [
"def format_variant(line, header_parser, check_info=False):\n \"\"\"\n Yield the variant in the right format. \n\n If the variants should be splitted on alternative alles one variant \n for each alternative will be yielded.\n\n Arguments:\n line (str): A string that represents a variant line i... | class VCFParser(object):
"""docstring for VCFParser"""
def __init__(self, infile=None, fsock=None, split_variants=False,
check_info=False, allele_symbol='0', fileformat = None):
super(VCFParser, self).__init__()
self.logger = logging.getLogger(__name__)
self.vcf = None
... |
moonso/vcf_parser | vcf_parser/utils/build_vep.py | build_vep_string | python | def build_vep_string(vep_info, vep_columns):
logger = getLogger(__name__)
logger.debug("Building vep string from {0}".format(vep_info))
logger.debug("Found vep headers {0}".format(vep_columns))
vep_strings = []
for vep_annotation in vep_info:
try:
vep_info_list = [
... | Build a vep string formatted string.
Take a list with vep annotations and build a new vep string
Args:
vep_info (list): A list with vep annotation dictionaries
vep_columns (list): A list with the vep column names found in the
header of the vcf
Returns:
string: ... | train | https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/utils/build_vep.py#L3-L31 | null | from logging import getLogger
def build_vep_string(vep_info, vep_columns):
"""
Build a vep string formatted string.
Take a list with vep annotations and build a new vep string
Args:
vep_info (list): A list with vep annotation dictionaries
vep_columns (list): A list with the vep column... |
moonso/vcf_parser | vcf_parser/utils/build_vep.py | build_vep_annotation | python | def build_vep_annotation(csq_info, reference, alternatives, vep_columns):
logger = getLogger(__name__)
# The keys in the vep dict are the vcf formatted alternatives, values are the
# dictionaries with vep annotations
vep_dict = {}
# If we have several alternatives we need to check what types of
... | Build a dictionary with the vep information from the vep annotation.
Indels are handled different by vep depending on the number of
alternative alleles there is for a variant.
If only one alternative:
Insertion: vep represents the alternative by removing the first
base f... | train | https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/utils/build_vep.py#L33-L134 | null | from logging import getLogger
def build_vep_string(vep_info, vep_columns):
"""
Build a vep string formatted string.
Take a list with vep annotations and build a new vep string
Args:
vep_info (list): A list with vep annotation dictionaries
vep_columns (list): A list with the vep column... |
ethereum/eth-utils | eth_utils/currency.py | from_wei | python | def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if number == 0:
return 0
if number < MIN_WEI or number > MAX_WEI:
raise Valu... | Takes a number of wei and converts it to any other ether unit. | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/currency.py#L40-L62 | null | import decimal
from decimal import localcontext
from typing import Union
from .types import is_integer, is_string
from .units import units
class denoms:
wei = int(units["wei"])
kwei = int(units["kwei"])
babbage = int(units["babbage"])
femtoether = int(units["femtoether"])
mwei = int(units["mwei"... |
ethereum/eth-utils | eth_utils/currency.py | to_wei | python | def to_wei(number: int, unit: str) -> int:
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if is_integer(number) or is_string(number):
d_number = decimal.Decimal(value=number)
elif isinstance(number, fl... | Takes a number of a unit and converts it to wei. | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/currency.py#L65-L103 | [
"def is_integer(value: Any) -> bool:\n return isinstance(value, integer_types) and not isinstance(value, bool)\n",
"def is_string(value: Any) -> bool:\n return isinstance(value, string_types)\n"
] | import decimal
from decimal import localcontext
from typing import Union
from .types import is_integer, is_string
from .units import units
class denoms:
wei = int(units["wei"])
kwei = int(units["kwei"])
babbage = int(units["babbage"])
femtoether = int(units["femtoether"])
mwei = int(units["mwei"... |
ethereum/eth-utils | eth_utils/conversions.py | to_hex | python | def to_hex(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> HexStr:
if hexstr is not None:
return HexStr(add_0x_prefix(hexstr.lower()))
if text is not None:
return HexStr(encode_hex(text.encode("utf-8")))
if is_boolean(primitive):
return HexStr("0x1")... | Auto converts any supported value into its hex representation.
Trims leading zeros, as defined in:
https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/conversions.py#L11-L42 | [
"def add_0x_prefix(value: str) -> str:\n if is_0x_prefixed(value):\n return value\n return \"0x\" + value\n",
"def encode_hex(value: AnyStr) -> str:\n if not is_string(value):\n raise TypeError(\"Value must be an instance of str or unicode\")\n binary_hex = codecs.encode(value, \"hex\") ... | from typing import Callable, Union, cast
from .decorators import validate_conversion_arguments
from .encoding import big_endian_to_int, int_to_big_endian
from .hexadecimal import add_0x_prefix, decode_hex, encode_hex, is_hex, remove_0x_prefix
from .types import is_boolean, is_integer, is_string
from .typing import Hex... |
ethereum/eth-utils | eth_utils/conversions.py | to_int | python | def to_int(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> int:
if hexstr is not None:
return int(hexstr, 16)
elif text is not None:
return int(text)
elif isinstance(primitive, (bytes, bytearray)):
return big_endian_to_int(primitive)
elif isinstanc... | Converts value to its integer representation.
Values are converted this way:
* primitive:
* bytes, bytearrays: big-endian integer
* bool: True => 1, False => 0
* hexstr: interpret hex as integer
* text: interpret as string of digits, like '12' => 12 | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/conversions.py#L46-L74 | [
"def big_endian_to_int(value: bytes) -> int:\n return int.from_bytes(value, \"big\")\n"
] | from typing import Callable, Union, cast
from .decorators import validate_conversion_arguments
from .encoding import big_endian_to_int, int_to_big_endian
from .hexadecimal import add_0x_prefix, decode_hex, encode_hex, is_hex, remove_0x_prefix
from .types import is_boolean, is_integer, is_string
from .typing import Hex... |
ethereum/eth-utils | eth_utils/conversions.py | text_if_str | python | def text_if_str(
to_type: Callable[..., T], text_or_primitive: Union[bytes, int, str]
) -> T:
if isinstance(text_or_primitive, str):
return to_type(text=text_or_primitive)
else:
return to_type(text_or_primitive) | Convert to a type, assuming that strings can be only unicode text (not a hexstr)
:param to_type function: takes the arguments (primitive, hexstr=hexstr, text=text),
eg~ to_bytes, to_text, to_hex, to_int, etc
:param text_or_primitive bytes, str, int: value to convert | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/conversions.py#L119-L132 | null | from typing import Callable, Union, cast
from .decorators import validate_conversion_arguments
from .encoding import big_endian_to_int, int_to_big_endian
from .hexadecimal import add_0x_prefix, decode_hex, encode_hex, is_hex, remove_0x_prefix
from .types import is_boolean, is_integer, is_string
from .typing import Hex... |
ethereum/eth-utils | eth_utils/conversions.py | hexstr_if_str | python | def hexstr_if_str(
to_type: Callable[..., T], hexstr_or_primitive: Union[bytes, int, str]
) -> T:
if isinstance(hexstr_or_primitive, str):
if remove_0x_prefix(hexstr_or_primitive) and not is_hex(hexstr_or_primitive):
raise ValueError(
"when sending a str, it must be a hex str... | Convert to a type, assuming that strings can be only hexstr (not unicode text)
:param to_type function: takes the arguments (primitive, hexstr=hexstr, text=text),
eg~ to_bytes, to_text, to_hex, to_int, etc
:param hexstr_or_primitive bytes, str, int: value to convert | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/conversions.py#L135-L154 | [
"def is_hex(value: Any) -> bool:\n if not is_text(value):\n raise TypeError(\n \"is_hex requires text typed arguments. Got: {0}\".format(repr(value))\n )\n elif value.lower() == \"0x\":\n return True\n\n unprefixed_value = remove_0x_prefix(value)\n if len(unprefixed_value... | from typing import Callable, Union, cast
from .decorators import validate_conversion_arguments
from .encoding import big_endian_to_int, int_to_big_endian
from .hexadecimal import add_0x_prefix, decode_hex, encode_hex, is_hex, remove_0x_prefix
from .types import is_boolean, is_integer, is_string
from .typing import Hex... |
ethereum/eth-utils | eth_utils/decorators.py | validate_conversion_arguments | python | def validate_conversion_arguments(to_wrap):
@functools.wraps(to_wrap)
def wrapper(*args, **kwargs):
_assert_one_val(*args, **kwargs)
if kwargs:
_validate_supported_kwarg(kwargs)
if len(args) == 0 and "primitive" not in kwargs:
_assert_hexstr_or_text_kwarg_is_tex... | Validates arguments for conversion functions.
- Only a single argument is present
- Kwarg must be 'primitive' 'hexstr' or 'text'
- If it is 'hexstr' or 'text' that it is a text type | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/decorators.py#L59-L77 | null | import functools
import itertools
from typing import Any, Callable, Dict, Iterable, Type
from .types import is_text
class combomethod(object):
def __init__(self, method):
self.method = method
def __get__(self, obj=None, objtype=None):
@functools.wraps(self.method)
def _wrapper(*args... |
ethereum/eth-utils | eth_utils/decorators.py | return_arg_type | python | def return_arg_type(at_position):
def decorator(to_wrap):
@functools.wraps(to_wrap)
def wrapper(*args, **kwargs):
result = to_wrap(*args, **kwargs)
ReturnType = type(args[at_position])
return ReturnType(result)
return wrapper
return decorator | Wrap the return value with the result of `type(args[at_position])` | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/decorators.py#L80-L94 | null | import functools
import itertools
from typing import Any, Callable, Dict, Iterable, Type
from .types import is_text
class combomethod(object):
def __init__(self, method):
self.method = method
def __get__(self, obj=None, objtype=None):
@functools.wraps(self.method)
def _wrapper(*args... |
ethereum/eth-utils | eth_utils/decorators.py | replace_exceptions | python | def replace_exceptions(
old_to_new_exceptions: Dict[Type[BaseException], Type[BaseException]]
) -> Callable[..., Any]:
old_exceptions = tuple(old_to_new_exceptions.keys())
def decorator(to_wrap: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(to_wrap)
# String type b/c pypy3 thr... | Replaces old exceptions with new exceptions to be raised in their place. | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/decorators.py#L97-L124 | null | import functools
import itertools
from typing import Any, Callable, Dict, Iterable, Type
from .types import is_text
class combomethod(object):
def __init__(self, method):
self.method = method
def __get__(self, obj=None, objtype=None):
@functools.wraps(self.method)
def _wrapper(*args... |
ethereum/eth-utils | eth_utils/abi.py | collapse_if_tuple | python | def collapse_if_tuple(abi):
typ = abi["type"]
if not typ.startswith("tuple"):
return typ
delimited = ",".join(collapse_if_tuple(c) for c in abi["components"])
# Whatever comes after "tuple" is the array dims. The ABI spec states that
# this will have the form "", "[]", or "[k]".
array_... | Converts a tuple from a dict to a parenthesized list of its types.
>>> from eth_utils.abi import collapse_if_tuple
>>> collapse_if_tuple(
... {
... 'components': [
... {'name': 'anAddress', 'type': 'address'},
... {'name': 'anInt', 'type': 'uint256'},
...... | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/abi.py#L6-L32 | null | from typing import Any, Dict
from .crypto import keccak
def _abi_to_signature(abi: Dict[str, Any]) -> str:
function_signature = "{fn_name}({fn_input_types})".format(
fn_name=abi["name"],
fn_input_types=",".join(
[collapse_if_tuple(abi_input) for abi_input in abi.get("inputs", [])]
... |
ethereum/eth-utils | eth_utils/address.py | is_hex_address | python | def is_hex_address(value: Any) -> bool:
if not is_text(value):
return False
elif not is_hex(value):
return False
else:
unprefixed = remove_0x_prefix(value)
return len(unprefixed) == 40 | Checks if the given string of text type is an address in hexadecimal encoded form. | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L10-L20 | [
"def is_hex(value: Any) -> bool:\n if not is_text(value):\n raise TypeError(\n \"is_hex requires text typed arguments. Got: {0}\".format(repr(value))\n )\n elif value.lower() == \"0x\":\n return True\n\n unprefixed_value = remove_0x_prefix(value)\n if len(unprefixed_value... | from typing import Any, AnyStr
from .crypto import keccak
from .hexadecimal import add_0x_prefix, decode_hex, encode_hex, is_hex, remove_0x_prefix
from .conversions import hexstr_if_str, to_hex
from .types import is_bytes, is_text
from .typing import Address, AnyAddress, ChecksumAddress, HexAddress
def is_binary_ad... |
ethereum/eth-utils | eth_utils/address.py | is_binary_address | python | def is_binary_address(value: Any) -> bool:
if not is_bytes(value):
return False
elif len(value) != 20:
return False
else:
return True | Checks if the given string is an address in raw bytes form. | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L23-L32 | [
"def is_bytes(value: Any) -> bool:\n return isinstance(value, bytes_types)\n"
] | from typing import Any, AnyStr
from .crypto import keccak
from .hexadecimal import add_0x_prefix, decode_hex, encode_hex, is_hex, remove_0x_prefix
from .conversions import hexstr_if_str, to_hex
from .types import is_bytes, is_text
from .typing import Address, AnyAddress, ChecksumAddress, HexAddress
def is_hex_addres... |
ethereum/eth-utils | eth_utils/address.py | is_address | python | def is_address(value: Any) -> bool:
if is_checksum_formatted_address(value):
return is_checksum_address(value)
elif is_hex_address(value):
return True
elif is_binary_address(value):
return True
else:
return False | Checks if the given string in a supported value
is an address in any of the known formats. | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L35-L47 | [
"def is_binary_address(value: Any) -> bool:\n \"\"\"\n Checks if the given string is an address in raw bytes form.\n \"\"\"\n if not is_bytes(value):\n return False\n elif len(value) != 20:\n return False\n else:\n return True\n",
"def is_checksum_address(value: Any) -> bool... | from typing import Any, AnyStr
from .crypto import keccak
from .hexadecimal import add_0x_prefix, decode_hex, encode_hex, is_hex, remove_0x_prefix
from .conversions import hexstr_if_str, to_hex
from .types import is_bytes, is_text
from .typing import Address, AnyAddress, ChecksumAddress, HexAddress
def is_hex_addres... |
ethereum/eth-utils | eth_utils/address.py | to_normalized_address | python | def to_normalized_address(value: AnyStr) -> HexAddress:
try:
hex_address = hexstr_if_str(to_hex, value).lower()
except AttributeError:
raise TypeError(
"Value must be any string, instead got type {}".format(type(value))
)
if is_address(hex_address):
return HexAddr... | Converts an address to its normalized hexadecimal representation. | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L50-L65 | [
"def is_address(value: Any) -> bool:\n \"\"\"\n Checks if the given string in a supported value\n is an address in any of the known formats.\n \"\"\"\n if is_checksum_formatted_address(value):\n return is_checksum_address(value)\n elif is_hex_address(value):\n return True\n elif i... | from typing import Any, AnyStr
from .crypto import keccak
from .hexadecimal import add_0x_prefix, decode_hex, encode_hex, is_hex, remove_0x_prefix
from .conversions import hexstr_if_str, to_hex
from .types import is_bytes, is_text
from .typing import Address, AnyAddress, ChecksumAddress, HexAddress
def is_hex_addres... |
ethereum/eth-utils | eth_utils/address.py | is_normalized_address | python | def is_normalized_address(value: Any) -> bool:
if not is_address(value):
return False
else:
return value == to_normalized_address(value) | Returns whether the provided value is an address in its normalized form. | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L68-L75 | [
"def is_address(value: Any) -> bool:\n \"\"\"\n Checks if the given string in a supported value\n is an address in any of the known formats.\n \"\"\"\n if is_checksum_formatted_address(value):\n return is_checksum_address(value)\n elif is_hex_address(value):\n return True\n elif i... | from typing import Any, AnyStr
from .crypto import keccak
from .hexadecimal import add_0x_prefix, decode_hex, encode_hex, is_hex, remove_0x_prefix
from .conversions import hexstr_if_str, to_hex
from .types import is_bytes, is_text
from .typing import Address, AnyAddress, ChecksumAddress, HexAddress
def is_hex_addres... |
ethereum/eth-utils | eth_utils/address.py | is_canonical_address | python | def is_canonical_address(address: Any) -> bool:
if not is_bytes(address) or len(address) != 20:
return False
return address == to_canonical_address(address) | Returns `True` if the `value` is an address in its canonical form. | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L86-L92 | [
"def to_canonical_address(address: AnyStr) -> Address:\n \"\"\"\n Given any supported representation of an address\n returns its canonical form (20 byte long string).\n \"\"\"\n return Address(decode_hex(to_normalized_address(address)))\n",
"def is_bytes(value: Any) -> bool:\n return isinstance(... | from typing import Any, AnyStr
from .crypto import keccak
from .hexadecimal import add_0x_prefix, decode_hex, encode_hex, is_hex, remove_0x_prefix
from .conversions import hexstr_if_str, to_hex
from .types import is_bytes, is_text
from .typing import Address, AnyAddress, ChecksumAddress, HexAddress
def is_hex_addres... |
ethereum/eth-utils | eth_utils/address.py | is_same_address | python | def is_same_address(left: AnyAddress, right: AnyAddress) -> bool:
if not is_address(left) or not is_address(right):
raise ValueError("Both values must be valid addresses")
else:
return to_normalized_address(left) == to_normalized_address(right) | Checks if both addresses are same or not. | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L95-L102 | [
"def is_address(value: Any) -> bool:\n \"\"\"\n Checks if the given string in a supported value\n is an address in any of the known formats.\n \"\"\"\n if is_checksum_formatted_address(value):\n return is_checksum_address(value)\n elif is_hex_address(value):\n return True\n elif i... | from typing import Any, AnyStr
from .crypto import keccak
from .hexadecimal import add_0x_prefix, decode_hex, encode_hex, is_hex, remove_0x_prefix
from .conversions import hexstr_if_str, to_hex
from .types import is_bytes, is_text
from .typing import Address, AnyAddress, ChecksumAddress, HexAddress
def is_hex_addres... |
ethereum/eth-utils | eth_utils/address.py | to_checksum_address | python | def to_checksum_address(value: AnyStr) -> ChecksumAddress:
norm_address = to_normalized_address(value)
address_hash = encode_hex(keccak(text=remove_0x_prefix(norm_address)))
checksum_address = add_0x_prefix(
"".join(
(
norm_address[i].upper()
if int(addre... | Makes a checksum address given a supported format. | train | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L105-L122 | [
"def to_normalized_address(value: AnyStr) -> HexAddress:\n \"\"\"\n Converts an address to its normalized hexadecimal representation.\n \"\"\"\n try:\n hex_address = hexstr_if_str(to_hex, value).lower()\n except AttributeError:\n raise TypeError(\n \"Value must be any string,... | from typing import Any, AnyStr
from .crypto import keccak
from .hexadecimal import add_0x_prefix, decode_hex, encode_hex, is_hex, remove_0x_prefix
from .conversions import hexstr_if_str, to_hex
from .types import is_bytes, is_text
from .typing import Address, AnyAddress, ChecksumAddress, HexAddress
def is_hex_addres... |
harmsm/PyCmdMessenger | PyCmdMessenger/arduino.py | ArduinoBoard.open | python | def open(self):
if not self._is_connected:
print("Connecting to arduino on {}... ".format(self.device),end="")
self.comm = serial.Serial()
self.comm.port = self.device
self.comm.baudrate = self.baud_rate
self.comm.timeout = self.timeout
... | Open the serial connection. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/arduino.py#L147-L166 | null | class ArduinoBoard:
"""
Class for connecting to an Arduino board over USB using PyCmdMessenger.
The board holds the serial handle (which, in turn, holds the device name,
baud rate, and timeout) and the board parameters (size of data types in
bytes, etc.). The default parameters are for an Arduin... |
harmsm/PyCmdMessenger | PyCmdMessenger/arduino.py | ArduinoBoard.close | python | def close(self):
if self._is_connected:
self.comm.close()
self._is_connected = False | Close serial connection. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/arduino.py#L189-L196 | null | class ArduinoBoard:
"""
Class for connecting to an Arduino board over USB using PyCmdMessenger.
The board holds the serial handle (which, in turn, holds the device name,
baud rate, and timeout) and the board parameters (size of data types in
bytes, etc.). The default parameters are for an Arduin... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger.send | python | def send(self,cmd,*args,arg_formats=None):
# Turn the command into an integer.
try:
command_as_int = self._cmd_name_to_int[cmd]
except KeyError:
err = "Command '{}' not recognized.\n".format(cmd)
raise ValueError(err)
# Figure out what formats to use... | Send a command (which may or may not have associated arguments) to an
arduino using the CmdMessage protocol. The command and any parameters
should be passed as direct arguments to send.
arg_formats is an optional string that specifies the formats to use for
each argument when passed... | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L120-L173 | [
"def _treat_star_format(self,arg_format_list,args):\n \"\"\"\n Deal with \"*\" format if specified.\n \"\"\"\n\n num_stars = len([a for a in arg_format_list if a == \"*\"])\n if num_stars > 0:\n\n # Make sure the repeated format argument only occurs once, is last,\n # and that there is ... | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger.receive | python | def receive(self,arg_formats=None):
# Read serial input until a command separator or empty character is
# reached
msg = [[]]
raw_msg = []
escaped = False
command_sep_found = False
while True:
tmp = self.board.read()
raw_msg.append(tmp)
... | Recieve commands coming off the serial port.
arg_formats is an optimal keyword that specifies the formats to use to
parse incoming arguments. If specified here, arg_formats supercedes
the formats specified on initialization. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L175-L289 | [
"def _treat_star_format(self,arg_format_list,args):\n \"\"\"\n Deal with \"*\" format if specified.\n \"\"\"\n\n num_stars = len([a for a in arg_format_list if a == \"*\"])\n if num_stars > 0:\n\n # Make sure the repeated format argument only occurs once, is last,\n # and that there is ... | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._treat_star_format | python | def _treat_star_format(self,arg_format_list,args):
num_stars = len([a for a in arg_format_list if a == "*"])
if num_stars > 0:
# Make sure the repeated format argument only occurs once, is last,
# and that there is at least one format in addition to it.
if num_stars... | Deal with "*" format if specified. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L291-L317 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._send_char | python | def _send_char(self,value):
if type(value) != str and type(value) != bytes:
err = "char requires a string or bytes array of length 1"
raise ValueError(err)
if len(value) != 1:
err = "char must be a single character, not \"{}\"".format(value)
raise ValueE... | Convert a single char to a bytes object. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L319-L339 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._send_byte | python | def _send_byte(self,value):
# Coerce to int. This will throw a ValueError if the value can't
# actually be converted.
if type(value) != int:
new_value = int(value)
if self.give_warnings:
w = "Coercing {} into int ({})".format(value,new_value)
... | Convert a numerical value into an integer, then to a byte object. Check
bounds for byte. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L341-L362 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._send_int | python | def _send_int(self,value):
# Coerce to int. This will throw a ValueError if the value can't
# actually be converted.
if type(value) != int:
new_value = int(value)
if self.give_warnings:
w = "Coercing {} into int ({})".format(value,new_value)
... | Convert a numerical value into an integer, then to a bytes object Check
bounds for signed int. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L364-L385 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._send_unsigned_int | python | def _send_unsigned_int(self,value):
# Coerce to int. This will throw a ValueError if the value can't
# actually be converted.
if type(value) != int:
new_value = int(value)
if self.give_warnings:
w = "Coercing {} into int ({})".format(value,new_value)
... | Convert a numerical value into an integer, then to a bytes object. Check
bounds for unsigned int. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L387-L407 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._send_long | python | def _send_long(self,value):
# Coerce to int. This will throw a ValueError if the value can't
# actually be converted.
if type(value) != int:
new_value = int(value)
if self.give_warnings:
w = "Coercing {} into int ({})".format(value,new_value... | Convert a numerical value into an integer, then to a bytes object. Check
bounds for signed long. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L409-L430 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._send_unsigned_long | python | def _send_unsigned_long(self,value):
# Coerce to int. This will throw a ValueError if the value can't
# actually be converted.
if type(value) != int:
new_value = int(value)
if self.give_warnings:
w = "Coercing {} into int ({})".format(value,new_value)
... | Convert a numerical value into an integer, then to a bytes object.
Check bounds for unsigned long. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L432-L453 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._send_float | python | def _send_float(self,value):
# convert to float. this will throw a ValueError if the type is not
# readily converted
if type(value) != float:
value = float(value)
# Range check
if value > self.board.float_max or value < self.board.float_min:
err = "Valu... | Return a float as a IEEE 754 format bytes object. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L455-L470 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._send_double | python | def _send_double(self,value):
# convert to float. this will throw a ValueError if the type is not
# readily converted
if type(value) != float:
value = float(value)
# Range check
if value > self.board.float_max or value < self.board.float_min:
err = "Val... | Return a float as a IEEE 754 format bytes object. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L472-L487 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._send_string | python | def _send_string(self,value):
if type(value) != bytes:
value = "{}".format(value).encode("ascii")
return value | Convert a string to a bytes object. If value is not a string, it is
be converted to one with a standard string.format call. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L489-L498 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._send_bool | python | def _send_bool(self,value):
# Sanity check.
if type(value) != bool and value not in [0,1]:
err = "{} is not boolean.".format(value)
raise ValueError(err)
return struct.pack("?",value) | Convert a boolean value into a bytes object. Uses 0 and 1 as output. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L500-L510 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._send_guess | python | def _send_guess(self,value):
if type(value) != str and type(value) != bytes and self.give_warnings:
w = "Warning: Sending {} as a string. This can give wildly incorrect values. Consider specifying a format and sending binary data.".format(value)
warnings.warn(w,Warning)
if type... | Send the argument as a string in a way that should (probably, maybe!) be
processed properly by C++ calls like atoi, atof, etc. This method is
NOT RECOMMENDED, particularly for floats, because values are often
mangled silently. Instead, specify a format (e.g. "f") and use the
CmdMesse... | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L512-L531 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._recv_string | python | def _recv_string(self,value):
s = value.decode('ascii')
# Strip null characters
s = s.strip("\x00")
# Strip other white space
s = s.strip()
return s | Recieve a binary (bytes) string, returning a python string. | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L588-L601 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
harmsm/PyCmdMessenger | PyCmdMessenger/PyCmdMessenger.py | CmdMessenger._recv_guess | python | def _recv_guess(self,value):
if self.give_warnings:
w = "Warning: Guessing input format for {}. This can give wildly incorrect values. Consider specifying a format and sending binary data.".format(value)
warnings.warn(w,Warning)
tmp_value = value.decode()
try:
... | Take the binary spew and try to make it into a float or integer. If
that can't be done, return a string.
Note: this is generally a bad idea, as values can be seriously mangled
by going from float -> string -> float. You'll generally be better off
using a format specifier and binary... | train | https://github.com/harmsm/PyCmdMessenger/blob/215d6f9402262662a14a2996f532934339639a5b/PyCmdMessenger/PyCmdMessenger.py#L610-L640 | null | class CmdMessenger:
"""
Basic interface for interfacing over a serial connection to an arduino
using the CmdMessenger library.
"""
def __init__(self,
board_instance,
commands,
field_separator=",",
command_separator=";",
... |
benmoran56/esper | esper.py | World.clear_database | python | def clear_database(self) -> None:
self._next_entity_id = 0
self._dead_entities.clear()
self._components.clear()
self._entities.clear()
self.clear_cache() | Remove all Entities and Components from the World. | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L46-L52 | [
"def clear_cache(self) -> None:\n self.get_component.cache_clear()\n self.get_components.cache_clear()\n"
] | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World.add_processor | python | def add_processor(self, processor_instance: Processor, priority=0) -> None:
assert issubclass(processor_instance.__class__, Processor)
processor_instance.priority = priority
processor_instance.world = self
self._processors.append(processor_instance)
self._processors.sort(key=lamb... | Add a Processor instance to the World.
:param processor_instance: An instance of a Processor,
subclassed from the Processor class
:param priority: A higher number is processed first. | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L54-L65 | null | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World.remove_processor | python | def remove_processor(self, processor_type: Processor) -> None:
for processor in self._processors:
if type(processor) == processor_type:
processor.world = None
self._processors.remove(processor) | Remove a Processor from the World, by type.
:param processor_type: The class type of the Processor to remove. | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L67-L75 | null | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World.get_processor | python | def get_processor(self, processor_type: Type[P]) -> P:
for processor in self._processors:
if type(processor) == processor_type:
return processor | Get a Processor instance, by type.
This method returns a Processor instance by type. This could be
useful in certain situations, such as wanting to call a method on a
Processor, from within another Processor.
:param processor_type: The type of the Processor you wish to retrieve.
... | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L77-L89 | null | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World.create_entity | python | def create_entity(self, *components) -> int:
self._next_entity_id += 1
# TODO: duplicate add_component code here for performance
for component in components:
self.add_component(self._next_entity_id, component)
# self.clear_cache()
return self._next_entity_id | Create a new Entity.
This method returns an Entity ID, which is just a plain integer.
You can optionally pass one or more Component instances to be
assigned to the Entity.
:param components: Optional components to be assigned to the
entity on creation.
:return: The next... | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L91-L109 | [
"def add_component(self, entity: int, component_instance: Any) -> None:\n \"\"\"Add a new Component instance to an Entity.\n\n Add a Component instance to an Entiy. If a Component of the same type\n is already assigned to the Entity, it will be replaced.\n\n :param entity: The Entity to associate the Co... | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World.delete_entity | python | def delete_entity(self, entity: int, immediate=False) -> None:
if immediate:
for component_type in self._entities[entity]:
self._components[component_type].discard(entity)
if not self._components[component_type]:
del self._components[component_typ... | Delete an Entity from the World.
Delete an Entity and all of it's assigned Component instances from
the world. By default, Entity deletion is delayed until the next call
to *World.process*. You can request immediate deletion, however, by
passing the "immediate=True" parameter. This shou... | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L111-L135 | [
"def clear_cache(self) -> None:\n self.get_component.cache_clear()\n self.get_components.cache_clear()\n"
] | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World.component_for_entity | python | def component_for_entity(self, entity: int, component_type: Type[C]) -> C:
return self._entities[entity][component_type] | Retrieve a Component instance for a specific Entity.
Retrieve a Component instance for a specific Entity. In some cases,
it may be necessary to access a specific Component instance.
For example: directly modifying a Component to handle user input.
Raises a KeyError if the given Entity ... | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L137-L149 | null | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World.components_for_entity | python | def components_for_entity(self, entity: int) -> Tuple[C, ...]:
return tuple(self._entities[entity].values()) | Retrieve all Components for a specific Entity, as a Tuple.
Retrieve all Components for a specific Entity. The method is probably
not appropriate to use in your Processors, but might be useful for
saving state, or passing specific Components between World instances.
Unlike most other met... | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L151-L165 | null | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World.has_component | python | def has_component(self, entity: int, component_type: Any) -> bool:
return component_type in self._entities[entity] | Check if a specific Entity has a Component of a certain type.
:param entity: The Entity you are querying.
:param component_type: The type of Component to check for.
:return: True if the Entity has a Component of this type,
otherwise False | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L167-L175 | null | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World.add_component | python | def add_component(self, entity: int, component_instance: Any) -> None:
component_type = type(component_instance)
if component_type not in self._components:
self._components[component_type] = set()
self._components[component_type].add(entity)
if entity not in self._entities... | Add a new Component instance to an Entity.
Add a Component instance to an Entiy. If a Component of the same type
is already assigned to the Entity, it will be replaced.
:param entity: The Entity to associate the Component with.
:param component_instance: A Component instance. | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L177-L197 | [
"def clear_cache(self) -> None:\n self.get_component.cache_clear()\n self.get_components.cache_clear()\n"
] | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World.remove_component | python | def remove_component(self, entity: int, component_type: Any) -> int:
self._components[component_type].discard(entity)
if not self._components[component_type]:
del self._components[component_type]
del self._entities[entity][component_type]
if not self._entities[entity]:
... | Remove a Component instance from an Entity, by type.
A Component instance can be removed by providing it's type.
For example: world.delete_component(enemy_a, Velocity) will remove
the Velocity instance from the Entity enemy_a.
Raises a KeyError if either the given entity or Component t... | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L199-L222 | [
"def clear_cache(self) -> None:\n self.get_component.cache_clear()\n self.get_components.cache_clear()\n"
] | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World._get_component | python | def _get_component(self, component_type: Type[C]) -> Iterable[Tuple[int, C]]:
entity_db = self._entities
for entity in self._components.get(component_type, []):
yield entity, entity_db[entity][component_type] | Get an iterator for Entity, Component pairs.
:param component_type: The Component type to retrieve.
:return: An iterator for (Entity, Component) tuples. | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L224-L233 | null | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World._get_components | python | def _get_components(self, *component_types: Type)-> Iterable[Tuple[int, ...]]:
entity_db = self._entities
comp_db = self._components
try:
for entity in set.intersection(*[comp_db[ct] for ct in component_types]):
yield entity, [entity_db[entity][ct] for ct in componen... | Get an iterator for Entity and multiple Component sets.
:param component_types: Two or more Component types.
:return: An iterator for Entity, (Component1, Component2, etc)
tuples. | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L235-L249 | null | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World.try_component | python | def try_component(self, entity: int, component_type: Type):
if component_type in self._entities[entity]:
yield self._entities[entity][component_type]
else:
return None | Try to get a single component type for an Entity.
This method will return the requested Component if it exists, but
will pass silently if it does not. This allows a way to access optional
Components that may or may not exist.
:param entity: The Entity ID to ... | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L259-L274 | null | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World._clear_dead_entities | python | def _clear_dead_entities(self):
for entity in self._dead_entities:
for component_type in self._entities[entity]:
self._components[component_type].discard(entity)
if not self._components[component_type]:
del self._components[component_type]
... | Finalize deletion of any Entities that are marked dead.
In the interest of performance, this method duplicates code from the
`delete_entity` method. If that method is changed, those changes should
be duplicated here as well. | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L276-L294 | [
"def clear_cache(self) -> None:\n self.get_component.cache_clear()\n self.get_components.cache_clear()\n"
] | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World._timed_process | python | def _timed_process(self, *args, **kwargs):
for processor in self._processors:
start_time = _time.process_time()
processor.process(*args, **kwargs)
process_time = int(round((_time.process_time() - start_time) * 1000, 2))
self.process_times[processor.__class__.__nam... | Track Processor execution time for benchmarking. | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L300-L306 | null | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | esper.py | World.process | python | def process(self, *args, **kwargs):
self._clear_dead_entities()
self._process(*args, **kwargs) | Call the process method on all Processors, in order of their priority.
Call the *process* method on all assigned Processors, respecting their
optional priority setting. In addition, any Entities that were marked
for deletion since the last call to *World.process*, will be deleted
at the... | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L308-L320 | [
"def _clear_dead_entities(self):\n \"\"\"Finalize deletion of any Entities that are marked dead.\n\n In the interest of performance, this method duplicates code from the\n `delete_entity` method. If that method is changed, those changes should\n be duplicated here as well.\n \"\"\"\n for entity in... | class World:
def __init__(self, timed=False):
"""A World object keeps track of all Entities, Components, and Processors.
A World contains a database of all Entity/Component assignments. It also
handles calling the process method on any Processors assigned to it.
"""
self._pr... |
benmoran56/esper | examples/pysdl2_example.py | texture_from_image | python | def texture_from_image(renderer, image_name):
soft_surface = ext.load_image(image_name)
texture = SDL_CreateTextureFromSurface(renderer.renderer, soft_surface)
SDL_FreeSurface(soft_surface)
return texture | Create an SDL2 Texture from an image file | train | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/examples/pysdl2_example.py#L76-L81 | null | from sdl2 import *
import sdl2.ext as ext
import esper
RESOLUTION = 720, 480
##################################
# Define some Components:
##################################
class Velocity:
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
class Renderable:
def __init__(self, texture... |
mozilla/taar | taar/flask_app.py | flaskrun | python | def flaskrun(app, default_host="127.0.0.1", default_port="8000"):
# Set up the command-line options
parser = optparse.OptionParser()
parser.add_option(
"-H",
"--host",
help="Hostname of the Flask app " + "[default %s]" % default_host,
default=default_host,
)
parser.a... | Takes a flask.Flask instance and runs it. Parses
command-line flags to configure the app. | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/flask_app.py#L41-L86 | null | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import sys
from flask import Flask
from dockerflow.flask import Dockerflow
import optparse
from decouple import config
i... |
mozilla/taar | taar/recommenders/hybrid_recommender.py | CuratedWhitelistCache.get_randomized_guid_sample | python | def get_randomized_guid_sample(self, item_count):
dataset = self.get_whitelist()
random.shuffle(dataset)
return dataset[:item_count] | Fetch a subset of randomzied GUIDs from the whitelist | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/hybrid_recommender.py#L28-L32 | [
"def get_whitelist(self):\n return self._data.get()[0]\n"
] | class CuratedWhitelistCache:
"""
This fetches the curated whitelist from S3.
"""
def __init__(self, ctx):
self._ctx = ctx
self._data = LazyJSONLoader(
self._ctx, TAAR_WHITELIST_BUCKET, TAAR_WHITELIST_KEY
)
def get_whitelist(self):
return self._data.get()... |
mozilla/taar | taar/recommenders/hybrid_recommender.py | CuratedRecommender.can_recommend | python | def can_recommend(self, client_data, extra_data={}):
self.logger.info("Curated can_recommend: {}".format(True))
return True | The Curated recommender will always be able to recommend
something | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/hybrid_recommender.py#L52-L56 | null | class CuratedRecommender(AbstractRecommender):
"""
The curated recommender just delegates to the whitelist
that is provided by the AMO team.
This recommender simply provides a randomized sample of
pre-approved addons for recommendation. It does not use any other
external data to generate recomm... |
mozilla/taar | taar/recommenders/hybrid_recommender.py | CuratedRecommender.recommend | python | def recommend(self, client_data, limit, extra_data={}):
guids = self._curated_wl.get_randomized_guid_sample(limit)
results = [(guid, 1.0) for guid in guids]
log_data = (client_data["client_id"], str(guids))
self.logger.info(
"Curated recommendations client_id: [%s], guids: ... | Curated recommendations are just random selections | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/hybrid_recommender.py#L58-L70 | [
"def get_randomized_guid_sample(self, item_count):\n \"\"\" Fetch a subset of randomzied GUIDs from the whitelist \"\"\"\n dataset = self.get_whitelist()\n random.shuffle(dataset)\n return dataset[:item_count]\n"
] | class CuratedRecommender(AbstractRecommender):
"""
The curated recommender just delegates to the whitelist
that is provided by the AMO team.
This recommender simply provides a randomized sample of
pre-approved addons for recommendation. It does not use any other
external data to generate recomm... |
mozilla/taar | taar/recommenders/hybrid_recommender.py | HybridRecommender.can_recommend | python | def can_recommend(self, client_data, extra_data={}):
ensemble_recommend = self._ensemble_recommender.can_recommend(
client_data, extra_data
)
curated_recommend = self._curated_recommender.can_recommend(
client_data, extra_data
)
result = ensemble_recommend... | The ensemble recommender is always going to be
available if at least one recommender is available | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/hybrid_recommender.py#L89-L100 | null | class HybridRecommender(AbstractRecommender):
"""
The EnsembleRecommender is a collection of recommenders where the
results from each recommendation is amplified or dampened by a
factor. The aggregate results are combines and used to recommend
addons for users.
"""
def __init__(self, ctx):... |
mozilla/taar | taar/recommenders/hybrid_recommender.py | HybridRecommender.recommend | python | def recommend(self, client_data, limit, extra_data={}):
preinstalled_addon_ids = client_data.get("installed_addons", [])
# Compute an extended limit by adding the length of
# the list of any preinstalled addons.
extended_limit = limit + len(preinstalled_addon_ids)
ensemble_sug... | Hybrid recommendations simply select half recommendations from
the ensemble recommender, and half from the curated one.
Duplicate recommendations are accomodated by rank ordering
by weight. | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/hybrid_recommender.py#L102-L169 | [
"def recommend(self, client_data, limit, extra_data={}):\n \"\"\"\n Curated recommendations are just random selections\n \"\"\"\n guids = self._curated_wl.get_randomized_guid_sample(limit)\n\n results = [(guid, 1.0) for guid in guids]\n\n log_data = (client_data[\"client_id\"], str(guids))\n se... | class HybridRecommender(AbstractRecommender):
"""
The EnsembleRecommender is a collection of recommenders where the
results from each recommendation is amplified or dampened by a
factor. The aggregate results are combines and used to recommend
addons for users.
"""
def __init__(self, ctx):... |
mozilla/taar | taar/recommenders/ensemble_recommender.py | EnsembleRecommender.can_recommend | python | def can_recommend(self, client_data, extra_data={}):
result = sum(
[
self._recommender_map[rkey].can_recommend(client_data)
for rkey in self.RECOMMENDER_KEYS
]
)
self.logger.info("Ensemble can_recommend: {}".format(result))
return r... | The ensemble recommender is always going to be
available if at least one recommender is available | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/ensemble_recommender.py#L54-L64 | null | class EnsembleRecommender(AbstractRecommender):
"""
The EnsembleRecommender is a collection of recommenders where the
results from each recommendation is amplified or dampened by a
factor. The aggregate results are combines and used to recommend
addons for users.
"""
def __init__(self, ctx... |
mozilla/taar | taar/recommenders/ensemble_recommender.py | EnsembleRecommender._recommend | python | def _recommend(self, client_data, limit, extra_data={}):
self.logger.info("Ensemble recommend invoked")
preinstalled_addon_ids = client_data.get("installed_addons", [])
# Compute an extended limit by adding the length of
# the list of any preinstalled addons.
extended_limit = li... | Ensemble recommendations are aggregated from individual
recommenders. The ensemble recommender applies a weight to
the recommendation outputs of each recommender to reorder the
recommendations to be a better fit.
The intuitive understanding is that the total space of
recommende... | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/ensemble_recommender.py#L81-L150 | null | class EnsembleRecommender(AbstractRecommender):
"""
The EnsembleRecommender is a collection of recommenders where the
results from each recommendation is amplified or dampened by a
factor. The aggregate results are combines and used to recommend
addons for users.
"""
def __init__(self, ctx... |
mozilla/taar | taar/recommenders/collaborative_recommender.py | synchronized | python | def synchronized(wrapped):
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
self = args[0]
with self._lock:
return wrapped(*args, **kwargs)
return wrapper | Synchronization decorator. | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/collaborative_recommender.py#L20-L29 | null | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from srgutil.interfaces import IMozLogging
from .lazys3 import LazyJSONLoader
import numpy as np
import operator as op
i... |
mozilla/taar | taar/recommenders/lazys3.py | LazyJSONLoader.get | python | def get(self, transform=None):
if not self.has_expired() and self._cached_copy is not None:
return self._cached_copy, False
return self._refresh_cache(transform), True | Return the JSON defined at the S3 location in the constructor.
The get method will reload the S3 object after the TTL has
expired.
Fetch the JSON object from cache or S3 if necessary | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/lazys3.py#L43-L54 | [
"def has_expired(self):\n return self._clock.time() > self._expiry_time\n"
] | class LazyJSONLoader:
def __init__(self, ctx, s3_bucket, s3_key, ttl=14400):
self._ctx = ctx
self.logger = self._ctx[IMozLogging].get_logger("taar")
self._clock = self._ctx[IClock]
self._s3_bucket = s3_bucket
self._s3_key = s3_key
self._ttl = int(ttl)
self._e... |
mozilla/taar | bin/pipstrap.py | hashed_download | python | def hashed_download(url, temp, digest):
# Based on pip 1.4.1's URLOpener but with cert verification removed
def opener():
opener = build_opener(HTTPSHandler())
# Strip out HTTPHandler to prevent MITM spoof:
for handler in opener.handlers:
if isinstance(handler, HTTPHandler):
... | Download ``url`` to ``temp``, make sure it has the SHA-256 ``digest``,
and return its path. | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/bin/pipstrap.py#L65-L95 | [
"def opener():\n opener = build_opener(HTTPSHandler())\n # Strip out HTTPHandler to prevent MITM spoof:\n for handler in opener.handlers:\n if isinstance(handler, HTTPHandler):\n opener.handlers.remove(handler)\n return opener\n",
"def read_chunks(response, chunk_size):\n while Tr... | #!/usr/bin/env python
"""A small script that can act as a trust root for installing pip 8
Embed this in your project, and your VCS checkout is all you have to trust. In
a post-peep era, this lets you claw your way to a hash-checking version of pip,
with which you can install the rest of your dependencies safely. All i... |
mozilla/taar | taar/recommenders/similarity_recommender.py | SimilarityRecommender._build_features_caches | python | def _build_features_caches(self):
_donors_pool = self._donors_pool.get()[0]
_lr_curves = self._lr_curves.get()[0]
if _donors_pool is None or _lr_curves is None:
# We need to have both donors_pool and lr_curves defined
# to reconstruct the matrices
return None... | This function build two feature cache matrices.
That's the self.categorical_features and
self.continuous_features attributes.
One matrix is for the continuous features and the other is for
the categorical features. This is needed to speed up the similarity
recommendation proces... | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/similarity_recommender.py#L103-L136 | null | class SimilarityRecommender(AbstractRecommender):
""" A recommender class that returns top N addons based on the
client similarity with a set of candidate addon donors.
Several telemetry fields are used to compute pairwise similarity
with the donors and similarities are converted into a likelihood
... |
mozilla/taar | taar/recommenders/similarity_recommender.py | SimilarityRecommender.get_lr | python | def get_lr(self, score):
# Find the index of the closest value that was precomputed in lr_curves
# This will significantly speed up |get_lr|.
# The lr_curves_cache is a list of scalar distance
# measurements
lr_curves_cache = np.array([s[0] for s in self.lr_curves])
# n... | Compute a :float: likelihood ratio from a provided similarity score when compared
to two probability density functions which are computed and pre-loaded during init.
The numerator indicates the probability density that a particular similarity score
corresponds to a 'good' addon donor, i.e. a cl... | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/similarity_recommender.py#L155-L183 | null | class SimilarityRecommender(AbstractRecommender):
""" A recommender class that returns top N addons based on the
client similarity with a set of candidate addon donors.
Several telemetry fields are used to compute pairwise similarity
with the donors and similarities are converted into a likelihood
... |
mozilla/taar | taar/recommenders/similarity_recommender.py | SimilarityRecommender.get_similar_donors | python | def get_similar_donors(self, client_data):
# Compute the distance between self and any comparable client.
distances = self.compute_clients_dist(client_data)
# Compute the LR based on precomputed distributions that relate the score
# to a probability of providing good addon recommendatio... | Computes a set of :float: similarity scores between a client and a set of candidate
donors for which comparable variables have been measured.
A custom similarity metric is defined in this function that combines the Hamming distance
for categorical variables with the Canberra distance for contin... | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/similarity_recommender.py#L220-L247 | [
"def compute_clients_dist(self, client_data):\n client_categorical_feats = [\n client_data.get(specified_key) for specified_key in CATEGORICAL_FEATURES\n ]\n client_continuous_feats = [\n client_data.get(specified_key) for specified_key in CONTINUOUS_FEATURES\n ]\n\n # Compute the dista... | class SimilarityRecommender(AbstractRecommender):
""" A recommender class that returns top N addons based on the
client similarity with a set of candidate addon donors.
Several telemetry fields are used to compute pairwise similarity
with the donors and similarities are converted into a likelihood
... |
mozilla/taar | taar/recommenders/recommendation_manager.py | RecommendationManager.recommend | python | def recommend(self, client_id, limit, extra_data={}):
if client_id in TEST_CLIENT_IDS:
data = self._whitelist_data.get()[0]
random.shuffle(data)
samples = data[:limit]
self.logger.info("Test ID detected [{}]".format(client_id))
return [(s, 1.1) for s ... | Return recommendations for the given client.
The recommendation logic will go through each recommender and
pick the first one that "can_recommend".
:param client_id: the client unique id.
:param limit: the maximum number of recommendations to return.
:param extra_data: a dictio... | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/recommendation_manager.py#L85-L116 | [
"def recommend(self, client_data, limit, extra_data={}):\n try:\n results = self._recommend(client_data, limit, extra_data)\n except Exception as e:\n results = []\n self._weight_cache._weights.force_expiry()\n self.logger.exception(\n \"Ensemble recommender crashed for ... | class RecommendationManager:
"""This class determines which of the set of recommendation
engines will actually be used to generate recommendations."""
def __init__(self, ctx):
"""Initialize the user profile fetcher and the recommenders.
"""
self._ctx = ctx
self.logger = self... |
mozilla/taar | taar/profile_fetcher.py | ProfileController.get_client_profile | python | def get_client_profile(self, client_id):
try:
response = self._table.get_item(Key={'client_id': client_id})
compressed_bytes = response['Item']['json_payload'].value
json_byte_data = zlib.decompress(compressed_bytes)
json_str_data = json_byte_data.decode('utf8')
... | This fetches a single client record out of DynamoDB | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/profile_fetcher.py#L33-L50 | null | class ProfileController:
"""
This class provides basic read/write access into a AWS DynamoDB
backed datastore. The profile controller and profile fetcher code
should eventually be merged as individually they don't "pull their
weight".
"""
def __init__(self, ctx, region_name, table_name):
... |
mozilla/taar | taar/plugin.py | clean_promoted_guids | python | def clean_promoted_guids(raw_promoted_guids):
valid = True
for row in raw_promoted_guids:
if len(row) != 2:
valid = False
break
if not (
(isinstance(row[0], str) or isinstance(row[0], unicode))
and (isinstance(row[1], int) or isinstance(row[1], f... | Verify that the promoted GUIDs are formatted correctly,
otherwise strip it down into an empty list. | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/plugin.py#L32-L52 | null | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from decouple import config
from flask import request
import json
# TAAR specific libraries
from taar.context import de... |
mozilla/taar | taar/plugin.py | configure_plugin | python | def configure_plugin(app): # noqa: C901
@app.route(
"/v1/api/client_has_addon/<hashed_client_id>/<addon_id>/", methods=["GET"]
)
def client_has_addon(hashed_client_id, addon_id):
# Use the module global PROXY_MANAGER
global PROXY_MANAGER
recommendation_manager = check_proxy... | This is a factory function that configures all the routes for
flask given a particular library. | train | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/plugin.py#L70-L192 | null | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from decouple import config
from flask import request
import json
# TAAR specific libraries
from taar.context import de... |
amelchio/pysonos | pysonos/services.py | Service.iter_actions | python | def iter_actions(self):
# pylint: disable=too-many-locals
# pylint: disable=invalid-name
ns = '{urn:schemas-upnp-org:service-1-0}'
# get the scpd body as bytes, and feed directly to elementtree
# which likes to receive bytes
scpd_body = requests.get(self.base_url + self.... | Yield the service's actions with their arguments.
Yields:
`Action`: the next action.
Each action is an Action namedtuple, consisting of action_name
(a string), in_args (a list of Argument namedtuples consisting of name
and argtype), and out_args (ditto), eg::
A... | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/services.py#L645-L711 | null | class Service(object):
"""A class representing a UPnP service.
This is the base class for all Sonos Service classes. This class has a
dynamic method dispatcher. Calls to methods which are not explicitly
defined here are dispatched automatically to the service action with the
same name.
"""
... |
amelchio/pysonos | pysonos/events.py | parse_event_xml | python | def parse_event_xml(xml_event):
result = {}
tree = XML.fromstring(xml_event)
# property values are just under the propertyset, which
# uses this namespace
properties = tree.findall(
'{urn:schemas-upnp-org:event-1-0}property')
for prop in properties: # pylint: disable=too-many-nested-bl... | Parse the body of a UPnP event.
Args:
xml_event (bytes): bytes containing the body of the event encoded
with utf-8.
Returns:
dict: A dict with keys representing the evented variables. The
relevant value will usually be a string representation of the
variable... | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/events.py#L37-L170 | [
"def from_didl_string(string):\n \"\"\"Convert a unicode xml string to a list of `DIDLObjects <DidlObject>`.\n\n Args:\n string (str): A unicode string containing an XML representation of one\n or more DIDL-Lite items (in the form ``'<DIDL-Lite ...>\n ...</DIDL-Lite>'``)\n\n R... | # -*- coding: utf-8 -*-
# pylint: disable=not-context-manager
# NOTE: The pylint not-content-manager warning is disabled pending the fix of
# a bug in pylint: https://github.com/PyCQA/pylint/issues/782
# Disable while we have Python 2.x compatability
# pylint: disable=useless-object-inheritance
"""Classes to handle... |
amelchio/pysonos | pysonos/events.py | Subscription.unsubscribe | python | def unsubscribe(self):
# Trying to unsubscribe if already unsubscribed, or not yet
# subscribed, fails silently
if self._has_been_unsubscribed or not self.is_subscribed:
return
# Cancel any auto renew
self._auto_renew_thread_flag.set()
# Send an unsubscribe r... | Unsubscribe from the service's events.
Once unsubscribed, a Subscription instance should not be reused | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/events.py#L586-L633 | null | class Subscription(object):
"""A class representing the subscription to a UPnP event."""
# pylint: disable=too-many-instance-attributes
def __init__(self, service, event_queue=None):
"""
Args:
service (Service): The SoCo `Service` to which the subscription
shoul... |
amelchio/pysonos | pysonos/core.py | SoCo.play_mode | python | def play_mode(self, playmode):
playmode = playmode.upper()
if playmode not in PLAY_MODES.keys():
raise KeyError("'%s' is not a valid play mode" % playmode)
self.avTransport.SetPlayMode([
('InstanceID', 0),
('NewPlayMode', playmode)
]) | Set the speaker's mode. | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L408-L417 | null | class SoCo(_SocoSingletonBase):
"""A simple class for controlling a Sonos speaker.
For any given set of arguments to __init__, only one instance of this class
may be created. Subsequent attempts to create an instance with the same
arguments will return the previously created instance. This means that ... |
amelchio/pysonos | pysonos/core.py | SoCo.repeat | python | def repeat(self, repeat):
shuffle = self.shuffle
self.play_mode = PLAY_MODE_BY_MEANING[(shuffle, repeat)] | Set the queue's repeat option | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L444-L447 | null | class SoCo(_SocoSingletonBase):
"""A simple class for controlling a Sonos speaker.
For any given set of arguments to __init__, only one instance of this class
may be created. Subsequent attempts to create an instance with the same
arguments will return the previously created instance. This means that ... |
amelchio/pysonos | pysonos/core.py | SoCo.cross_fade | python | def cross_fade(self):
response = self.avTransport.GetCrossfadeMode([
('InstanceID', 0),
])
cross_fade_state = response['CrossfadeMode']
return bool(int(cross_fade_state)) | bool: The speaker's cross fade state.
True if enabled, False otherwise | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L451-L461 | null | class SoCo(_SocoSingletonBase):
"""A simple class for controlling a Sonos speaker.
For any given set of arguments to __init__, only one instance of this class
may be created. Subsequent attempts to create an instance with the same
arguments will return the previously created instance. This means that ... |
amelchio/pysonos | pysonos/core.py | SoCo.mute | python | def mute(self):
response = self.renderingControl.GetMute([
('InstanceID', 0),
('Channel', 'Master')
])
mute_state = response['CurrentMute']
return bool(int(mute_state)) | bool: The speaker's mute state.
True if muted, False otherwise. | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L705-L716 | null | class SoCo(_SocoSingletonBase):
"""A simple class for controlling a Sonos speaker.
For any given set of arguments to __init__, only one instance of this class
may be created. Subsequent attempts to create an instance with the same
arguments will return the previously created instance. This means that ... |
amelchio/pysonos | pysonos/core.py | SoCo.loudness | python | def loudness(self):
response = self.renderingControl.GetLoudness([
('InstanceID', 0),
('Channel', 'Master'),
])
loudness = response["CurrentLoudness"]
return bool(int(loudness)) | bool: The Sonos speaker's loudness compensation.
True if on, False otherwise.
Loudness is a complicated topic. You can find a nice summary about this
feature here: http://forums.sonos.com/showthread.php?p=4698#post4698 | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L802-L815 | null | class SoCo(_SocoSingletonBase):
"""A simple class for controlling a Sonos speaker.
For any given set of arguments to __init__, only one instance of this class
may be created. Subsequent attempts to create an instance with the same
arguments will return the previously created instance. This means that ... |
amelchio/pysonos | pysonos/core.py | SoCo.join | python | def join(self, master):
self.avTransport.SetAVTransportURI([
('InstanceID', 0),
('CurrentURI', 'x-rincon:{0}'.format(master.uid)),
('CurrentURIMetaData', '')
])
self._zgs_cache.clear()
self._parse_zone_group_state() | Join this speaker to another "master" speaker. | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L1079-L1087 | null | class SoCo(_SocoSingletonBase):
"""A simple class for controlling a Sonos speaker.
For any given set of arguments to __init__, only one instance of this class
may be created. Subsequent attempts to create an instance with the same
arguments will return the previously created instance. This means that ... |
amelchio/pysonos | pysonos/core.py | SoCo.unjoin | python | def unjoin(self):
self.avTransport.BecomeCoordinatorOfStandaloneGroup([
('InstanceID', 0)
])
self._zgs_cache.clear()
self._parse_zone_group_state() | Remove this speaker from a group.
Seems to work ok even if you remove what was previously the group
master from it's own group. If the speaker was not in a group also
returns ok. | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L1089-L1101 | null | class SoCo(_SocoSingletonBase):
"""A simple class for controlling a Sonos speaker.
For any given set of arguments to __init__, only one instance of this class
may be created. Subsequent attempts to create an instance with the same
arguments will return the previously created instance. This means that ... |
amelchio/pysonos | pysonos/core.py | SoCo.set_sleep_timer | python | def set_sleep_timer(self, sleep_time_seconds):
# Note: A value of None for sleep_time_seconds is valid, and needs to
# be preserved distinctly separate from 0. 0 means go to sleep now,
# which will immediately start the sound tappering, and could be a
# useful feature, while None means c... | Sets the sleep timer.
Args:
sleep_time_seconds (int or NoneType): How long to wait before
turning off speaker in seconds, None to cancel a sleep timer.
Maximum value of 86399
Raises:
SoCoException: Upon errors interacting with Sonos controller
... | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/core.py#L1714-L1749 | null | class SoCo(_SocoSingletonBase):
"""A simple class for controlling a Sonos speaker.
For any given set of arguments to __init__, only one instance of this class
may be created. Subsequent attempts to create an instance with the same
arguments will return the previously created instance. This means that ... |
amelchio/pysonos | pysonos/snapshot.py | Snapshot.restore | python | def restore(self, fade=False):
try:
if self.is_coordinator:
self._restore_coordinator()
finally:
self._restore_volume(fade)
# Now everything is set, see if we need to be playing, stopped
# or paused ( only for coordinators)
if self.is_coo... | Restore the state of a device to that which was previously saved.
For coordinator devices restore everything. For slave devices
only restore volume etc., not transport info (transport info
comes from the slave's coordinator).
Args:
fade (bool): Whether volume should be fade... | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/snapshot.py#L161-L184 | [
"def _restore_coordinator(self):\n \"\"\"Do the coordinator-only part of the restore.\"\"\"\n # Start by ensuring that the speaker is paused as we don't want\n # things all rolling back when we are changing them, as this could\n # include things like audio\n transport_info = self.device.get_current_t... | class Snapshot(object):
"""A snapshot of the current state.
Note:
This does not change anything to do with the configuration
such as which group the speaker is in, just settings that impact
what is playing, or how it is played.
List of sources that may be playing using root of ... |
amelchio/pysonos | pysonos/snapshot.py | Snapshot._restore_coordinator | python | def _restore_coordinator(self):
# Start by ensuring that the speaker is paused as we don't want
# things all rolling back when we are changing them, as this could
# include things like audio
transport_info = self.device.get_current_transport_info()
if transport_info is not None:
... | Do the coordinator-only part of the restore. | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/snapshot.py#L186-L231 | [
"def _restore_queue(self):\n \"\"\"Restore the previous state of the queue.\n\n Note:\n The restore currently adds the items back into the queue\n using the URI, for items the Sonos system already knows about\n this is OK, but for other items, they may be missing some of\n their me... | class Snapshot(object):
"""A snapshot of the current state.
Note:
This does not change anything to do with the configuration
such as which group the speaker is in, just settings that impact
what is playing, or how it is played.
List of sources that may be playing using root of ... |
amelchio/pysonos | pysonos/snapshot.py | Snapshot._restore_volume | python | def _restore_volume(self, fade):
self.device.mute = self.mute
# Can only change volume on device with fixed volume set to False
# otherwise get uPnP error, so check first. Before issuing a network
# command to check, fixed volume always has volume set to 100.
# So only checked f... | Reinstate volume.
Args:
fade (bool): Whether volume should be faded up on restore. | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/snapshot.py#L233-L264 | null | class Snapshot(object):
"""A snapshot of the current state.
Note:
This does not change anything to do with the configuration
such as which group the speaker is in, just settings that impact
what is playing, or how it is played.
List of sources that may be playing using root of ... |
amelchio/pysonos | pysonos/discovery.py | _discover_thread | python | def _discover_thread(callback,
timeout,
include_invisible,
interface_addr):
def create_socket(interface_addr=None):
""" A helper function for creating a socket for discover purposes.
Create and return a socket with appropriate options ... | Discover Sonos zones on the local network. | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/discovery.py#L40-L159 | null | # -*- coding: utf-8 -*-
"""This module contains methods for discovering Sonos devices on the
network."""
from __future__ import unicode_literals
import logging
import threading
import socket
import select
from textwrap import dedent
import time
import struct
import ifaddr
from . import config
from .utils import real... |
amelchio/pysonos | pysonos/discovery.py | discover_thread | python | def discover_thread(callback,
timeout=5,
include_invisible=False,
interface_addr=None):
thread = StoppableThread(
target=_discover_thread,
args=(callback, timeout, include_invisible, interface_addr))
thread.start()
return thread | Return a started thread with a discovery callback. | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/discovery.py#L162-L171 | null | # -*- coding: utf-8 -*-
"""This module contains methods for discovering Sonos devices on the
network."""
from __future__ import unicode_literals
import logging
import threading
import socket
import select
from textwrap import dedent
import time
import struct
import ifaddr
from . import config
from .utils import real... |
amelchio/pysonos | pysonos/discovery.py | discover | python | def discover(timeout=5,
include_invisible=False,
interface_addr=None,
all_households=False):
found_zones = set()
first_response = None
def callback(zone):
nonlocal first_response
if first_response is None:
first_response = time.monotonic(... | Discover Sonos zones on the local network.
Return a set of `SoCo` instances for each zone found.
Include invisible zones (bridges and slave zones in stereo pairs if
``include_invisible`` is `True`. Will block for up to ``timeout`` seconds,
after which return `None` if no zones found.
Args:
... | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/discovery.py#L174-L231 | [
"def discover_thread(callback,\n timeout=5,\n include_invisible=False,\n interface_addr=None):\n \"\"\" Return a started thread with a discovery callback. \"\"\"\n thread = StoppableThread(\n target=_discover_thread,\n args=(callback, time... | # -*- coding: utf-8 -*-
"""This module contains methods for discovering Sonos devices on the
network."""
from __future__ import unicode_literals
import logging
import threading
import socket
import select
from textwrap import dedent
import time
import struct
import ifaddr
from . import config
from .utils import real... |
amelchio/pysonos | pysonos/discovery.py | by_name | python | def by_name(name):
devices = discover(all_households=True)
for device in (devices or []):
if device.player_name == name:
return device
return None | Return a device by name.
Args:
name (str): The name of the device to return.
Returns:
:class:`~.SoCo`: The first device encountered among all zone with the
given player name. If none are found `None` is returned. | train | https://github.com/amelchio/pysonos/blob/23527c445a00e198fbb94d44b92f7f99d139e325/pysonos/discovery.py#L262-L276 | [
"def discover(timeout=5,\n include_invisible=False,\n interface_addr=None,\n all_households=False):\n \"\"\" Discover Sonos zones on the local network.\n\n Return a set of `SoCo` instances for each zone found.\n Include invisible zones (bridges and slave zones in stereo ... | # -*- coding: utf-8 -*-
"""This module contains methods for discovering Sonos devices on the
network."""
from __future__ import unicode_literals
import logging
import threading
import socket
import select
from textwrap import dedent
import time
import struct
import ifaddr
from . import config
from .utils import real... |
dshean/demcoreg | demcoreg/glas_proc.py | main | python | def main():
parser = getparser()
args = parser.parse_args()
fn = args.fn
sitename = args.sitename
#User-specified output extent
#Note: not checked, untested
if args.extent is not None:
extent = (args.extent).split()
else:
extent = (geolib.site_dict[sitename]).extent
... | ICESat-1 filters | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/glas_proc.py#L59-L296 | [
"def getparser():\n parser = argparse.ArgumentParser(description=\"Process and filter ICESat GLAS points\")\n parser.add_argument('fn', type=str, help='GLAH14 HDF5 filename')\n site_choices = geolib.site_dict.keys()\n parser.add_argument('sitename', type=str, choices=site_choices, help='Site name')\n ... | #! /usr/bin/env python
#David Shean
#dshean@gmail.com
#Utility to process ICESat-1 GLAS products, filter and clip to specified bounding box
#Input is HDF5 GLAH14
#https://nsidc.org/data/GLAH14/versions/34
#http://nsidc.org/data/docs/daac/glas_altimetry/data-dictionary-glah14.html
import os, sys
from datetime import ... |
dshean/demcoreg | demcoreg/dem_mask.py | get_nlcd_fn | python | def get_nlcd_fn():
#This is original filename, which requires ~17 GB
#nlcd_fn = os.path.join(datadir, 'nlcd_2011_landcover_2011_edition_2014_10_10/nlcd_2011_landcover_2011_edition_2014_10_10.img')
#get_nlcd.sh now creates a compressed GTiff, which is 1.1 GB
nlcd_fn = os.path.join(datadir, 'nlcd_2011_lan... | Calls external shell script `get_nlcd.sh` to fetch:
2011 Land Use Land Cover (nlcd) grids, 30 m
http://www.mrlc.gov/nlcd11_leg.php | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L34-L49 | null | #! /usr/bin/env python
"""
Utility to automate reference surface identification for raster co-registration
Note: Initial run may take a long time to download and process required data (NLCD, global bareground, glacier polygons)
Can control location of these data files with DATADIR environmental variable
export DATAD... |
dshean/demcoreg | demcoreg/dem_mask.py | get_bareground_fn | python | def get_bareground_fn():
bg_fn = os.path.join(datadir, 'bare2010/bare2010.vrt')
if not os.path.exists(bg_fn):
cmd = ['get_bareground.sh',]
sys.exit("Missing bareground data source. If already downloaded, specify correct datadir. If not, run `%s` to download" % cmd[0])
#subprocess.call(cm... | Calls external shell script `get_bareground.sh` to fetch:
~2010 global bare ground, 30 m
Note: unzipped file size is 64 GB! Original products are uncompressed, and tiles are available globally (including empty data over ocean)
The shell script will compress all downloaded tiles using lossless LZW compres... | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L51-L67 | null | #! /usr/bin/env python
"""
Utility to automate reference surface identification for raster co-registration
Note: Initial run may take a long time to download and process required data (NLCD, global bareground, glacier polygons)
Can control location of these data files with DATADIR environmental variable
export DATAD... |
dshean/demcoreg | demcoreg/dem_mask.py | get_glacier_poly | python | def get_glacier_poly():
#rgi_fn = os.path.join(datadir, 'rgi50/regions/rgi50_merge.shp')
#Update to rgi60, should have this returned from get_rgi.sh
rgi_fn = os.path.join(datadir, 'rgi60/regions/rgi60_merge.shp')
if not os.path.exists(rgi_fn):
cmd = ['get_rgi.sh',]
sys.exit("Missing rgi ... | Calls external shell script `get_rgi.sh` to fetch:
Randolph Glacier Inventory (RGI) glacier outline shapefiles
Full RGI database: rgi50.zip is 410 MB
The shell script will unzip and merge regional shp into single global shp
http://www.glims.org/RGI/ | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L70-L88 | null | #! /usr/bin/env python
"""
Utility to automate reference surface identification for raster co-registration
Note: Initial run may take a long time to download and process required data (NLCD, global bareground, glacier polygons)
Can control location of these data files with DATADIR environmental variable
export DATAD... |
dshean/demcoreg | demcoreg/dem_mask.py | get_icemask | python | def get_icemask(ds, glac_shp_fn=None):
print("Masking glaciers")
if glac_shp_fn is None:
glac_shp_fn = get_glacier_poly()
if not os.path.exists(glac_shp_fn):
print("Unable to locate glacier shp: %s" % glac_shp_fn)
else:
print("Found glacier shp: %s" % glac_shp_fn)
#All of t... | Generate glacier polygon raster mask for input Dataset res/extent | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L91-L105 | [
"def get_glacier_poly():\n \"\"\"Calls external shell script `get_rgi.sh` to fetch:\n\n Randolph Glacier Inventory (RGI) glacier outline shapefiles \n\n Full RGI database: rgi50.zip is 410 MB\n\n The shell script will unzip and merge regional shp into single global shp\n\n http://www.glims.org/RGI/\n... | #! /usr/bin/env python
"""
Utility to automate reference surface identification for raster co-registration
Note: Initial run may take a long time to download and process required data (NLCD, global bareground, glacier polygons)
Can control location of these data files with DATADIR environmental variable
export DATAD... |
dshean/demcoreg | demcoreg/dem_mask.py | get_nlcd_mask | python | def get_nlcd_mask(nlcd_ds, filter='not_forest', out_fn=None):
print("Loading NLCD LULC")
b = nlcd_ds.GetRasterBand(1)
l = b.ReadAsArray()
print("Filtering NLCD LULC with: %s" % filter)
#Original nlcd products have nan as ndv
#12 - ice
#31 - rock
#11 - open water, includes riv... | Generate raster mask for specified NLCD LULC filter | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L108-L141 | null | #! /usr/bin/env python
"""
Utility to automate reference surface identification for raster co-registration
Note: Initial run may take a long time to download and process required data (NLCD, global bareground, glacier polygons)
Can control location of these data files with DATADIR environmental variable
export DATAD... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.