Instruction:
How would you code a function in Python 3 to
render a file using the current context.

Response:
def render_file(context, path, absolute=False):
    """
    Like :py:func:`read_file`, except that the file is rendered as a Jinja template
    using the current context. If `absolute` is True, use absolute path, otherwise
    path is assumed to be relative to Tarbell template root dir.

    For example:

    .. code-block:: html+jinja

        <div class="chapter">
            {{ render_file('_chapters/one.txt') }}
        </div>
    """
    site = g.current_site
    if not absolute:
        path = os.path.join(site.path, path)

    return render_template(path, **context)


Instruction:
Write a Python 3 function for
returning a formatted date string.

Response:
def format_date(value, format='%b %d, %Y', convert_tz=None):
    """
    Format an Excel date or date string, returning a formatted date.
    To return a Python :py:class:`datetime.datetime` object, pass ``None``
    as a ``format`` argument.

    >>> format_date(42419.82163)
    'Feb. 19, 2016'

    .. code-block:: html+jinja

        {{ row.date|format_date('%Y-%m-%d') }}
    """
    if isinstance(value, float) or isinstance(value, int):
        seconds = (value - 25569) * 86400.0
        parsed = datetime.datetime.utcfromtimestamp(seconds)
    else:
        parsed = dateutil.parser.parse(value)
    if convert_tz:
        local_zone = dateutil.tz.gettz(convert_tz)
        parsed = parsed.astimezone(tz=local_zone)

    if format:
        return parsed.strftime(format)
    else:
        return parsed


Instruction:
Can you generate a brief explanation for the following Python 3 code
def plot_composition(df, intervals, axes=None):

    generics = df.columns
    if (axes is not None) and (len(axes) != len(generics)):
        raise ValueError("If 'axes' is not None then it must be the same "
                         "length as 'df.columns'")

    if axes is None:
        _, axes = plt.subplots(nrows=len(generics), ncols=1)
        if len(generics) == 1:
            axes = [axes]

    for ax, generic in zip(axes, generics):
        ax.plot(df.loc[:, generic], label=generic)
        # no legend line to avoid clutter
        ax.legend(loc='center right', handlelength=0)
        dates = intervals.loc[intervals.loc[:, "generic"] == generic,
                              ["start_date", "end_date", "contract"]]
        date_ticks = set(
            dates.loc[:, "start_date"].tolist() +
            dates.loc[:, "end_date"].tolist()
        )
        xticks = [ts.toordinal() for ts in date_ticks]
        xlabels = [ts.strftime("%Y-%m-%d") for ts in date_ticks]
        ax.set_xticks(xticks)
        ax.set_xticklabels(xlabels)
        y_top = ax.get_ylim()[1]
        count = 0
        # label and colour each underlying
        for _, dt1, dt2, instr in dates.itertuples():
            if count % 2:
                fc = "b"
            else:
                fc = "r"
            count += 1
            ax.axvspan(dt1, dt2, facecolor=fc, alpha=0.2)
            x_mid = dt1 + (dt2 - dt1) / 2
            ax.text(x_mid, y_top, instr, rotation=45)

    return axes

Response: Plot a dataframe of generics and label underlying instruments which are composed of.


Instruction:
How would you implement a function in Python 3 that
extracts intervals where generics are composed of different tradeable instruments.

Response:
def intervals(weights):
    """
    Extract intervals where generics are composed of different tradeable
    instruments.

    Parameters
    ----------
    weights: DataFrame or dict
        A DataFrame or dictionary of DataFrames with columns representing
        generics and a MultiIndex of date and contract. Values represent
        weights on tradeables for each generic.

    Returns
    -------
    A DataFrame with [columns]
    ['contract', 'generic', 'start_date', 'end_date']

    """
    intrvls = []
    if isinstance(weights, dict):
        for root in weights:
            wts = weights[root]
            intrvls.append(_intervals(wts))
        intrvls = pd.concat(intrvls, axis=0)
    else:
        intrvls = _intervals(weights)
    intrvls = intrvls.reset_index(drop=True)
    return intrvls


Instruction:
Explain what the following Python 3 code does
def synchronize(self):
        LOG.info(_LI('Syncing Neutron Router DB <-> EOS'))
        routers, router_interfaces = self.get_routers_and_interfaces()
        expected_vrfs = set()
        if self._use_vrf:
            expected_vrfs.update(self.driver._arista_router_name(
                r['id'], r['name']) for r in routers)
        expected_vlans = set(r['seg_id'] for r in router_interfaces)
        if self._enable_cleanup:
            self.do_cleanup(expected_vrfs, expected_vlans)
        self.create_routers(routers)
        self.create_router_interfaces(router_interfaces)

Response: Synchronizes the Router DB with the EOS.


Instruction:
Can you create a Python 3 function that
creates a new router entry in DB and create it Arista HW.

Response:
def create_router(self, context, router):
        """Create a new router entry in DB, and create it Arista HW."""

        # Add router to the DB
        new_router = super(AristaL3ServicePlugin, self).create_router(
            context,
            router)
        # create router on the Arista Hw
        try:
            self.driver.create_router(context, new_router)
            return new_router
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE("Error creating router on Arista HW router=%s "),
                          new_router)
                super(AristaL3ServicePlugin, self).delete_router(
                    context,
                    new_router['id']
                )


Instruction:
Implement a function in Python 3 to
update an existing router in DB and update it in Arista HW.

Response:
def update_router(self, context, router_id, router):
        """Update an existing router in DB, and update it in Arista HW."""

        # Read existing router record from DB
        original_router = self.get_router(context, router_id)
        # Update router DB
        new_router = super(AristaL3ServicePlugin, self).update_router(
            context, router_id, router)

        # Modify router on the Arista Hw
        try:
            self.driver.update_router(context, router_id,
                                      original_router, new_router)
            return new_router
        except Exception:
            LOG.error(_LE("Error updating router on Arista HW router=%s "),
                      new_router)


Instruction:
Make a summary of the following Python 3 code
def delete_router(self, context, router_id):

        router = self.get_router(context, router_id)

        # Delete router on the Arista Hw
        try:
            self.driver.delete_router(context, router_id, router)
        except Exception as e:
            LOG.error(_LE("Error deleting router on Arista HW "
                          "router %(r)s exception=%(e)s"),
                      {'r': router, 'e': e})

        super(AristaL3ServicePlugin, self).delete_router(context, router_id)

Response: Delete an existing router from Arista HW and from the DB.


Instruction:
Can you tell what is the following Python 3 function doing
def add_router_interface(self, context, router_id, interface_info):

        new_router = super(AristaL3ServicePlugin, self).add_router_interface(
            context, router_id, interface_info)

        core = directory.get_plugin()

        # Get network info for the subnet that is being added to the router.
        # Check if the interface information is by port-id or subnet-id
        add_by_port, add_by_sub = self._validate_interface_info(interface_info)
        if add_by_sub:
            subnet = core.get_subnet(context, interface_info['subnet_id'])
        elif add_by_port:
            port = core.get_port(context, interface_info['port_id'])
            subnet_id = port['fixed_ips'][0]['subnet_id']
            subnet = core.get_subnet(context, subnet_id)
        network_id = subnet['network_id']

        # To create SVI's in Arista HW, the segmentation Id is required
        # for this network.
        ml2_db = NetworkContext(self, context, {'id': network_id})
        seg_id = ml2_db.network_segments[0]['segmentation_id']

        # Package all the info needed for Hw programming
        router = self.get_router(context, router_id)
        router_info = copy.deepcopy(new_router)
        router_info['seg_id'] = seg_id
        router_info['name'] = router['name']
        router_info['cidr'] = subnet['cidr']
        router_info['gip'] = subnet['gateway_ip']
        router_info['ip_version'] = subnet['ip_version']

        try:
            self.driver.add_router_interface(context, router_info)
            return new_router
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error(_LE("Error Adding subnet %(subnet)s to "
                              "router %(router_id)s on Arista HW"),
                          {'subnet': subnet, 'router_id': router_id})
                super(AristaL3ServicePlugin, self).remove_router_interface(
                    context,
                    router_id,
                    interface_info)

Response: Add a subnet of a network to an existing router.


Instruction:
Can you implement a function in Python 3 that
removes a subnet of a network from an existing router.

Response:
def remove_router_interface(self, context, router_id, interface_info):
        """Remove a subnet of a network from an existing router."""

        router_to_del = (
            super(AristaL3ServicePlugin, self).remove_router_interface(
                context,
                router_id,
                interface_info)
            )

        # Get network information of the subnet that is being removed
        core = directory.get_plugin()
        subnet = core.get_subnet(context, router_to_del['subnet_id'])
        network_id = subnet['network_id']

        # For SVI removal from Arista HW, segmentation ID is needed
        ml2_db = NetworkContext(self, context, {'id': network_id})
        seg_id = ml2_db.network_segments[0]['segmentation_id']

        router = self.get_router(context, router_id)
        router_info = copy.deepcopy(router_to_del)
        router_info['seg_id'] = seg_id
        router_info['name'] = router['name']

        try:
            self.driver.remove_router_interface(context, router_info)
            return router_to_del
        except Exception as exc:
            LOG.error(_LE("Error removing interface %(interface)s from "
                          "router %(router_id)s on Arista HW"
                          "Exception =(exc)s"),
                      {'interface': interface_info, 'router_id': router_id,
                       'exc': exc})


Instruction:
Make a summary of the following Python 3 code
def initialize_switch_endpoints(self):
        self._switches = {}
        self._port_group_info = {}
        self._validate_config()
        for s in cfg.CONF.ml2_arista.switch_info:
            switch_ip, switch_user, switch_pass = s.split(":")
            if switch_pass == "''":
                switch_pass = ''
            self._switches[switch_ip] = api.EAPIClient(
                switch_ip,
                switch_user,
                switch_pass,
                verify=False,
                timeout=cfg.CONF.ml2_arista.conn_timeout)
        self._check_dynamic_acl_support()

Response: Initialize switch endpoints for switch communication


Instruction:
Given the following Python 3 function, write the documentation
def _check_dynamic_acl_support(self):
        cmds = ['ip access-list openstack-test dynamic',
                'no ip access-list openstack-test']
        for switch_ip, switch_client in self._switches.items():
            try:
                self.run_openstack_sg_cmds(cmds)
            except Exception:
                LOG.error("Switch %s does not support dynamic ACLs. SG "
                          "support will not be enabled on this switch.",
                          switch_ip)

Response: Log an error if any switches don t support dynamic ACLs.


Instruction:
Can you write a function in Python 3 where it
ensures at least one switch is configured

