output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Conditionally attach the policies to a role
How would you explain what the following Python 3 function does def conditionally_attach_managed_policies(role_name, sr_entry): service_type = sr_entry['type'] if not (service_type in SERVICE_TYPE_ROLE and "aws_managed_policies" in sr_entry): print_if_verbose("not eligible for policies; service_type: {} is not ...
As a Python code analyst, you investigate and solve complex coding mysteries
Create a KMS Master Key for encryption and decryption of sensitive values in cf templates and latebind configs.
Can you generate a brief explanation for the following Python 3 code def conditionally_create_kms_key(role_name, service_type): if service_type not in KMS_SERVICE_TYPES: print_if_verbose("not eligible for kms; service_type: {} is not valid for kms".format(service_type)) return # Converting all periods to u...
You are a Python code architect, reviewing and designing scalable and efficient code
def sum_abs_distance(labels, preds): """ Compute the sum of abs distances. :param labels: A float tensor of shape [batch_size, ..., X] representing the labels. :param preds: A float tensor of shape [batch_size, ..., X] representing the predictions. :return: A float tensor of shape [batch_size, ...]...
How would you implement a function in Python 3 that computes the sum of abs distances.
As a Python code translator, you convert algorithms and pseudocode into Python.
def l1_distance(labels, preds): """ Compute the l1_distance. :param labels: A float tensor of shape [batch_size, ..., X] representing the labels. :param preds: A float tensor of shape [batch_size, ..., X] representing the predictions. :return: A float tensor of shape [batch_size, ...] representing ...
Write a Python 3 function for computing the l1_distance. :param labels: A float tensor of shape [batch_size, ..., X] representing the labels. :param preds: A float tensor of shape [batch_size, ..., X] representing the predictions. :return: A float tensor of shape [batch_size, ...] representing the l1 distance.
As a python code expert, you are capable of creating scripts from specifications.
Compute the smooth l1 distance.
Make a summary of the following Python 3 code def smooth_l1_distance(labels, preds, delta=1.0): with tf.variable_scope("smooth_l1"): return tf.reduce_sum(tf.losses.huber_loss( labels=labels, predictions=preds, delta=delta, loss_collection=None, red...
You are a Python code generator, capable of creating scripts from specifications.
Compute the l2_distance. :param labels: A float tensor of shape [batch_size, ..., X] representing the labels. :param preds: A float tensor of shape [batch_size, ..., X] representing the predictions. :return: A float tensor of shape [batch_size, ...] representing the l2 distance.
Can you tell what is the following Python 3 function doing def l2_distance(labels, preds): with tf.variable_scope("l2_distance"): return tf.norm(preds - labels, ord=2)
You are a Python code analyst, evaluating scripts for potential improvements.
Calculate the cross entropy.
Can you tell what is the following Python 3 function doing def cross_entropy(labels, logits): with tf.variable_scope("cross_entropy"): return tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits)
As a Python code translator, you convert algorithms and pseudocode into Python.
Handles command line args and sets the context of the current environment.
Make a summary of the following Python 3 code def handle_args_and_set_context(args): parser = argparse.ArgumentParser() parser.add_argument("template_file", help="/path/to/template_file.json") parser.add_argument("env", help=", ".join(EFConfig.ENV_LIST)) parser.add_argument("--sr", help="optional /path/to/servi...
As a Python code composer, you craft elegant and concise scripts.
Given a service name find all templates below ; write to dest
Can you generate the documentation for the following Python 3 function def merge_files(service, skip_on_user_group_error=False): if WHERE == "ec2": config_reader = EFInstanceinitConfigReader("s3", service, log_info, RESOURCES["s3"]) resolver = EFTemplateResolver() elif WHERE == "virtualbox-kvm": config_...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_metadata_or_fail(metadata_key): """ Call get_metadata; halt with fail() if it raises an exception """ try: return http_get_metadata(metadata_key) except IOError as error: fail("Exception in http_get_metadata {} {}".format(metadata_key, repr(error)))
Write a Python 3 script to call get_metadata ; halt with fail
As a Python code composer, you craft elegant and concise scripts.
def load(self, template, parameters=None): """ 'template' Loads template text from a 'string' or 'file' type Template text contains {{TOKEN}} symbols to be replaced 'parameters' parameters contains environment-specific sections as discussed in the class documentation. the 'parameters' arg c...
Implement a function in Python 3 to load a template from a string or file.
As a Python code composer, you craft elegant and concise scripts.
def search_parameters(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> Returns Hierarchically resolved value for 'symbol', or None if a match is not found or there are no pa...
How would you code a function in Python 3 to search the parameters blob for a given symbol.
You are a Python code architect, reviewing and designing scalable and efficient code
def render(self): """ Find {{}} tokens; resolve then replace them as described elsewhere Resolution is multi-pass: tokens may be nested to form parts of other tokens. Token search steps when resolving symbols - 1. lookups of AWS resource identifiers, such as a security group ID - 2. secure ...
Create a Python 3 function for finding all resolvable symbols in the template and resolve them as described elsewhere
As a python code expert, you are capable of creating scripts from specifications.
def count_braces(self): """ returns a count of "{{" and "}}" in the template, as (N_left_braces, N_right_braces) Useful to check after resolve() has run, to infer that template has an error since no {{ or }} should be present in the template after resolve() """ n_left = len(re.findall("{{", self...
How would you code a function in Python 3 to return a count of left and right braces in the template as ( N_left_braces N_right_braces
As a Python code composer, you craft elegant and concise scripts.
def resolved_ok(self): """ Shortcut to testing unresolved_symbols and count_braces separately. Returns false if there are unresolved symbols or {{ or }} braces remaining, true otherwise """ left_braces, right_braces = self.count_braces() return len(self.unresolved_symbols()) == left_braces == ri...
Write a Python 3 function that can return true if all unresolved symbols and count_braces are equal.
You are a Python code analyst, evaluating scripts for potential improvements.
Handles the command line args and sets the Context object based on the CLI args.
Can you generate a brief explanation for the following Python 3 code def handle_args_and_set_context(args): parser = argparse.ArgumentParser() parser.add_argument("env", help="environment") parser.add_argument("path_to_template", help="path to the config template to process") parser.add_argument("--no_params", ...
You are a Python code generator, capable of creating scripts from specifications.
def merge_files(context): """ Given a context containing path to template, env, and service: merge config into template and output the result to stdout Args: context: a populated context object """ resolver = EFTemplateResolver( profile=context.profile, region=context.region, env=conte...
Create a Python 3 function to give a context containing path to template env and service merge config into a single object.
As a Python code composer, you craft elegant and concise scripts.
def handle_args(args): """ Handle command line arguments Raises: Exception if the config path wasn't explicitly state and dead reckoning based on script location fails """ parser = argparse.ArgumentParser() parser.add_argument("configpath", default=None, nargs="?", help="/path/to/c...
Can you implement a function in Python 3 that handles command line arguments
You are a Python code generator, capable of creating scripts from specifications.
Loads a JSON file into a dict
How would you explain what the following Python 3 function does def load_json(json_filespec): json_fh = open(json_filespec) config_dict = json.load(json_fh) json_fh.close() return config_dict
As a python code expert, you are capable of creating scripts from specifications.
Lookup a key version from a token in a node s bucket.
Can you generate a brief explanation for the following Python 3 code def lookup(self, token): # get search key and env/service from token try: key, envservice = token.split(",") except ValueError: return None # get env, service from value try: env, service = envservice.split("/") ...
As a Python code analyst, you investigate and solve complex coding mysteries
Check to see if an alert policy exists in NewRelic. Return True if so False if not.
Make a summary of the following Python 3 code def alert_policy_exists(self, policy_name): if next((policy for policy in self.all_alerts if policy['name'] == policy_name), False): return True
As a python code expert, you are capable of creating scripts from specifications.
Creates an alert policy in NewRelic
Make a summary of the following Python 3 code def create_alert_policy(self, policy_name): policy_data = { 'policy': { 'incident_preference': 'PER_POLICY', 'name': policy_name } } create_policy = requests.post( 'https://api.newrelic.com/v2/alerts_policies.json', headers=self.auth_header, data=j...
As a Python code composer, you craft elegant and concise scripts.
Get specified element href by element name
Explain what the following Python 3 code does def element_href(name): if name: element = fetch_meta_by_name(name) if element.href: return element.href
You are a Python code generator, capable of creating scripts from specifications.
def element_as_json(name): """ Get specified element json data by name :param name: name of element :return: json data representing element, else None """ if name: element = fetch_json_by_name(name) if element.json: return element.json
Write a Python 3 function that can get specified element json data by name.
As a Python code composer, you craft elegant and concise scripts.
Get specified element json data by name with filter.
How would you explain what the following Python 3 function does def element_as_json_with_filter(name, _filter): if name: element_href = element_href_use_filter(name, _filter) if element_href: return element_by_href_as_json(element_href)
You are a Python code architect, reviewing and designing scalable and efficient code
Get specified element META data based on search query
Given the following Python 3 function, write the documentation def element_info_as_json(name): if name: element = fetch_meta_by_name(name) if element.json: return element.json
As a Python code analyst, you investigate and solve complex coding mysteries
def element_info_as_json_with_filter(name, _filter): """ Top level json meta data (href, name, type) for element :param str name: name of element :param str _filter: filter of entry point :return: list dict with metadata, otherwise None """ if name and _filter: element = fetch_meta_...
Write a Python 3 function for getting the element metadata as json with the given name and filter
You are a Python code architect, reviewing and designing scalable and efficient code
def element_href_use_wildcard(name): """ Get element href using a wildcard rather than matching only on the name field. This will likely return multiple results. :param name: name of element :return: list of matched elements """ if name: element = fetch_meta_by_name(name, exact_match=Fa...
Can you implement a function in Python 3 that gets element href using a wildcard rather than matching only on the name field.
As a python code expert, you are capable of creating scripts from specifications.
def element_href_use_filter(name, _filter): """ Get element href using filter Filter should be a valid entry point value, ie host, router, network, single_fw, etc :param name: name of element :param _filter: filter type, unknown filter will result in no matches :return: element href (if found)...
Write a Python 3 function that can get element href using filter
You are a Python code generator, capable of creating scripts from specifications.
def element_by_href_as_json(href, params=None): """ Get specified element by href :param href: link to object :param params: optional search query parameters :return: json data representing element, else None """ if href: element = fetch_json_by_href(href, params=params) if elem...
Write a Python 3 script for getting specified element by href as json data.
You are a Python code analyst, evaluating scripts for potential improvements.
def element_name_by_href(href): """ The element href is known, possibly from a reference in an elements json. You want to retrieve the name of this element. :param str href: href of element :return: str name of element, or None """ if href: element = fetch_json_by_href(href) ...
Write a Python 3 script to get the name of an element from an analyzed element.
As a python code expert, you are capable of creating scripts from specifications.
def element_name_and_type_by_href(href): """ Retrieve the element name and type of element based on the href. You may have a href that is within another element reference and want more information on that reference. :param str href: href of element :return: tuple (name, type) """ if hre...
How would you implement a function in Python 3 that retrieves the element name and type of element based on the href.
You are a Python code analyst, evaluating scripts for potential improvements.
Get an attribute from an element by href.
Given the following Python 3 function, write the documentation def element_attribute_by_href(href, attr_name): if href: element = fetch_json_by_href(href) if element.json: return element.json.get(attr_name)
You are a Python code architect, reviewing and designing scalable and efficient code
Get specified element returned as an SMCResult object
Here you have a function in Python 3, explain what it does def element_by_href_as_smcresult(href, params=None): if href: element = fetch_json_by_href(href, params=params) if element: return element
As a Python code composer, you craft elegant and concise scripts.
def element_as_smcresult_use_filter(name, _filter): """ Return SMCResult object and use search filter to find object :param name: name of element to find :param _filter: filter to use, i.e. tcp_service, host, etc :return: :py:class:`smc.api.web.SMCResult` """ if name: element = fetc...
Write a Python 3 script for returning SMCResult object and use search filter to find object
You are a Python code generator, capable of creating scripts from specifications.
Find the href of the elements in a list of names.
Can you generate the documentation for the following Python 3 function def element_href_by_batch(list_to_find, filter=None): # @ReservedAssignment try: if filter: return [{k: element_href_use_filter(k, filter) for k in list_to_find}] return [{k: element_href(k) for ...
As a Python code analyst, you investigate and solve complex coding mysteries
def all_elements_by_type(name): """ Get specified elements based on the entry point verb from SMC api To get the entry points available, you can get these from the session:: session.cache.entry_points Execution will get the entry point for the element type, then get all elements that match. ...
Create a Python 3 function to get all elements of the specified type from the top level entry point verb from SMC API.
As a Python code composer, you craft elegant and concise scripts.
Fetch json based on the element name
Here you have a function in Python 3, explain what it does def fetch_json_by_name(name): result = fetch_meta_by_name(name) if result.href: result = fetch_json_by_href(result.href) return result
You are a Python code analyst, evaluating scripts for potential improvements.
Fetch json for element by using href.
Can you tell what is the following Python 3 function doing def fetch_json_by_href(href, params=None): result = SMCRequest(href=href, params=params).read() if result: result.href = href return result
As a Python code translator, you convert algorithms and pseudocode into Python.
Creates a new GatewaySettings object.
Can you tell what is the following Python 3 function doing def create(cls, name, negotiation_expiration=200000, negotiation_retry_timer=500, negotiation_retry_max_number=32, negotiation_retry_timer_max=7000, certificate_cache_crl_validity=90000, ...
As a Python code analyst, you investigate and solve complex coding mysteries
Create new External Gateway :param str name: name of test_external gateway :param bool trust_all_cas: whether to trust all internal CA's (default: True) :return: instance with meta :rtype: ExternalGateway
Can you generate a brief explanation for the following Python 3 code def create(cls, name, trust_all_cas=True): json = {'name': name, 'trust_all_cas': trust_all_cas} return ElementCreator(cls, json)
You are a Python code generator, capable of creating scripts from specifications.
Update or create an ExternalGateway with the given name.
Can you generate a brief explanation for the following Python 3 code def update_or_create(cls, name, external_endpoint=None, vpn_site=None, trust_all_cas=True, with_status=False): """ Update or create an ExternalGateway. The ``external_endpoint`` and ``vpn_site`` parameters are expected ...
As a Python code composer, you craft elegant and concise scripts.
Creates an external endpoint.
How would you explain what the following Python 3 function does def create(self, name, address=None, enabled=True, balancing_mode='active', ipsec_vpn=True, nat_t=False, force_nat_t=False, dynamic=False, ike_phase1_id_type=None, ike_phase1_id_value=None): """ Create an test_...
As a Python code analyst, you investigate and solve complex coding mysteries
def update_or_create(cls, external_gateway, name, with_status=False, **kw): """ Update or create external endpoints for the specified external gateway. An ExternalEndpoint is considered unique based on the IP address for the endpoint (you cannot add two external endpoints with the same I...
Can you implement a function in Python 3 that updates or create an external endpoint for the specified external gateway.
As a Python code analyst, you investigate and solve complex coding mysteries
def enable_disable(self): """ Enable or disable this endpoint. If enabled, it will be disabled and vice versa. :return: None """ if self.enabled: self.data['enabled'] = False else: self.data['enabled'] = True self.update()
Write a Python 3 script to enable or disable this endpoint.
You are a Python code analyst, evaluating scripts for potential improvements.
def enable_disable_force_nat_t(self): """ Enable or disable NAT-T on this endpoint. If enabled, it will be disabled and vice versa. :return: None """ if self.force_nat_t: self.data['force_nat_t'] = False else: self.data['force_nat_t'] = Tr...
Create a Python 3 function to enable or disable NAT - T on this endpoint.
As a python code expert, you are capable of creating scripts from specifications.
def create(self, name, site_element): """ Create a VPN site for an internal or external gateway :param str name: name of site :param list site_element: list of protected networks/hosts :type site_element: list[str,Element] :raises CreateElementFailed: create element fail...
Write a Python 3 script for creating a VPN site for an internal or external gateway.
As a Python code composer, you craft elegant and concise scripts.
Update or create VPN Site elements based on value of provided site_element list.
Can you generate a brief explanation for the following Python 3 code def update_or_create(cls, external_gateway, name, site_element=None, with_status=False): """ Update or create a VPN Site elements or modify an existing VPN site based on value of provided site_element list. The resu...
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_site_element(self, element): """ Add a site element or list of elements to this VPN. :param list element: list of Elements or href's of vpn site elements :type element: list(str,Network) :raises UpdateElementFailed: fails due to reason :return: None ...
Can you write a function in Python 3 where it adds a site element or href s of vpn site elements to this VPN.
As a Python code analyst, you investigate and solve complex coding mysteries
Helper function to find a location by name.
Explain what the following Python 3 code does def location_helper(name, search_only=False): try: return name.href except AttributeError: if name and name.startswith('http'): return name except ElementNotFound: return Location.create(name=name.name).href if not \ ...
As a Python code analyst, you investigate and solve complex coding mysteries
Change user password. Change is committed immediately.
Can you tell what is the following Python 3 function doing def change_password(self, password): self.make_request( ModificationFailed, method='update', resource='change_password', params={'password': password})
You are a Python code generator, capable of creating scripts from specifications.
Adds a permission to this Admin User.
Can you generate a brief explanation for the following Python 3 code def add_permission(self, permission): if 'permissions' not in self.data: self.data['superuser'] = False self.data['permissions'] = {'permission':[]} for p in permission: self.data['permissio...
You are a Python code architect, reviewing and designing scalable and efficient code
Return each permission mapping for this Admin User.
How would you explain what the following Python 3 function does def permissions(self): if 'permissions' in self.data: _permissions = self.data['permissions']['permission'] return [Permission(**perm) for perm in _permissions] return []
You are a Python code architect, reviewing and designing scalable and efficient code
Create an admin user account.
Can you generate a brief explanation for the following Python 3 code def create(cls, name, local_admin=False, allow_sudo=False, superuser=False, enabled=True, engine_target=None, can_use_api=True, console_superuser=False, allowed_to_login_in_shared=True, comment=None): ...
You are a Python code analyst, evaluating scripts for potential improvements.
Change Engine password for all engines on allowed list.
Here you have a function in Python 3, explain what it does def change_engine_password(self, password): self.make_request( ModificationFailed, method='update', resource='change_engine_password', params={'password': password})
You are a Python code generator, capable of creating scripts from specifications.
Create a new API Client.
Explain what the following Python 3 code does def create(cls, name, enabled=True, superuser=True): json = { 'enabled': enabled, 'name': name, 'superuser': superuser} return ElementCreator(cls, json)
As a python code expert, you are capable of creating scripts from specifications.
def _create(cls, name, node_type, physical_interfaces, nodes=1, loopback_ndi=None, log_server_ref=None, domain_server_address=None, enable_antivirus=False, enable_gti=False, sidewinder_proxy_enabled=False, de...
Write a Python 3 script for creating the engine configuration as a dict.
As a Python code composer, you craft elegant and concise scripts.
Rename the firewall engine nodes and internal gateway
How would you explain what the following Python 3 function does def rename(self, name): for node in self.nodes: node.rename(name) self.update(name=name) self.vpn.rename(name)
As a Python code composer, you craft elegant and concise scripts.
Returns the location for this engine. May be None if no specific location has been assigned.
Can you generate a brief explanation for the following Python 3 code def location(self): location = Element.from_href(self.location_ref) if location and location.name == 'Default': return None return location
As a Python code composer, you craft elegant and concise scripts.
def nodes(self): """ Return a list of child nodes of this engine. This can be used to iterate to obtain access to node level operations :: >>> print(list(engine.nodes)) [Node(name=myfirewall node 1)] >>> engine.nodes.get(0) Node(na...
How would you implement a function in Python 3 that returns a list of child nodes of this engine. This is a recursive method that returns a list of child nodes of this engine.
As a Python code translator, you convert algorithms and pseudocode into Python.
Retrieve the permissions for this engine instance.
Can you generate the documentation for the following Python 3 function def permissions(self): acl_list = list(AccessControlList.objects.all()) def acl_map(elem_href): for elem in acl_list: if elem.href == elem_href: return elem acls = self...
You are a Python code architect, reviewing and designing scalable and efficient code
def pending_changes(self): """ Pending changes provides insight into changes on an engine that are pending approval or disapproval. Feature requires SMC >= v6.2. :raises UnsupportedEngineFeature: SMC version >= 6.2 is required to support pending changes :rtype: Pendi...
Can you create a Python 3 function that returns a new PendingChanges object that represents the pending changes on an engine that are a pending approval or disapproval.
As a Python code composer, you craft elegant and concise scripts.
def alias_resolving(self): """ Alias definitions with resolved values as defined on this engine. Aliases can be used in rules to simplify multiple object creation :: fw = Engine('myfirewall') for alias in fw.alias_resolving(): print(alias, alias.r...
Can you implement a function in Python 3 that yields all aliases that are resolved on this engine.
You are a Python code analyst, evaluating scripts for potential improvements.
Add blacklist entries to the engine node in bulk.
Can you generate a brief explanation for the following Python 3 code def blacklist_bulk(self, blacklist): self.make_request( EngineCommandFailed, method='create', resource='blacklist', json=blacklist.entries)
You are a Python code generator, capable of creating scripts from specifications.
Returns a generator of the entries in the blacklist for this entry.
Can you tell what is the following Python 3 function doing def blacklist_show(self, **kw): try: from smc_monitoring.monitors.blacklist import BlacklistQuery except ImportError: pass else: query = BlacklistQuery(self.name) for record in query.fetch_...
As a Python code analyst, you investigate and solve complex coding mysteries
Add a route to the specified network.
Given the following Python 3 function, write the documentation def add_route(self, gateway, network): self.make_request( EngineCommandFailed, method='create', resource='add_route', params={'gateway': gateway, 'network': network})
You are a Python code architect, reviewing and designing scalable and efficient code
def routing_monitoring(self): """ Return route table for the engine, including gateway, networks and type of route (dynamic, static). Calling this can take a few seconds to retrieve routes from the engine. Find all routes for engine resource:: >>> engine = E...
Write a Python 3 script for returning a list of route elements for the routing monitoring system.
You are a Python code generator, capable of creating scripts from specifications.
def virtual_resource(self): """ Available on a Master Engine only. To get all virtual resources call:: engine.virtual_resource.all() :raises UnsupportedEngineFeature: master engine only :rtype: CreateCollection(VirtualResource) """ resource = create...
Write a Python 3 function that can return a new VirtualResource instance with all the virtual resources in the master engine.
You are a Python code generator, capable of creating scripts from specifications.
def add_interface(self, interface): """ Add interface is a lower level option to adding interfaces directly to the engine. The interface is expected to be an instance of Layer3PhysicalInterface, Layer2PhysicalInterface, TunnelInterface, or ClusterInterface. The engines instance c...
Create a Python 3 function for adding an interface to the cache.
You are a Python code architect, reviewing and designing scalable and efficient code
Refresh existing policy on specified device.
Explain what the following Python 3 code does def refresh(self, timeout=3, wait_for_finish=False, **kw): return Task.execute(self, 'refresh', timeout=timeout, wait_for_finish=wait_for_finish, **kw)
As a Python code composer, you craft elegant and concise scripts.
def generate_snapshot(self, filename='snapshot.zip'): """ Generate and retrieve a policy snapshot from the engine This is blocking as file is downloaded :param str filename: name of file to save file to, including directory path :raises EngineCommandFailed: snapshot ...
Implement a Python 3 function for generating and retrieve a policy snapshot from the engine
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_site(self, name, site_elements=None): """ Add a VPN site with site elements to this engine. VPN sites identify the sites with protected networks to be included in the VPN. Add a network and new VPN site:: >>> net = Network.get_or_create(name='wireless...
How would you implement a function in Python 3 that adds a VPN site with site elements to this engine.
You are a Python code analyst, evaluating scripts for potential improvements.
def generate_certificate(self, common_name, public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=2048, signing_ca=None): """ Generate an internal gateway certificate used for VPN on this engine. Certificate request should be an instance of VPNCertific...
Can you write a function in Python 3 where it generates an internal VPNCertificate object for the specified key.
You are a Python code architect, reviewing and designing scalable and efficient code
Create a new virtual resource. Called through engine engine. virtual_resource. create (...
How would you explain what the following Python 3 function does def create(self, name, vfw_id, domain='Shared Domain', show_master_nic=False, connection_limit=0, comment=None): """ Create a new virtual resource. Called through engine reference:: engine.virtual_resourc...
You are a Python code generator, capable of creating scripts from specifications.
Enable SNMP on the engine. Specify a list of interfaces that have NDI s to enable on those interfaces.
Can you tell what is the following Python 3 function doing def enable(self, snmp_agent, snmp_location=None, snmp_interface=None): agent = element_resolver(snmp_agent) snmp_interface = [] if not snmp_interface else snmp_interface interfaces = self._iface_dict(snmp_interface) self.eng...
As a Python code analyst, you investigate and solve complex coding mysteries
Update the SNMP configuration for the current node.
How would you explain what the following Python 3 function does def update_configuration(self, **kwargs): updated = False if 'snmp_agent' in kwargs: kwargs.update(snmp_agent_ref=kwargs.pop('snmp_agent')) snmp_interface = kwargs.pop('snmp_interface', None) for name, value in k...
You are a Python code generator, capable of creating scripts from specifications.
def interface(self): """ Return a list of physical interfaces that the SNMP agent is bound to. :rtype: list(PhysicalInterface) """ nics = set([nic.get('nicid') for nic in \ getattr(self.engine, 'snmp_interface', [])]) return [self.engine.inter...
Implement a Python 3 function for returning a list of physical interfaces that the SNMP is bound to.
You are a Python code architect, reviewing and designing scalable and efficient code
def enable(self, interface_id, dns_relay_profile=None): """ Enable the DNS Relay service on this engine. :param int interface_id: interface id to enable relay :param str,DNSRelayProfile dns_relay_profile: DNSRelayProfile element or str href :raises EngineCommandFaile...
How would you code a function in Python 3 to enable the DNS Relay service on this engine.
You are a Python code generator, capable of creating scripts from specifications.
Disable DNS Relay on this engine
Here you have a function in Python 3, explain what it does def disable(self): self.engine.data.update(dns_relay_interface=[]) self.engine.data.pop('dns_relay_profile_ref', None)
As a Python code translator, you convert algorithms and pseudocode into Python.
def remove(self, values): """ Remove DNS entries from this ranked DNS list. A DNS entry can be either a raw IP Address, or an element of type :class:`smc.elements.network.Host` or :class:`smc.elements.servers.DNSServer`. :param list values: list of IP addresses, Host and...
Can you implement a function in Python 3 that removes DNS entries from this ranked DNS list.
You are a Python code architect, reviewing and designing scalable and efficient code
Enable a layer 2 interface policy.
Can you generate the documentation for the following Python 3 function def enable(self, policy): if hasattr(policy, 'href'): if not isinstance(policy, InterfacePolicy): raise LoadPolicyFailed('Invalid policy type specified. The policy' 'type must be InterfacePolic...
You are a Python code architect, reviewing and designing scalable and efficient code
Create an IPS Policy with the specified name and template.
Make a summary of the following Python 3 code def create(cls, name, template='High-Security IPS Template'): try: if cls.typeof == 'ips_template_policy' and template is None: fw_template = None else: fw_template = IPSTemplatePolicy(template).href ex...
As a python code expert, you are capable of creating scripts from specifications.
Get an element from the collection by an arg or kwarg.
Explain what the following Python 3 code does def get(self, *args, **kwargs): if self: if args: index = args[0] if index <= len(self) -1: return self[args[0]] return None elif kwargs: key, value = kwargs....
You are a Python code generator, capable of creating scripts from specifications.
def upload_as_zip(name, filename): """ Upload an IPList as a zip file. Useful when IPList is very large. This is the default upload format for IPLists. :param str name: name of IPList :param str filename: name of zip file to upload, full path :return: None """ location = list(IPList.obj...
Write a Python 3 script for uploading an IPList as a zip file. Useful when IPLists are very large.
As a python code expert, you are capable of creating scripts from specifications.
Uploads the IPList as text from a file.
Here you have a function in Python 3, explain what it does def upload_as_text(name, filename): location = list(IPList.objects.filter(name)) if location: iplist = location[0] return iplist.upload(filename=filename, as_type='txt')
As a Python code translator, you convert algorithms and pseudocode into Python.
Upload the IPList as json payload.
Here you have a function in Python 3, explain what it does def upload_as_json(name, mylist): location = list(IPList.objects.filter(name)) if location: iplist = location[0] return iplist.upload(json=mylist, as_type='json')
You are a Python code analyst, evaluating scripts for potential improvements.
def download_as_text(name, filename): """ Download IPList as text to specified filename. :param str name: name of IPList :param str filename: name of file for IPList download """ location = list(IPList.objects.filter(name)) if location: iplist = location[0] return iplist.dow...
Can you create a Python 3 function that downloads IPList as text to specified filename.
You are a Python code analyst, evaluating scripts for potential improvements.
def download_as_json(name): """ Download IPList as json. This would allow for easily manipulation of the IPList, but generally recommended only for smaller lists :param str name: name of IPList :return: None """ location = list(IPList.objects.filter(name)) if location: ipli...
How would you implement a function in Python 3 that downloads the specified IPList as json.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create an IPList with initial list contents.
Explain what the following Python 3 code does def create_iplist_with_data(name, iplist): iplist = IPList.create(name=name, iplist=iplist) return iplist
As a Python code analyst, you investigate and solve complex coding mysteries
def enable(self, ospf_profile=None, router_id=None): """ Enable OSPF on this engine. For master engines, enable OSPF on the virtual firewall. Once enabled on the engine, add an OSPF area to an interface:: engine.dynamic_routing.ospf.enable() interface = engine.r...
Implement a Python 3 function for enabling OSPF on this virtual firewall.
You are a Python code analyst, evaluating scripts for potential improvements.
Update the OSPF configuration using kwargs that match the enable constructor.
Given the following Python 3 function, write the documentation def update_configuration(self, **kwargs): updated = False if 'ospf_profile' in kwargs: kwargs.update(ospfv2_profile_ref=kwargs.pop('ospf_profile')) for name, value in kwargs.items(): _value = element_resolver(...
You are a Python code architect, reviewing and designing scalable and efficient code
Creates a new OSPF Area.
Can you generate a brief explanation for the following Python 3 code def create(cls, name, interface_settings_ref=None, area_id=1, area_type='normal', outbound_filters=None, inbound_filters=None, shortcut_capable_area=False, ospfv2_virtual_links_endpoints_container=None, ...
As a Python code composer, you craft elegant and concise scripts.
def create(cls, name, dead_interval=40, hello_interval=10, hello_interval_type='normal', dead_multiplier=1, mtu_mismatch_detection=True, retransmit_interval=5, router_priority=1, transmit_delay=1, authentication_type=None, password=None, key_cha...
How would you implement a function in Python 3 that creates a new custom OSPF interface settings.
As a Python code composer, you craft elegant and concise scripts.
Create an OSPF Key Chain with list of key chain entries
Explain what the following Python 3 code does def create(cls, name, key_chain_entry): key_chain_entry = key_chain_entry or [] json = {'name': name, 'ospfv2_key_chain_entry': key_chain_entry} return ElementCreator(cls, json)
You are a Python code architect, reviewing and designing scalable and efficient code
Creates an OSPF profile with the given name domain settings and optional redistribution entry.
Can you tell what is the following Python 3 function doing def create(cls, name, domain_settings_ref=None, external_distance=110, inter_distance=110, intra_distance=110, redistribution_entry=None, default_metric=None, comment=None): """ Create an OSPF Profile. ...
You are a Python code architect, reviewing and designing scalable and efficient code
Create custom domain settings
Here you have a function in Python 3, explain what it does def create(cls, name, abr_type='cisco', auto_cost_bandwidth=100, deprecated_algorithm=False, initial_delay=200, initial_hold_time=1000, max_hold_time=10000, shutdown_max_metric_lsa=0, startup_max_metric_lsa=0): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_hook(function): """ Provide a pre-filter to the create function that provides the ability to modify the element json before submitting to the SMC. To register a create hook, set on the class or top level Element class to enable this on any descendent of Element:: Element._cre...
Write a Python 3 function that can provide a pre-filter to the create function that provides the ability to modify the element json before submitting to the SMC. To register a create hook, set on the class or top level Element class to enable this on any descendent of Element:: Element._create_hook = classmethod(myhook...
As a Python code composer, you craft elegant and concise scripts.
Decorator for handling exception parameter.
How would you explain what the following Python 3 function does def exception(function): @functools.wraps(function) def wrapper(*exception, **kwargs): result = function(**kwargs) if exception: result.exception = exception[0] return result return wrapper
You are a Python code analyst, evaluating scripts for potential improvements.
def add_snmp(data, interfaces): """ Format data for adding SNMP to an engine. :param list data: list of interfaces as provided by kw :param list interfaces: interfaces to enable SNMP by id """ snmp_interface = [] if interfaces: # Not providing interfaces will enable SNMP on all NDIs ...
How would you code a function in Python 3 to format data for adding SNMP to an engine.
As a python code expert, you are capable of creating scripts from specifications.
Create a Layer 3 Firewall.
Can you tell what is the following Python 3 function doing def create_bulk(cls, name, interfaces=None, primary_mgt=None, backup_mgt=None, log_server_ref=None, domain_server_address=None, location_ref=None, default_nat=False, ...
As a Python code translator, you convert algorithms and pseudocode into Python.