Search is not available for this dataset
text stringlengths 75 104k |
|---|
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... |
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
... |
def send_multisig_tx(self,
safe_address: str,
to: str,
value: int,
data: bytes,
operation: int,
safe_tx_gas: int,
data_gas: int,
... |
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... |
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... |
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... |
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,
... |
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... |
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... |
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... |
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... |
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)
... |
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... |
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... |
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) |
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... |
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... |
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... |
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... |
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.
"""
... |
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... |
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) |
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))
... |
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 |
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... |
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
... |
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... |
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).
'''... |
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).
... |
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
... |
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... |
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... |
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
"""
... |
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 ... |
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 '... |
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:
... |
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, ...)
... |
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', ...)
... |
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... |
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... |
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:... |
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
... |
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... |
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 ... |
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)
... |
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
... |
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:
#... |
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... |
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... |
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... |
def error(self, message):
'''Suppress default exit behavior'''
message = self._remessage_invalid_subparser(message)
raise utils.UsageError(message) |
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... |
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... |
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() |
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... |
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... |
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... |
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 ... |
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... |
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... |
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) |
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 |
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 |
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 |
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)
... |
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... |
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 ... |
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... |
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... |
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... |
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... |
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... |
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... |
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 |
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... |
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:
... |
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:
... |
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... |
def text(self):
"Returns tab-delimited, newline terminated string of VcfRecord."
stringifier = [self.chrom, self.pos, self.vcf_id, self.ref, self.alt,
self.qual, self.filter, self.info,
self._format_field()]
for sample in self.sample_tag_values:
... |
def add_sample_tag_value(self, tag_name, new_sample_values):
"""Appends a new format tag-value for all samples.
Args:
tag_name: string tag name; must not already exist
new_sample
Raises:
KeyError: if tag_name to be added already exists
"""
if... |
def add_or_replace_filter(self, new_filter):
"""Replaces null or blank filter or adds filter to existing list."""
if self.filter.lower() in self._FILTERS_TO_REPLACE:
self.filter = new_filter
elif new_filter not in self.filter.split(";"):
self.filter = ";".join([self.filte... |
def available_categories(cls, user, products=AllProducts):
''' Returns the categories available to the user. Specify `products` if
you want to restrict to just the categories that hold the specified
products, otherwise it'll do all. '''
# STOPGAP -- this needs to be elsewhere tbqh
... |
def ProductsForm(category, products):
''' Produces an appropriate _ProductsForm subclass for the given render
type. '''
# Each Category.RENDER_TYPE value has a subclass here.
cat = inventory.Category
RENDER_TYPES = {
cat.RENDER_TYPE_QUANTITY: _QuantityBoxProductsForm,
cat.RENDER_TYP... |
def staff_products_form_factory(user):
''' Creates a StaffProductsForm that restricts the available products to
those that are available to a user. '''
products = inventory.Product.objects.all()
products = ProductController.available_products(user, products=products)
product_ids = [product.id for ... |
def add_product_error(self, product, error):
''' Adds an error to the given product's field '''
''' if product in field_names:
field = field_names[product]
elif isinstance(product, inventory.Product):
return
else:
field = None '''
self.add_er... |
def initial_data(cls, product_quantities):
''' Prepares initial data for an instance of this form.
product_quantities is a sequence of (product,quantity) tuples '''
f = [
{
_ItemQuantityProductsForm.CHOICE_FIELD: product.id,
_ItemQuantityProductsForm.... |
def product_quantities(self):
''' Yields a sequence of (product, quantity) tuples from the
cleaned form data. '''
products = set()
# Track everything so that we can yield some zeroes
all_products = set()
for form in self:
if form.empty_permitted and not form... |
def memoise(cls, func):
''' Decorator that stores the result of the stored function in the
user's results cache until the batch completes. Keyword arguments are
not yet supported.
Arguments:
func (callable(*a)): The function whose results we want
to store. Th... |
def model_fields_form_factory(model):
''' Creates a form for specifying fields from a model to display. '''
fields = model._meta.get_fields()
choices = []
for field in fields:
if hasattr(field, "verbose_name"):
choices.append((field.name, field.verbose_name))
class ModelFields... |
def _items(self, cart_status, category=None):
''' Aggregates the items that this user has purchased.
Arguments:
cart_status (int or Iterable(int)): etc
category (Optional[models.inventory.Category]): the category
of items to restrict to.
Returns:
... |
def items_pending_or_purchased(self):
''' Returns the items that this user has purchased or has pending. '''
status = [commerce.Cart.STATUS_PAID, commerce.Cart.STATUS_ACTIVE]
return self._items(status) |
def items_purchased(self, category=None):
''' Aggregates the items that this user has purchased.
Arguments:
category (Optional[models.inventory.Category]): the category
of items to restrict to.
Returns:
[ProductAndQuantity, ...]: A list of product-quanti... |
def send_email(self, to, kind, **kwargs):
''' Sends an e-mail to the given address.
to: The address
kind: the ID for an e-mail kind; it should point to a subdirectory of
self.template_prefix containing subject.txt and message.html, which
are django templates for the subj... |
def iter_changeset_stream(start_sqn=None, base_url='https://planet.openstreetmap.org/replication/changesets', expected_interval=60, parse_timestamps=True, state_dir=None):
"""Start processing an OSM changeset stream and yield one (action, primitive) tuple
at a time to the caller."""
# This is a lot like th... |
def iter_osm_stream(start_sqn=None, base_url='https://planet.openstreetmap.org/replication/minute', expected_interval=60, parse_timestamps=True, state_dir=None):
"""Start processing an OSM diff stream and yield one changeset at a time to
the caller."""
# If the user specifies a state_dir, read the state fr... |
def parse_osm_file(f, parse_timestamps=True):
"""Parse a file-like containing OSM XML into memory and return an object with
the nodes, ways, and relations it contains. """
nodes = []
ways = []
relations = []
for p in iter_osm_file(f, parse_timestamps):
if type(p) == model.Node:
... |
def iter_osm_notes(feed_limit=25, interval=60, parse_timestamps=True):
""" Parses the global OSM Notes feed and yields as much Note information as possible. """
last_seen_guid = None
while True:
u = urllib2.urlopen('https://www.openstreetmap.org/api/0.6/notes/feed?limit=%d' % feed_limit)
t... |
def passes_filter(self, user):
''' Returns true if the condition passes the filter '''
cls = type(self.condition)
qs = cls.objects.filter(pk=self.condition.id)
return self.condition in self.pre_filter(qs, user) |
def user_quantity_remaining(self, user, filtered=False):
''' Returns the number of items covered by this flag condition the
user can add to the current cart. This default implementation returns
a big number if is_met() is true, otherwise 0.
Either this method, or is_met() must be overri... |
def is_met(self, user, filtered=False):
''' Returns True if this flag condition is met, otherwise returns
False. It determines if the condition is met by calling pre_filter
with a queryset containing only self.condition. '''
if filtered:
return True # Why query again?
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.