Response:
def _validate_config(self):
        """Ensure at least one switch is configured"""
        if len(cfg.CONF.ml2_arista.get('switch_info')) < 1:
            msg = _('Required option - when "sec_group_support" is enabled, '
                    'at least one switch must be specified ')
            LOG.exception(msg)
            raise arista_exc.AristaConfigError(msg=msg)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def run_openstack_sg_cmds(self, commands, switch):
        if not switch:
            LOG.exception("No client found for switch")
            return []
        if len(commands) == 0:
            return []
        command_start = ['enable', 'configure']
        command_end = ['exit']
        full_command = command_start + commands + command_end
        return self._run_eos_cmds(full_command, switch)

Response: Execute a list of commands on Arista switch and send them to the Arista server.


Instruction:
Write a Python 3 script for
executing a list of commands on Arista switch and return the result of the command.

Response:
def _run_eos_cmds(self, commands, switch):
        """Execute/sends a CAPI (Command API) command to EOS.

        This method is useful for running show commands that require no
        prefix or postfix commands.

        :param commands : List of commands to be executed on EOS.
        :param switch: Endpoint on the Arista switch to be configured
        """
        LOG.info(_LI('Executing command on Arista EOS: %s'), commands)

        try:
            # this returns array of return values for every command in
            # commands list
            ret = switch.execute(commands)
            LOG.info(_LI('Results of execution on Arista EOS: %s'), ret)
            return ret
        except Exception:
            msg = (_('Error occurred while trying to execute '
                     'commands %(cmd)s on EOS %(host)s') %
                   {'cmd': commands, 'host': switch})
            LOG.exception(msg)


Instruction:
Implement a function in Python 3 to
return list of switch_ip and interface tuples from local_link_info

Response:
def _get_switchports(profile):
        """Return list of (switch_ip, interface) tuples from local_link_info"""
        switchports = []
        if profile.get('local_link_information'):
            for link in profile['local_link_information']:
                if 'switch_info' in link and 'port_id' in link:
                    switch = link['switch_info']
                    interface = link['port_id']
                    switchports.append((switch, interface))
                else:
                    LOG.warning("Incomplete link information: %s", link)
        return switchports


Instruction:
Write a Python 3 script to
refresh data on switch interfaces port group membership

Response:
def _update_port_group_info(self, switches=None):
        """Refresh data on switch interfaces' port group membership"""
        if switches is None:
            switches = self._switches.keys()
        for switch_ip in switches:
            client = self._switches.get(switch_ip)
            ret = self._run_eos_cmds(['show interfaces'], client)
            if not ret or len(ret) == 0:
                LOG.warning("Unable to retrieve interface info for %s",
                            switch_ip)
                continue
            intf_info = ret[0]
            self._port_group_info[switch_ip] = intf_info.get('interfaces', {})


Instruction:
Explain what the following Python 3 code does
def _get_port_for_acl(self, port_id, switch):
        all_intf_info = self._port_group_info.get(switch, {})
        intf_info = all_intf_info.get(port_id, {})
        member_info = intf_info.get('interfaceMembership', '')
        port_group_info = re.search('Member of (?P<port_group>\S+)',
                                    member_info)
        if port_group_info:
            port_id = port_group_info.group('port_group')
        return port_id

Response: Gets the interface name for a given port_id for a switch.


Instruction:
Make a summary of the following Python 3 code
def _supported_rule(protocol, ethertype):
        if not protocol or protocol not in utils.SUPPORTED_SG_PROTOCOLS:
            return False

        if ethertype != n_const.IPv4:
            return False

        return True

Response: Checks that the rule is an IPv4 rule of a supported protocol


Instruction:
Can you implement a function in Python 3 that
gets EOS formatted rule

Response:
def _format_rule(self, protocol, cidr, min_port, max_port, direction):
        """Get EOS formatted rule"""
        if cidr is None:
            cidr = 'any'

        if direction == n_const.INGRESS_DIRECTION:
            dst_ip = 'any'
            src_ip = cidr
        elif direction == n_const.EGRESS_DIRECTION:
            dst_ip = cidr
            src_ip = 'any'

        if protocol == n_const.PROTO_NAME_ICMP:
            rule = "permit icmp %s %s" % (src_ip, dst_ip)
            if min_port:
                rule += " %s" % (min_port)
                if max_port:
                    rule += " %s" % (max_port)
        else:
            rule = "permit %s %s %s" % (protocol, src_ip, dst_ip)
            if min_port and max_port:
                rule += " range %s %s" % (min_port, max_port)
            elif min_port and not max_port:
                rule += " eq %s" % min_port
        return rule


Instruction:
Can you implement a function in Python 3 that
formats list of rules for EOS and sort into ingress and egress rules

Response:
def _format_rules_for_eos(self, rules):
        """Format list of rules for EOS and sort into ingress/egress rules"""
        in_rules = []
        eg_rules = []
        for rule in rules:
            protocol = rule.get('protocol')
            cidr = rule.get('remote_ip_prefix', 'any')
            min_port = rule.get('port_range_min')
            max_port = rule.get('port_range_max')
            direction = rule.get('direction')
            ethertype = rule.get('ethertype')
            if not self._supported_rule(protocol, ethertype):
                continue
            formatted_rule = self._format_rule(protocol, cidr, min_port,
                                               max_port, direction)
            if rule['direction'] == n_const.INGRESS_DIRECTION:
                in_rules.append(formatted_rule)
            elif rule['direction'] == n_const.EGRESS_DIRECTION:
                eg_rules.append(formatted_rule)
        return in_rules, eg_rules


Instruction:
Write a Python 3 script to
run all cmds on all configured switches

Response:
def run_cmds_on_all_switches(self, cmds):
        """Runs all cmds on all configured switches

        This helper is used for ACL and rule creation/deletion as ACLs
        and rules must exist on all switches.
        """
        for switch in self._switches.values():
            self.run_openstack_sg_cmds(cmds, switch)


Instruction:
How would you explain what the following Python 3 function does
def run_per_switch_cmds(self, switch_cmds):
        for switch_ip, cmds in switch_cmds.items():
            switch = self._switches.get(switch_ip)
            self.run_openstack_sg_cmds(cmds, switch)

Response:
Applies cmds to appropriate switches
        This will run only the set of cmds that are specified for a switch on that switch.


Instruction:
Make a summary of the following Python 3 code
def _get_switches(self, profile):
        switchports = self._get_switchports(profile)
        switches = set([switchport[0] for switchport in switchports])
        return switches

Response: Get set of switches referenced in a port binding profile


Instruction:
Make a summary of the following Python 3 code
def get_create_security_group_commands(self, sg_id, sg_rules):
        cmds = []
        in_rules, eg_rules = self._format_rules_for_eos(sg_rules)
        cmds.append("ip access-list %s dynamic" %
                    self._acl_name(sg_id, n_const.INGRESS_DIRECTION))
        for in_rule in in_rules:
            cmds.append(in_rule)
        cmds.append("exit")
        cmds.append("ip access-list %s dynamic" %
                    self._acl_name(sg_id, n_const.EGRESS_DIRECTION))
        for eg_rule in eg_rules:
            cmds.append(eg_rule)
        cmds.append("exit")
        return cmds

Response: Returns the list of commands to create a security group.


Instruction:
Can you write a function in Python 3 where it
returns the list of commands to delete a security group

Response:
def get_delete_security_group_commands(self, sg_id):
        """Commands for deleting ACL"""
        cmds = []
        cmds.append("no ip access-list %s" %
                    self._acl_name(sg_id, n_const.INGRESS_DIRECTION))
        cmds.append("no ip access-list %s" %
                    self._acl_name(sg_id, n_const.EGRESS_DIRECTION))
        return cmds


Instruction:
Here you have a function in Python 3, explain what it does
def get_delete_security_group_rule_commands(self, sg_id, sg_rule):
        return self._get_rule_cmds(sg_id, sg_rule, delete=True)

Response: Returns the list of commands to remove a rule from an existing security group


Instruction:
Make a summary of the following Python 3 code
def _get_interface_commands(self, sg_id, profile, delete=False):
        rule_prefix = ""
        if delete:
            rule_prefix = "no "
        switch_cmds = {}
        switchports = self._get_switchports(profile)
        for switch_ip, intf in switchports:
            cmds = []
            intf_id = self._get_port_for_acl(intf, switch_ip)
            cmds.append("interface %s" % intf_id)
            name = self._acl_name(sg_id, n_const.INGRESS_DIRECTION)
            cmds.append(rule_prefix + "ip access-group %s %s" %
                        (name, a_const.INGRESS_DIRECTION))
            name = self._acl_name(sg_id, n_const.EGRESS_DIRECTION)
            cmds.append(rule_prefix + "ip access-group %s %s" %
                        (name, a_const.EGRESS_DIRECTION))
            cmds.append("exit")
            if switch_ip not in switch_cmds.keys():
                switch_cmds[switch_ip] = []
            switch_cmds[switch_ip].extend(cmds)
        return switch_cmds

Response: Helper method for getting the list of commands for an interface ACL apply or remove.


Instruction:
How would you explain what the following Python 3 function does
def get_remove_security_group_commands(self, sg_id, profile):
        return self._get_interface_commands(sg_id, profile, delete=True)

Response: Returns the list of commands to remove ACL from interface


Instruction:
Explain what the following Python 3 code does
def _parse_acl_config(self, acl_config):
        parsed_acls = dict()
        for acl in acl_config['aclList']:
            parsed_acls[acl['name']] = set()
            for rule in acl['sequence']:
                parsed_acls[acl['name']].add(rule['text'])
        return parsed_acls

Response:
Parse the ACLs and rules
        and return a dict of rule sets.


Instruction:
Can you tell what is the following Python 3 function doing
def _parse_binding_config(self, binding_config):
        parsed_bindings = set()
        for acl in binding_config['aclList']:
            for intf in acl['configuredIngressIntfs']:
                parsed_bindings.add((intf['name'], acl['name'],
                                     a_const.INGRESS_DIRECTION))
            for intf in acl['configuredEgressIntfs']:
                parsed_bindings.add((intf['name'], acl['name'],
                                     a_const.EGRESS_DIRECTION))
        return parsed_bindings

Response: Parse the config file for the ACL bindings.


Instruction:
Write a Python 3 function that can
retrieve ACLs rules and interface bindings from switch

Response:
def _get_dynamic_acl_info(self, switch_ip):
        """Retrieve ACLs, ACLs rules and interface bindings from switch"""
        cmds = ["enable",
                "show ip access-lists dynamic",
                "show ip access-lists summary dynamic"]
        switch = self._switches.get(switch_ip)

        _, acls, bindings = self._run_eos_cmds(cmds, switch)

        parsed_acls = self._parse_acl_config(acls)
        parsed_bindings = self._parse_binding_config(bindings)

        return parsed_acls, parsed_bindings


