output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def generate_secret(length=32):
"""
Generate a random secret consisting of mixed-case letters and numbers
Args:
length (int): Length of the generated password
Returns:
a randomly generated secret string
Raises:
None
"""
alphabet = string.ascii_letters + string.digits
random_bytes = os.... | Write a Python 3 function that can
generate a random secret consisting of mixed - case letters and numbers | You are a Python code generator, capable of creating scripts from specifications. |
Generates a file with the secrets encrypted in KMS
| How would you explain what the following Python 3 function does
def generate_secret_file(file_path, pattern, service, environment, clients):
changed = False
with open(file_path) as json_file:
data = json.load(json_file, object_pairs_hook=OrderedDict)
try:
for key, value in data["params"][environment].... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Handles command line arguments and sets the EFPWContext object. | Make a summary of the following Python 3 code
def handle_args_and_set_context(args):
parser = argparse.ArgumentParser()
parser.add_argument("service", help="name of service password is being generated for")
parser.add_argument("env", help=", ".join(EFConfig.ENV_LIST))
group = parser.add_mutually_exclusive_group... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function tiles the input tensor into 2D. | Given the following Python 3 function, write the documentation
def tile_2d(input, k_x, k_y, name, reorder_required=True):
size = input.get_shape().as_list()
c, h, w = size[3], size[1], size[2]
batch_size = size[0]
if batch_size is None:
batch_size = -1
# Check if tiling is possible and defi... | You are a Python code architect, reviewing and designing scalable and efficient code |
An inverse tiling layer.
An inverse to the tiling layer can be of great use, since you can keep the resolution of your output low,
but harness the benefits of the resolution of a higher level feature layer.
If you insist on a source you can call it very lightly inspired by yolo9000 "passthrough... | Given the following Python 3 function, write the documentation
def inverse_tile_2d(input, k_x, k_y, name):
batch_size, h, w, c = input.get_shape().as_list()
if batch_size is None:
batch_size = -1
# Check if tiling is possible and define output shape.
assert w % k_x == 0 and h % k_y == 0
#... | You are a Python code generator, capable of creating scripts from specifications. |
A feature passthrough layer inspired by yolo9000 and the inverse tiling layer. | Explain what the following Python 3 code does
def feature_passthrough(early_feat, late_feat, filters, name, kernel_size=(1, 1)):
_, h_early, w_early, c_early = early_feat.get_shape().as_list()
_, h_late, w_late, c_late = late_feat.get_shape().as_list()
s_x = int(w_early / w_late)
s_y = int(h_early / h_... | You are a Python code analyst, evaluating scripts for potential improvements. |
A layer that can be used to upsampling a feature passthrough. | Can you tell what is the following Python 3 function doing
def upsampling_feature_passthrough(early_feat, late_feat, filters, name, kernel_size=(1, 1)):
_, h_early, w_early, c_early = early_feat.get_shape().as_list()
_, h_late, w_late, c_late = late_feat.get_shape().as_list()
s_x = int(w_early / w_late)
... | As a Python code composer, you craft elegant and concise scripts. |
def load(self):
"""Loads the config"""
try:
with open(self._ef_site_config, 'r') as yml_file:
return yaml.safe_load(yml_file)
except (IOError, yaml.parser.ParserError) as error:
print("Error: {}".format(error), file=sys.stderr)
sys.exit(1) | Create a Python 3 function to
load the config file | You are a Python code analyst, evaluating scripts for potential improvements. |
Interpolate two losses linearly. | Given the following Python 3 function, write the documentation
def interpolate_loss(labels, loss1, loss2, interpolation_values):
with tf.variable_scope("interpolate_focus_loss"):
# Select the probs or weights with the labels.
t = tf.reduce_sum(labels * interpolation_values, axis=-1)
return (... | You are a Python code generator, capable of creating scripts from specifications. |
Calculates the alpha balanced cross entropy. | Can you generate a brief explanation for the following Python 3 code
def alpha_balance_loss(labels, loss, alpha_weights):
with tf.variable_scope("alpha_balance"):
# Broadcast multiply labels with alpha weights to select weights and then reduce them along last axis.
weights = tf.reduce_sum(labels * a... | You are a Python code analyst, evaluating scripts for potential improvements. |
def batch_alpha_balance_loss(labels, loss):
"""
Calculate the alpha balanced cross_entropy.
This means for each sample the cross entropy is calculated and then weighted by the class specific weight.
There is yet no paper for this type of loss.
:param labels: A float tensor of shape [batch_size, .... | Write a Python 3 function for
calculating the alpha balanced cross entropy. | You are a Python code architect, reviewing and designing scalable and efficient code |
Mask a loss by using a tensor filled with 0 or 1. | Given the following Python 3 function, write the documentation
def mask_loss(input_tensor, binary_tensor):
with tf.variable_scope("mask_loss"):
mask = tf.cast(tf.cast(binary_tensor, tf.bool), tf.float32)
return input_tensor * mask | As a Python code translator, you convert algorithms and pseudocode into Python. |
def mean_on_masked(loss, mask, epsilon=1e-8, axis=None):
"""
Average a loss correctly when it was masked.
:param loss: A float tensor of shape [batch_size, ...] representing the (already masked) loss to be averaged.
:param mask: A float tensor of shape [batch_size, ...] representing the mask.
:para... | How would you code a function in Python 3 to
average a loss correctly when it was masked. | You are a Python code generator, capable of creating scripts from specifications. |
def mask_and_mean_loss(input_tensor, binary_tensor, axis=None):
"""
Mask a loss by using a tensor filled with 0 or 1 and average correctly.
:param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy
:param binary_tensor: A float tensor of shape [batch_size, ...] ... | Write a Python 3 function that can
mask a loss by using a tensor filled with 0 or 1 and average correctly. | As a Python code analyst, you investigate and solve complex coding mysteries |
Creates a variance corrected loss. | Make a summary of the following Python 3 code
def variance_corrected_loss(loss, sigma_2=None):
with tf.variable_scope("variance_corrected_loss"):
sigma_cost = 0
if sigma_2 is None:
# FIXME the paper has been updated Apr 2018, check if implementation is still valid.
sigma = tf... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def multiloss(losses, logging_namespace="multiloss", exclude_from_weighting=[]):
"""
Create a loss from multiple losses my mixing them.
This multi-loss implementation is inspired by the Paper "Multi-Task Learning Using Uncertainty to Weight Losses
for Scene Geometry and Semantics" by Kendall, Gal and Ci... | Implement a function in Python 3 to
create a loss from multiple losses. | As a Python code composer, you craft elegant and concise scripts. |
Calculate the alpha balanced focal loss. | How would you explain what the following Python 3 function does
def focus_loss(labels, probs, loss, gamma):
with tf.variable_scope("focus_loss"):
# Compute p_t that is used in paper.
# FIXME is it possible that the 1-p term does not make any sense?
p_t = tf.reduce_sum(probs * labels, axis=-1... | You are a Python code generator, capable of creating scripts from specifications. |
Decorator for composable network layers. | Can you generate the documentation for the following Python 3 function
def layer(op):
'''Decorator for composable network layers.'''
def layer_decorated(self, *args, **kwargs):
# Automatically set a name if not provided.
name = kwargs.setdefault('name', self.get_unique_name(op.__name__))
... | As a python code expert, you are capable of creating scripts from specifications. |
def _load(self, data_path, ignore_missing=False):
'''Load network weights.
data_path: The path to the numpy-serialized network weights
session: The current TensorFlow session
ignore_missing: If true, serialized weights for missing layers are ignored.
'''
if data_path.ends... | Write a Python 3 function that can
load the network weights. | You are a Python code architect, reviewing and designing scalable and efficient code |
Set the input for the next operation by replacing the terminal nodes. | Explain what the following Python 3 code does
def feed(self, *args):
'''Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers.
'''
assert len(args) != 0
self.terminals = []
for fed_layer in ar... | As a Python code composer, you craft elegant and concise scripts. |
Returns an index - suffixed unique name for the given prefix. | Can you generate a brief explanation for the following Python 3 code
def get_unique_name(self, prefix):
'''Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix.
'''
ident = sum(t.startswith(prefix) for t, _ in s... | As a python code expert, you are capable of creating scripts from specifications. |
Creates a new TensorFlow variable. | Here you have a function in Python 3, explain what it does
def make_var(self, op_name, name, shape):
'''Creates a new TensorFlow variable.'''
if op_name in self.weights and name in self.weights[op_name]:
if self.verbose:
print("Using: {} {}".format(op_name, name))
... | As a python code expert, you are capable of creating scripts from specifications. |
Converts a tf. estimator. ModeKeys in a nice readable string. | Given the following Python 3 function, write the documentation
def mode_to_str(mode):
if mode == tf.estimator.ModeKeys.TRAIN:
return "train"
if mode == tf.estimator.ModeKeys.EVAL:
return "eval"
if mode == tf.estimator.ModeKeys.PREDICT:
return "predict"
return "unknown" | You are a Python code analyst, evaluating scripts for potential improvements. |
def tf_if(condition, a, b):
"""
Implements an if condition in tensorflow.
:param condition: A boolean condition.
:param a: Case a.
:param b: Case b.
:return: A if condition was true, b otherwise.
"""
int_condition = tf.to_float(tf.to_int64(condition))
return a * int_condition + (1 - ... | Write a Python 3 function that can
implement an if condition in tensorflow. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _read_data_legacy(prefix, batch_size):
"""
Loads a tf record as tensors you can use.
:param prefix: The path prefix as defined in the write data method.
:param batch_size: The batch size you want for the tensors.
:return: A feature tensor dict and a label tensor dict.
"""
prefix = prefix... | How would you code a function in Python 3 to
load a tf record as tensors you can use. | You are a Python code architect, reviewing and designing scalable and efficient code |
Reads a dataset from the file system. | Can you tell what is the following Python 3 function doing
def _read_data(prefix, batch_size, augmentation=None):
prefix = prefix.replace("\\", "/")
folder = "/".join(prefix.split("/")[:-1])
phase = prefix.split("/")[-1]
config = json.load(open(prefix + '_config.json'))
num_threads = config["num_thr... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create an input function that loads a dataset. | How would you explain what the following Python 3 function does
def create_input_fn(prefix, batch_size, augmentation=None):
# Check if the version is too old for dataset api to work better than manually loading data.
if tf.__version__.startswith("1.6") or tf.__version__.startswith("1.5") or tf.__version__.start... | As a Python code analyst, you investigate and solve complex coding mysteries |
Writes a tf record containing a feature dict and a label dict. | Can you generate the documentation for the following Python 3 function
def write_data(hyper_params,
mode,
sequence,
num_threads):
"""
Write a tf record containing a feature dict and a label dict.
:param hyper_params: The hyper parameters required for writing {"p... | You are a Python code architect, reviewing and designing scalable and efficient code |
def env(self, value):
"""
Sets context.env, context.env_short, and context.account_alias if env is valid
For envs of the form "global.<account>" and "mgmt.<account_alias>",
env is captured as "global" or "mgmt" and account_alias is parsed
out of the full env rather than looked up
Args:
val... | Write a Python 3 function that can
set the context. env and context. env_short and context. account_alias attributes. | As a python code expert, you are capable of creating scripts from specifications. |
Sets the service registry object in context doesn t check it
| Explain what the following Python 3 code does
def service_registry(self, sr):
if type(sr) is not EFServiceRegistry:
raise TypeError("sr value must be type 'EFServiceRegistry'")
self._service_registry = sr | You are a Python code analyst, evaluating scripts for potential improvements. |
def account_id(self, value):
"""
Sets the current account id
Args:
value: current account id (string)
Returns:
None
"""
if type(value) is not str:
raise TypeError("commit value must be string")
self._account_id = value | How would you code a function in Python 3 to
set the current account id for the next commit | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the AWS client if it exists or None if not. | Here you have a function in Python 3, explain what it does
def aws_client(self, client_id=None):
if client_id is None:
return self._aws_clients
elif self._aws_clients is not None and self._aws_clients.has_key(client_id):
return self._aws_clients[client_id]
else:
return None | You are a Python code architect, reviewing and designing scalable and efficient code |
Sets the AWS clients in the context object | How would you explain what the following Python 3 function does
def set_aws_clients(self, clients):
if type(clients) is not dict:
raise TypeError("clients must be a dict")
self._aws_clients = clients | You are a Python code generator, capable of creating scripts from specifications. |
def handle_args_and_set_context(args):
"""
Args:
args: the command line args, probably passed from main() as sys.argv[1:]
Returns:
a populated EFVersionContext object
"""
parser = argparse.ArgumentParser()
parser.add_argument("service_name", help="name of the service")
parser.add_argument("key", h... | How would you code a function in Python 3 to
handle command line args and sets the EFVersionContext object. | As a python code expert, you are capable of creating scripts from specifications. |
def validate_context(context):
"""
Set the key for the current context.
Args:
context: a populated EFVersionContext object
"""
# Service must exist in service registry
if not context.service_registry.service_record(context.service_name):
fail("service: {} not found in service registry: {}".for... | How would you code a function in Python 3 to
validate that the current context is valid. | As a python code expert, you are capable of creating scripts from specifications. |
Check if AMI is the same as the current AMI in the version records. | Can you generate a brief explanation for the following Python 3 code
def precheck_ami_id(context):
# get the current AMI
key = "{}/{}".format(context.env, context.service_name)
print_if_verbose("precheck_ami_id with key: {}".format(key))
current_ami = context.versionresolver.lookup("ami-id,{}".format(key))
pr... | You are a Python code generator, capable of creating scripts from specifications. |
def precheck_dist_hash(context):
"""
Is the dist in service the same as the dist marked current in the version records?
This tool won't update records unless the world state is coherent.
Args:
context: a populated EFVersionContext object
Returns:
True if ok to proceed
Raises:
RuntimeError if not... | Write a Python 3 function that can
check if the dist in service is the same as the current dist version in the version records. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def precheck(context):
"""
calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_'
(e.g. "precheck_ami_id")
Checking function should return True if OK, or raise RuntimeError w/ message if not
Args:
context: a populated EFVersionContext object
Returns:
True if the p... | Can you implement a function in Python 3 that
checks if precheck function for a key is set in EFVersionContext object. | As a python code expert, you are capable of creating scripts from specifications. |
def get_versions(context, return_stable=False):
"""
Get all versions of a key
Args:
context: a populated EFVersionContext object
return_stable: (default:False) If True, stop fetching if 'stable' version is found; return only that version
Returns:
json list of object data sorted in reverse by last_mo... | Create a Python 3 function for
getting all versions of a key | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the latest version that matches the provided value | Explain what the following Python 3 code does
def get_version_by_value(context, value):
versions = get_versions(context)
for version in versions:
if version.value == value:
return version
fail("Didn't find a matching version for: "
"{}:{} in env/service: {}/{}".format(
context.key, valu... | As a python code expert, you are capable of creating scripts from specifications. |
Roll back by finding the most recent stable tagged version and putting it again. | Explain what the following Python 3 code does
def cmd_rollback(context):
last_stable = get_versions(context, return_stable=True)
if len(last_stable) != 1:
fail("Didn't find a version marked stable for key: {} in env/service: {}/{}".format(
context.key, context.env, context.service_name))
context.valu... | As a Python code composer, you craft elegant and concise scripts. |
def cmd_rollback_to(context):
"""
Roll back by finding a specific version in the history of the service and
putting it as the new current version.
Args:
context: a populated EFVersionContext object
"""
version = get_version_by_value(context, context.rollback_to)
context.value = version.value
context... | Create a Python 3 function to
roll back to a specific version. | You are a Python code architect, reviewing and designing scalable and efficient code |
def cmd_set(context):
"""
Set the new "current" value for a key.
If the existing current version and the new version have identical /value/ and /status,
then nothing is written, to avoid stacking up redundant entreis in the version table.
Args:
context: a populated EFVersionContext object
"""
# If ke... | Can you create a Python 3 function that
sets the current value for a key. | You are a Python code generator, capable of creating scripts from specifications. |
def to_json(self):
"""
called by VersionEncoder.default() when doing json.dumps() on the object
the json materializes in reverse order from the order used here
"""
return {
"build_number": self._build_number,
"commit_hash": self._commit_hash,
"last_modified": self._last_modif... | Create a Python 3 function to
return a json representation of this object. | As a Python code composer, you craft elegant and concise scripts. |
def learn(self, steps=1, **kwargs):
"""
Train the model using the environment and the agent.
Note that the model might be shared between multiple agents (which most probably are of the same type)
at the same time.
:param steps: The number of steps to train for.
"""
... | Create a Python 3 function to
train the model using the environment and agent. | You are a Python code generator, capable of creating scripts from specifications. |
def get_value(self, symbol):
"""
Hierarchically searches for 'symbol' in the parameters blob if there is one (would have
been retrieved by 'load()'). Order is: default, <env_short>, <env>
Args:
symbol: the key to resolve
Returns:
Hierarchically resolved value for 'symbol' in the environm... | Implement a Python 3 function for
getting the value for the given symbol in the environment set. | As a Python code analyst, you investigate and solve complex coding mysteries |
Overlays a classification on an image. | Can you generate a brief explanation for the following Python 3 code
def overlay_classification_on_image(classification, rgb_image, scale=1):
with tf.variable_scope("debug_overlay"):
if not classification.get_shape()[3] in [1, 2, 3]:
raise RuntimeError("The classification can either be of 1, 2 o... | As a python code expert, you are capable of creating scripts from specifications. |
Converts a tensor with index form to a one hot tensor. | Can you tell what is the following Python 3 function doing
def inflate_to_one_hot(tensor, classes):
one_hot = tf.one_hot(tensor, classes)
shape = one_hot.get_shape().as_list()
return tf.reshape(one_hot, shape=[-1, shape[1], shape[2], shape[4]]) | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the account alias of an env | Can you generate a brief explanation for the following Python 3 code
def accountaliasofenv(self, lookup, default=None):
if lookup in EFConfig.ENV_ACCOUNT_MAP:
return EFConfig.ENV_ACCOUNT_MAP[lookup]
else:
return None | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the custom data for the specified file. | Can you generate the documentation for the following Python 3 function
def customdata(self, lookup, default=None):
try:
if lookup in EFConfig.CUSTOM_DATA:
return EFConfig.CUSTOM_DATA[lookup]
else:
return default
except AttributeError:
return default | As a Python code composer, you craft elegant and concise scripts. |
def fail(message, exception_data=None):
"""
Print a failure message and exit nonzero
"""
print(message, file=sys.stderr)
if exception_data:
print(repr(exception_data))
sys.exit(1) | Write a Python 3 function for
printing a failure message and exit nonzero . | You are a Python code generator, capable of creating scripts from specifications. |
def http_get_metadata(metadata_path, timeout=__HTTP_DEFAULT_TIMEOUT_SEC):
"""
Fetch AWS metadata from http://169.254.169.254/latest/meta-data/<metadata_path>
ARGS:
metadata_path - the optional path and required key to the EC2 metadata (e.g. "instance-id")
RETURN:
response content on success
RAISE:
... | Implement a Python 3 function for
fetching AWS metadata from http://169. 254. 168. 254. 254. | You are a Python code architect, reviewing and designing scalable and efficient code |
def is_in_virtualbox():
"""
Is the current environment a virtualbox instance?
Returns a boolean
Raises IOError if the necessary tooling isn't available
"""
if not isfile(__VIRT_WHAT) or not access(__VIRT_WHAT, X_OK):
raise IOError("virt-what not available")
try:
return subprocess.check_output(["su... | Implement a function in Python 3 to
return a boolean indicating if the current environment is in virtualbox. | You are a Python code generator, capable of creating scripts from specifications. |
def whereami():
"""
Determine if this is an ec2 instance or "running locally"
Returns:
"ec2" - this is an ec2 instance
"virtualbox-kvm" - kernel VM (virtualbox with vagrant)
"local" - running locally and not in a known VM
"unknown" - I have no idea where I am
"""
# If the metadata endpoint res... | Write a Python 3 script to
determine if this is an EC2 instance or running locally | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns just the env this ec2 instance is in. Doesn t require API access like get_instance_aws_context does
| Can you generate the documentation for the following Python 3 function
def http_get_instance_env():
try:
info = json.loads(http_get_metadata('iam/info'))
except Exception as error:
raise IOError("Error looking up metadata:iam/info: " + repr(error))
return info["InstanceProfileArn"].split(":")[5].split("/"... | As a python code expert, you are capable of creating scripts from specifications. |
Get the AWS context for the instance. | Explain what the following Python 3 code does
def get_instance_aws_context(ec2_client):
result = {}
try:
result["region"] = http_get_metadata("placement/availability-zone/")
result["region"] = result["region"][:-1]
result["instance_id"] = http_get_metadata('instance-id')
except IOError as error:
r... | As a python code expert, you are capable of creating scripts from specifications. |
Pulls the latest version of EF_REPO_BRANCH from the current repo | Given the following Python 3 function, write the documentation
def pull_repo():
try:
current_repo = subprocess.check_output(["git", "remote", "-v", "show"])
except subprocess.CalledProcessError as error:
raise RuntimeError("Exception checking current repo", error)
current_repo = re.findall("(https://|@)(.... | You are a Python code analyst, evaluating scripts for potential improvements. |
Create boto3 clients for one or more AWS services. | How would you explain what the following Python 3 function does
def create_aws_clients(region, profile, *clients):
if not profile:
profile = None
client_key = (region, profile)
aws_clients = client_cache.get(client_key, {})
requested_clients = set(clients)
new_clients = requested_clients.difference(aws_... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_account_alias(env):
"""
Given an env, return <account_alias> if env is valid
Args:
env: an environment, such as "prod", "staging", "proto<N>", "mgmt.<account_alias>"
Returns:
the alias of the AWS account that holds the env
Raises:
ValueError if env is misformatted or doesn't name a known e... | Write a Python 3 function for
giving an environment return the alias of the AWS account that holds the env | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_env_short(env):
"""
Given an env, return <env_short> if env is valid
Args:
env: an environment, such as "prod", "staging", "proto<N>", "mgmt.<account_alias>"
Returns:
the shortname of the env, such as "prod", "staging", "proto", "mgmt"
Raises:
ValueError if env is misformatted or doesn't n... | How would you implement a function in Python 3 that
returns the short name of a env if it is valid otherwise raises a ValueError | As a Python code composer, you craft elegant and concise scripts. |
def env_valid(env):
"""
Given an env, determine if it's valid
Args:
env: the env to check
Returns:
True if the env is valid
Raises:
ValueError with message if the env is not valid
"""
if env not in EFConfig.ENV_LIST:
raise ValueError("unknown env: {}; env must be one of: ".format(env) + ",... | Create a Python 3 function for
checking if a env is valid | You are a Python code generator, capable of creating scripts from specifications. |
Checks if a given env is a valid global or mgmt env | Can you tell what is the following Python 3 function doing
def global_env_valid(env):
if env not in EFConfig.ACCOUNT_SCOPED_ENVS:
raise ValueError("Invalid global env: {}; global envs are: {}".format(env, EFConfig.ACCOUNT_SCOPED_ENVS))
return True | As a Python code analyst, you investigate and solve complex coding mysteries |
Encrypt a secret for a given service and environment. | Make a summary of the following Python 3 code
def kms_encrypt(kms_client, service, env, secret):
# Converting all periods to underscores because they are invalid in KMS alias names
key_alias = '{}-{}'.format(env, service.replace('.', '_'))
try:
response = kms_client.encrypt(
KeyId='alias/{}'.format(key... | As a Python code analyst, you investigate and solve complex coding mysteries |
Decrypt a base64 encoded string of ciphertext into a EFPWContext object. | Can you generate a brief explanation for the following Python 3 code
def kms_decrypt(kms_client, secret):
try:
decrypted_secret = kms_client.decrypt(CiphertextBlob=base64.b64decode(secret))['Plaintext']
except TypeError:
fail("Malformed base64 string data")
except ClientError as error:
if error.respon... | You are a Python code analyst, evaluating scripts for potential improvements. |
Obtain the full key arn based on the alias provided | How would you explain what the following Python 3 function does
def kms_key_arn(kms_client, alias):
try:
response = kms_client.describe_key(KeyId=alias)
key_arn = response["KeyMetadata"]["Arn"]
except ClientError as error:
raise RuntimeError("Failed to obtain key arn for alias {}, error: {}".format(alia... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_template_parameters_file(template_full_path):
"""
Checks for existance of parameters file against supported suffixes and returns parameters file path if found
Args:
template_full_path: full filepath for template file
Returns:
filename of parameters file if it exists
"""
for s... | How would you code a function in Python 3 to
check for existance of parameters file against supported suffixes and returns parameters file path if it exists | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_template_parameters_s3(template_key, s3_resource):
"""
Checks for existance of parameters object in S3 against supported suffixes and returns parameters file key if found
Args:
template_key: S3 key for template file. omit bucket.
s3_resource: a boto3 s3 resource
Returns:
filename of paramete... | Write a Python 3 function that can
check for existance of parameters object in S3 against supported suffixes and returns the key of the parameters object if it exists | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_autoscaling_group_properties(asg_client, env, service):
"""
Gets the autoscaling group properties based on the service name that is provided. This function will attempt the find
the autoscaling group base on the following logic:
1. If the service name provided matches the autoscaling group name
2.... | Write a Python 3 script for
getting the autoscaling group properties based on the service name that is provided. This function will attempt the find the autoscaling group base on the following logic: 1. If the service name provided matches the autoscaling group name 2. If the service name provided matches the Name tag ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Export a graph stored in a checkpoint as a. pb file. | Given the following Python 3 function, write the documentation
def export_graph(checkpoint_path, output_nodes):
if not tf.gfile.Exists(checkpoint_path):
raise AssertionError(
"Export directory doesn't exists. Please specify an export "
"directory: %s" % checkpoint_path)
if not o... | You are a Python code generator, capable of creating scripts from specifications. |
Loads a frozen graph from a. pb file. | Explain what the following Python 3 code does
def load_graph(frozen_graph_filename, namespace_prefix="", placeholders=None):
# Load graph def from protobuff and import the definition
with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the load - balancer description for the specified load - balancer | Explain what the following Python 3 code does
def _elbv2_load_balancer(self, lookup):
client = EFAwsResolver.__CLIENTS['elbv2']
elbs = client.describe_load_balancers(Names=[lookup])
# getting the first one, since we requested only one lb
elb = elbs['LoadBalancers'][0]
return elb | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the ARN of the certificate that is issued by the given region and domain. | Can you generate the documentation for the following Python 3 function
def acm_certificate_arn(self, lookup, default=None):
# @todo: Only searches the first 100 certificates in the account
try:
# This a region-specific client, so we'll make a new client in the right place using existing SESSION
reg... | As a python code expert, you are capable of creating scripts from specifications. |
def ec2_elasticip_elasticip_id(self, lookup, default=None):
"""
Args:
lookup: the CloudFormation resource name of the Elastic IP ID to look up
default: the optional value to return if lookup failed; returns None if not set
Returns:
The ID of the first Elastic IP found with a description ma... | Write a Python 3 script to
return the ID of the first Elastic IP with a description matching lookup | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the IP address assigned to the Elastic IP | How would you explain what the following Python 3 function does
def ec2_elasticip_elasticip_ipaddress(self, lookup, default=None):
# Extract environment from resource ID to build stack name
m = re.search('ElasticIp([A-Z]?[a-z]+[0-9]?)\w+', lookup)
# The lookup string was not a valid ElasticIp resource label... | As a Python code composer, you craft elegant and concise scripts. |
Returns the ID of the first Elastic Network Interface with the given description matching lookup or default if lookup failed. | How would you explain what the following Python 3 function does
def ec2_eni_eni_id(self, lookup, default=None):
enis = EFAwsResolver.__CLIENTS["ec2"].describe_network_interfaces(Filters=[{
'Name': 'description',
'Values': [lookup]
}])
if len(enis.get("NetworkInterfaces")) > 0:
return enis[... | As a python code expert, you are capable of creating scripts from specifications. |
Returns the ID of the network ACL with the given name. | Given the following Python 3 function, write the documentation
def ec2_network_network_acl_id(self, lookup, default=None):
network_acl_id = EFAwsResolver.__CLIENTS["ec2"].describe_network_acls(Filters=[{
'Name': 'tag:Name',
'Values': [lookup]
}])
if len(network_acl_id["NetworkAcls"]) > 0:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the security group ID for the specified security group name | Can you tell what is the following Python 3 function doing
def ec2_security_group_security_group_id(self, lookup, default=None):
try:
response = EFAwsResolver.__CLIENTS["ec2"].describe_security_groups(Filters=[{
'Name':'group-name', 'Values':[lookup]
}])
except:
return default
if l... | As a python code expert, you are capable of creating scripts from specifications. |
def ec2_subnet_subnet_id(self, lookup, default=None):
"""
Return:
the ID of a single subnet or default/None if no match
Args:
lookup: the friendly name of the subnet to look up (subnet-<env>-a or subnet-<env>-b)
default: the optional value to return if lookup failed; returns None if not se... | Create a Python 3 function to
return the ID of a single subnet in the EC2 container | As a python code expert, you are capable of creating scripts from specifications. |
Returns a list of availability zones in use in the named VPC. | Can you generate a brief explanation for the following Python 3 code
def ec2_vpc_availabilityzones(self, lookup, default=None):
vpc_id = self.ec2_vpc_vpc_id(lookup)
if vpc_id is None:
return default
subnets = EFAwsResolver.__CLIENTS["ec2"].describe_subnets(Filters=[{
'Name': 'vpc-id',
'Val... | As a python code expert, you are capable of creating scripts from specifications. |
def ec2_vpc_subnets(self, lookup, default=None):
"""
Args:
lookup - the friendly name of the VPC whose subnets we want
Returns:
A comma-separated list of all subnets in use in the named VPC or default/None if no match found
"""
vpc_id = self.ec2_vpc_vpc_id(lookup)
if vpc_id is None:
... | Can you create a Python 3 function that
returns a comma - separated list of all subnets in use in the named VPC | As a python code expert, you are capable of creating scripts from specifications. |
Returns the CIDR block of the named VPC or default if no match is found | How would you explain what the following Python 3 function does
def ec2_vpc_cidrblock(self, lookup, default=None):
vpcs = EFAwsResolver.__CLIENTS["ec2"].describe_vpcs(Filters=[{
'Name': 'tag:Name',
'Values': [lookup]
}])
if len(vpcs.get("Vpcs")) > 0:
return vpcs["Vpcs"][0]["CidrBlock"]
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def elbv2_load_balancer_hosted_zone(self, lookup, default=None):
"""
Args:
lookup: the friendly name of the V2 elb to look up
default: value to return in case of no match
Returns:
The hosted zone ID of the ELB found with a name matching 'lookup'.
"""
try:
elb = self._elbv2_lo... | Write a Python 3 script for
returning the hosted zone ID of the ELB found with a friendly name matching lookup. | You are a Python code architect, reviewing and designing scalable and efficient code |
def elbv2_load_balancer_dns_name(self, lookup, default=None):
"""
Args:
lookup: the friendly name of the V2 elb to look up
default: value to return in case of no match
Returns:
The hosted zone ID of the ELB found with a name matching 'lookup'.
"""
try:
elb = self._elbv2_load_... | Write a Python 3 script to
return the hosted zone ID of the ELB with a friendly name matching lookup. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the ARN of the v2 load balancer that has the suffix of app. | Make a summary of the following Python 3 code
def elbv2_load_balancer_arn_suffix(self, lookup, default=None):
try:
elb = self._elbv2_load_balancer(lookup)
m = re.search(r'.+?(app\/[^\/]+\/[^\/]+)$', elb['LoadBalancerArn'])
return m.group(1)
except ClientError:
return default | As a Python code composer, you craft elegant and concise scripts. |
def elbv2_target_group_arn_suffix(self, lookup, default=None):
"""
Args:
lookup: the friendly name of the v2 elb target group
default: value to return in case of no match
Returns:
The shorthand fragment of the target group's ARN, of the form
`targetgroup/*/*`
"""
try:
c... | Implement a Python 3 function for
returning the ARN of the target group in the v2 target group | As a Python code composer, you craft elegant and concise scripts. |
Returns the ID of the WAF rule whose name matches lookup. | Can you generate a brief explanation for the following Python 3 code
def waf_rule_id(self, lookup, default=None):
# list_rules returns at most 100 rules per request
list_limit = 100
rules = EFAwsResolver.__CLIENTS["waf"].list_rules(Limit=list_limit)
while True:
for rule in rules["Rules"]:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def waf_web_acl_id(self, lookup, default=None):
"""
Args:
lookup: the friendly name of a Web ACL
default: the optional value to return if lookup failed; returns None if not set
Returns:
the ID of the WAF Web ACL whose name matches rule_name or default/None if no match found
"""
# l... | Create a Python 3 function to
return the ID of the WAF Web ACL whose name matches the given name. If no match is found returns default. | As a Python code analyst, you investigate and solve complex coding mysteries |
def route53_public_hosted_zone_id(self, lookup, default=None):
"""
Args:
lookup: The zone name to look up. Must end with "."
default: the optional value to return if lookup failed; returns None if not set
Returns:
the ID of the public hosted zone for the 'lookup' domain, or default/None if... | Can you implement a function in Python 3 that
returns the public hosted zone ID for the given domain name. | You are a Python code generator, capable of creating scripts from specifications. |
def ec2_route_table_main_route_table_id(self, lookup, default=None):
"""
Args:
lookup: the friendly name of the VPC whose main route table we are looking up
default: the optional value to return if lookup failed; returns None if not set
Returns:
the ID of the main route table of the named ... | How would you implement a function in Python 3 that
returns the ID of the main route table of the named VPC or None if lookup failed | As a Python code analyst, you investigate and solve complex coding mysteries |
def ec2_route_table_tagged_route_table_id(self, lookup, default=None):
"""
Args:
lookup: the tagged route table name, should be unique
default: the optional value to return if lookup failed; returns None if not set
Returns:
the ID of the route table, or default if no match/multiple matches... | Create a Python 3 function to
return the ID of the route table with the given name. If no match or multiple matches returns default. | You are a Python code architect, reviewing and designing scalable and efficient code |
def cloudfront_domain_name(self, lookup, default=None):
"""
Args:
lookup: any CNAME on the Cloudfront distribution
default: the optional value to return if lookup failed; returns None if not set
Returns:
The domain name (FQDN) of the Cloudfront distrinbution, or default/None if no match
... | Write a Python 3 script to
return the domain name of the Cloudfront distrinbution. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def cloudfront_origin_access_identity_oai_canonical_user_id(self, lookup, default=None):
"""
Args:
lookup: the FQDN of the Origin Access Identity (from its comments)
default: the optional value to return if lookup failed; returns None if not set
Returns:
the S3 Canonical User ID of the OAI... | Implement a Python 3 function for
returning the S3 Canonical User ID of the Origin Access Identity associated with the FQDN in lookup. | You are a Python code generator, capable of creating scripts from specifications. |
def cognito_identity_identity_pool_arn(self, lookup, default=None):
"""
Args:
lookup: Cognito Federated Identity name, proto0-cms-identity-pool
default: the optional value to return if lookup failed; returns None if not set
Returns:
the constructed ARN for the cognito identity pool,... | Create a Python 3 function for
returning the full ARN for a cognito identity pool | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the Cognito Identity Pool ID corresponding to the given lookup. | Given the following Python 3 function, write the documentation
def cognito_identity_identity_pool_id(self, lookup, default=None):
# List size cannot be greater than 60
list_limit = 60
client = EFAwsResolver.__CLIENTS["cognito-identity"]
response = client.list_identity_pools(MaxResults=list_limit)
w... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the User Pool ARN corresponding to the given lookup. | Make a summary of the following Python 3 code
def cognito_idp_user_pool_arn(self, lookup, default=None):
client = EFAwsResolver.__CLIENTS["cognito-idp"]
user_pool_id = self.cognito_idp_user_pool_id(lookup, default)
if user_pool_id == default:
return default
response = client.describe_user_pool(Us... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the full key arn for a given lookup | Make a summary of the following Python 3 code
def kms_key_arn(self, lookup):
key_arn = ef_utils.kms_key_arn(EFAwsResolver.__CLIENTS["kms"], lookup)
return key_arn | As a Python code translator, you convert algorithms and pseudocode into Python. |
Handles command line args and sets up EFContext object | Explain what the following Python 3 code does
def handle_args_and_set_context(args):
parser = argparse.ArgumentParser()
parser.add_argument("env", help=", ".join(EFConfig.ENV_LIST))
parser.add_argument("--sr", help="optional /path/to/service_registry_file.json", default=None)
parser.add_argument("--commit", hel... | You are a Python code analyst, evaluating scripts for potential improvements. |
Create security groups as needed ; name and number created depend on service_type
Args env service name and type of the service in service registry Returns a new registry with the new security groups created | Make a summary of the following Python 3 code
def conditionally_create_security_groups(env, service_name, service_type):
if service_type not in SG_SERVICE_TYPES:
print_if_verbose("not eligible for security group(s); service type: {}".format(service_type))
return
target_name = "{}-{}".format(env, service_na... | As a python code expert, you are capable of creating scripts from specifications. |
def conditionally_create_role(role_name, sr_entry):
"""
Create role_name if a role by that name does not already exist; attach a custom list of Principals
to its AssumeRolePolicy
Args:
role_name: the name for the role to create
sr_entry: service registry entry
Example of a (complex) AssumeRole policy... | Create a Python 3 function for
creating a role by name if a role by that name does not already exist ; attach a custom list of Principals athorically defined AssumeRolePolicy athorically defined AssumeRole policy document comprised of two IAM entities and a service. | You are a Python code analyst, evaluating scripts for potential improvements. |
def conditionally_create_profile(role_name, service_type):
"""
Check that there is a 1:1 correspondence with an InstanceProfile having the same name
as the role, and that the role is contained in it. Create InstanceProfile and attach to role if needed.
"""
# make instance profile if this service_type gets an ... | Can you write a function in Python 3 where it
creates an instance profile if needed and attach to the role if needed. | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.