INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Get Gnosis Safe Master contract. It should be used to access Safe methods on Proxy contracts.: param w3: Web3 instance: param address: address of the safe contract/ proxy contract: return: Safe Contract | def get_safe_contract(w3: Web3, address=None):
"""
Get Gnosis Safe Master contract. It should be used to access Safe methods on Proxy contracts.
:param w3: Web3 instance
:param address: address of the safe contract/proxy contract
:return: Safe Contract
"""
return w3.eth.contract(address,
... |
Get Old Gnosis Safe Master contract. It should be used to access Safe methods on Proxy contracts.: param w3: Web3 instance: param address: address of the safe contract/ proxy contract: return: Safe Contract | def get_old_safe_contract(w3: Web3, address=None):
"""
Get Old Gnosis Safe Master contract. It should be used to access Safe methods on Proxy contracts.
:param w3: Web3 instance
:param address: address of the safe contract/proxy contract
:return: Safe Contract
"""
return w3.eth.contract(addr... |
Get Paying Proxy Contract. This should be used just for contract creation/ changing master_copy If you want to call Safe methods you should use get_safe_contract with the Proxy address so you can access every method of the Safe: param w3: Web3 instance: param address: address of the proxy contract: return: Paying Proxy... | def get_paying_proxy_contract(w3: Web3, address=None):
"""
Get Paying Proxy Contract. This should be used just for contract creation/changing master_copy
If you want to call Safe methods you should use `get_safe_contract` with the Proxy address,
so you can access every method of the Safe
:param w3: ... |
Get ERC20 interface: param w3: Web3 instance: param address: address of the proxy contract: return: ERC 20 contract | def get_erc20_contract(w3: Web3, address=None):
"""
Get ERC20 interface
:param w3: Web3 instance
:param address: address of the proxy contract
:return: ERC 20 contract
"""
return w3.eth.contract(address,
abi=ERC20_INTERFACE['abi'],
byteco... |
: param signatures: signatures in form of { bytes32 r } { bytes32 s } { uint8 v }: param pos: position of the signature: return: Tuple with v r s | def signature_split(signatures: bytes, pos: int) -> Tuple[int, int, int]:
"""
:param signatures: signatures in form of {bytes32 r}{bytes32 s}{uint8 v}
:param pos: position of the signature
:return: Tuple with v, r, s
"""
signature_pos = 65 * pos
v = signatures[64 + signature_pos]
r = int... |
Convert signature to bytes: param vrs: tuple of v r s: return: signature in form of { bytes32 r } { bytes32 s } { uint8 v } | def signature_to_bytes(vrs: Tuple[int, int, int]) -> bytes:
"""
Convert signature to bytes
:param vrs: tuple of v, r, s
:return: signature in form of {bytes32 r}{bytes32 s}{uint8 v}
"""
byte_order = 'big'
v, r, s = vrs
return (r.to_bytes(32, byteorder=byte_order) +
s.to_byt... |
Convert signatures to bytes: param signatures: list of tuples ( v r s ): return: 65 bytes per signature | def signatures_to_bytes(signatures: List[Tuple[int, int, int]]) -> bytes:
"""
Convert signatures to bytes
:param signatures: list of tuples(v, r, s)
:return: 65 bytes per signature
"""
return b''.join([signature_to_bytes(vrs) for vrs in signatures]) |
Find v and r valid values for a given s: param s: random value: return: v r | def find_valid_random_signature(s: int) -> Tuple[int, int]:
"""
Find v and r valid values for a given s
:param s: random value
:return: v, r
"""
for _ in range(10000):
r = int(os.urandom(31).hex(), 16)
v = (r % 2) + 27
if r < secpk1n:
... |
: param master_copy: Master Copy of Gnosis Safe already deployed: param initializer: Data initializer to send to GnosisSafe setup method: param funder: Address that should get the payment ( if payment set ): param payment_token: Address if a token is used. If not set 0x0 will be ether: param payment: Payment: return: T... | def _build_proxy_contract_creation_constructor(self,
master_copy: str,
initializer: bytes,
funder: str,
payment_toke... |
: param master_copy: Master Copy of Gnosis Safe already deployed: param initializer: Data initializer to send to GnosisSafe setup method: param funder: Address that should get the payment ( if payment set ): param payment_token: Address if a token is used. If not set 0x0 will be ether: param payment: Payment: return: T... | def _build_proxy_contract_creation_tx(self,
master_copy: str,
initializer: bytes,
funder: str,
payment_token: str,
... |
Use pyethereum Transaction to generate valid tx using a random signature: param tx_dict: Web3 tx dictionary: param s: Signature s value: return: PyEthereum creation tx for the proxy contract | def _build_contract_creation_tx_with_valid_signature(self, tx_dict: Dict[str, None], s: int) -> Transaction:
"""
Use pyethereum `Transaction` to generate valid tx using a random signature
:param tx_dict: Web3 tx dictionary
:param s: Signature s value
:return: PyEthereum creation ... |
Gas estimation done using web3 and calling the node Payment cannot be estimated as no ether is in the address. So we add some gas later.: param master_copy: Master Copy of Gnosis Safe already deployed: param initializer: Data initializer to send to GnosisSafe setup method: param funder: Address that should get the paym... | def _estimate_gas(self,
master_copy: str,
initializer: bytes,
funder: str,
payment_token: str) -> int:
"""
Gas estimation done using web3 and calling the node
Payment cannot be estimated, as no ether is in th... |
Signed transaction that compatible with w3. eth. sendRawTransaction Is not used because pyEthereum implementation of Transaction was found to be more robust regarding invalid signatures | def _sign_web3_transaction(tx: Dict[str, any], v: int, r: int, s: int) -> (bytes, HexBytes):
"""
Signed transaction that compatible with `w3.eth.sendRawTransaction`
Is not used because `pyEthereum` implementation of Transaction was found to be more
robust regarding invalid signatures
... |
Check if proxy is valid: param address: address of the proxy: return: True if proxy is valid False otherwise | def check_proxy_code(self, address) -> bool:
"""
Check if proxy is valid
:param address: address of the proxy
:return: True if proxy is valid, False otherwise
"""
deployed_proxy_code = self.w3.eth.getCode(address)
proxy_code_fns = (get_paying_proxy_deployed_byteco... |
Check safe has enough funds to pay for a tx: param safe_address: Address of the safe: param safe_tx_gas: Start gas: param data_gas: Data gas: param gas_price: Gas Price: param gas_token: Gas Token to use token instead of ether for the gas: return: True if enough funds False otherwise | def check_funds_for_tx_gas(self, safe_address: str, safe_tx_gas: int, data_gas: int, gas_price: int,
gas_token: str) -> bool:
"""
Check safe has enough funds to pay for a tx
:param safe_address: Address of the safe
:param safe_tx_gas: Start gas
:par... |
Deploy master contract. Takes deployer_account ( if unlocked in the node ) or the deployer private key: param deployer_account: Unlocked ethereum account: param deployer_private_key: Private key of an ethereum account: return: deployed contract address | def deploy_master_contract(self, deployer_account=None, deployer_private_key=None) -> str:
"""
Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key
:param deployer_account: Unlocked ethereum account
:param deployer_private_key: Private key ... |
Deploy proxy contract. Takes deployer_account ( if unlocked in the node ) or the deployer private key: param initializer: Initializer: param deployer_account: Unlocked ethereum account: param deployer_private_key: Private key of an ethereum account: return: deployed contract address | def deploy_paying_proxy_contract(self, initializer=b'', deployer_account=None, deployer_private_key=None) -> str:
"""
Deploy proxy contract. Takes deployer_account (if unlocked in the node) or the deployer private key
:param initializer: Initializer
:param deployer_account: Unlocked ethe... |
Deploy proxy contract using the Proxy Factory Contract. Takes deployer_account ( if unlocked in the node ) or the deployer private key: param initializer: Initializer: param deployer_account: Unlocked ethereum account: param deployer_private_key: Private key of an ethereum account: return: deployed contract address | def deploy_proxy_contract(self, initializer=b'', deployer_account=None, deployer_private_key=None) -> str:
"""
Deploy proxy contract using the `Proxy Factory Contract`.
Takes deployer_account (if unlocked in the node) or the deployer private key
:param initializer: Initializer
:p... |
Deploy proxy contract using create2 withthe Proxy Factory Contract. Takes deployer_account ( if unlocked in the node ) or the deployer_private_key: param salt_nonce: Uint256 for create2 salt: param initializer: Data for safe creation: param gas: Gas: param gas_price: Gas Price: param deployer_private_key: Private key o... | def deploy_proxy_contract_with_nonce(self, salt_nonce: int, initializer: bytes, gas: int, gas_price: int,
deployer_private_key=None) -> Tuple[bytes, Dict[str, any], str]:
"""
Deploy proxy contract using `create2` withthe `Proxy Factory Contract`.
Takes `d... |
Deploy proxy factory contract. Takes deployer_account ( if unlocked in the node ) or the deployer private key: param deployer_account: Unlocked ethereum account: param deployer_private_key: Private key of an ethereum account: return: deployed contract address | def deploy_proxy_factory_contract(self, deployer_account=None, deployer_private_key=None) -> str:
"""
Deploy proxy factory contract. Takes deployer_account (if unlocked in the node) or the deployer private key
:param deployer_account: Unlocked ethereum account
:param deployer_private_key... |
Estimate tx gas using safe requiredTxGas method: return: int: Estimated gas: raises: CannotEstimateGas: If gas cannot be estimated: raises: ValueError: Cannot decode received data | def estimate_tx_gas_with_safe(self, safe_address: str, to: str, value: int, data: bytes, operation: int,
block_identifier='pending') -> int:
"""
Estimate tx gas using safe `requiredTxGas` method
:return: int: Estimated gas
:raises: CannotEstimateGas: If ... |
Estimate tx gas using web3 | def estimate_tx_gas_with_web3(self, safe_address: str, to: str, value: int, data: bytes) -> int:
"""
Estimate tx gas using web3
"""
return self.ethereum_client.estimate_gas(safe_address, to, value, data, block_identifier='pending') |
Estimate tx gas. Use the max of calculation using safe method and web3 if operation == CALL or use just the safe calculation otherwise | def estimate_tx_gas(self, safe_address: str, to: str, value: int, data: bytes, operation: int) -> int:
"""
Estimate tx gas. Use the max of calculation using safe method and web3 if operation == CALL or
use just the safe calculation otherwise
"""
# Costs to route through the proxy... |
Estimates the gas for the verification of the signatures and other safe related tasks before and after executing a transaction. Calculation will be the sum of: - Base cost of 15000 gas - 100 of gas per word of data_bytes - Validate the signatures 5000 * threshold ( ecrecover for ecdsa ~ = 4K gas ): param safe_address: ... | def estimate_tx_operational_gas(self, safe_address: str, data_bytes_length: int):
"""
Estimates the gas for the verification of the signatures and other safe related tasks
before and after executing a transaction.
Calculation will be the sum of:
- Base cost of 15000 gas
... |
Send multisig tx to the Safe: param tx_gas: Gas for the external tx. If not ( safe_tx_gas + data_gas ) * 2 will be used: param tx_gas_price: Gas price of the external tx. If not gas_price will be used: return: Tuple ( tx_hash tx ): raises: InvalidMultisigTx: If user tx cannot go through the Safe | def send_multisig_tx(self,
safe_address: str,
to: str,
value: int,
data: bytes,
operation: int,
safe_tx_gas: int,
data_gas: int,
... |
Prepare Safe creation: param owners: Owners of the Safe: param threshold: Minimum number of users required to operate the Safe: param salt_nonce: Web3 instance: param gas_price: Gas Price: param payment_receiver: Address to refund when the Safe is created. Address ( 0 ) if no need to refund: param payment_token: Paymen... | def build(self, owners: List[str], threshold: int, salt_nonce: int,
gas_price: int, payment_receiver: Optional[str] = None,
payment_token: Optional[str] = None,
payment_token_eth_value: float = 1.0, fixed_creation_cost: Optional[int] = None):
"""
Prepare Safe cr... |
Calculate gas manually based on tests of previosly deployed safes: param owners: Safe owners: param safe_setup_data: Data for proxy setup: param payment_token: If payment token we will need more gas to transfer and maybe storage if first time: return: total gas needed for deployment | def _calculate_gas(owners: List[str], safe_setup_data: bytes, payment_token: str) -> int:
"""
Calculate gas manually, based on tests of previosly deployed safes
:param owners: Safe owners
:param safe_setup_data: Data for proxy setup
:param payment_token: If payment token, we will... |
Gas estimation done using web3 and calling the node Payment cannot be estimated as no ether is in the address. So we add some gas later.: param initializer: Data initializer to send to GnosisSafe setup method: param salt_nonce: Nonce that will be used to generate the salt to calculate the address of the new proxy contr... | def _estimate_gas(self, initializer: bytes, salt_nonce: int,
payment_token: str, payment_receiver: str) -> int:
"""
Gas estimation done using web3 and calling the node
Payment cannot be estimated, as no ether is in the address. So we add some gas later.
:param initi... |
: return: Web3 contract tx prepared for call transact or buildTransaction | def w3_tx(self):
"""
:return: Web3 contract tx prepared for `call`, `transact` or `buildTransaction`
"""
safe_contract = get_safe_contract(self.w3, address=self.safe_address)
return safe_contract.functions.execTransaction(
self.to,
self.value,
... |
: param tx_sender_address:: param tx_gas: Force a gas limit: param block_identifier:: return: 1 if everything ok | def call(self, tx_sender_address: Optional[str] = None, tx_gas: Optional[int] = None,
block_identifier='pending') -> int:
"""
:param tx_sender_address:
:param tx_gas: Force a gas limit
:param block_identifier:
:return: `1` if everything ok
"""
paramet... |
Send multisig tx to the Safe: param tx_sender_private_key: Sender private key: param tx_gas: Gas for the external tx. If not ( safe_tx_gas + data_gas ) * 2 will be used: param tx_gas_price: Gas price of the external tx. If not gas_price will be used: param tx_nonce: Force nonce for tx_sender: param block_identifier: la... | def execute(self,
tx_sender_private_key: str,
tx_gas: Optional[int] = None,
tx_gas_price: Optional[int] = None,
tx_nonce: Optional[int] = None,
block_identifier='pending') -> Tuple[bytes, Dict[str, any]]:
"""
Send multisig t... |
Appends towrite to the write queue | async def write(self, towrite: bytes, await_blocking=False):
"""
Appends towrite to the write queue
>>> await test.write(b"HELLO")
# Returns without wait time
>>> await test.write(b"HELLO", await_blocking = True)
# Returns when the bufer is flushed
:param towrit... |
Reads a given number of bytes | async def read(self, num_bytes=0) -> bytes:
"""
Reads a given number of bytes
:param bytecount: How many bytes to read, leave it at default
to read everything that is available
:returns: incoming bytes
"""
if num_bytes < 1:
num_bytes... |
Reads a given number of bytes | async def _read(self, num_bytes) -> bytes:
"""
Reads a given number of bytes
:param num_bytes: How many bytes to read
:returns: incoming bytes
"""
while True:
if self.in_waiting < num_bytes:
await asyncio.sleep(self._asyncio_sleep_time)
... |
Reads one line | async def readline(self) -> bytes:
"""
Reads one line
>>> # Keeps waiting for a linefeed incase there is none in the buffer
>>> await test.readline()
:returns: bytes forming a line
"""
while True:
line = self._serial_instance.readline()
i... |
Verifies and sends message. | def send(self, message):
"""Verifies and sends message.
:param message: Message instance.
:param envelope_from: Email address to be used in MAIL FROM command.
"""
assert message.send_to, "No recipients have been added"
if message.has_bad_headers(self.mail.default_sender... |
Creates a MIMEText object with the given subtype ( default: plain ) If the text is unicode the utf - 8 charset is used. | def _mimetext(self, text, subtype='plain'):
"""Creates a MIMEText object with the given subtype (default: 'plain')
If the text is unicode, the utf-8 charset is used.
"""
charset = self.charset or 'utf-8'
return MIMEText(text, _subtype=subtype, _charset=charset) |
Creates the email | def as_string(self, default_from=None):
"""Creates the email"""
encoding = self.charset or 'utf-8'
attachments = self.attachments or []
if len(attachments) == 0 and not self.html:
# No html content and zero attachments means plain text
msg = self._mimetext(self... |
Checks for bad headers i. e. newlines in subject sender or recipients. | def has_bad_headers(self, default_from=None):
"""Checks for bad headers i.e. newlines in subject, sender or recipients.
"""
sender = self.sender or default_from
reply_to = self.reply_to or ''
for val in [self.subject, sender, reply_to] + self.recipients:
for c in '\r... |
Adds an attachment to the message. | def attach(self,
filename=None,
content_type=None,
data=None,
disposition=None,
headers=None):
"""Adds an attachment to the message.
:param filename: filename of attachment
:param content_type: file mimetype
:par... |
Records all messages. Use in unit tests for example:: | def record_messages(self):
"""Records all messages. Use in unit tests for example::
with mail.record_messages() as outbox:
response = app.test_client.get("/email-sending-view/")
assert len(outbox) == 1
assert outbox[0].subject == "testing"
Yo... |
Register Services that can be accessed by this DAL. Upon registration the service is set up. | def register_services(self, **services):
"""
Register Services that can be accessed by this DAL. Upon
registration, the service is set up.
:param **services: Keyword arguments where the key is the name
to register the Service as and the value is the Service.
"""
... |
: param middleware: Middleware in order of execution | def register_context_middleware(self, *middleware):
"""
:param middleware: Middleware in order of execution
"""
for m in middleware:
if not is_generator(m):
raise Exception('Middleware {} must be a Python generator callable.'.format(m))
self._middlewa... |
Load a configuration module and return a Config | def from_module(module_name):
"""
Load a configuration module and return a Config
"""
d = importlib.import_module(module_name)
config = {}
for key in dir(d):
if key.isupper():
config[key] = getattr(d, key)
return Config(config) |
Register resources with the ResourceManager. | def register_resources(self, **resources):
"""
Register resources with the ResourceManager.
"""
for key, resource in resources.items():
if key in self._resources:
raise AlreadyExistsException('A Service for {} is already registered.'.format(key))
... |
Raises an exception if value for key is empty. | def require(self, key):
"""
Raises an exception if value for ``key`` is empty.
"""
value = self.get(key)
if not value:
raise ValueError('"{}" is empty.'.format(key))
return value |
Setup the context. Should only be called by __enter__ ing the context. | def _setup(self):
"""
Setup the context. Should only be called by
__enter__'ing the context.
"""
self.data_manager.ctx_stack.push(self)
self._setup_hook()
middleware = self.data_manager.get_middleware(self)
# Create each middleware generator
# Th... |
Teardown a Resource or Middleware. | def _exit(self, obj, type, value, traceback):
"""
Teardown a Resource or Middleware.
"""
if type is None:
# No in-context exception occurred
try:
obj.next()
except StopIteration:
# Resource closed as expected
... |
Hook to setup this service with a specific DataManager. | def setup(self, data_manager):
"""
Hook to setup this service with a specific DataManager.
Will recursively setup sub-services.
"""
self._data_manager = data_manager
if self._data_manager:
self._dal = self._data_manager.get_dal()
else:
sel... |
The group index with respect to wavelength. | def ng(self, wavelength):
'''
The group index with respect to wavelength.
Args:
wavelength (float, list, None): The wavelength(s) the group
index will be evaluated at.
Returns:
float, list: The group index at the target wavelength(s).
'''... |
The group velocity dispersion ( GVD ) with respect to wavelength. | def gvd(self, wavelength):
'''
The group velocity dispersion (GVD) with respect to wavelength.
Args:
wavelength (float, list, None): The wavelength(s) the GVD will
be evaluated at.
Returns:
float, list: The GVD at the target wavelength(s).
... |
Helpful function to evaluate Cauchy equations. | def _cauchy_equation(wavelength, coefficients):
'''
Helpful function to evaluate Cauchy equations.
Args:
wavelength (float, list, None): The wavelength(s) the
Cauchy equation will be evaluated at.
coefficients (list): A list of the coefficients of
... |
Main function | def main():
"""
Main function
"""
bc = BackendUpdate()
bc.initialize()
logger.info("backend_client, version: %s", __version__)
logger.debug("~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
success = False
if bc.item_type and bc.action == 'list':
success = bc.get_resource_list(bc.item_type, b... |
Login on backend with username and password | def initialize(self):
# pylint: disable=attribute-defined-outside-init
"""Login on backend with username and password
:return: None
"""
try:
logger.info("Authenticating...")
self.backend = Backend(self.backend_url)
self.backend.login(self.user... |
Dump the data to a JSON formatted file: param data: data to be dumped: param filename: name of the file to use. Only the file name not the full path!: return: dumped file absolute file name | def file_dump(self, data, filename): # pylint: disable=no-self-use
"""
Dump the data to a JSON formatted file
:param data: data to be dumped
:param filename: name of the file to use. Only the file name, not the full path!
:return: dumped file absolute file name
"""
... |
Get a specific resource list | def get_resource_list(self, resource_name, name=''):
# pylint: disable=too-many-locals, too-many-nested-blocks
"""Get a specific resource list
If name is not None, it may be a request to get the list of the services of an host.
"""
try:
logger.info("Trying to get %s ... |
Get a specific resource by name | def get_resource(self, resource_name, name):
# pylint: disable=too-many-locals, too-many-nested-blocks
"""Get a specific resource by name"""
try:
logger.info("Trying to get %s: '%s'", resource_name, name)
services_list = False
if resource_name == 'host' and '... |
Delete a specific resource by name | def delete_resource(self, resource_name, name):
"""Delete a specific resource by name"""
try:
logger.info("Trying to get %s: '%s'", resource_name, name)
if name is None:
# No name is defined, delete all the resources...
if not self.dry_run:
... |
Create or update a specific resource | def create_update_resource(self, resource_name, name, update=False):
# pylint: disable=too-many-return-statements, too-many-locals
# pylint: disable=too-many-nested-blocks
"""Create or update a specific resource
:param resource_name: backend resource endpoint (eg. host, user, ...)
... |
Returns the response from the requested endpoint with the requested method: param method: str. one of the methods accepted by Requests ( POST GET... ): param endpoint: str. the relative endpoint to access: param params: ( optional ) Dictionary or bytes to be sent in the query string for the: class: Request.: param data... | def get_response(self, method, endpoint, headers=None, json=None, params=None, data=None):
# pylint: disable=too-many-arguments
"""
Returns the response from the requested endpoint with the requested method
:param method: str. one of the methods accepted by Requests ('POST', 'GET', ...)
... |
Decodes and returns the response as JSON ( dict ) or raise BackendException: param response: requests. response object: return: dict | def decode(response):
"""
Decodes and returns the response as JSON (dict) or raise BackendException
:param response: requests.response object
:return: dict
"""
# Second stage. Errors are backend errors (bad login, bad url, ...)
try:
response.raise_for... |
Set token in authentification for next requests: param token: str. token to set in auth. If None reinit auth | def set_token(self, token):
"""
Set token in authentification for next requests
:param token: str. token to set in auth. If None, reinit auth
"""
if token:
auth = HTTPBasicAuth(token, '')
self._token = token
self.authenticated = True # TODO: R... |
Log into the backend and get the token | def login(self, username, password, generate='enabled', proxies=None):
"""
Log into the backend and get the token
generate parameter may have following values:
- enabled: require current token (default)
- force: force new token generation
- disabled
if login is:... |
Connect to alignak backend and retrieve all available child endpoints of root | def get_domains(self):
"""
Connect to alignak backend and retrieve all available child endpoints of root
If connection is successful, returns a list of all the resources available in the backend:
Each resource is identified with its title and provides its endpoint relative to backend
... |
Get all items in the specified endpoint of alignak backend | def get_all(self, endpoint, params=None):
# pylint: disable=too-many-locals
"""
Get all items in the specified endpoint of alignak backend
If an error occurs, a BackendException is raised.
If the max_results parameter is not specified in parameters, it is set to
BACKEND... |
Method to update an item | def patch(self, endpoint, data, headers=None, inception=False):
"""
Method to update an item
The headers must include an If-Match containing the object _etag.
headers = {'If-Match': contact_etag}
The data dictionary contain the fields that must be modified.
If the ... |
Method to delete an item or all items | def delete(self, endpoint, headers):
"""
Method to delete an item or all items
headers['If-Match'] must contain the _etag identifier of the element to delete
:param endpoint: endpoint (API URL)
:type endpoint: str
:param headers: headers (example: Content-Type)
... |
Returns True if path1 and path2 refer to the same file. | def samefile(path1, path2):
"""
Returns True if path1 and path2 refer to the same file.
"""
# Check if both are on the same volume and have the same file ID
info1 = fs.getfileinfo(path1)
info2 = fs.getfileinfo(path2)
return (info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber and
... |
Given a path return a pair containing a new REPARSE_DATA_BUFFER and the length of the buffer ( not necessarily the same as sizeof due to packing issues ). If no path is provided the maximum length is assumed. | def new_junction_reparse_buffer(path=None):
"""
Given a path, return a pair containing a new REPARSE_DATA_BUFFER and the
length of the buffer (not necessarily the same as sizeof due to packing
issues).
If no path is provided, the maximum length is assumed.
"""
if path is None:
#... |
Create a junction at link_name pointing to source. | def create(source, link_name):
"""
Create a junction at link_name pointing to source.
"""
success = False
if not os.path.isdir(source):
raise Exception("%s is not a directory" % source)
if os.path.exists(link_name):
raise Exception("%s: junction link name already exists" % link_n... |
Return information for the volume containing the given path. This is going to be a pair containing ( file system file system flags ). | def getvolumeinfo(path):
"""
Return information for the volume containing the given path. This is going
to be a pair containing (file system, file system flags).
"""
# Add 1 for a trailing backslash if necessary, and 1 for the terminating
# null character.
volpath = ctypes.create_unicode_bu... |
Sets command name and formatting for subsequent calls to logger | def initialize_logger(args):
"""Sets command name and formatting for subsequent calls to logger"""
global log_filename
log_filename = os.path.join(os.getcwd(), "jacquard.log")
if args.log_file:
_validate_log_file(args.log_file)
log_filename = args.log_file
logging.basicConfig(forma... |
Suppress default exit behavior | def error(self, message):
'''Suppress default exit behavior'''
message = self._remessage_invalid_subparser(message)
raise utils.UsageError(message) |
Recognizes and claims MuTect VCFs form the set of all input VCFs. | def claim(self, file_readers):
"""Recognizes and claims MuTect VCFs form the set of all input VCFs.
Each defined caller has a chance to evaluate and claim all the incoming
files as something that it can process.
Args:
file_readers: the collection of currently unclaimed file... |
Returns a standardized column header. | def _get_new_column_header(self, vcf_reader):
"""Returns a standardized column header.
MuTect sample headers include the name of input alignment, which is
nice, but doesn't match up with the sample names reported in Strelka
or VarScan. To fix this, we replace with NORMAL and TUMOR using... |
Build a file path from * paths * and return the contents. | def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as filename:
return filename.read() |
Recognizes and claims VarScan VCFs form the set of all input VCFs. | def claim(self, file_readers):
"""Recognizes and claims VarScan VCFs form the set of all input VCFs.
Each defined caller has a chance to evaluate and claim all the incoming
files as something that it can process. Since VarScan can claim
high-confidence files as well, this process is sig... |
Extract ( float ) value of dependent tag or None if absent. | def _get_dependent_value(tag_values, dependent_tag_id):
'''Extract (float) value of dependent tag or None if absent.'''
try:
values = tag_values[dependent_tag_id].split(",")
return max([float(value) for value in values])
except KeyError:
return None
ex... |
Derive mean and stdev. | def _init_population_stats(self, vcf_reader, dependent_tag_id):
'''Derive mean and stdev.
Adapted from online variance algorithm from Knuth, The Art of Computer
Programming, volume 2
Returns: mean and stdev when len(values) > 1, otherwise (None, None)
Values rounded to _MA... |
Allows each caller to claim incoming files as they are recognized. | def claim(self, unclaimed_file_readers):
"""Allows each caller to claim incoming files as they are recognized.
Args:
unclaimed_file_readers: Usually, all files in the input dir.
Returns:
A tuple of unclaimed file readers and claimed VcfReaders. The
presence ... |
Generates parsed VcfRecord objects. | def vcf_records(self, format_tags=None, qualified=False):
"""Generates parsed VcfRecord objects.
Typically called in a for loop to process each vcf record in a
VcfReader. VcfReader must be opened in advanced and closed when
complete. Skips all headers.
Args:
qualifi... |
Similar to follow but also looks up if inode of file is changed e. g. if it was re - created. | def follow_path(file_path, buffering=-1, encoding=None, errors='strict'):
"""
Similar to follow, but also looks up if inode of file is changed
e.g. if it was re-created.
Returned generator yields strings encoded by using encoding.
If encoding is not specified, it defaults to locale.getpreferredenco... |
Split data into lines where lines are separated by LINE_TERMINATORS. | def splitlines(self, data):
"""
Split data into lines where lines are separated by LINE_TERMINATORS.
:param data: Any chunk of binary data.
:return: List of lines without any characters at LINE_TERMINATORS.
"""
return re.split(b'|'.join(self.LINE_TERMINATORS), data) |
Read given number of bytes from file.: param read_size: Number of bytes to read. - 1 to read all.: return: Number of bytes read and data that was read. | def read(self, read_size=-1):
"""
Read given number of bytes from file.
:param read_size: Number of bytes to read. -1 to read all.
:return: Number of bytes read and data that was read.
"""
read_str = self.file.read(read_size)
return len(read_str), read_str |
Return line terminator data begins with or None. | def prefix_line_terminator(self, data):
"""
Return line terminator data begins with or None.
"""
for t in self.LINE_TERMINATORS:
if data.startswith(t):
return t
return None |
Return line terminator data ends with or None. | def suffix_line_terminator(self, data):
"""
Return line terminator data ends with or None.
"""
for t in self.LINE_TERMINATORS:
if data.endswith(t):
return t
return None |
Seek next line relative to the current file position. | def seek_next_line(self):
"""
Seek next line relative to the current file position.
:return: Position of the line or -1 if next line was not found.
"""
where = self.file.tell()
offset = 0
while True:
data_len, data = self.read(self.read_size)
... |
Seek previous line relative to the current file position. | def seek_previous_line(self):
"""
Seek previous line relative to the current file position.
:return: Position of the line or -1 if previous line was not found.
"""
where = self.file.tell()
offset = 0
while True:
if offset == where:
br... |
Return the last lines of the file. | def tail(self, lines=10):
"""
Return the last lines of the file.
"""
self.file.seek(0, SEEK_END)
for i in range(lines):
if self.seek_previous_line() == -1:
break
data = self.file.read()
for t in self.LINE_TERMINATORS:
if ... |
Return the top lines of the file. | def head(self, lines=10):
"""
Return the top lines of the file.
"""
self.file.seek(0)
for i in range(lines):
if self.seek_next_line() == -1:
break
end_pos = self.file.tell()
self.file.seek(0)
data = self.file.read... |
Iterator generator that returns lines as data is added to the file. | def follow(self):
"""
Iterator generator that returns lines as data is added to the file.
None will be yielded if no new line is available.
Caller may either wait and re-try or end iteration.
"""
trailing = True
while True:
where = sel... |
Recognizes and claims Strelka VCFs form the set of all input VCFs. | def claim(self, file_readers):
"""Recognizes and claims Strelka VCFs form the set of all input VCFs.
Each defined caller has a chance to evaluate and claim all the incoming
files as something that it can process.
Args:
file_readers: the collection of currently unclaimed fil... |
Generates parsed VcfRecord objects. | def vcf_records(self, qualified=False):
"""Generates parsed VcfRecord objects.
Typically called in a for loop to process each vcf record in a
VcfReader. VcfReader must be opened in advanced and closed when
complete. Skips all headers.
Args:
qualified: When True, sam... |
Alternative constructor that parses VcfRecord from VCF string. | def parse_record(cls, vcf_line, sample_names):
"""Alternative constructor that parses VcfRecord from VCF string.
Aspire to parse/represent the data such that it could be reliably
round-tripped. (This nicety means INFO fields and FORMAT tags should be
treated as ordered to avoid shufflin... |
Creates a sample dict of tag - value dicts for a single variant record. | def _sample_tag_values(cls, sample_names, rformat, sample_fields):
"""Creates a sample dict of tag-value dicts for a single variant record.
Args:
sample_names: list of sample name strings.
rformat: record format string (from VCF record).
sample_fields: list of string... |
Returns set of format tags. | def format_tags(self):
"""Returns set of format tags."""
tags = VcfRecord._EMPTY_SET
if self.sample_tag_values:
first_sample = list(self.sample_tag_values.keys())[0]
tags = set(self.sample_tag_values[first_sample].keys())
return tags |
Adds new info field ( flag or key = value pair ). | def add_info_field(self, field):
"""Adds new info field (flag or key=value pair).
Args:
field: String flag (e.g. "SOMATIC") or key-value ("NEW_DP=42")
Raises:
KeyError: if info field already exists
"""
if field in self.info_dict:
msg = "New i... |
Updates info attribute from info dict. | def _join_info_fields(self):
"""Updates info attribute from info dict."""
if self.info_dict:
info_fields = []
if len(self.info_dict) > 1:
self.info_dict.pop(".", None)
for field, value in self.info_dict.items():
if field == value:
... |
Returns string representation of format field. | def _format_field(self):
"""Returns string representation of format field."""
format_field = "."
if self.sample_tag_values:
first_sample = list(self.sample_tag_values.keys())[0]
tag_names = self.sample_tag_values[first_sample].keys()
if tag_names:
... |
Returns string representation of sample - format values. | def _sample_field(self, sample):
"""Returns string representation of sample-format values.
Raises:
KeyError: if requested sample is not defined.
"""
tag_values = self.sample_tag_values[sample].values()
if tag_values:
return ":".join(tag_values)
el... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.