Instruction:
Create a Python 3 function for
querying the neutron DB for the expected ACLs.

Response:
def get_expected_acls(self):
        """Query the neutron DB for Security Groups and Rules

        Groups and rules are returned as a dict of rule sets:
        {<eos_acl1_name>: set([<eos_acl1_rules>]),
         <eos_acl2_name>: set([<eos_acl2_rules>]),
         ...,
        }
        """
        security_groups = db_lib.get_security_groups()

        expected_acls = collections.defaultdict(set)
        for sg in security_groups:
            in_rules, out_rules = self._format_rules_for_eos(sg['rules'])
            ingress_acl_name = self._acl_name(sg['id'],
                                              n_const.INGRESS_DIRECTION)
            egress_acl_name = self._acl_name(sg['id'],
                                             n_const.EGRESS_DIRECTION)
            expected_acls[ingress_acl_name].update(in_rules)
            expected_acls[egress_acl_name].update(out_rules)
        return expected_acls


Instruction:
Can you write a function in Python 3 where it
queries the neutron DB for SG - > switch interface bindings and return a dict of expected bindings for each switch.

Response:
def get_expected_bindings(self):
        """Query the neutron DB for SG->switch interface bindings

        Bindings are returned as a dict of bindings for each switch:
        {<switch1>: set([(intf1, acl_name, direction),
                         (intf2, acl_name, direction)]),
         <switch2>: set([(intf1, acl_name, direction)]),
         ...,
        }
        """
        sg_bindings = db_lib.get_baremetal_sg_bindings()

        all_expected_bindings = collections.defaultdict(set)
        for sg_binding, port_binding in sg_bindings:
            sg_id = sg_binding['security_group_id']
            try:
                binding_profile = json.loads(port_binding.profile)
            except ValueError:
                binding_profile = {}
            switchports = self._get_switchports(binding_profile)
            for switch, intf in switchports:
                ingress_name = self._acl_name(sg_id, n_const.INGRESS_DIRECTION)
                egress_name = self._acl_name(sg_id, n_const.EGRESS_DIRECTION)
                all_expected_bindings[switch].add(
                    (intf, ingress_name, a_const.INGRESS_DIRECTION))
                all_expected_bindings[switch].add(
                    (intf, egress_name, a_const.EGRESS_DIRECTION))
        return all_expected_bindings


Instruction:
Write a Python 3 script for
adjusting interface names for expected bindings where LAGs exist

Response:
def adjust_bindings_for_lag(self, switch_ip, bindings):
        """Adjusting interface names for expected bindings where LAGs exist"""

        # Get latest LAG info for switch
        self._update_port_group_info([switch_ip])

        # Update bindings to account for LAG info
        adjusted_bindings = set()
        for binding in bindings:
            adjusted_bindings.add(
                (self._get_port_for_acl(binding[0], switch_ip),) + binding[1:])
        return adjusted_bindings


Instruction:
Can you write a function in Python 3 where it
returns the list of commands required synchronize switch ACLs and expected ACLs and switch rules.

Response:
def get_sync_acl_cmds(self, switch_acls, expected_acls):
        """Returns the list of commands required synchronize switch ACLs

        1. Identify unexpected ACLs and delete them
        2. Iterate over expected ACLs
           a. Add missing ACLs + all rules
           b. Delete unexpected rules
           c. Add missing rules
        """
        switch_cmds = list()

        # Delete any stale ACLs
        acls_to_delete = (set(switch_acls.keys()) - set(expected_acls.keys()))
        for acl in acls_to_delete:
            switch_cmds.append('no ip access-list %s' % acl)

        # Update or create ACLs and rules
        for acl, expected_rules in expected_acls.items():
            switch_rules = switch_acls.get(acl, set())
            rules_to_delete = switch_rules - expected_rules
            rules_to_add = expected_rules - switch_rules
            # Check if ACL requires create or rule changes
            if (acl in switch_acls and
                    len(rules_to_add | rules_to_delete) == 0):
                continue
            switch_cmds.append('ip access-list %s dynamic' % acl)
            # Delete any stale rules
            for rule in rules_to_delete:
                switch_cmds.append('no ' + rule)
            # Add any missing rules
            for rule in rules_to_add:
                switch_cmds.append(rule)
                switch_cmds.append('exit')
        return switch_cmds


Instruction:
Can you create a Python 3 function that
returns the list of commands required to synchronize the ACL bindings with the expected bindings.

Response:
def get_sync_binding_cmds(self, switch_bindings, expected_bindings):
        """Returns the list of commands required to synchronize ACL bindings

        1. Delete any unexpected bindings
        2. Add any missing bindings
        """
        switch_cmds = list()

        # Update any necessary switch interface ACLs
        bindings_to_delete = switch_bindings - expected_bindings
        bindings_to_add = expected_bindings - switch_bindings
        for intf, acl, direction in bindings_to_delete:
            switch_cmds.extend(['interface %s' % intf,
                                'no ip access-group %s %s' %
                                (acl, direction),
                                'exit'])
        for intf, acl, direction in bindings_to_add:
            switch_cmds.extend(['interface %s' % intf,
                                'ip access-group %s %s' % (acl, direction),
                                'exit'])
        return switch_cmds


Instruction:
How would you implement a function in Python 3 that
flattens a DataFrame of instrument weights into a long DataFrame.

Response:
def flatten(weights):
    """
    Flatten weights into a long DataFrame.

    Parameters
    ----------
    weights: pandas.DataFrame or dict
        A DataFrame of instrument weights with a MultiIndex where the top level
        contains pandas. Timestamps and the second level is instrument names.
        The columns consist of generic names. If dict is given this should be
        a dict of pandas.DataFrame in the above format, with keys for different
        root generics, e.g. 'CL'

    Returns
    -------
    A long DataFrame of weights, where columns are "date", "contract",
    "generic" and "weight". If a dictionary is passed, DataFrame will contain
    additional colum "key" containing the key value and be sorted according to
    this key value.

    Example
    -------
    >>> import pandas as pd
    >>> import mapping.util as util
    >>> vals = [[1, 0], [0, 1], [1, 0], [0, 1]]
    >>> widx = pd.MultiIndex.from_tuples([(pd.Timestamp('2015-01-03'), 'CLF5'),
    ...                                   (pd.Timestamp('2015-01-03'), 'CLG5'),
    ...                                   (pd.Timestamp('2015-01-04'), 'CLG5'),
    ...                                   (pd.Timestamp('2015-01-04'), 'CLH5')])
    >>> weights = pd.DataFrame(vals, index=widx, columns=["CL1", "CL2"])
    >>> util.flatten(weights)
    """  # NOQA
    if isinstance(weights, pd.DataFrame):
        wts = weights.stack().reset_index()
        wts.columns = ["date", "contract", "generic", "weight"]
    elif isinstance(weights, dict):
        wts = []
        for key in sorted(weights.keys()):
            wt = weights[key].stack().reset_index()
            wt.columns = ["date", "contract", "generic", "weight"]
            wt.loc[:, "key"] = key
            wts.append(wt)
        wts = pd.concat(wts, axis=0).reset_index(drop=True)
    else:
        raise ValueError("weights must be pd.DataFrame or dict")

    return wts


Instruction:
Can you generate the documentation for the following Python 3 function
def unflatten(flat_weights):
    if flat_weights.columns.contains("key"):
        weights = {}
        for key in flat_weights.loc[:, "key"].unique():
            flt_wts = flat_weights.loc[flat_weights.loc[:, "key"] == key, :]
            flt_wts = flt_wts.drop(labels="key", axis=1)
            wts = flt_wts.pivot_table(index=["date", "contract"],
                                      columns=["generic"],
                                      values=["weight"])
            wts.columns = wts.columns.droplevel(0)
            weights[key] = wts
    else:
        weights = flat_weights.pivot_table(index=["date", "contract"],
                                           columns=["generic"],
                                           values=["weight"])
        weights.columns = weights.columns.droplevel(0)

    return weights

Response: Unflattens a single - level dataframe into a single - level DataFrame.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def calc_rets(returns, weights):

    if not isinstance(returns, dict):
        returns = {"": returns}
    if not isinstance(weights, dict):
        weights = {"": weights}

    generic_superset = []
    for root in weights:
        generic_superset.extend(weights[root].columns.tolist())
    if len(set(generic_superset)) != len(generic_superset):
        raise ValueError("Columns for weights must all be unique")

    _check_indices(returns, weights)

    grets = []
    cols = []
    for root in returns:
        root_wts = weights[root]
        root_rets = returns[root]
        for generic in root_wts.columns:
            gnrc_wts = root_wts.loc[:, generic]
            # drop generics where weight is 0, this avoids potential KeyError
            # in later indexing of rets even when ret has weight of 0
            gnrc_wts = gnrc_wts.loc[gnrc_wts != 0]
            rets = root_rets.loc[gnrc_wts.index]
            # groupby time
            group_rets = (rets * gnrc_wts).groupby(level=0)
            grets.append(group_rets.apply(pd.DataFrame.sum, skipna=False))
        cols.extend(root_wts.columns.tolist())

    rets = pd.concat(grets, axis=1, keys=cols).sort_index(axis=1)
    return rets

Response: Calculates continuous return series for futures instruments.


Instruction:
Can you generate the documentation for the following Python 3 function
def reindex(prices, index, limit):
    if not index.is_unique:
        raise ValueError("'index' must be unique")

    index = index.sort_values()
    index.names = ["date", "instrument"]
    price_dts = prices.sort_index().index.unique(level=0)
    index_dts = index.unique(level=0)

    mask = price_dts < index_dts[0]
    leading_price_dts = price_dts[mask]
    if len(leading_price_dts) == 0:
        raise ValueError("'prices' must have a date preceding first date in "
                         "'index'")
    prev_dts = index_dts.tolist()
    prev_dts.insert(0, leading_price_dts[-1])
    # avoid just lagging to preserve the calendar
    previous_date = dict(zip(index_dts, prev_dts))

    first_instr = index.to_frame(index=False)
    first_instr = (
        first_instr.drop_duplicates(subset=["instrument"], keep="first")
    )
    first_instr.loc[:, "prev_date"] = (
        first_instr.loc[:, "date"].apply(lambda x: previous_date[x])
    )
    additional_indices = pd.MultiIndex.from_tuples(
        first_instr.loc[:, ["prev_date", "instrument"]].values.tolist()
    )

    augmented_index = index.union(additional_indices).sort_values()
    prices = prices.reindex(augmented_index)
    if limit != 0:
        prices = prices.groupby(level=1).fillna(method="ffill", limit=limit)
    return prices

