text_prompt stringlengths 100 17.7k ⌀ | code_prompt stringlengths 7 9.86k ⌀ |
|---|---|
<SYSTEM_TASK:>
Add the file at ``src`` to the archive.
<END_TASK>
<USER_TASK:>
Description:
def add_file(self, src, dest=None):
"""Add the file at ``src`` to the archive.
If ``dest`` is ``None`` then it is added under just the original
filename. So ``add_file('foo/bar.txt')`` ends up at ``bar.t... |
dest = dest or os.path.basename(src)
with open(src, 'rb') as fp:
contents = fp.read()
self.add_contents(dest, contents) |
<SYSTEM_TASK:>
Add file contents to the archive under ``dest``.
<END_TASK>
<USER_TASK:>
Description:
def add_contents(self, dest, contents):
"""Add file contents to the archive under ``dest``.
If ``dest`` is a path, it will be added compressed and world-readable
(user-writeable). You may also p... |
assert not self._closed, "Archive closed"
if not isinstance(dest, zipfile.ZipInfo):
dest = zinfo(dest) # see for some caveats
# Ensure we apply the compression
dest.compress_type = self.zip_compression
# Mark host OS as Linux for all archives
dest.create_sys... |
<SYSTEM_TASK:>
Close the zip file.
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""Close the zip file.
Note underlying tempfile is removed when archive is garbage collected.
""" |
self._closed = True
self._zip_file.close()
log.debug(
"Created custodian serverless archive size: %0.2fmb",
(os.path.getsize(self._temp_archive_file.name) / (
1024.0 * 1024.0)))
return self |
<SYSTEM_TASK:>
Return the b64 encoded sha256 checksum of the archive.
<END_TASK>
<USER_TASK:>
Description:
def get_checksum(self, encoder=base64.b64encode, hasher=hashlib.sha256):
"""Return the b64 encoded sha256 checksum of the archive.""" |
assert self._closed, "Archive not closed"
with open(self._temp_archive_file.name, 'rb') as fh:
return encoder(checksum(fh, hasher())).decode('ascii') |
<SYSTEM_TASK:>
Create or update an alias for the given function.
<END_TASK>
<USER_TASK:>
Description:
def publish_alias(self, func_data, alias):
"""Create or update an alias for the given function.
""" |
if not alias:
return func_data['FunctionArn']
func_name = func_data['FunctionName']
func_version = func_data['Version']
exists = resource_exists(
self.client.get_alias, FunctionName=func_name, Name=alias)
if not exists:
log.debug("Publishing... |
<SYSTEM_TASK:>
report on guard duty enablement by account
<END_TASK>
<USER_TASK:>
Description:
def report(config, tags, accounts, master, debug, region):
"""report on guard duty enablement by account""" |
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
session = get_session(
master_info.get('role'), 'c7n-guardian',
master_info.get('profile'),
region)
client = session.client('guardduty')
detector_id = get_or_create_detector_... |
<SYSTEM_TASK:>
suspend guard duty in the given accounts.
<END_TASK>
<USER_TASK:>
Description:
def disable(config, tags, accounts, master, debug,
suspend, disable_detector, delete_detector, dissociate, region):
"""suspend guard duty in the given accounts.""" |
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
if sum(map(int, (suspend, disable_detector, dissociate))) != 1:
raise ValueError((
"One and only of suspend, disable-detector, dissociate"
"can be specified."))
master_se... |
<SYSTEM_TASK:>
enable guard duty on a set of accounts
<END_TASK>
<USER_TASK:>
Description:
def enable(config, master, tags, accounts, debug, message, region):
"""enable guard duty on a set of accounts""" |
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
regions = expand_regions(region)
for r in regions:
log.info("Processing Region:%s", r)
enable_region(master_info, accounts_config, executor, message, r) |
<SYSTEM_TASK:>
Return all the security group names configured in this action.
<END_TASK>
<USER_TASK:>
Description:
def get_action_group_names(self):
"""Return all the security group names configured in this action.""" |
return self.get_group_names(
list(itertools.chain(
*[self._get_array('add'),
self._get_array('remove'),
self._get_array('isolation-group')]))) |
<SYSTEM_TASK:>
Resolve security names to security groups resources.
<END_TASK>
<USER_TASK:>
Description:
def get_groups_by_names(self, names):
"""Resolve security names to security groups resources.""" |
if not names:
return []
client = utils.local_session(
self.manager.session_factory).client('ec2')
sgs = self.manager.retry(
client.describe_security_groups,
Filters=[{
'Name': 'group-name', 'Values': names}]).get(
... |
<SYSTEM_TASK:>
Resolve any security group names to the corresponding group ids
<END_TASK>
<USER_TASK:>
Description:
def resolve_group_names(self, r, target_group_ids, groups):
"""Resolve any security group names to the corresponding group ids
With the context of a given network attached resource.
... |
names = self.get_group_names(target_group_ids)
if not names:
return target_group_ids
target_group_ids = list(target_group_ids)
vpc_id = self.vpc_expr.search(r)
if not vpc_id:
raise PolicyExecutionError(self._format_error(
"policy:{policy}... |
<SYSTEM_TASK:>
Resolve the resources security groups that need be modified.
<END_TASK>
<USER_TASK:>
Description:
def resolve_remove_symbols(self, r, target_group_ids, rgroups):
"""Resolve the resources security groups that need be modified.
Specifically handles symbolic names that match annotations fro... |
if 'matched' in target_group_ids:
return r.get('c7n:matched-security-groups', ())
elif 'network-location' in target_group_ids:
for reason in r.get('c7n:NetworkLocation', ()):
if reason['reason'] == 'SecurityGroupMismatch':
return list(reason['... |
<SYSTEM_TASK:>
Return lists of security groups to set on each resource
<END_TASK>
<USER_TASK:>
Description:
def get_groups(self, resources):
"""Return lists of security groups to set on each resource
For each input resource, parse the various add/remove/isolation-
group policies for 'modify-sec... |
resolved_groups = self.get_groups_by_names(self.get_action_group_names())
return_groups = []
for idx, r in enumerate(resources):
rgroups = self.sg_expr.search(r) or []
add_groups = self.resolve_group_names(
r, self._get_array('add'), resolved_groups)
... |
<SYSTEM_TASK:>
jsonschema generation helper
<END_TASK>
<USER_TASK:>
Description:
def type_schema(
type_name, inherits=None, rinherit=None,
aliases=None, required=None, **props):
"""jsonschema generation helper
params:
- type_name: name of the type
- inherits: list of document fragment... |
if aliases:
type_names = [type_name]
type_names.extend(aliases)
else:
type_names = [type_name]
if rinherit:
s = copy.deepcopy(rinherit)
s['properties']['type'] = {'enum': type_names}
else:
s = {
'type': 'object',
'properties': {
... |
<SYSTEM_TASK:>
Return a mapping of key value to resources with the corresponding value.
<END_TASK>
<USER_TASK:>
Description:
def group_by(resources, key):
"""Return a mapping of key value to resources with the corresponding value.
Key may be specified as dotted form for nested dictionary lookup
""" |
resource_map = {}
parts = key.split('.')
for r in resources:
v = r
for k in parts:
v = v.get(k)
if not isinstance(v, dict):
break
resource_map.setdefault(v, []).append(r)
return resource_map |
<SYSTEM_TASK:>
Some sources from apis return lowerCased where as describe calls
<END_TASK>
<USER_TASK:>
Description:
def camelResource(obj):
"""Some sources from apis return lowerCased where as describe calls
always return TitleCase, this function turns the former to the later
""" |
if not isinstance(obj, dict):
return obj
for k in list(obj.keys()):
v = obj.pop(k)
obj["%s%s" % (k[0].upper(), k[1:])] = v
if isinstance(v, dict):
camelResource(v)
elif isinstance(v, list):
list(map(camelResource, v))
return obj |
<SYSTEM_TASK:>
Return a list of ec2 instances for the query.
<END_TASK>
<USER_TASK:>
Description:
def query_instances(session, client=None, **query):
"""Return a list of ec2 instances for the query.
""" |
if client is None:
client = session.client('ec2')
p = client.get_paginator('describe_instances')
results = p.paginate(**query)
return list(itertools.chain(
*[r["Instances"] for r in itertools.chain(
*[pp['Reservations'] for pp in results])])) |
<SYSTEM_TASK:>
Cache a session thread local for up to 45m
<END_TASK>
<USER_TASK:>
Description:
def local_session(factory):
"""Cache a session thread local for up to 45m""" |
factory_region = getattr(factory, 'region', 'global')
s = getattr(CONN_CACHE, factory_region, {}).get('session')
t = getattr(CONN_CACHE, factory_region, {}).get('time')
n = time.time()
if s is not None and t + (60 * 45) > n:
return s
s = factory()
setattr(CONN_CACHE, factory_regio... |
<SYSTEM_TASK:>
Return an identifier for a snapshot of a database or cluster.
<END_TASK>
<USER_TASK:>
Description:
def snapshot_identifier(prefix, db_identifier):
"""Return an identifier for a snapshot of a database or cluster.
""" |
now = datetime.now()
return '%s-%s-%s' % (prefix, db_identifier, now.strftime('%Y-%m-%d-%H-%M')) |
<SYSTEM_TASK:>
Decorator for retry boto3 api call on transient errors.
<END_TASK>
<USER_TASK:>
Description:
def get_retry(codes=(), max_attempts=8, min_delay=1, log_retries=False):
"""Decorator for retry boto3 api call on transient errors.
https://www.awsarchitectureblog.com/2015/03/backoff.html
https://en... |
max_delay = max(min_delay, 2) ** max_attempts
def _retry(func, *args, **kw):
for idx, delay in enumerate(
backoff_delays(min_delay, max_delay, jitter=True)):
try:
return func(*args, **kw)
except ClientError as e:
if e.response['Er... |
<SYSTEM_TASK:>
Generic wrapper to log uncaught exceptions in a function.
<END_TASK>
<USER_TASK:>
Description:
def worker(f):
"""Generic wrapper to log uncaught exceptions in a function.
When we cross concurrent.futures executor boundaries we lose our
traceback information, and when doing bulk operations we... |
def _f(*args, **kw):
try:
return f(*args, **kw)
except Exception:
worker_log.exception(
'Error invoking %s',
"%s.%s" % (f.__module__, f.__name__))
raise
functools.update_wrapper(_f, f)
return _f |
<SYSTEM_TASK:>
Reformat schema to be in a more displayable format.
<END_TASK>
<USER_TASK:>
Description:
def reformat_schema(model):
""" Reformat schema to be in a more displayable format. """ |
if not hasattr(model, 'schema'):
return "Model '{}' does not have a schema".format(model)
if 'properties' not in model.schema:
return "Schema in unexpected format."
ret = copy.deepcopy(model.schema['properties'])
if 'type' in ret:
del(ret['type'])
for key in model.schema... |
<SYSTEM_TASK:>
Returns all extant rds engine upgrades.
<END_TASK>
<USER_TASK:>
Description:
def _get_available_engine_upgrades(client, major=False):
"""Returns all extant rds engine upgrades.
As a nested mapping of engine type to known versions
and their upgrades.
Defaults to minor upgrades, but confi... |
results = {}
engine_versions = client.describe_db_engine_versions()['DBEngineVersions']
for v in engine_versions:
if not v['Engine'] in results:
results[v['Engine']] = {}
if 'ValidUpgradeTarget' not in v or len(v['ValidUpgradeTarget']) == 0:
continue
for t in... |
<SYSTEM_TASK:>
Create a local output directory per execution.
<END_TASK>
<USER_TASK:>
Description:
def get_local_output_dir():
"""Create a local output directory per execution.
We've seen occassional (1/100000) perm issues with lambda on temp
directory and changing unix execution users (2015-2018), so use ... |
output_dir = os.environ.get('C7N_OUTPUT_DIR', '/tmp/' + str(uuid.uuid4()))
if not os.path.exists(output_dir):
try:
os.mkdir(output_dir)
except OSError as error:
log.warning("Unable to make output directory: {}".format(error))
return output_dir |
<SYSTEM_TASK:>
Get policy lambda execution configuration.
<END_TASK>
<USER_TASK:>
Description:
def init_config(policy_config):
"""Get policy lambda execution configuration.
cli parameters are serialized into the policy lambda config,
we merge those with any policy specific execution options.
--assume ... |
global account_id
exec_options = policy_config.get('execution-options', {})
# Remove some configuration options that don't make sense to translate from
# cli to lambda automatically.
# - assume role on cli doesn't translate, it is the default lambda role and
# used to provision the lambda... |
<SYSTEM_TASK:>
index policy metrics
<END_TASK>
<USER_TASK:>
Description:
def index_metrics(
config, start, end, incremental=False, concurrency=5, accounts=None,
period=3600, tag=None, index='policy-metrics', verbose=False):
"""index policy metrics""" |
logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('botocore').setLevel(logging.WARNING)
logging.getLogger('elasticsearch').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING)
logging.getLogger('requests').setLevel(logging.WARNING)
... |
<SYSTEM_TASK:>
make config revision look like describe output.
<END_TASK>
<USER_TASK:>
Description:
def transform_revision(self, revision):
"""make config revision look like describe output.""" |
config = self.manager.get_source('config')
return config.load_resource(revision) |
<SYSTEM_TASK:>
Add basic options ot the subparser.
<END_TASK>
<USER_TASK:>
Description:
def _default_options(p, blacklist=""):
""" Add basic options ot the subparser.
`blacklist` is a list of options to exclude from the default set.
e.g.: ['region', 'log-group']
""" |
provider = p.add_argument_group(
"provider", "AWS account information, defaults per the aws cli")
if 'region' not in blacklist:
provider.add_argument(
"-r", "--region", action='append', default=[],
dest='regions', metavar='REGION',
help="AWS Region to target... |
<SYSTEM_TASK:>
Add options specific to the report subcommand.
<END_TASK>
<USER_TASK:>
Description:
def _report_options(p):
""" Add options specific to the report subcommand. """ |
_default_options(p, blacklist=['cache', 'log-group', 'quiet'])
p.add_argument(
'--days', type=float, default=1,
help="Number of days of history to consider")
p.add_argument(
'--raw', type=argparse.FileType('wb'),
help="Store raw json of collected records to given file path")... |
<SYSTEM_TASK:>
Add options specific to metrics subcommand.
<END_TASK>
<USER_TASK:>
Description:
def _metrics_options(p):
""" Add options specific to metrics subcommand. """ |
_default_options(p, blacklist=['log-group', 'output-dir', 'cache', 'quiet'])
p.add_argument(
'--start', type=date_parse,
help='Start date (requires --end, overrides --days)')
p.add_argument(
'--end', type=date_parse, help='End date')
p.add_argument(
'--days', type=int, ... |
<SYSTEM_TASK:>
Add options specific to logs subcommand.
<END_TASK>
<USER_TASK:>
Description:
def _logs_options(p):
""" Add options specific to logs subcommand. """ |
_default_options(p, blacklist=['cache', 'quiet'])
# default time range is 0 to "now" (to include all log entries)
p.add_argument(
'--start',
default='the beginning', # invalid, will result in 0
help='Start date and/or time',
)
p.add_argument(
'--end',
defau... |
<SYSTEM_TASK:>
Add options specific to schema subcommand.
<END_TASK>
<USER_TASK:>
Description:
def _schema_options(p):
""" Add options specific to schema subcommand. """ |
p.add_argument(
'resource', metavar='selector', nargs='?',
default=None).completer = _schema_tab_completer
p.add_argument(
'--summary', action="store_true",
help="Summarize counts of available resources, actions and filters")
p.add_argument('--json', action="store_true", he... |
<SYSTEM_TASK:>
Type convert the csv record, modifies in place.
<END_TASK>
<USER_TASK:>
Description:
def process_user_record(cls, info):
"""Type convert the csv record, modifies in place.""" |
keys = list(info.keys())
# Value conversion
for k in keys:
v = info[k]
if v in ('N/A', 'no_information'):
info[k] = None
elif v == 'false':
info[k] = False
elif v == 'true':
info[k] = True
# ... |
<SYSTEM_TASK:>
Builds and returns a cloud API service object.
<END_TASK>
<USER_TASK:>
Description:
def _create_service_api(credentials, service_name, version, developer_key=None,
cache_discovery=False, http=None):
"""Builds and returns a cloud API service object.
Args:
credentia... |
# The default logging of the discovery obj is very noisy in recent versions.
# Lower the default logging level of just this module to WARNING unless
# debug is enabled.
if log.getEffectiveLevel() > logging.DEBUG:
logging.getLogger(discovery.__name__).setLevel(logging.WARNING)
discovery_kwa... |
<SYSTEM_TASK:>
Safely initialize a repository class to a property.
<END_TASK>
<USER_TASK:>
Description:
def client(self, service_name, version, component, **kw):
"""Safely initialize a repository class to a property.
Args:
repository_class (class): The class to initialize.
versi... |
service = _create_service_api(
self._credentials,
service_name,
version,
kw.get('developer_key'),
kw.get('cache_discovery', False),
self._http or _build_http())
return ServiceClient(
gcp_service=service,
co... |
<SYSTEM_TASK:>
Builds pagination-aware request object.
<END_TASK>
<USER_TASK:>
Description:
def _build_next_request(self, verb, prior_request, prior_response):
"""Builds pagination-aware request object.
More details:
https://developers.google.com/api-client-library/python/guide/pagination
... |
method = getattr(self._component, verb + '_next')
return method(prior_request, prior_response) |
<SYSTEM_TASK:>
Run execute with retries and rate limiting.
<END_TASK>
<USER_TASK:>
Description:
def _execute(self, request):
"""Run execute with retries and rate limiting.
Args:
request (object): The HttpRequest object to execute.
Returns:
dict: The response from the AP... |
if self._rate_limiter:
# Since the ratelimiter library only exposes a context manager
# interface the code has to be duplicated to handle the case where
# no rate limiter is defined.
with self._rate_limiter:
return request.execute(http=self.http,
... |
<SYSTEM_TASK:>
Check if a resource is locked.
<END_TASK>
<USER_TASK:>
Description:
def info(self, account_id, resource_id, parent_id):
"""Check if a resource is locked.
If a resource has an explicit status we use that, else
we defer to the parent resource lock status.
""" |
resource = self.record(account_id, resource_id)
if resource is None and not parent_id:
return {'ResourceId': resource_id,
'LockStatus': self.STATE_UNLOCKED}
elif resource is None:
parent = self.record(account_id, parent_id)
if parent is No... |
<SYSTEM_TASK:>
ENI flow stream processor that rollups, enhances,
<END_TASK>
<USER_TASK:>
Description:
def process_eni_metrics(
stream_eni, myips, stream,
start, end, period, sample_size,
resolver, sink_uri):
"""ENI flow stream processor that rollups, enhances,
and indexes the stream b... |
stats = Counter()
period_counters = flow_stream_stats(myips, stream, period)
client = InfluxDBClient.from_dsn(sink_uri)
resource = resolver.resolve_resource(stream_eni)
points = []
for period in sorted(period_counters):
pc = period_counters[period]
pd = datetime.fromtimestamp(p... |
<SYSTEM_TASK:>
publish the given function.
<END_TASK>
<USER_TASK:>
Description:
def publish(self, func):
"""publish the given function.""" |
project = self.session.get_default_project()
func_name = "projects/{}/locations/{}/functions/{}".format(
project, self.region, func.name)
func_info = self.get(func.name)
source_url = None
archive = func.get_archive()
if not func_info or self._delta_source(ar... |
<SYSTEM_TASK:>
Ensure the given identities are in the iam role bindings for the topic.
<END_TASK>
<USER_TASK:>
Description:
def ensure_iam(self, publisher=None):
"""Ensure the given identities are in the iam role bindings for the topic.
""" |
topic = self.get_topic_param()
client = self.session.client('pubsub', 'v1', 'projects.topics')
policy = client.execute_command('getIamPolicy', {'resource': topic})
policy.pop('etag')
found = False
for binding in policy.get('bindings', {}):
if binding['role'] ... |
<SYSTEM_TASK:>
Get the parent container for the log sink
<END_TASK>
<USER_TASK:>
Description:
def get_parent(self, log_info):
"""Get the parent container for the log sink""" |
if self.data.get('scope', 'log') == 'log':
if log_info.scope_type != 'projects':
raise ValueError("Invalid log subscriber scope")
parent = "%s/%s" % (log_info.scope_type, log_info.scope_id)
elif self.data['scope'] == 'project':
parent = 'projects/{}'.... |
<SYSTEM_TASK:>
Ensure the log sink and its pub sub topic exist.
<END_TASK>
<USER_TASK:>
Description:
def ensure_sink(self):
"""Ensure the log sink and its pub sub topic exist.""" |
topic_info = self.pubsub.ensure_topic()
scope, sink_path, sink_info = self.get_sink(topic_info)
client = self.session.client('logging', 'v2', '%s.sinks' % scope)
try:
sink = client.execute_command('get', {'sinkName': sink_path})
except HttpError as e:
if ... |
<SYSTEM_TASK:>
Remove any provisioned log sink if auto created
<END_TASK>
<USER_TASK:>
Description:
def remove(self, func):
"""Remove any provisioned log sink if auto created""" |
if not self.data['name'].startswith(self.prefix):
return
parent = self.get_parent(self.get_log())
_, sink_path, _ = self.get_sink()
client = self.session.client(
'logging', 'v2', '%s.sinks' % (parent.split('/', 1)[0]))
try:
client.execute_comm... |
<SYSTEM_TASK:>
Match a given cwe event as cloudtrail with an api call
<END_TASK>
<USER_TASK:>
Description:
def match(cls, event):
"""Match a given cwe event as cloudtrail with an api call
That has its information filled out.
""" |
if 'detail' not in event:
return False
if 'eventName' not in event['detail']:
return False
k = event['detail']['eventName']
# We want callers to use a compiled expression, but want to avoid
# initialization cost of doing it without cause. Not thread safe... |
<SYSTEM_TASK:>
extract resources ids from a cloud trail event.
<END_TASK>
<USER_TASK:>
Description:
def get_trail_ids(cls, event, mode):
"""extract resources ids from a cloud trail event.""" |
resource_ids = ()
event_name = event['detail']['eventName']
event_source = event['detail']['eventSource']
for e in mode.get('events', []):
if not isinstance(e, dict):
# Check if we have a short cut / alias
info = CloudWatchEvents.match(event)
... |
<SYSTEM_TASK:>
Generate a c7n-org accounts config file using AWS Organizations
<END_TASK>
<USER_TASK:>
Description:
def main(role, ou, assume, profile, output, regions, active):
"""Generate a c7n-org accounts config file using AWS Organizations
With c7n-org you can then run policies or arbitrary scripts across... |
session = get_session(assume, 'c7n-org', profile)
client = session.client('organizations')
accounts = []
for path in ou:
ou = get_ou_from_path(client, path)
accounts.extend(get_accounts_for_ou(client, ou, active))
results = []
for a in accounts:
tags = []
path_... |
<SYSTEM_TASK:>
time series lastest record time by account.
<END_TASK>
<USER_TASK:>
Description:
def status(config):
"""time series lastest record time by account.""" |
with open(config) as fh:
config = yaml.safe_load(fh.read())
jsonschema.validate(config, CONFIG_SCHEMA)
last_index = get_incremental_starts(config, None)
accounts = {}
for (a, region), last in last_index.items():
accounts.setdefault(a, {})[region] = last
print(yaml.safe_dump(acco... |
<SYSTEM_TASK:>
Generator that returns the events
<END_TASK>
<USER_TASK:>
Description:
def fetch_events(cursor, config, account_name):
"""Generator that returns the events""" |
query = config['indexer'].get('query',
'select * from events where user_agent glob \'*CloudCustodian*\'')
for event in cursor.execute(query):
event['account'] = account_name
event['_index'] = config['indexer']['idx_name']
event['_type'] = config['indexer'].get('idx_type', 'trai... |
<SYSTEM_TASK:>
Creates a session using available authentication type.
<END_TASK>
<USER_TASK:>
Description:
def _initialize_session(self):
"""
Creates a session using available authentication type.
Auth priority:
1. Token Auth
2. Tenant Auth
3. Azure CLI Auth
""" |
# Only run once
if self.credentials is not None:
return
tenant_auth_variables = [
constants.ENV_TENANT_ID, constants.ENV_SUB_ID,
constants.ENV_CLIENT_ID, constants.ENV_CLIENT_SECRET
]
token_auth_variables = [
constants.ENV_ACCES... |
<SYSTEM_TASK:>
Build auth json string for deploying
<END_TASK>
<USER_TASK:>
Description:
def get_functions_auth_string(self, target_subscription_id):
"""
Build auth json string for deploying
Azure Functions. Look for dedicated
Functions environment variables or
fall back to norm... |
self._initialize_session()
function_auth_variables = [
constants.ENV_FUNCTION_TENANT_ID,
constants.ENV_FUNCTION_CLIENT_ID,
constants.ENV_FUNCTION_CLIENT_SECRET
]
# Use dedicated function env vars if available
if all(k in os.environ for k in... |
<SYSTEM_TASK:>
Create an api gw response from a wsgi app and environ.
<END_TASK>
<USER_TASK:>
Description:
def create_gw_response(app, wsgi_env):
"""Create an api gw response from a wsgi app and environ.
""" |
response = {}
buf = []
result = []
def start_response(status, headers, exc_info=None):
result[:] = [status, headers]
return buf.append
appr = app(wsgi_env, start_response)
close_func = getattr(appr, 'close', None)
try:
buf.extend(list(appr))
finally:
cl... |
<SYSTEM_TASK:>
Create a wsgi environment from an apigw request.
<END_TASK>
<USER_TASK:>
Description:
def create_wsgi_request(event, server_name='apigw'):
"""Create a wsgi environment from an apigw request.
""" |
path = urllib.url2pathname(event['path'])
script_name = (
event['headers']['Host'].endswith('.amazonaws.com') and
event['requestContext']['stage'] or '').encode('utf8')
query = event['queryStringParameters']
query_string = query and urllib.urlencode(query) or ""
body = event['body']... |
<SYSTEM_TASK:>
Retrieve logs from a log group.
<END_TASK>
<USER_TASK:>
Description:
def retrieve_logs(self, include_lambda_messages=True, max_entries=None):
# type: (bool, Optional[int]) -> Iterator[Dict[str, Any]]
"""Retrieve logs from a log group.
:type include_lambda_messages: boolean
... |
# TODO: Add support for startTime/endTime.
shown = 0
for event in self._client.iter_log_events(self._log_group_name,
interleaved=True):
if not include_lambda_messages and \
self._is_lambda_message(event):
... |
<SYSTEM_TASK:>
Validate app configuration.
<END_TASK>
<USER_TASK:>
Description:
def validate_configuration(config):
# type: (Config) -> None
"""Validate app configuration.
The purpose of this method is to provide a fail fast mechanism
for anything we know is going to fail deployment.
We can detect ... |
routes = config.chalice_app.routes
validate_routes(routes)
validate_route_content_types(routes, config.chalice_app.api.binary_types)
_validate_manage_iam_role(config)
validate_python_version(config)
validate_unique_function_names(config)
validate_feature_flags(config.chalice_app) |
<SYSTEM_TASK:>
Validate configuration matches a specific python version.
<END_TASK>
<USER_TASK:>
Description:
def validate_python_version(config, actual_py_version=None):
# type: (Config, Optional[str]) -> None
"""Validate configuration matches a specific python version.
If the ``actual_py_version`` is not... |
lambda_version = config.lambda_python_version
if actual_py_version is None:
actual_py_version = 'python%s.%s' % sys.version_info[:2]
if actual_py_version != lambda_version:
# We're not making this a hard error for now, but we may
# turn this into a hard fail.
warnings.warn("... |
<SYSTEM_TASK:>
Execute a pip command with the given arguments.
<END_TASK>
<USER_TASK:>
Description:
def _execute(self,
command, # type: str
args, # type: List[str]
env_vars=None, # type: EnvVars
shim=None # type: OptStr
... |
main_args = [command] + args
logger.debug("calling pip %s", ' '.join(main_args))
rc, out, err = self._wrapped_pip.main(main_args, env_vars=env_vars,
shim=shim)
return rc, out, err |
<SYSTEM_TASK:>
Build an sdist into a wheel file.
<END_TASK>
<USER_TASK:>
Description:
def build_wheel(self, wheel, directory, compile_c=True):
# type: (str, str, bool) -> None
"""Build an sdist into a wheel file.""" |
arguments = ['--no-deps', '--wheel-dir', directory, wheel]
env_vars = self._osutils.environ()
shim = ''
if not compile_c:
env_vars.update(pip_no_compile_c_env_vars)
shim = pip_no_compile_c_shim
# Ignore rc and stderr from this command since building the w... |
<SYSTEM_TASK:>
Download all dependencies as sdist or wheel.
<END_TASK>
<USER_TASK:>
Description:
def download_all_dependencies(self, requirements_filename, directory):
# type: (str, str) -> None
"""Download all dependencies as sdist or wheel.""" |
arguments = ['-r', requirements_filename, '--dest', directory]
rc, out, err = self._execute('download', arguments)
# When downloading all dependencies we expect to get an rc of 0 back
# since we are casting a wide net here letting pip have options about
# what to download. If a ... |
<SYSTEM_TASK:>
Download wheel files for manylinux for all the given packages.
<END_TASK>
<USER_TASK:>
Description:
def download_manylinux_wheels(self, abi, packages, directory):
# type: (str, List[str], str) -> None
"""Download wheel files for manylinux for all the given packages.""" |
# If any one of these dependencies fails pip will bail out. Since we
# are only interested in all the ones we can download, we need to feed
# each package to pip individually. The return code of pip doesn't
# matter here since we will inspect the working directory to see which
#... |
<SYSTEM_TASK:>
Transform a name to a valid cfn name.
<END_TASK>
<USER_TASK:>
Description:
def to_cfn_resource_name(name):
# type: (str) -> str
"""Transform a name to a valid cfn name.
This will convert the provided name to a CamelCase name.
It's possible that the conversion to a CFN resource name
c... |
if not name:
raise ValueError("Invalid name: %r" % name)
word_separators = ['-', '_']
for word_separator in word_separators:
word_parts = [p for p in name.split(word_separator) if p]
name = ''.join([w[0].upper() + w[1:] for w in word_parts])
return re.sub(r'[^A-Za-z0-9]+', '', n... |
<SYSTEM_TASK:>
Delete a top level key from the deployed JSON file.
<END_TASK>
<USER_TASK:>
Description:
def remove_stage_from_deployed_values(key, filename):
# type: (str, str) -> None
"""Delete a top level key from the deployed JSON file.""" |
final_values = {} # type: Dict[str, Any]
try:
with open(filename, 'r') as f:
final_values = json.load(f)
except IOError:
# If there is no file to delete from, then this funciton is a noop.
return
try:
del final_values[key]
with open(filename, 'wb') ... |
<SYSTEM_TASK:>
Record deployed values to a JSON file.
<END_TASK>
<USER_TASK:>
Description:
def record_deployed_values(deployed_values, filename):
# type: (Dict[str, Any], str) -> None
"""Record deployed values to a JSON file.
This allows subsequent deploys to lookup previously deployed values.
""" |
final_values = {} # type: Dict[str, Any]
if os.path.isfile(filename):
with open(filename, 'r') as f:
final_values = json.load(f)
final_values.update(deployed_values)
with open(filename, 'wb') as f:
data = serialize_to_json(final_values)
f.write(data.encode('utf-8')) |
<SYSTEM_TASK:>
Create a zip file from a source input directory.
<END_TASK>
<USER_TASK:>
Description:
def create_zip_file(source_dir, outfile):
# type: (str, str) -> None
"""Create a zip file from a source input directory.
This function is intended to be an equivalent to
`zip -r`. You give it a source ... |
with zipfile.ZipFile(outfile, 'w',
compression=zipfile.ZIP_DEFLATED) as z:
for root, _, filenames in os.walk(source_dir):
for filename in filenames:
full_name = os.path.join(root, filename)
archive_name = os.path.relpath(full_name, source... |
<SYSTEM_TASK:>
Update a Lambda function's code and configuration.
<END_TASK>
<USER_TASK:>
Description:
def update_function(self,
function_name, # type: str
zip_contents, # type: str
environment_variables=None, # type: ... |
return_value = self._update_function_code(function_name=function_name,
zip_contents=zip_contents)
self._update_function_config(
environment_variables=environment_variables,
runtime=runtime,
timeout=timeout,
... |
<SYSTEM_TASK:>
Delete a role by first deleting all inline policies.
<END_TASK>
<USER_TASK:>
Description:
def delete_role(self, name):
# type: (str) -> None
"""Delete a role by first deleting all inline policies.""" |
client = self._client('iam')
inline_policies = client.list_role_policies(
RoleName=name
)['PolicyNames']
for policy_name in inline_policies:
self.delete_role_policy(name, policy_name)
client.delete_role(RoleName=name) |
<SYSTEM_TASK:>
Get rest api id associated with an API name.
<END_TASK>
<USER_TASK:>
Description:
def get_rest_api_id(self, name):
# type: (str) -> Optional[str]
"""Get rest api id associated with an API name.
:type name: str
:param name: The name of the rest api.
:rtype: str
... |
rest_apis = self._client('apigateway').get_rest_apis()['items']
for api in rest_apis:
if api['name'] == name:
return api['id']
return None |
<SYSTEM_TASK:>
Authorize API gateway to invoke a lambda function is needed.
<END_TASK>
<USER_TASK:>
Description:
def add_permission_for_apigateway(self, function_name,
region_name, account_id,
rest_api_id, random_id=None):
# type: (str,... |
source_arn = self._build_source_arn_str(region_name, account_id,
rest_api_id)
self._add_lambda_permission_if_needed(
source_arn=source_arn,
function_arn=function_name,
service_name='apigateway',
) |
<SYSTEM_TASK:>
Return the function policy for a lambda function.
<END_TASK>
<USER_TASK:>
Description:
def get_function_policy(self, function_name):
# type: (str) -> Dict[str, Any]
"""Return the function policy for a lambda function.
This function will extract the policy string as a json documen... |
client = self._client('lambda')
try:
policy = client.get_policy(FunctionName=function_name)
return json.loads(policy['Policy'])
except client.exceptions.ResourceNotFoundException:
return {'Statement': []} |
<SYSTEM_TASK:>
Download an SDK to a directory.
<END_TASK>
<USER_TASK:>
Description:
def download_sdk(self, rest_api_id, output_dir,
api_gateway_stage=DEFAULT_STAGE_NAME,
sdk_type='javascript'):
# type: (str, str, str, str) -> None
"""Download an SDK to a directo... |
zip_stream = self.get_sdk_download_stream(
rest_api_id, api_gateway_stage=api_gateway_stage,
sdk_type=sdk_type)
tmpdir = tempfile.mkdtemp()
with open(os.path.join(tmpdir, 'sdk.zip'), 'wb') as f:
f.write(zip_stream.read())
tmp_extract = os.path.join(tm... |
<SYSTEM_TASK:>
Generate an SDK for a given SDK.
<END_TASK>
<USER_TASK:>
Description:
def get_sdk_download_stream(self, rest_api_id,
api_gateway_stage=DEFAULT_STAGE_NAME,
sdk_type='javascript'):
# type: (str, str, str) -> file
"""Generate an... |
response = self._client('apigateway').get_sdk(
restApiId=rest_api_id, stageName=api_gateway_stage,
sdkType=sdk_type)
return response['body'] |
<SYSTEM_TASK:>
Verify a subscription arn matches the topic and function name.
<END_TASK>
<USER_TASK:>
Description:
def verify_sns_subscription_current(self, subscription_arn, topic_name,
function_arn):
# type: (str, str, str) -> bool
"""Verify a subscription arn m... |
sns_client = self._client('sns')
try:
attributes = sns_client.get_subscription_attributes(
SubscriptionArn=subscription_arn)['Attributes']
return (
# Splitting on ':' is safe because topic names can't have
# a ':' char.
... |
<SYSTEM_TASK:>
Configure S3 bucket to invoke a lambda function.
<END_TASK>
<USER_TASK:>
Description:
def connect_s3_bucket_to_lambda(self, bucket, function_arn, events,
prefix=None, suffix=None):
# type: (str, str, List[str], OptStr, OptStr) -> None
"""Configure S3 bu... |
s3 = self._client('s3')
existing_config = s3.get_bucket_notification_configuration(
Bucket=bucket)
# Because we're going to PUT this config back to S3, we need
# to remove `ResponseMetadata` because that's added in botocore
# and isn't a param of the put_bucket_notif... |
<SYSTEM_TASK:>
Check if the uuid matches the resource and function arn provided.
<END_TASK>
<USER_TASK:>
Description:
def verify_event_source_current(self, event_uuid, resource_name,
service_name, function_arn):
# type: (str, str, str, str) -> bool
"""Check if the uui... |
client = self._client('lambda')
try:
attributes = client.get_event_source_mapping(UUID=event_uuid)
actual_arn = attributes['EventSourceArn']
arn_start, actual_name = actual_arn.rsplit(':', 1)
return (
actual_name == resource_name and
... |
<SYSTEM_TASK:>
Load the chalice config file from the project directory.
<END_TASK>
<USER_TASK:>
Description:
def load_project_config(self):
# type: () -> Dict[str, Any]
"""Load the chalice config file from the project directory.
:raise: OSError/IOError if unable to load the config file.
... |
config_file = os.path.join(self.project_dir, '.chalice', 'config.json')
with open(config_file) as f:
return json.loads(f.read()) |
<SYSTEM_TASK:>
Generate a cloudformation template for a starter CD pipeline.
<END_TASK>
<USER_TASK:>
Description:
def generate_pipeline(ctx, codebuild_image, source, buildspec_file, filename):
# type: (click.Context, str, str, str, str) -> None
"""Generate a cloudformation template for a starter CD pipeline.
... |
from chalice import pipeline
factory = ctx.obj['factory'] # type: CLIFactory
config = factory.create_config_obj()
p = pipeline.CreatePipelineTemplate()
params = pipeline.PipelineParameters(
app_name=config.app_name,
lambda_python_version=config.lambda_python_version,
codebu... |
<SYSTEM_TASK:>
Return resources associated with a given stage.
<END_TASK>
<USER_TASK:>
Description:
def deployed_resources(self, chalice_stage_name):
# type: (str) -> DeployedResources
"""Return resources associated with a given stage.
If a deployment to a given stage has never happened,
... |
# This is arguably the wrong level of abstraction.
# We might be able to move this elsewhere.
deployed_file = os.path.join(
self.project_dir, '.chalice', 'deployed',
'%s.json' % chalice_stage_name)
data = self._load_json_file(deployed_file)
if data is not... |
<SYSTEM_TASK:>
Auto generate policy for an application.
<END_TASK>
<USER_TASK:>
Description:
def generate_policy(self, config):
# type: (Config) -> Dict[str, Any]
"""Auto generate policy for an application.""" |
# Admittedly, this is pretty bare bones logic for the time
# being. All it really does it work out, given a Config instance,
# which files need to analyzed and then delegates to the
# appropriately analyzer functions to do the real work.
# This may change in the future.
... |
<SYSTEM_TASK:>
Return all clients calls made in provided source code.
<END_TASK>
<USER_TASK:>
Description:
def get_client_calls(source_code):
# type: (str) -> APICallT
"""Return all clients calls made in provided source code.
:returns: A dict of service_name -> set([client calls]).
Example: {"s3": ... |
parsed = parse_code(source_code)
t = SymbolTableTypeInfer(parsed)
binder = t.bind_types()
collector = APICallCollector(binder)
api_calls = collector.collect_api_calls(parsed.parsed_ast)
return api_calls |
<SYSTEM_TASK:>
Return client calls for a chalice app.
<END_TASK>
<USER_TASK:>
Description:
def get_client_calls_for_app(source_code):
# type: (str) -> APICallT
"""Return client calls for a chalice app.
This is similar to ``get_client_calls`` except it will
automatically traverse into chalice views with... |
parsed = parse_code(source_code)
parsed.parsed_ast = AppViewTransformer().visit(parsed.parsed_ast)
ast.fix_missing_locations(parsed.parsed_ast)
t = SymbolTableTypeInfer(parsed)
binder = t.bind_types()
collector = APICallCollector(binder)
api_calls = collector.collect_api_calls(parsed.parsed... |
<SYSTEM_TASK:>
Match the url against known routes.
<END_TASK>
<USER_TASK:>
Description:
def match_route(self, url):
# type: (str) -> MatchResult
"""Match the url against known routes.
This method takes a concrete route "/foo/bar", and
matches it against a set of routes. These routes ca... |
# Otherwise we need to check for param substitution
parsed_url = urlparse(url)
parsed_qs = parse_qs(parsed_url.query, keep_blank_values=True)
query_params = {k: v[-1] for k, v in parsed_qs.items()}
path = parsed_url.path
# API Gateway removes the trailing slash if the ro... |
<SYSTEM_TASK:>
Translate event for an authorizer input.
<END_TASK>
<USER_TASK:>
Description:
def _prepare_authorizer_event(self, arn, lambda_event, lambda_context):
# type: (str, EventType, LambdaContext) -> EventType
"""Translate event for an authorizer input.""" |
authorizer_event = lambda_event.copy()
authorizer_event['type'] = 'TOKEN'
try:
authorizer_event['authorizationToken'] = authorizer_event.get(
'headers', {})['authorization']
except KeyError:
raise NotAuthorizedError(
{'x-amzn-Reque... |
<SYSTEM_TASK:>
Estimate the frequency of the baseband signal using FFT
<END_TASK>
<USER_TASK:>
Description:
def estimate_frequency(self, start: int, end: int, sample_rate: float):
"""
Estimate the frequency of the baseband signal using FFT
:param start: Start of the area that shall be investiga... |
# ensure power of 2 for faster fft
length = 2 ** int(math.log2(end - start))
data = self.data[start:start + length]
try:
w = np.fft.fft(data)
frequencies = np.fft.fftfreq(len(w))
idx = np.argmax(np.abs(w))
freq = frequencies[idx]
... |
<SYSTEM_TASK:>
Build the order of component based on their priority and predecessors
<END_TASK>
<USER_TASK:>
Description:
def build_component_order(self):
"""
Build the order of component based on their priority and predecessors
:rtype: list of Component
""" |
present_components = [item for item in self.__dict__.values() if isinstance(item, Component) and item.enabled]
result = [None] * len(present_components)
used_prios = set()
for component in present_components:
index = component.priority % len(present_components)
i... |
<SYSTEM_TASK:>
This method clusters some bitvectors based on their length. An example output is
<END_TASK>
<USER_TASK:>
Description:
def cluster_lengths(self):
"""
This method clusters some bitvectors based on their length. An example output is
2: [0.5, 1]
4: [1, 0.75, 1, 1]
Me... |
number_ones = dict() # dict of tuple. 0 = number ones vector, 1 = number of blocks for this vector
for vector in self.bitvectors:
vec_len = 4 * (len(vector) // 4)
if vec_len == 0:
continue
if vec_len not in number_ones:
number_ones[... |
<SYSTEM_TASK:>
Find candidate addresses using LCS algorithm
<END_TASK>
<USER_TASK:>
Description:
def find_candidates(candidates):
"""
Find candidate addresses using LCS algorithm
perform a scoring based on how often a candidate appears in a longer candidate
Input is something like
... |
result = defaultdict(int)
for i, c_i in enumerate(candidates):
for j in range(i, len(candidates)):
lcs = util.longest_common_substring(c_i.hex_value, candidates[j].hex_value)
if lcs:
result[lcs] += 1
return result |
<SYSTEM_TASK:>
Choose a pair of address candidates ensuring they have the same length and starting with the highest scored ones
<END_TASK>
<USER_TASK:>
Description:
def choose_candidate_pair(candidates):
"""
Choose a pair of address candidates ensuring they have the same length and starting with the hig... |
highscored = sorted(candidates, key=candidates.get, reverse=True)
for i, h_i in enumerate(highscored):
for h_j in highscored[i+1:]:
if len(h_i) == len(h_j):
yield (h_i, h_j) |
<SYSTEM_TASK:>
continuous haar wavelet transform based on the paper
<END_TASK>
<USER_TASK:>
Description:
def cwt_haar(x: np.ndarray, scale=10):
"""
continuous haar wavelet transform based on the paper
"A practical guide to wavelet analysis" by Christopher Torrence and Gilbert P Compo
""" |
next_power_two = 2 ** int(np.log2(len(x)))
x = x[0:next_power_two]
num_data = len(x)
# get FFT of x (eq. (3) in paper)
x_hat = np.fft.fft(x)
# Get omega (eq. (5) in paper)
f = (2.0 * np.pi / num_data)
omega = f * np.concatenate((np.arange(0, num_data // 2), np.arange(num_data // 2, n... |
<SYSTEM_TASK:>
Finding the synchronization works by finding the first difference between two messages.
<END_TASK>
<USER_TASK:>
Description:
def __find_sync_range(self, messages, preamble_end: int, search_end: int):
"""
Finding the synchronization works by finding the first difference between two message... |
possible_sync_pos = defaultdict(int)
for i, msg in enumerate(messages):
bits_i = msg.decoded_bits[preamble_end:search_end]
for j in range(i, len(messages)):
bits_j = messages[j].decoded_bits[preamble_end:search_end]
first_diff = next((k for k, ... |
<SYSTEM_TASK:>
Search all differences between protocol messages regarding a reference message
<END_TASK>
<USER_TASK:>
Description:
def find_differences(self, refindex: int):
"""
Search all differences between protocol messages regarding a reference message
:param refindex: index of reference me... |
differences = defaultdict(set)
if refindex >= len(self.protocol.messages):
return differences
if self.proto_view == 0:
proto = self.protocol.decoded_proto_bits_str
elif self.proto_view == 1:
proto = self.protocol.decoded_hex_str
elif self.pr... |
<SYSTEM_TASK:>
Return true if redraw is needed
<END_TASK>
<USER_TASK:>
Description:
def set_parameters(self, samples: np.ndarray, window_size, data_min, data_max) -> bool:
"""
Return true if redraw is needed
""" |
redraw_needed = False
if self.samples_need_update:
self.spectrogram.samples = samples
redraw_needed = True
self.samples_need_update = False
if window_size != self.spectrogram.window_size:
self.spectrogram.window_size = window_size
red... |
<SYSTEM_TASK:>
Return the length of this message in byte.
<END_TASK>
<USER_TASK:>
Description:
def get_byte_length(self, decoded=True) -> int:
"""
Return the length of this message in byte.
""" |
end = len(self.decoded_bits) if decoded else len(self.__plain_bits)
end = self.convert_index(end, 0, 2, decoded=decoded)[0]
return int(end) |
<SYSTEM_TASK:>
Return the SRC address of a message if SRC_ADDRESS label is present in message type of the message
<END_TASK>
<USER_TASK:>
Description:
def get_src_address_from_data(self, decoded=True):
"""
Return the SRC address of a message if SRC_ADDRESS label is present in message type of the message... |
src_address_label = next((lbl for lbl in self.message_type if lbl.field_type
and lbl.field_type.function == FieldType.Function.SRC_ADDRESS), None)
if src_address_label:
start, end = self.get_label_range(src_address_label, view=1, decode=decoded)
... |
<SYSTEM_TASK:>
Set all protocols in copy mode. They will return a copy of their protocol.
<END_TASK>
<USER_TASK:>
Description:
def set_copy_mode(self, use_copy: bool):
"""
Set all protocols in copy mode. They will return a copy of their protocol.
This is used for writable mode in CFC.
:... |
for group in self.rootItem.children:
for proto in group.children:
proto.copy_data = use_copy |
<SYSTEM_TASK:>
Push values to buffer. If buffer can't store all values a ValueError is raised
<END_TASK>
<USER_TASK:>
Description:
def push(self, values: np.ndarray):
"""
Push values to buffer. If buffer can't store all values a ValueError is raised
""" |
n = len(values)
if len(self) + n > self.size:
raise ValueError("Too much data to push to RingBuffer")
slide_1 = np.s_[self.right_index:min(self.right_index + n, self.size)]
slide_2 = np.s_[:max(self.right_index + n - self.size, 0)]
with self.__data.get_lock():
... |
<SYSTEM_TASK:>
Pop number of elements. If there are not enough elements, all remaining elements are returned and the
<END_TASK>
<USER_TASK:>
Description:
def pop(self, number: int, ensure_even_length=False):
"""
Pop number of elements. If there are not enough elements, all remaining elements are returne... |
if ensure_even_length:
number -= number % 2
if len(self) == 0 or number == 0:
return np.array([], dtype=np.complex64)
if number < 0:
# take everything
number = len(self)
else:
number = min(number, len(self))
with sel... |
<SYSTEM_TASK:>
Scrolls the mouse if ROI Selection reaches corner of view
<END_TASK>
<USER_TASK:>
Description:
def scroll_mouse(self, mouse_x: int):
"""
Scrolls the mouse if ROI Selection reaches corner of view
:param mouse_x:
:return:
""" |
scrollbar = self.horizontalScrollBar()
if mouse_x - self.view_rect().x() > self.view_rect().width():
scrollbar.setValue(scrollbar.value() + 5)
elif mouse_x < self.view_rect().x():
scrollbar.setValue(scrollbar.value() - 5) |
<SYSTEM_TASK:>
Return the boundaries of the view in scene coordinates
<END_TASK>
<USER_TASK:>
Description:
def view_rect(self) -> QRectF:
"""
Return the boundaries of the view in scene coordinates
""" |
top_left = self.mapToScene(0, 0)
bottom_right = self.mapToScene(self.viewport().width() - 1, self.viewport().height() - 1)
return QRectF(top_left, bottom_right) |
<SYSTEM_TASK:>
get start and end index of bit sequence from selected samples
<END_TASK>
<USER_TASK:>
Description:
def get_bitseq_from_selection(self, selection_start: int, selection_width: int):
"""
get start and end index of bit sequence from selected samples
:rtype: tuple[int,int,int,int]
... |
start_message, start_index, end_message, end_index = -1, -1, -1, -1
if not self.messages or not self.messages[0].bit_sample_pos:
return start_message, start_index, end_message, end_index
if selection_start + selection_width < self.messages[0].bit_sample_pos[0]:
return s... |
<SYSTEM_TASK:>
Calculates the frequency of at most nbits logical ones and returns the mean of these frequencies
<END_TASK>
<USER_TASK:>
Description:
def estimate_frequency_for_one(self, sample_rate: float, nbits=42) -> float:
"""
Calculates the frequency of at most nbits logical ones and returns the mea... |
return self.__estimate_frequency_for_bit(True, sample_rate, nbits) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.