output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Calculates continuous return series for futures instruments.
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....
You are a Python code analyst, evaluating scripts for potential improvements.
Reindex a Series of prices with a pd. MultiIndex of instrument weights and fill forward missing values with previous price up to limit.
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) ...
As a python code expert, you are capable of creating scripts from specifications.
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...
Write a Python 3 function for calculating the number of tradeable contracts for rebalancing from a set of current and desired generic notional holdings.
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert number of contracts prices multipliers and fx rates to a notional value of the current tradeable instruments.
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. Parame...
As a python code expert, you are capable of creating scripts from specifications.
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 ---------- instr...
Implement a function in Python 3 to convert notional amount of tradeable instruments to number of instrument contracts.
You are a Python code generator, capable of creating scripts from specifications.
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 contr...
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 ...
You are a Python code analyst, evaluating scripts for potential improvements.
Calculates the days to expiration for a single resource item.
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(weig...
You are a Python code analyst, evaluating scripts for potential improvements.
Check if the port is a baremetal port with exactly one security group.
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 Fal...
As a Python code translator, you convert algorithms and pseudocode into Python.
Synchronize with CVX and update the internal state of all resources.
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 reso...
You are a Python code analyst, evaluating scripts for potential improvements.
Called in trunk plugin s AFTER_INIT method
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, ...
You are a Python code analyst, evaluating scripts for potential improvements.
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 ...
Can you create a Python 3 function that creates a router on Arista HW Device.
As a Python code composer, you craft elegant and concise scripts.
Deletes a router from Arista HW Device.
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['delet...
As a Python code composer, you craft elegant and concise scripts.
Adds an interface to existing HW router on Arista HW device.
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 ...
You are a Python code analyst, evaluating scripts for potential improvements.
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: S...
Write a Python 3 function for deleting an interface from existing HW router on Arista HW device.
As a python code expert, you are capable of creating scripts from specifications.
Creates a router on Arista Switch.
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')) ...
As a python code expert, you are capable of creating scripts from specifications.
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...
Can you write a function in Python 3 where it deletes a router from Arista Switch.
As a Python code translator, you convert algorithms and pseudocode into Python.
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'] ...
How would you code a function in Python 3 to add an interface to a router.
As a Python code composer, you craft elegant and concise scripts.
Removes previously configured router interface from Arista HW.
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 fo...
As a Python code composer, you craft elegant and concise scripts.
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 s...
Create a Python 3 function for executing a list of commands on Arista switch and send them to the Arista switch
You are a Python code architect, reviewing and designing scalable and efficient code
Converts IPv4 address to binary form.
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]
As a python code expert, you are capable of creating scripts from specifications.
Converts IPv6 address to binary form.
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
You are a Python code generator, capable of creating scripts from specifications.
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))
Can you write a function in Python 3 where it converts binary address to Ipv4 format.
You are a Python code analyst, evaluating scripts for potential improvements.
Converts binary address to Ipv6 format.
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))
As a Python code translator, you convert algorithms and pseudocode into Python.
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: ...
Implement a function in Python 3 to run migrations in offline mode.
You are a Python code analyst, evaluating scripts for potential improvements.
Determine the port type based on the device owner and vnic type.
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....
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 function for getting the binding keys from the port binding
As a Python code composer, you craft elegant and concise scripts.
Enqueue port binding delete
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, ...
You are a Python code architect, reviewing and designing scalable and efficient code
Provision the network on CVX and create the segments on CVX
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_t...
You are a Python code generator, capable of creating scripts from specifications.
Send network updates to CVX
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_n...
As a python code expert, you are capable of creating scripts from specifications.
Delete the network from CVX and tenant from CVX
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) ...
As a python code expert, you are capable of creating scripts from specifications.
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 ne...
Write a Python 3 function that can send port updates to CVX
As a Python code composer, you craft elegant and concise scripts.
Delete the port from CVX
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)
As a Python code analyst, you investigate and solve complex coding mysteries
Bind the baremetal port to the segment
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_ap...
You are a Python code architect, reviewing and designing scalable and efficient code
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 ...
Create a Python 3 function for finding the appropriate physnet for the current node in the context.
As a python code expert, you are capable of creating scripts from specifications.
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.d...
Implement a Python 3 function for allocating dynamic segments for the port and continue binding.
As a Python code composer, you craft elegant and concise scripts.
Bind a port to a network segment.
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...
As a python code expert, you are capable of creating scripts from specifications.
Try to release dynamic segment if necessary.
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: " ...
As a Python code analyst, you investigate and solve complex coding mysteries
Calculates weight allocations for a given set of timestamps for a given root generic.
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 cal...
As a Python code translator, you convert algorithms and pseudocode into Python.
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.
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='weig...
You are a Python code analyst, evaluating scripts for potential improvements.
This function returns a static transition for a given date based on a given transition.
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 base...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
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 ...
As a python code expert, you are capable of creating scripts from specifications.
Synchronize a switch with the expected config.
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 switc...
You are a Python code analyst, evaluating scripts for potential improvements.
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 confi...
Can you create a Python 3 function that performs synchronization of the security groups between ML2 and EOS.
You are a Python code architect, reviewing and designing scalable and efficient code
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 re...
Can you implement a function in Python 3 that checks validity of CLI commands for Arista s VLAN type driver.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the UUID for the region s vlan assignment on CVX
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
As a Python code composer, you craft elegant and concise scripts.
Returns the status of the region s VLAN pool in CVX
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-p...
As a python code expert, you are capable of creating scripts from specifications.
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. ...
Can you create a Python 3 function that executes a list of commands on Arista EOS and return the response.
As a Python code translator, you convert algorithms and pseudocode into Python.
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. :...
Can you implement a function in Python 3 that builds full EOS s openstack CLI command.
As a Python code analyst, you investigate and solve complex coding mysteries
Execute a list of commands on the OpenStack device.
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) ...
As a Python code composer, you craft elegant and concise scripts.
Returns dictionary which contains mac to hostname mapping
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 = ...
You are a Python code architect, reviewing and designing scalable and efficient code
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) ...
How would you implement a function in Python 3 that returns dictionary which contains physical topology information for a given host_id
As a Python code translator, you convert algorithms and pseudocode into Python.
Filter segments are not needed on CVX
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_mode...
You are a Python code architect, reviewing and designing scalable and efficient code
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
Implement a function in Python 3 to filter unsupported network types
As a Python code composer, you craft elegant and concise scripts.
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_necessa...
Can you create a Python 3 function that filters ports not bound to a host or network
You are a Python code analyst, evaluating scripts for potential improvements.
def filter_by_device_owner(query, device_owners=None): """Filter ports by device_owner Either filter using specified device_owner or using the list of all device_owners supported and unsupported by the arista ML2 plugin """ port_model = models_v2.Port if not device_owners: device_owners...
Can you implement a function in Python 3 that filters ports by device_owner
As a Python code composer, you craft elegant and concise scripts.
Filter ports attached to devices we don t care about
Given the following Python 3 function, write the documentation def filter_by_device_id(query): port_model = models_v2.Port unsupported_device_id_filter = [ port_model.device_id.notilike('%s%%' % id) for id in utils.UNSUPPORTED_DEVICE_IDS] query = (query .filter(and_(*unsupported...
You are a Python code analyst, evaluating scripts for potential improvements.
Filter ports by vnic_type
Explain what the following Python 3 code does def filter_by_vnic_type(query, vnic_type): port_model = models_v2.Port binding_model = ml2_models.PortBinding dst_binding_model = ml2_models.DistributedPortBinding query = (query .outerjoin_if_necessary( binding_model, ...
As a Python code analyst, you investigate and solve complex coding mysteries
def filter_unmanaged_physnets(query): """Filter ports managed by other ML2 plugins """ config = cfg.CONF.ml2_arista managed_physnets = config['managed_physnets'] # Filter out ports bound to segments on physnets that we're not # managing segment_model = segment_models.NetworkSegment if manag...
Can you write a function in Python 3 where it filters ports managed by other ML2 plugins
As a python code expert, you are capable of creating scripts from specifications.
Filter ports that aren t in active status
Make a summary of the following Python 3 code def filter_inactive_ports(query): port_model = models_v2.Port query = (query .filter(port_model.status == n_const.PORT_STATUS_ACTIVE)) return query
You are a Python code generator, capable of creating scripts from specifications.
def filter_unnecessary_ports(query, device_owners=None, vnic_type=None, active=True): """Filter out all ports are not needed on CVX """ query = (query .filter_unbound_ports() .filter_by_device_owner(device_owners) .filter_by_device_id() ...
Can you write a function in Python 3 where it filters out ports that are not needed on CVX.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns list of all project ids that may be relevant on CVX
How would you explain what the following Python 3 function does def get_tenants(tenant_id=None): if tenant_id == '': return [] session = db.get_reader_session() project_ids = set() with session.begin(): for m in [models_v2.Network, models_v2.Port]: q = session.query(m.project...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_networks(network_id=None): """Returns list of all networks that may be relevant on CVX""" session = db.get_reader_session() with session.begin(): model = models_v2.Network networks = session.query(model).filter(model.project_id != '') if network_id: networks = net...
How would you code a function in Python 3 to return list of all networks that may be relevant on CVX
You are a Python code generator, capable of creating scripts from specifications.
Returns list of all network segments that may be relevant on CVX
Can you tell what is the following Python 3 function doing def get_segments(segment_id=None): session = db.get_reader_session() with session.begin(): model = segment_models.NetworkSegment segments = session.query(model).filter_unnecessary_segments() if segment_id: segments = ...
As a python code expert, you are capable of creating scripts from specifications.
Returns a list of all instances in the neutron database
Make a summary of the following Python 3 code def get_instances(device_owners=None, vnic_type=None, instance_id=None): session = db.get_reader_session() with session.begin(): port_model = models_v2.Port binding_model = ml2_models.PortBinding instances = (session .que...
As a Python code composer, you craft elegant and concise scripts.
Returns filtered list of vms that may be relevant on CVX
Can you tell what is the following Python 3 function doing def get_vm_instances(instance_id=None): return get_instances(device_owners=[n_const.DEVICE_OWNER_COMPUTE_PREFIX], vnic_type=portbindings.VNIC_NORMAL, instance_id=instance_id)
You are a Python code architect, reviewing and designing scalable and efficient code
Returns list of all ports in neutron the db
Can you generate a brief explanation for the following Python 3 code def get_ports(device_owners=None, vnic_type=None, port_id=None, active=True): session = db.get_reader_session() with session.begin(): port_model = models_v2.Port ports = (session .query(port_model) ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_vm_ports(port_id=None): """Returns filtered list of vms that may be relevant on CVX""" return get_ports(device_owners=[n_const.DEVICE_OWNER_COMPUTE_PREFIX, t_const.TRUNK_SUBPORT_OWNER], vnic_type=portbindings.VNIC_NORMAL, port_id=port_id)
Implement a function in Python 3 to return filtered list of vms that may be relevant on CVX
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a filtered list of port bindings that may be relevant on CVX.
Can you generate a brief explanation for the following Python 3 code def get_port_bindings(binding_key=None): session = db.get_reader_session() with session.begin(): binding_level_model = ml2_models.PortBindingLevel aliased_blm = aliased(ml2_models.PortBindingLevel) port_binding_model = ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns True if any networks or ports exist for a tenant.
Can you generate the documentation for the following Python 3 function def tenant_provisioned(tenant_id): session = db.get_reader_session() with session.begin(): res = any( session.query(m).filter(m.tenant_id == tenant_id).count() for m in [models_v2.Network, models_v2.Port] ...
As a python code expert, you are capable of creating scripts from specifications.
def instance_provisioned(device_id): """Returns true if any ports exist for an instance.""" session = db.get_reader_session() with session.begin(): port_model = models_v2.Port res = bool(session.query(port_model) .filter(port_model.device_id == device_id).count()) retu...
Write a Python 3 function that can return True if any ports exist for an instance.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns true if port is already provisioned.
Make a summary of the following Python 3 code def port_provisioned(port_id): session = db.get_reader_session() with session.begin(): port_model = models_v2.Port res = bool(session.query(port_model) .filter(port_model.id == port_id).count()) return res
You are a Python code generator, capable of creating scripts from specifications.
Get trunk subport s parent port
Given the following Python 3 function, write the documentation def get_parent(port_id): session = db.get_reader_session() res = dict() with session.begin(): subport_model = trunk_models.SubPort trunk_model = trunk_models.Trunk subport = (session.query(subport_model). ...
As a Python code composer, you craft elegant and concise scripts.
Returns entries from PortBindingLevel based on the specified filters.
Make a summary of the following Python 3 code def get_port_binding_level(filters): session = db.get_reader_session() with session.begin(): return (session.query(ml2_models.PortBindingLevel). filter_by(**filters). order_by(ml2_models.PortBindingLevel.level). ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def read(file, frames=-1, start=0, stop=None, dtype='float64', always_2d=False, fill_value=None, out=None, samplerate=None, channels=None, format=None, subtype=None, endian=None, closefd=True): """Provide audio data from a sound file as NumPy array. By default, the whole file is read from the...
Can you write a function in Python 3 where it reads audio data from a sound file.
As a python code expert, you are capable of creating scripts from specifications.
def write(file, data, samplerate, subtype=None, endian=None, format=None, closefd=True): """Write data to a sound file. .. note:: If `file` exists, it will be truncated and overwritten! Parameters ---------- file : str or int or file-like object The file to write to. See :class:...
Implement a Python 3 function for writing data to a sound file.
You are a Python code architect, reviewing and designing scalable and efficient code
def blocks(file, blocksize=None, overlap=0, frames=-1, start=0, stop=None, dtype='float64', always_2d=False, fill_value=None, out=None, samplerate=None, channels=None, format=None, subtype=None, endian=None, closefd=True): """Return a generator for block-wise reading. By defaul...
Implement a function in Python 3 to return a generator for reading audio files in a specific block - wise fashion.
You are a Python code analyst, evaluating scripts for potential improvements.
def available_subtypes(format=None): """Return a dictionary of available subtypes. Parameters ---------- format : str If given, only compatible subtypes are returned. Examples -------- >>> import soundfile as sf >>> sf.available_subtypes('FLAC') {'PCM_24': 'Signed 24 bit PC...
Can you implement a function in Python 3 that returns a dictionary of available subtypes.
You are a Python code analyst, evaluating scripts for potential improvements.
def check_format(format, subtype=None, endian=None): """Check if the combination of format/subtype/endian is valid. Examples -------- >>> import soundfile as sf >>> sf.check_format('WAV', 'PCM_24') True >>> sf.check_format('FLAC', 'VORBIS') False """ try: return bool(_f...
Can you implement a function in Python 3 that checks if the combination of format subtype and endian is valid.
You are a Python code architect, reviewing and designing scalable and efficient code
def _format_int(format, subtype, endian): """Return numeric ID for given format|subtype|endian combo.""" result = _check_format(format) if subtype is None: subtype = default_subtype(format) if subtype is None: raise TypeError( "No default subtype for major format ...
Can you create a Python 3 function that returns numeric ID for given format|subtype|endian combo.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _check_mode(mode): """Check if mode is valid and return its integer representation.""" if not isinstance(mode, (_unicode, str)): raise TypeError("Invalid mode: {0!r}".format(mode)) mode_set = set(mode) if mode_set.difference('xrwb+') or len(mode) > len(mode_set): raise ValueError("In...
Can you write a function in Python 3 where it checks if mode is valid and return its integer representation.
You are a Python code architect, reviewing and designing scalable and efficient code
def _create_info_struct(file, mode, samplerate, channels, format, subtype, endian): """Check arguments and create SF_INFO struct.""" original_format = format if format is None: format = _get_format_from_filename(file, mode) assert isinstance(format, (_unicode, str)) ...
How would you code a function in Python 3 to check arguments and create SF_INFO struct.
As a Python code composer, you craft elegant and concise scripts.
def _get_format_from_filename(file, mode): """Return a format string obtained from file (or file.name). If file already exists (= read mode), an empty string is returned on error. If not, an exception is raised. The return type will always be str or unicode (even if file/file.name is a bytes objec...
Create a Python 3 function to get a format string obtained from a file extension.
You are a Python code generator, capable of creating scripts from specifications.
def _format_str(format_int): """Return the string representation of a given numeric format.""" for dictionary in _formats, _subtypes, _endians: for k, v in dictionary.items(): if v == format_int: return k else: return 'n/a'
Create a Python 3 function to return the string representation of a given numeric format.
You are a Python code architect, reviewing and designing scalable and efficient code
Return the ID and short description of a given format.
Can you generate a brief explanation for the following Python 3 code def _format_info(format_int, format_flag=_snd.SFC_GET_FORMAT_INFO): format_info = _ffi.new("SF_FORMAT_INFO*") format_info.format = format_int _snd.sf_command(_ffi.NULL, format_flag, format_info, _ffi.sizeof("SF_FORMAT_I...
You are a Python code architect, reviewing and designing scalable and efficient code
Check if format_str is valid and return format ID.
Can you tell what is the following Python 3 function doing def _check_format(format_str): if not isinstance(format_str, (_unicode, str)): raise TypeError("Invalid format: {0!r}".format(format_str)) try: format_int = _formats[format_str.upper()] except KeyError: raise ValueError("Unkn...
As a python code expert, you are capable of creating scripts from specifications.
def _has_virtual_io_attrs(file, mode_int): """Check if file has all the necessary attributes for virtual IO.""" readonly = mode_int == _snd.SFM_READ writeonly = mode_int == _snd.SFM_WRITE return all([ hasattr(file, 'seek'), hasattr(file, 'tell'), hasattr(file, 'write') or readonl...
Can you create a Python 3 function that checks if file has all the necessary attributes for virtual IO.
You are a Python code architect, reviewing and designing scalable and efficient code
def extra_info(self): """Retrieve the log string generated when opening the file.""" info = _ffi.new("char[]", 2**14) _snd.sf_command(self._file, _snd.SFC_GET_LOG_INFO, info, _ffi.sizeof(info)) return _ffi.string(info).decode('utf-8', 'replace')
How would you code a function in Python 3 to retrieve the extra info generated when opening the file.
As a Python code analyst, you investigate and solve complex coding mysteries
def seek(self, frames, whence=SEEK_SET): """Set the read/write position. Parameters ---------- frames : int The frame index or offset to seek. whence : {SEEK_SET, SEEK_CUR, SEEK_END}, optional By default (``whence=SEEK_SET``), `frames` are counted from ...
Can you create a Python 3 function that sets the absolute position of the file.
You are a Python code architect, reviewing and designing scalable and efficient code
Read from the file and return data as NumPy array.
Make a summary of the following Python 3 code def read(self, frames=-1, dtype='float64', always_2d=False, fill_value=None, out=None): """Read from the file and return data as NumPy array. Reads the given number of frames in the given data format starting at the current read/write p...
As a Python code composer, you craft elegant and concise scripts.
Read from the file and return the data as a buffer object.
Explain what the following Python 3 code does def buffer_read(self, frames=-1, dtype=None): frames = self._check_frames(frames, fill_value=None) ctype = self._check_dtype(dtype) cdata = _ffi.new(ctype + '[]', frames * self.channels) read_frames = self._cdata_io('read', cdata, ctype, fram...
As a Python code composer, you craft elegant and concise scripts.
def buffer_read_into(self, buffer, dtype): """Read from the file into a given buffer object. Fills the given `buffer` with frames in the given data format starting at the current read/write position (which can be changed with :meth:`.seek`) until the buffer is full or the end of...
Can you create a Python 3 function that reads from the file into a given buffer object.
As a Python code analyst, you investigate and solve complex coding mysteries
Write audio data from a NumPy array to the file.
Can you generate the documentation for the following Python 3 function def write(self, data): import numpy as np # no copy is made if data has already the correct memory layout: data = np.ascontiguousarray(data) written = self._array_io('write', data, len(data)) assert written ==...
You are a Python code architect, reviewing and designing scalable and efficient code
def buffer_write(self, data, dtype): """Write audio data from a buffer/bytes object to the file. Writes the contents of `data` to the file at the current read/write position. This also advances the read/write position by the number of frames that were written and enlarges the fi...
Create a Python 3 function to write audio data from a buffer or bytes object to the file.
As a Python code analyst, you investigate and solve complex coding mysteries
Return a generator for reading audio files in a specific block size.
Make a summary of the following Python 3 code def blocks(self, blocksize=None, overlap=0, frames=-1, dtype='float64', always_2d=False, fill_value=None, out=None): """Return a generator for block-wise reading. By default, the generator yields blocks of the given `blocksize` (using...
You are a Python code generator, capable of creating scripts from specifications.
def truncate(self, frames=None): """Truncate the file to a given number of frames. After this command, the read/write position will be at the new end of the file. Parameters ---------- frames : int, optional Only the data before `frames` is kept, the rest is...
Write a Python 3 script for truncating the file to a given number of frames.
You are a Python code generator, capable of creating scripts from specifications.
def close(self): """Close the file. Can be called multiple times.""" if not self.closed: # be sure to flush data to disk before closing the file self.flush() err = _snd.sf_close(self._file) self._file = None _error_check(err)
Implement a Python 3 function for closing the file. Can be called multiple times.
As a Python code translator, you convert algorithms and pseudocode into Python.
Open the file and return the file handle.
Can you generate the documentation for the following Python 3 function def _open(self, file, mode_int, closefd): if isinstance(file, (_unicode, bytes)): if _os.path.isfile(file): if 'x' in self.mode: raise OSError("File exists: {0!r}".format(self.name)) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _init_virtual_io(self, file): """Initialize callback functions for sf_open_virtual().""" @_ffi.callback("sf_vio_get_filelen") def vio_get_filelen(user_data): curr = file.tell() file.seek(0, SEEK_END) size = file.tell() file.seek(curr, SEEK_SET)...
Implement a Python 3 function for initializing the virtual io for the current version of the file.
You are a Python code analyst, evaluating scripts for potential improvements.
def _check_frames(self, frames, fill_value): """Reduce frames to no more than are available in the file.""" if self.seekable(): remaining_frames = self.frames - self.tell() if frames < 0 or (frames > remaining_frames and fill_value is None): ...
Can you implement a function in Python 3 that reduces frames to no more than are available in the file.
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert buffer to cdata and check for valid size.
Can you tell what is the following Python 3 function doing def _check_buffer(self, data, ctype): assert ctype in _ffi_types.values() if not isinstance(data, bytes): data = _ffi.from_buffer(data) frames, remainder = divmod(len(data), self.channels * ...
As a Python code translator, you convert algorithms and pseudocode into Python.