Response: Reindex a Series of prices with a pd. MultiIndex of instrument weights and fill forward missing values with previous price up to limit.


Instruction:
Write a Python 3 function for
calculating the number of tradeable contracts for rebalancing from a set of current and desired generic notional holdings.

Response:
def calc_trades(current_contracts, desired_holdings, trade_weights, prices,
                multipliers, **kwargs):
    """
    Calculate the number of tradeable contracts for rebalancing from a set
    of current contract holdings to a set of desired generic notional holdings
    based on prevailing prices and mapping from generics to tradeable
    instruments. Differences between current holdings and desired holdings
    are treated as 0. Zero trades are dropped.

    Parameters
    ----------
    current_contracts: pandas.Series
        Series of current number of contracts held for tradeable instruments.
        Can pass 0 if all holdings are 0.
    desired_holdings: pandas.Series
        Series of desired holdings in base notional currency of generics. Index
        is generic contracts, these should be the same generics as in
        trade_weights.
    trade_weights: pandas.DataFrame or dict
        A pandas.DataFrame of loadings of generic contracts on tradeable
        instruments **for a given date**. The columns refer to generic
        contracts and the index is strings representing instrument names.
        If dict is given keys should be root generic names, e.g. 'CL', and
        values should be pandas.DataFrames of loadings. The union of all
        columns should be a superset of the desired_holdings.index
    prices: pandas.Series
        Series of instrument prices. Index is instrument name and values are
        number of contracts. Extra instrument prices will be ignored.
    multipliers: pandas.Series
        Series of instrument multipliers. Index is instrument name and
        values are the multiplier associated with the contract.
        multipliers.index should be a superset of mapped desired_holdings
        intruments.
    kwargs: key word arguments
        Key word arguments to be passed to to_contracts()

    Returns
    -------
    A pandas.Series of instrument contract trades, lexigraphically sorted.

    Example
    -------
    >>> import pandas as pd
    >>> import mapping.util as util
    >>> wts = pd.DataFrame([[0.5, 0], [0.5, 0.5], [0, 0.5]],
    ...                    index=["CLX16", "CLZ16", "CLF17"],
    ...                    columns=["CL1", "CL2"])
    >>> desired_holdings = pd.Series([200000, -50000], index=["CL1", "CL2"])
    >>> current_contracts = pd.Series([0, 1, 0],
    ...                               index=['CLX16', 'CLZ16', 'CLF17'])
    >>> prices = pd.Series([50.32, 50.41, 50.48],
    ...                    index=['CLX16', 'CLZ16', 'CLF17'])
    >>> multipliers = pd.Series([100, 100, 100],
    ...                        index=['CLX16', 'CLZ16', 'CLF17'])
    >>> trades = util.calc_trades(current_contracts, desired_holdings, wts,
    ...                           prices, multipliers)
    """
    if not isinstance(trade_weights, dict):
        trade_weights = {"": trade_weights}

    generics = []
    for key in trade_weights:
        generics.extend(trade_weights[key].columns)

    if not set(desired_holdings.index).issubset(set(generics)):
        raise ValueError("'desired_holdings.index' contains values which "
                         "cannot be mapped to tradeables.\n"
                         "Received: 'desired_holdings.index'\n {0}\n"
                         "Expected in 'trade_weights' set of columns:\n {1}\n"
                         .format(sorted(desired_holdings.index),
                                 sorted(generics)))

    desired_contracts = []
    for root_key in trade_weights:
        gnrc_weights = trade_weights[root_key]

        subset = gnrc_weights.columns.intersection(desired_holdings.index)
        gnrc_des_hlds = desired_holdings.loc[subset]
        gnrc_weights = gnrc_weights.loc[:, subset]
        # drop indexes where all non zero weights were in columns dropped above
        gnrc_weights = gnrc_weights.loc[~(gnrc_weights == 0).all(axis=1)]

        instr_des_hlds = gnrc_des_hlds * gnrc_weights
        instr_des_hlds = instr_des_hlds.sum(axis=1)
        wprices = prices.loc[instr_des_hlds.index]
        desired_contracts.append(to_contracts(instr_des_hlds, wprices,
                                              multipliers, **kwargs))

    desired_contracts = pd.concat(desired_contracts, axis=0)

    trades = desired_contracts.subtract(current_contracts, fill_value=0)
    trades = trades.loc[trades != 0]
    trades = trades.sort_index()
    return trades


Instruction:
Here you have a function in Python 3, explain what it does
def to_notional(instruments, prices, multipliers, desired_ccy=None,
                instr_fx=None, fx_rates=None):
    """
    Convert number of contracts of tradeable instruments to notional value of
    tradeable instruments in a desired currency.

    Parameters
    ----------
    instruments: pandas.Series
        Series of instrument holdings. Index is instrument name and values are
        number of contracts.
    prices: pandas.Series
        Series of instrument prices. Index is instrument name and values are
        instrument prices. prices.index should be a superset of
        instruments.index otherwise NaN returned for instruments without prices
    multipliers: pandas.Series
        Series of instrument multipliers. Index is instrument name and
        values are the multiplier associated with the contract.
        multipliers.index should be a superset of instruments.index
    desired_ccy: str
        Three letter string representing desired currency to convert notional
        values to, e.g. 'USD'. If None is given currency conversion is ignored.
    instr_fx: pandas.Series
        Series of instrument fx denominations. Index is instrument name and
        values are three letter strings representing the currency the
        instrument is denominated in. instr_fx.index should match prices.index
    fx_rates: pandas.Series
        Series of fx rates used for conversion to desired_ccy. Index is strings
        representing the FX pair, e.g. 'AUDUSD' or 'USDCAD'. Values are the
        corresponding exchange rates.

    Returns
    -------
    pandas.Series of notional amounts of instruments with Index of instruments
    names

    Example
    -------
    >>> import pandas as pd
    >>> import mapping.util as util
    >>> current_contracts = pd.Series([-1, 1], index=['CLX16', 'CLZ16'])
    >>> prices = pd.Series([50.32, 50.41], index=['CLX16', 'CLZ16'])
    >>> multipliers = pd.Series([100, 100], index=['CLX16', 'CLZ16'])
    >>> ntln = util.to_notional(current_contracts, prices, multipliers)
    """
    notionals = _instr_conv(instruments, prices, multipliers, True,
                            desired_ccy, instr_fx, fx_rates)
    return notionals

Response: Convert number of contracts prices multipliers and fx rates to a notional value of the current tradeable instruments.


Instruction:
Implement a function in Python 3 to
convert notional amount of tradeable instruments to number of instrument contracts.

Response:
def to_contracts(instruments, prices, multipliers, desired_ccy=None,
                 instr_fx=None, fx_rates=None, rounder=None):
    """
    Convert notional amount of tradeable instruments to number of instrument
    contracts, rounding to nearest integer number of contracts.

    Parameters
    ----------
    instruments: pandas.Series
        Series of instrument holdings. Index is instrument name and values are
        notional amount on instrument.
    prices: pandas.Series
        Series of instrument prices. Index is instrument name and values are
        instrument prices. prices.index should be a superset of
        instruments.index
    multipliers: pandas.Series
        Series of instrument multipliers. Index is instrument name and
        values are the multiplier associated with the contract.
        multipliers.index should be a superset of instruments.index
    desired_ccy: str
        Three letter string representing desired currency to convert notional
        values to, e.g. 'USD'. If None is given currency conversion is ignored.
    instr_fx: pandas.Series
        Series of instrument fx denominations. Index is instrument name and
        values are three letter strings representing the currency the
        instrument is denominated in. instr_fx.index should match prices.index
    fx_rates: pandas.Series
        Series of fx rates used for conversion to desired_ccy. Index is strings
        representing the FX pair, e.g. 'AUDUSD' or 'USDCAD'. Values are the
        corresponding exchange rates.
    rounder: function
        Function to round pd.Series contracts to integers, if None default
        pd.Series.round is used.

    Returns
    -------
    pandas.Series of contract numbers of instruments with Index of instruments
    names
    """
    contracts = _instr_conv(instruments, prices, multipliers, False,
                            desired_ccy, instr_fx, fx_rates)
    if rounder is None:
        rounder = pd.Series.round

    contracts = rounder(contracts)
    contracts = contracts.astype(int)
    return contracts


Instruction:
Write a Python 3 function that can
determine tradeable instrument multiplier based on generic asset multipliers and weights mapping from generics to tradeables. Parameters ---------- weights: pandas.DataFrame or dict A pandas.DataFrame of loadings of generic contracts on tradeable instruments **for a given date**. The columns are integers refering to generic number indexed from 0, e.g. [0, 1], and the index is strings representing instrument names. If dict is given keys should be generic instrument names, e.g. 'CL', and values should be pandas.DataFrames of loadings. The union of all indexes should be a superset of the instruments.index root_generic_multiplier: pandas.Series Series of multipliers for generic instruments lexigraphically sorted. If a dictionary of weights is given, root_generic_multiplier.index should correspond to the weights keys. Returns ------- A pandas.Series of multipliers for tradeable instruments. Examples -------- >>> import pandas as pd >>> import mapping.util as util >>> wts = pd.DataFrame([[0.5, 0], [0.5, 0.5], [0, 0.5]], ... index=["CLX16", "CLZ16", "CLF17"], ... columns=[0, 1]) >>> ast_mult = pd.Series([1000], index=["CL"]) >>> util.get_multiplier(wts, ast_mult)

Response:
def get_multiplier(weights, root_generic_multiplier):
    """
    Determine tradeable instrument multiplier based on generic asset
    multipliers and weights mapping from generics to tradeables.

    Parameters
    ----------
    weights: pandas.DataFrame or dict
        A pandas.DataFrame of loadings of generic contracts on tradeable
        instruments **for a given date**. The columns are integers refering to
        generic number indexed from 0, e.g. [0, 1], and the index is strings
        representing instrument names. If dict is given keys should be generic
        instrument names, e.g. 'CL', and values should be pandas.DataFrames of
        loadings. The union of all indexes should be a superset of the
        instruments.index
    root_generic_multiplier: pandas.Series
        Series of multipliers for generic instruments lexigraphically sorted.
        If a dictionary of weights is given, root_generic_multiplier.index
        should correspond to the weights keys.

    Returns
    -------
    A pandas.Series of multipliers for tradeable instruments.

    Examples
    --------
    >>> import pandas as pd
    >>> import mapping.util as util
    >>> wts = pd.DataFrame([[0.5, 0], [0.5, 0.5], [0, 0.5]],
    ...                    index=["CLX16", "CLZ16", "CLF17"],
    ...                    columns=[0, 1])
    >>> ast_mult = pd.Series([1000], index=["CL"])
    >>> util.get_multiplier(wts, ast_mult)
    """
    if len(root_generic_multiplier) > 1 and not isinstance(weights, dict):
        raise ValueError("For multiple generic instruments weights must be a "
                         "dictionary")

    mults = []
    intrs = []
    for ast, multiplier in root_generic_multiplier.iteritems():
        if isinstance(weights, dict):
            weights_ast = weights[ast].index
        else:
            weights_ast = weights.index
        mults.extend(np.repeat(multiplier, len(weights_ast)))
        intrs.extend(weights_ast)

    imults = pd.Series(mults, intrs)
    imults = imults.sort_index()
    return imults


Instruction:
Explain what the following Python 3 code does
def weighted_expiration(weights, contract_dates):
    cols = weights.columns
    weights = weights.reset_index(level=-1)
    expiries = contract_dates.to_dict()
    weights.loc[:, "expiry"] = weights.iloc[:, 0].apply(lambda x: expiries[x])
    diffs = (pd.DatetimeIndex(weights.expiry)
             - pd.Series(weights.index, weights.index)).apply(lambda x: x.days)
    weights = weights.loc[:, cols]
    wexp = weights.mul(diffs, axis=0).groupby(level=0).sum()
    return wexp

Response: Calculates the days to expiration for a single resource item.


Instruction:
How would you explain what the following Python 3 function does
def _valid_baremetal_port(port):
        if port.get(portbindings.VNIC_TYPE) != portbindings.VNIC_BAREMETAL:
            return False
        sgs = port.get('security_groups', [])
        if len(sgs) == 0:
            # Nothing to do
            return False
        if len(port.get('security_groups', [])) > 1:
            LOG.warning('SG provisioning failed for %(port)s. Only one '
                        'SG may be applied per port.',
                        {'port': port['id']})
            return False
        return True

Response: Check if the port is a baremetal port with exactly one security group.


Instruction:
Explain what the following Python 3 code does
def synchronize_resources(self):
        # Grab the sync lock
        if not self._rpc.sync_start():
            LOG.info("%(pid)s Failed to grab the sync lock",
                     {'pid': os.getpid()})
            greenthread.sleep(1)
            return

        for resource in self._resources_to_update:
            self.update_neutron_resource(resource)
        self._resources_to_update = list()

        # Sync any necessary resources.
        # We delete in reverse order and create in order to ensure that
        # dependent resources  are deleted before the resources they depend
        # on and created after them
        for resource_type in reversed(self.sync_order):
            resource_type.delete_cvx_resources()
        for resource_type in self.sync_order:
            resource_type.create_cvx_resources()

        # Release the sync lock
        self._rpc.sync_end()

        # Update local uuid if this was a full sync
        if self._synchronizing_uuid:
            LOG.info("%(pid)s Full sync for cvx uuid %(uuid)s complete",
                     {'uuid': self._synchronizing_uuid,
                      'pid': os.getpid()})
            self._cvx_uuid = self._synchronizing_uuid
            self._synchronizing_uuid = None

Response: Synchronize with CVX and update the internal state of all resources.


Instruction:
Here you have a function in Python 3, explain what it does
def register(self, resource, event, trigger, **kwargs):
        super(AristaTrunkDriver, self).register(resource, event,
                                                trigger, kwargs)
        registry.subscribe(self.subport_create,
                           resources.SUBPORTS, events.AFTER_CREATE)
        registry.subscribe(self.subport_delete,
                           resources.SUBPORTS, events.AFTER_DELETE)
        registry.subscribe(self.trunk_create,
                           resources.TRUNK, events.AFTER_CREATE)
        registry.subscribe(self.trunk_update,
                           resources.TRUNK, events.AFTER_UPDATE)
        registry.subscribe(self.trunk_delete,
                           resources.TRUNK, events.AFTER_DELETE)
        self.core_plugin = directory.get_plugin()
        LOG.debug("Arista trunk driver initialized.")

Response: Called in trunk plugin s AFTER_INIT method


Instruction:
Can you create a Python 3 function that
creates a router on Arista HW Device.

Response:
def create_router_on_eos(self, router_name, rdm, server):
        """Creates a router on Arista HW Device.

        :param router_name: globally unique identifier for router/VRF
        :param rdm: A value generated by hashing router name
        :param server: Server endpoint on the Arista switch to be configured
        """
        cmds = []
        rd = "%s:%s" % (rdm, rdm)

        for c in self.routerDict['create']:
            cmds.append(c.format(router_name, rd))

        if self._mlag_configured:
            mac = VIRTUAL_ROUTER_MAC
            for c in self._additionalRouterCmdsDict['create']:
                cmds.append(c.format(mac))

        self._run_config_cmds(cmds, server)


Instruction:
How would you explain what the following Python 3 function does
def delete_router_from_eos(self, router_name, server):
        cmds = []
        for c in self.routerDict['delete']:
            cmds.append(c.format(router_name))
        if self._mlag_configured:
            for c in self._additionalRouterCmdsDict['delete']:
                cmds.append(c)

        self._run_config_cmds(cmds, server)

Response: Deletes a router from Arista HW Device.


Instruction:
Explain what the following Python 3 code does
def add_interface_to_router(self, segment_id,
                                router_name, gip, router_ip, mask, server):
        """Adds an interface to existing HW router on Arista HW device.

        :param segment_id: VLAN Id associated with interface that is added
        :param router_name: globally unique identifier for router/VRF
        :param gip: Gateway IP associated with the subnet
        :param router_ip: IP address of the router
        :param mask: subnet mask to be used
        :param server: Server endpoint on the Arista switch to be configured
        """

        if not segment_id:
            segment_id = DEFAULT_VLAN
        cmds = []
        for c in self._interfaceDict['add']:
            if self._mlag_configured:
                # In VARP config, use router ID else, use gateway IP address.
                ip = router_ip
            else:
                ip = gip + '/' + mask
            cmds.append(c.format(segment_id, router_name, ip))
        if self._mlag_configured:
            for c in self._additionalInterfaceCmdsDict['add']:
                cmds.append(c.format(gip))

        self._run_config_cmds(cmds, server)

Response: Adds an interface to existing HW router on Arista HW device.


Instruction:
Write a Python 3 function for
deleting an interface from existing HW router on Arista HW device.

Response:
def delete_interface_from_router(self, segment_id, router_name, server):
        """Deletes an interface from existing HW router on Arista HW device.

        :param segment_id: VLAN Id associated with interface that is added
        :param router_name: globally unique identifier for router/VRF
        :param server: Server endpoint on the Arista switch to be configured
        """

        if not segment_id:
            segment_id = DEFAULT_VLAN
        cmds = []
        for c in self._interfaceDict['remove']:
            cmds.append(c.format(segment_id))

        self._run_config_cmds(cmds, server)


Instruction:
Can you tell what is the following Python 3 function doing
def create_router(self, context, router):
        if router:
            router_name = self._arista_router_name(router['id'],
                                                   router['name'])

            hashed = hashlib.sha256(router_name.encode('utf-8'))
            rdm = str(int(hashed.hexdigest(), 16) % 65536)

            mlag_peer_failed = False
            for s in self._servers:
                try:
                    self.create_router_on_eos(router_name, rdm, s)
                    mlag_peer_failed = False
                except Exception:
                    if self._mlag_configured and not mlag_peer_failed:
                        # In paied switch, it is OK to fail on one switch
                        mlag_peer_failed = True
                    else:
                        msg = (_('Failed to create router %s on EOS') %
                               router_name)
                        LOG.exception(msg)
                        raise arista_exc.AristaServicePluginRpcError(msg=msg)

Response: Creates a router on Arista Switch.


Instruction:
Can you write a function in Python 3 where it
deletes a router from Arista Switch.

Response:
def delete_router(self, context, router_id, router):
        """Deletes a router from Arista Switch."""

        if router:
            router_name = self._arista_router_name(router_id, router['name'])
            mlag_peer_failed = False
            for s in self._servers:
                try:
                    self.delete_router_from_eos(router_name, s)
                    mlag_peer_failed = False
                except Exception:
                    if self._mlag_configured and not mlag_peer_failed:
                        # In paied switch, it is OK to fail on one switch
                        mlag_peer_failed = True
                    else:
                        msg = (_('Failed to create router %s on EOS') %
                               router_name)
                        LOG.exception(msg)
                        raise arista_exc.AristaServicePluginRpcError(msg=msg)


Instruction:
How would you code a function in Python 3 to
add an interface to a router.

Response:
def add_router_interface(self, context, router_info):
        """Adds an interface to a router created on Arista HW router.

        This deals with both IPv6 and IPv4 configurations.
        """
        if router_info:
            self._select_dicts(router_info['ip_version'])
            cidr = router_info['cidr']
            subnet_mask = cidr.split('/')[1]
            router_name = self._arista_router_name(router_info['id'],
                                                   router_info['name'])
            if self._mlag_configured:
                # For MLAG, we send a specific IP address as opposed to cidr
                # For now, we are using x.x.x.253 and x.x.x.254 as virtual IP
                mlag_peer_failed = False
                for i, server in enumerate(self._servers):
                    # Get appropriate virtual IP address for this router
                    router_ip = self._get_router_ip(cidr, i,
                                                    router_info['ip_version'])
                    try:
                        self.add_interface_to_router(router_info['seg_id'],
                                                     router_name,
                                                     router_info['gip'],
                                                     router_ip, subnet_mask,
                                                     server)
                        mlag_peer_failed = False
                    except Exception:
                        if not mlag_peer_failed:
                            mlag_peer_failed = True
                        else:
                            msg = (_('Failed to add interface to router '
                                     '%s on EOS') % router_name)
                            LOG.exception(msg)
                            raise arista_exc.AristaServicePluginRpcError(
                                msg=msg)

            else:
                for s in self._servers:
                    self.add_interface_to_router(router_info['seg_id'],
                                                 router_name,
                                                 router_info['gip'],
                                                 None, subnet_mask, s)


Instruction:
Make a summary of the following Python 3 code
def remove_router_interface(self, context, router_info):
        if router_info:
            router_name = self._arista_router_name(router_info['id'],
                                                   router_info['name'])
            mlag_peer_failed = False
            for s in self._servers:
                try:
                    self.delete_interface_from_router(router_info['seg_id'],
                                                      router_name, s)
                    if self._mlag_configured:
                        mlag_peer_failed = False
                except Exception:
                    if self._mlag_configured and not mlag_peer_failed:
                        mlag_peer_failed = True
                    else:
                        msg = (_('Failed to add interface to router '
                                 '%s on EOS') % router_name)
                        LOG.exception(msg)
                        raise arista_exc.AristaServicePluginRpcError(msg=msg)

Response: Removes previously configured router interface from Arista HW.


Instruction:
Create a Python 3 function for
executing a list of commands on Arista switch and send them to the Arista switch

Response:
def _run_config_cmds(self, commands, server):
        """Execute/sends a CAPI (Command API) command to EOS.

        In this method, list of commands is appended with prefix and
        postfix commands - to make is understandble by EOS.

        :param commands : List of command to be executed on EOS.
        :param server: Server endpoint on the Arista switch to be configured
        """
        command_start = ['enable', 'configure']
        command_end = ['exit']
        full_command = command_start + commands + command_end
        self._run_eos_cmds(full_command, server)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _get_binary_from_ipv4(self, ip_addr):

        return struct.unpack("!L", socket.inet_pton(socket.AF_INET,
                                                    ip_addr))[0]

Response: Converts IPv4 address to binary form.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _get_binary_from_ipv6(self, ip_addr):

        hi, lo = struct.unpack("!QQ", socket.inet_pton(socket.AF_INET6,
                                                       ip_addr))
        return (hi << 64) | lo

Response: Converts IPv6 address to binary form.


Instruction:
Can you write a function in Python 3 where it
converts binary address to Ipv4 format.

Response:
def _get_ipv4_from_binary(self, bin_addr):
        """Converts binary address to Ipv4 format."""

        return socket.inet_ntop(socket.AF_INET, struct.pack("!L", bin_addr))


Instruction:
Explain what the following Python 3 code does
def _get_ipv6_from_binary(self, bin_addr):

        hi = bin_addr >> 64
        lo = bin_addr & 0xFFFFFFFF
        return socket.inet_ntop(socket.AF_INET6, struct.pack("!QQ", hi, lo))

Response: Converts binary address to Ipv6 format.


Instruction:
Implement a function in Python 3 to
run migrations in offline mode.

Response:
def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL or an Engine.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    set_mysql_engine()

    kwargs = dict()
    if neutron_config.database.connection:
        kwargs['url'] = neutron_config.database.connection
    else:
        kwargs['dialect_name'] = neutron_config.database.engine
    kwargs['include_object'] = include_object
    kwargs['version_table'] = ARISTA_VERSION_TABLE
    context.configure(**kwargs)

    with context.begin_transaction():
        context.run_migrations()


Instruction:
Here you have a function in Python 3, explain what it does
def get_instance_type(self, port):
        if port[portbindings.VNIC_TYPE] == portbindings.VNIC_BAREMETAL:
            return a_const.BAREMETAL_RESOURCE
        owner_to_type = {
            n_const.DEVICE_OWNER_DHCP: a_const.DHCP_RESOURCE,
            n_const.DEVICE_OWNER_DVR_INTERFACE: a_const.ROUTER_RESOURCE,
            trunk_consts.TRUNK_SUBPORT_OWNER: a_const.VM_RESOURCE}
        if port['device_owner'] in owner_to_type.keys():
            return owner_to_type[port['device_owner']]
        elif port['device_owner'].startswith(
                n_const.DEVICE_OWNER_COMPUTE_PREFIX):
            return a_const.VM_RESOURCE
        return None

Response: Determine the port type based on the device owner and vnic type.


Instruction:
Write a Python 3 function for
getting the binding keys from the port binding

Response:
def _get_binding_keys(self, port, host):
        """Get binding keys from the port binding"""
        binding_keys = list()
        switch_binding = port[portbindings.PROFILE].get(
            'local_link_information', None)
        if switch_binding:
            for binding in switch_binding:
                switch_id = binding.get('switch_id')
                port_id = binding.get('port_id')
                binding_keys.append((port['id'], (switch_id, port_id)))
        else:
            binding_keys.append((port['id'], host))
        return binding_keys


Instruction:
Can you generate the documentation for the following Python 3 function
def delete_port_binding(self, port, host):
        if not self.get_instance_type(port):
            return
        for pb_key in self._get_binding_keys(port, host):
            pb_res = MechResource(pb_key, a_const.PORT_BINDING_RESOURCE,
                                  a_const.DELETE)
            self.provision_queue.put(pb_res)

Response: Enqueue port binding delete


Instruction:
How would you explain what the following Python 3 function does
def create_network_postcommit(self, context):
        network = context.current

        log_context("create_network_postcommit: network", network)

        segments = context.network_segments
        tenant_id = network['project_id']
        self.create_tenant(tenant_id)
        self.create_network(network)
        self.create_segments(segments)

Response: Provision the network on CVX and create the segments on CVX


Instruction:
Can you generate the documentation for the following Python 3 function
def update_network_postcommit(self, context):
        network = context.current
        orig_network = context.original

        log_context("update_network_postcommit: network", network)
        log_context("update_network_postcommit: orig", orig_network)

        segments = context.network_segments

        self.create_network(network)

        # New segments may have been added
        self.create_segments(segments)

Response: Send network updates to CVX


Instruction:
Explain what the following Python 3 code does
def delete_network_postcommit(self, context):
        network = context.current

        log_context("delete_network_postcommit: network", network)

        segments = context.network_segments
        tenant_id = network['project_id']
        self.delete_segments(segments)
        self.delete_network(network)
        self.delete_tenant_if_removed(tenant_id)

Response: Delete the network from CVX and tenant from CVX


Instruction:
Write a Python 3 function that can
send port updates to CVX

Response:
def update_port_postcommit(self, context):
        """Send port updates to CVX

        This method is also responsible for the initial creation of ports
        as we wait until after a port is bound to send the port data to CVX
        """
        port = context.current
        orig_port = context.original
        network = context.network.current

        log_context("update_port_postcommit: port", port)
        log_context("update_port_postcommit: orig", orig_port)

        tenant_id = port['project_id']

        # Device id can change without a port going DOWN, but the new device
        # id may not be supported
        if orig_port and port['device_id'] != orig_port['device_id']:
            self._delete_port_resources(orig_port, context.original_host)

        if context.status == n_const.PORT_STATUS_DOWN:
            if (context.original_host and
                    context.status != context.original_status):
                self._delete_port_resources(orig_port, context.original_host)
                self._try_to_release_dynamic_segment(context, migration=True)
        else:
            self.create_tenant(tenant_id)
            self.create_network(network)
            if context.binding_levels:
                segments = [
                    level['bound_segment'] for level in context.binding_levels]
                self.create_segments(segments)
            self.create_instance(port)
            self.create_port(port)
            self.create_port_binding(port, context.host)


Instruction:
Here you have a function in Python 3, explain what it does
def delete_port_postcommit(self, context):
        port = context.current

        log_context("delete_port_postcommit: port", port)

        self._delete_port_resources(port, context.host)
        self._try_to_release_dynamic_segment(context)

Response: Delete the port from CVX


Instruction:
Here you have a function in Python 3, explain what it does
def _bind_baremetal_port(self, context, segment):
        port = context.current
        vif_details = {
            portbindings.VIF_DETAILS_VLAN: str(
                segment[driver_api.SEGMENTATION_ID])
        }
        context.set_binding(segment[driver_api.ID],
                            portbindings.VIF_TYPE_OTHER,
                            vif_details,
                            n_const.ACTIVE)
        LOG.debug("AristaDriver: bound port info- port ID %(id)s "
                  "on network %(network)s",
                  {'id': port['id'],
                   'network': context.network.current['id']})
        if port.get('trunk_details'):
            self.trunk_driver.bind_port(port)
        return True

Response: Bind the baremetal port to the segment


Instruction:
Create a Python 3 function for
finding the appropriate physnet for the current node in the context.

Response:
def _get_physnet(self, context):
        """Find the appropriate physnet for the host

        - Baremetal ports' physnet is determined by looking at the
          local_link_information contained in the binding profile
        - Other ports' physnet is determined by looking for the host in the
          topology
        """
        port = context.current
        physnet = None
        if (port.get(portbindings.VNIC_TYPE) == portbindings.VNIC_BAREMETAL):
            physnet = self.eapi.get_baremetal_physnet(context)
        else:
            physnet = self.eapi.get_host_physnet(context)
        # If the switch is part of an mlag pair, the physnet is called
        # peer1_peer2
        physnet = self.mlag_pairs.get(physnet, physnet)
        return physnet


Instruction:
Implement a Python 3 function for
allocating dynamic segments for the port and continue binding.

Response:
def _bind_fabric(self, context, segment):
        """Allocate dynamic segments for the port

        Segment physnets are based on the switch to which the host is
        connected.
        """
        port_id = context.current['id']
        physnet = self._get_physnet(context)
        if not physnet:
            LOG.debug("bind_port for port %(port)s: no physical_network "
                      "found", {'port': port_id})
            return False

        next_segment = context.allocate_dynamic_segment(
            {'network_id': context.network.current['id'],
             'network_type': n_const.TYPE_VLAN,
             'physical_network': physnet})
        LOG.debug("bind_port for port %(port)s: "
                  "current_segment=%(current_seg)s, "
                  "next_segment=%(next_seg)s",
                  {'port': port_id, 'current_seg': segment,
                   'next_seg': next_segment})
        context.continue_binding(segment['id'], [next_segment])
        return True


Instruction:
Here you have a function in Python 3, explain what it does
def bind_port(self, context):
        port = context.current

        log_context("bind_port: port", port)

        for segment in context.segments_to_bind:
            physnet = segment.get(driver_api.PHYSICAL_NETWORK)
            segment_type = segment[driver_api.NETWORK_TYPE]
            if not physnet:
                if (segment_type == n_const.TYPE_VXLAN and self.manage_fabric):
                    if self._bind_fabric(context, segment):
                        continue
            elif (port.get(portbindings.VNIC_TYPE)
                    == portbindings.VNIC_BAREMETAL):
                if (not self.managed_physnets or
                        physnet in self.managed_physnets):
                    if self._bind_baremetal_port(context, segment):
                        continue
            LOG.debug("Arista mech driver unable to bind port %(port)s to "
                      "%(seg_type)s segment on physical_network %(physnet)s",
                      {'port': port.get('id'), 'seg_type': segment_type,
                       'physnet': physnet})

Response: Bind a port to a network segment.


Instruction:
Explain what the following Python 3 code does
def _try_to_release_dynamic_segment(self, context, migration=False):
        if migration:
            binding_levels = context.original_binding_levels
        else:
            binding_levels = context.binding_levels
        LOG.debug("_try_release_dynamic_segment: "
                  "binding_levels=%(bl)s", {'bl': binding_levels})
        if not binding_levels:
            return

        for prior_level, binding in enumerate(binding_levels[1:]):
            allocating_driver = binding_levels[prior_level].get(
                driver_api.BOUND_DRIVER)
            if allocating_driver != a_const.MECHANISM_DRV_NAME:
                continue
            bound_segment = binding.get(driver_api.BOUND_SEGMENT, {})
            segment_id = bound_segment.get('id')
            if not db_lib.segment_is_dynamic(segment_id):
                continue
            if not db_lib.segment_bound(segment_id):
                context.release_dynamic_segment(segment_id)
                LOG.debug("Released dynamic segment %(seg)s allocated "
                          "by %(drv)s", {'seg': segment_id,
                                         'drv': allocating_driver})

Response: Try to release dynamic segment if necessary.


Instruction:
Make a summary of the following Python 3 code
def roller(timestamps, contract_dates, get_weights, **kwargs):
    timestamps = sorted(timestamps)
    contract_dates = contract_dates.sort_values()
    _check_contract_dates(contract_dates)
    weights = []
    # for loop speedup only validate inputs the first function call to
    # get_weights()
    validate_inputs = True
    ts = timestamps[0]
    weights.extend(get_weights(ts, contract_dates,
                               validate_inputs=validate_inputs, **kwargs))
    validate_inputs = False
    for ts in timestamps[1:]:
        weights.extend(get_weights(ts, contract_dates,
                                   validate_inputs=validate_inputs, **kwargs))

    weights = aggregate_weights(weights)
    return weights

Response: Calculates weight allocations for a given set of timestamps for a given root generic.


Instruction:
Make a summary of the following Python 3 code
def aggregate_weights(weights, drop_date=False):
    dwts = pd.DataFrame(weights,
                        columns=["generic", "contract", "weight", "date"])
    dwts = dwts.pivot_table(index=['date', 'contract'],
                            columns=['generic'], values='weight', fill_value=0)
    dwts = dwts.astype(float)
    dwts = dwts.sort_index()
    if drop_date:
        dwts.index = dwts.index.levels[-1]
    return dwts

Response: Takes a list of tuples of weight on this contract and returns a pandas. DataFrame of loadings of generic contracts on the tradeable contracts for that date.


Instruction:
How would you explain what the following Python 3 function does
def static_transition(timestamp, contract_dates, transition, holidays=None,
                      validate_inputs=True):
    """
    An implementation of *get_weights* parameter in roller().
    Return weights to tradeable instruments for a given date based on a
    transition DataFrame which indicates how to roll through the roll period.

    Parameters
    ----------
    timestamp: pandas.Timestamp
        The timestamp to return instrument weights for
    contract_dates: pandas.Series
        Series with index of tradeable contract names and pandas.Timestamps
        representing the last date of the roll as values, sorted by values.
        Index must be unique and values must be strictly monotonic.
    transition: pandas.DataFrame
        A DataFrame with a index of integers representing business day offsets
        from the last roll date and a column which is a MultiIndex where the
        top level is generic instruments and the second level is
        ['front', 'back'] which refer to the front month contract and the back
        month contract of the roll. Note that for different generics, e.g. CL1,
        CL2, the front and back month contract during a roll would refer to
        different underlying instruments. The values represent the fraction of
        the roll on each day during the roll period. The first row of the
        transition period should be completely allocated to the front contract
        and the last row should be completely allocated to the back contract.
    holidays: array_like of datetime64[D]
        Holidays to exclude when calculating business day offsets from the last
        roll date. See numpy.busday_count.
    validate_inputs: Boolean
        Whether or not to validate ordering of contract_dates and transition.
        **Caution** this is provided for speed however if this is set to False
        and inputs are not defined properly algorithm may return incorrect
        data.

    Returns
    -------
    A list of tuples consisting of the generic instrument name, the tradeable
    contract as a string, the weight on this contract as a float and the date
    as a pandas.Timestamp.

    Examples
    --------
    >>> import pandas as pd
    >>> import mapping.mappings as mappings
    >>> cols = pd.MultiIndex.from_product([["CL1", "CL2"], ['front', 'back']])
    >>> idx = [-2, -1, 0]
    >>> transition = pd.DataFrame([[1.0, 0.0, 1.0, 0.0], [0.5, 0.5, 0.5, 0.5],
    ...                            [0.0, 1.0, 0.0, 1.0]],
    ...                           index=idx, columns=cols)
    >>> contract_dates = pd.Series([pd.Timestamp('2016-10-20'),
    ...                             pd.Timestamp('2016-11-21'),
    ...                             pd.Timestamp('2016-12-20')],
    ...                            index=['CLX16', 'CLZ16', 'CLF17'])
    >>> ts = pd.Timestamp('2016-10-19')
    >>> wts = mappings.static_transition(ts, contract_dates, transition)
    """

    if validate_inputs:
        # required for MultiIndex slicing
        _check_static(transition.sort_index(axis=1))
        # the algorithm below will return invalid results if contract_dates is
        # not as expected so better to fail explicitly
        _check_contract_dates(contract_dates)

    if not holidays:
        holidays = []

    # further speedup can be obtained using contract_dates.loc[timestamp:]
    # but this requires swapping contract_dates index and values
    after_contract_dates = contract_dates.loc[contract_dates >= timestamp]
    contracts = after_contract_dates.index
    front_expiry_dt = after_contract_dates.iloc[0]
    days_to_expiry = np.busday_count(front_expiry_dt.date(), timestamp.date(),
                                     holidays=holidays)

    name2num = dict(zip(transition.columns.levels[0],
                        range(len(transition.columns.levels[0]))))
    if days_to_expiry in transition.index:
        weights_iter = transition.loc[days_to_expiry].iteritems()
    # roll hasn't started yet
    elif days_to_expiry < transition.index.min():
        # provides significant speedup over transition.iloc[0].iteritems()
        vals = transition.values[0]
        weights_iter = zip(transition.columns.tolist(), vals)
    # roll is finished
    else:
        vals = transition.values[-1]
        weights_iter = zip(transition.columns.tolist(), vals)

    cwts = []
    for idx_tuple, weighting in weights_iter:
        gen_name, position = idx_tuple
        if weighting != 0:
            if position == "front":
                cntrct_idx = name2num[gen_name]
            elif position == "back":
                cntrct_idx = name2num[gen_name] + 1
            try:
                cntrct_name = contracts[cntrct_idx]
            except IndexError as e:
                raise type(e)(("index {0} is out of bounds in\n{1}\nas of {2} "
                               "resulting from {3} mapping")
                              .format(cntrct_idx, after_contract_dates,
                                      timestamp, idx_tuple)
                              ).with_traceback(sys.exc_info()[2])
            cwts.append((gen_name, cntrct_name, weighting, timestamp))

    return cwts

Response: This function returns a static transition for a given date based on a given transition.


Instruction:
Implement a Python 3 function for
mapping tradeable instruments to generics given weights and tradeable instrument holdings. This is solving the equation Ax = b where A is the weights, and b is the instrument holdings. When Ax = b has no solution we solve for x' such that Ax' is closest to b in the least squares sense with the additional constraint that sum(x') = sum(instruments). Scenarios with exact solutions and non exact solutions are depicted below +------------+-----+-----+ Instruments | contract | CL1 | CL2 | ------------------------------------ |------------+-----+-----| Scenario 1 | Scenario 2 | Scenario 3 | CLX16 | 0.5 | 0 | 10 | 10 | 10 | CLZ16 | 0.5 | 0.5 | 20 | 20 | 25 | CLF17 | 0 | 0.5 | 10 | 11 | 11 +------------+-----+-----+ In scenario 1 the solution is given by x = [20, 20], in scenario 2 the solution is given by x = [19.5, 21.5], and in scenario 3 the solution is given by x = [22, 24]. NOTE: Integer solutions are not guruanteed, as demonstrated above. This is intended for use with contract numbers but can also be used with notional amounts of contracts. Parameters ---------- instruments: pandas.Series Series of tradeable instrument holdings where the index is the name of the tradeable instrument and the value is the number of that instrument held. weights: pandas.DataFrame or dict A pandas.DataFrame of loadings of generic contracts on tradeable instruments for a given date. The columns are generic instruments and the index is strings representing instrument names. If dict is given keys should be root generic, e.g. 'CL', and values should be pandas.DataFrames of loadings. The union of all indexes should be a superset of the instruments.index Returns ------- A pandas.Series where the index is the generic and the value is the number of contracts, sorted by index. Examples -------- >>> import pandas as pd >>> import mapping.mappings as mappings >>> wts = pd.DataFrame([[0.5, 0], [0.5, 0.5], [0, 0.5]], ... index=["CLX16", "CLZ16", "CLF17"], ... columns=["CL1", "CL2"]) >>> instrs = pd.Series([10, 20, 10], index=["CLX16", "CLZ16", "CLF17"]) >>> generics = mappings.to_generics(instrs, wts)

Response:
def to_generics(instruments, weights):
    """
    Map tradeable instruments to generics given weights and tradeable
    instrument holdings. This is solving the equation Ax = b where A is the
    weights, and b is the instrument holdings. When Ax = b has no solution we
    solve for x' such that Ax' is closest to b in the least squares sense with
    the additional constraint that sum(x') = sum(instruments).

    Scenarios with exact solutions and non exact solutions are depicted below

    +------------+-----+-----+ Instruments
    | contract   | CL1 | CL2 | ------------------------------------
    |------------+-----+-----| Scenario 1 | Scenario 2 | Scenario 3
    | CLX16      | 0.5 | 0   | 10         | 10         | 10
    | CLZ16      | 0.5 | 0.5 | 20         | 20         | 25
    | CLF17      | 0   | 0.5 | 10         | 11         | 11
    +------------+-----+-----+

    In scenario 1 the solution is given by x = [20, 20], in scenario 2 the
    solution is given by x = [19.5, 21.5], and in scenario 3 the solution is
    given by x = [22, 24].

    NOTE: Integer solutions are not guruanteed, as demonstrated above. This is
    intended for use with contract numbers but can also be used with notional
    amounts of contracts.

    Parameters
    ----------
    instruments: pandas.Series
        Series of tradeable instrument holdings where the index is the name of
        the tradeable instrument and the value is the number of that instrument
        held.
    weights: pandas.DataFrame or dict
        A pandas.DataFrame of loadings of generic contracts on tradeable
        instruments for a given date. The columns are generic instruments
        and the index is strings representing instrument names. If dict is
        given keys should be root generic, e.g. 'CL', and values should be
        pandas.DataFrames of loadings. The union of all indexes should be a
        superset of the instruments.index

    Returns
    -------
    A pandas.Series where the index is the generic and the value is the number
    of contracts, sorted by index.

    Examples
    --------
    >>> import pandas as pd
    >>> import mapping.mappings as mappings
    >>> wts = pd.DataFrame([[0.5, 0], [0.5, 0.5], [0, 0.5]],
    ...                    index=["CLX16", "CLZ16", "CLF17"],
    ...                    columns=["CL1", "CL2"])
    >>> instrs = pd.Series([10, 20, 10], index=["CLX16", "CLZ16", "CLF17"])
    >>> generics = mappings.to_generics(instrs, wts)
    """
    if not isinstance(weights, dict):
        weights = {"": weights}

    allocations = []
    unmapped_instr = instruments.index
    for key in weights:
        w = weights[key]
        # may not always have instrument holdings for a set of weights so allow
        # weights to be a superset of instruments, drop values where no
        # holdings
        winstrs = instruments.reindex(w.index).dropna()
        w = w.loc[winstrs.index]
        # drop generics where all weights for instruments on the genric are 0.
        # This avoids numerical rounding issues where solution has epsilon
        # weight on a generic
        w = w.loc[:, ~(w == 0).all(axis=0)]

        unmapped_instr = unmapped_instr.difference(winstrs.index)

        A = w.values
        b = winstrs.values
        x = cvxpy.Variable(A.shape[1])
        constrs = [CVX_SUM(x) == np.sum(b)]
        obj = cvxpy.Minimize(cvxpy.sum_squares(A * x - b))
        prob = cvxpy.Problem(obj, constrs)
        prob.solve()

        vals = np.array(x.value).squeeze()
        idx = w.columns.tolist()
        allocations.append(pd.Series(vals, index=idx))

    if len(unmapped_instr) > 0:
        raise KeyError("Unmapped instruments %s. weights must be a superset of"
                       " instruments" % unmapped_instr.tolist())

    allocations = pd.concat(allocations, axis=0)
    allocations = allocations.sort_index()
    return allocations


Instruction:
Here you have a function in Python 3, explain what it does
def synchronize_switch(self, switch_ip, expected_acls, expected_bindings):

        # Get ACL rules and interface mappings from the switch
        switch_acls, switch_bindings = self._get_dynamic_acl_info(switch_ip)

        # Adjust expected bindings for switch LAG config
        expected_bindings = self.adjust_bindings_for_lag(switch_ip,
                                                         expected_bindings)
        # Get synchronization commands
        switch_cmds = list()
        switch_cmds.extend(
            self.get_sync_acl_cmds(switch_acls, expected_acls))
        switch_cmds.extend(
            self.get_sync_binding_cmds(switch_bindings, expected_bindings))

        # Update switch config
        self.run_openstack_sg_cmds(switch_cmds, self._switches.get(switch_ip))

Response: Synchronize a switch with the expected config.


Instruction:
Can you create a Python 3 function that
performs synchronization of the security groups between ML2 and EOS.

Response:
def synchronize(self):
        """Perform sync of the security groups between ML2 and EOS."""

        # Get expected ACLs and rules
        expected_acls = self.get_expected_acls()

        # Get expected interface to ACL mappings
        all_expected_bindings = self.get_expected_bindings()

        # Check that config is correct on every registered switch
        for switch_ip in self._switches.keys():
            expected_bindings = all_expected_bindings.get(switch_ip, [])
            try:
                self.synchronize_switch(switch_ip, expected_acls,
                                        expected_bindings)
            except Exception:
                LOG.exception("Failed to sync SGs for %(switch)s",
                              {'switch': switch_ip})


Instruction:
Can you implement a function in Python 3 that
checks validity of CLI commands for Arista s VLAN type driver.

Response:
def check_vlan_type_driver_commands(self):
        """Checks the validity of CLI commands for Arista's VLAN type driver.

           This method tries to execute the commands used exclusively by the
           arista_vlan type driver and stores the commands if they succeed.
        """
        cmd = ['show openstack resource-pool vlan region %s uuid'
               % self.region]
        try:
            self._run_eos_cmds(cmd)
            self.cli_commands['resource-pool'] = cmd
        except arista_exc.AristaRpcError:
            self.cli_commands['resource-pool'] = []
            LOG.warning(
                _LW("'resource-pool' command '%s' is not available on EOS"),
                cmd)


Instruction:
How would you explain what the following Python 3 function does
def get_vlan_assignment_uuid(self):
        vlan_uuid_cmd = self.cli_commands['resource-pool']
        if vlan_uuid_cmd:
            return self._run_eos_cmds(commands=vlan_uuid_cmd)[0]
        return None

Response: Returns the UUID for the region s vlan assignment on CVX


Instruction:
Explain what the following Python 3 code does
def get_vlan_allocation(self):
        if not self.cli_commands['resource-pool']:
            LOG.warning(_('The version of CVX you are using does not support'
                          'arista VLAN type driver.'))
        else:
            cmd = ['show openstack resource-pools region %s' % self.region]
            command_output = self._run_eos_cmds(cmd)
            if command_output:
                regions = command_output[0]['physicalNetwork']
                if self.region in regions.keys():
                    return regions[self.region]['vlanPool']['default']
        return {'assignedVlans': '',
                'availableVlans': '',
                'allocatedVlans': ''}

Response: Returns the status of the region s VLAN pool in CVX


Instruction:
Can you create a Python 3 function that
executes a list of commands on Arista EOS and return the response.

Response:
def _run_eos_cmds(self, commands, commands_to_log=None):
        """Execute/sends a CAPI (Command API) command to EOS.

        In this method, list of commands is appended with prefix and
        postfix commands - to make is understandble by EOS.

        :param commands : List of command to be executed on EOS.
        :param commands_to_log : This should be set to the command that is
                                 logged. If it is None, then the commands
                                 param is logged.
        """

        # Always figure out who is master (starting with the last known val)
        try:
            if self._get_eos_master() is None:
                msg = "Failed to identify CVX master"
                self.set_cvx_unavailable()
                raise arista_exc.AristaRpcError(msg=msg)
        except Exception:
            self.set_cvx_unavailable()
            raise

        self.set_cvx_available()
        log_cmds = commands
        if commands_to_log:
            log_cmds = commands_to_log

        LOG.info(_LI('Executing command on Arista EOS: %s'), log_cmds)
        # this returns array of return values for every command in
        # full_command list
        try:
            response = self._send_eapi_req(cmds=commands,
                                           commands_to_log=log_cmds)
            if response is None:
                # Reset the server as we failed communicating with it
                self._server_ip = None
                self.set_cvx_unavailable()
                msg = "Failed to communicate with CVX master"
                raise arista_exc.AristaRpcError(msg=msg)
            return response
        except arista_exc.AristaRpcError:
            raise


Instruction:
Can you implement a function in Python 3 that
builds full EOS s openstack CLI command.

Response:
def _build_command(self, cmds, sync=False):
        """Build full EOS's openstack CLI command.

        Helper method to add commands to enter and exit from openstack
        CLI modes.

        :param cmds: The openstack CLI commands that need to be executed
                     in the openstack config mode.
        :param sync: This flags indicates that the region is being synced.
        """

        region_cmd = 'region %s' % self.region
        if sync:
            region_cmd = self.cli_commands[const.CMD_REGION_SYNC]

        full_command = [
            'enable',
            'configure',
            'cvx',
            'service openstack',
            region_cmd,
        ]
        full_command.extend(cmds)
        return full_command


Instruction:
Can you generate the documentation for the following Python 3 function
def _run_openstack_cmds(self, commands, commands_to_log=None, sync=False):

        full_command = self._build_command(commands, sync=sync)
        if commands_to_log:
            full_log_command = self._build_command(commands_to_log, sync=sync)
        else:
            full_log_command = None
        return self._run_eos_cmds(full_command, full_log_command)

Response: Execute a list of commands on the OpenStack device.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_baremetal_physnet(self, context):
        port = context.current
        host_id = context.host
        cmd = ['show network physical-topology hosts']
        try:
            response = self._run_eos_cmds(cmd)
            binding_profile = port.get(portbindings.PROFILE, {})
            link_info = binding_profile.get('local_link_information', [])
            for link in link_info:
                switch_id = link.get('switch_id')
                for host in response[0]['hosts'].values():
                    if switch_id == host['name']:
                        physnet = host['hostname']
                        LOG.debug("get_physical_network: Physical Network for "
                                  "%(host)s is %(physnet)s",
                                  {'host': host_id, 'physnet': physnet})
                        return physnet
            LOG.debug("Physical network not found for %(host)s",
                      {'host': host_id})
        except Exception as exc:
            LOG.error(_LE('command %(cmd)s failed with '
                      '%(exc)s'), {'cmd': cmd, 'exc': exc})
        return None

Response: Returns dictionary which contains mac to hostname mapping


Instruction:
How would you implement a function in Python 3 that
returns dictionary which contains physical topology information for a given host_id

Response:
def get_host_physnet(self, context):
        """Returns dictionary which contains physical topology information

        for a given host_id
        """
        host_id = utils.hostname(context.host)
        cmd = ['show network physical-topology neighbors']
        try:
            response = self._run_eos_cmds(cmd)
            # Get response for 'show network physical-topology neighbors'
            # command
            neighbors = response[0]['neighbors']
            for neighbor in neighbors:
                if host_id in neighbor:
                    physnet = neighbors[neighbor]['toPort'][0]['hostname']
                    LOG.debug("get_physical_network: Physical Network for "
                              "%(host)s is %(physnet)s", {'host': host_id,
                                                          'physnet': physnet})
                    return physnet
            LOG.debug("Physical network not found for %(host)s",
                      {'host': host_id})
        except Exception as exc:
            LOG.error(_LE('command %(cmd)s failed with '
                      '%(exc)s'), {'cmd': cmd, 'exc': exc})
        return None


Instruction:
Explain what the following Python 3 code does
def filter_unnecessary_segments(query):
    segment_model = segment_models.NetworkSegment
    network_model = models_v2.Network
    query = (query
             .join_if_necessary(network_model)
             .join_if_necessary(segment_model)
             .filter(network_model.project_id != '')
             .filter_network_type())
    return query

Response: Filter segments are not needed on CVX


Instruction:
Implement a function in Python 3 to
filter unsupported network types

Response:
def filter_network_type(query):
    """Filter unsupported segment types"""
    segment_model = segment_models.NetworkSegment
    query = (query
             .filter(
                 segment_model.network_type.in_(
                     utils.SUPPORTED_NETWORK_TYPES)))
    return query


Instruction:
Can you create a Python 3 function that
filters ports not bound to a host or network

Response:
def filter_unbound_ports(query):
    """Filter ports not bound to a host or network"""
    # hack for pep8 E711: comparison to None should be
    # 'if cond is not None'
    none = None
    port_model = models_v2.Port
    binding_level_model = ml2_models.PortBindingLevel
    query = (query
             .join_if_necessary(port_model)
             .join_if_necessary(binding_level_model)
             .filter(
                 binding_level_model.host != '',
                 port_model.device_id != none,
                 port_model.network_id != none))
    return query