repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
openstack/networking-arista | networking_arista/ml2/mechanism_arista.py | AristaDriver.delete_network_postcommit | def delete_network_postcommit(self, context):
"""Delete the network from CVX"""
network = context.current
log_context("delete_network_postcommit: network", network)
segments = context.network_segments
tenant_id = network['project_id']
self.delete_segments(segments)
... | python | def delete_network_postcommit(self, context):
"""Delete the network from CVX"""
network = context.current
log_context("delete_network_postcommit: network", network)
segments = context.network_segments
tenant_id = network['project_id']
self.delete_segments(segments)
... | [
"def",
"delete_network_postcommit",
"(",
"self",
",",
"context",
")",
":",
"network",
"=",
"context",
".",
"current",
"log_context",
"(",
"\"delete_network_postcommit: network\"",
",",
"network",
")",
"segments",
"=",
"context",
".",
"network_segments",
"tenant_id",
... | Delete the network from CVX | [
"Delete",
"the",
"network",
"from",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/mechanism_arista.py#L233-L243 |
openstack/networking-arista | networking_arista/ml2/mechanism_arista.py | AristaDriver.update_port_postcommit | 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... | python | 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... | [
"def",
"update_port_postcommit",
"(",
"self",
",",
"context",
")",
":",
"port",
"=",
"context",
".",
"current",
"orig_port",
"=",
"context",
".",
"original",
"network",
"=",
"context",
".",
"network",
".",
"current",
"log_context",
"(",
"\"update_port_postcommit... | 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 | [
"Send",
"port",
"updates",
"to",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/mechanism_arista.py#L253-L287 |
openstack/networking-arista | networking_arista/ml2/mechanism_arista.py | AristaDriver.delete_port_postcommit | def delete_port_postcommit(self, context):
"""Delete the port from CVX"""
port = context.current
log_context("delete_port_postcommit: port", port)
self._delete_port_resources(port, context.host)
self._try_to_release_dynamic_segment(context) | python | def delete_port_postcommit(self, context):
"""Delete the port from CVX"""
port = context.current
log_context("delete_port_postcommit: port", port)
self._delete_port_resources(port, context.host)
self._try_to_release_dynamic_segment(context) | [
"def",
"delete_port_postcommit",
"(",
"self",
",",
"context",
")",
":",
"port",
"=",
"context",
".",
"current",
"log_context",
"(",
"\"delete_port_postcommit: port\"",
",",
"port",
")",
"self",
".",
"_delete_port_resources",
"(",
"port",
",",
"context",
".",
"ho... | Delete the port from CVX | [
"Delete",
"the",
"port",
"from",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/mechanism_arista.py#L289-L296 |
openstack/networking-arista | networking_arista/ml2/mechanism_arista.py | AristaDriver._bind_baremetal_port | def _bind_baremetal_port(self, context, segment):
"""Bind the baremetal port to the segment"""
port = context.current
vif_details = {
portbindings.VIF_DETAILS_VLAN: str(
segment[driver_api.SEGMENTATION_ID])
}
context.set_binding(segment[driver_api.ID],... | python | def _bind_baremetal_port(self, context, segment):
"""Bind the baremetal port to the segment"""
port = context.current
vif_details = {
portbindings.VIF_DETAILS_VLAN: str(
segment[driver_api.SEGMENTATION_ID])
}
context.set_binding(segment[driver_api.ID],... | [
"def",
"_bind_baremetal_port",
"(",
"self",
",",
"context",
",",
"segment",
")",
":",
"port",
"=",
"context",
".",
"current",
"vif_details",
"=",
"{",
"portbindings",
".",
"VIF_DETAILS_VLAN",
":",
"str",
"(",
"segment",
"[",
"driver_api",
".",
"SEGMENTATION_ID... | Bind the baremetal port to the segment | [
"Bind",
"the",
"baremetal",
"port",
"to",
"the",
"segment"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/mechanism_arista.py#L298-L315 |
openstack/networking-arista | networking_arista/ml2/mechanism_arista.py | AristaDriver._get_physnet | 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
... | python | 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
... | [
"def",
"_get_physnet",
"(",
"self",
",",
"context",
")",
":",
"port",
"=",
"context",
".",
"current",
"physnet",
"=",
"None",
"if",
"(",
"port",
".",
"get",
"(",
"portbindings",
".",
"VNIC_TYPE",
")",
"==",
"portbindings",
".",
"VNIC_BAREMETAL",
")",
":"... | 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 | [
"Find",
"the",
"appropriate",
"physnet",
"for",
"the",
"host"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/mechanism_arista.py#L317-L334 |
openstack/networking-arista | networking_arista/ml2/mechanism_arista.py | AristaDriver._bind_fabric | 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... | python | 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... | [
"def",
"_bind_fabric",
"(",
"self",
",",
"context",
",",
"segment",
")",
":",
"port_id",
"=",
"context",
".",
"current",
"[",
"'id'",
"]",
"physnet",
"=",
"self",
".",
"_get_physnet",
"(",
"context",
")",
"if",
"not",
"physnet",
":",
"LOG",
".",
"debug... | Allocate dynamic segments for the port
Segment physnets are based on the switch to which the host is
connected. | [
"Allocate",
"dynamic",
"segments",
"for",
"the",
"port"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/mechanism_arista.py#L336-L359 |
openstack/networking-arista | networking_arista/ml2/mechanism_arista.py | AristaDriver.bind_port | def bind_port(self, context):
"""Bind port to a network segment.
Provisioning request to Arista Hardware to plug a host
into appropriate network is done when the port is created
this simply tells the ML2 Plugin that we are binding the port
"""
port = context.current
... | python | def bind_port(self, context):
"""Bind port to a network segment.
Provisioning request to Arista Hardware to plug a host
into appropriate network is done when the port is created
this simply tells the ML2 Plugin that we are binding the port
"""
port = context.current
... | [
"def",
"bind_port",
"(",
"self",
",",
"context",
")",
":",
"port",
"=",
"context",
".",
"current",
"log_context",
"(",
"\"bind_port: port\"",
",",
"port",
")",
"for",
"segment",
"in",
"context",
".",
"segments_to_bind",
":",
"physnet",
"=",
"segment",
".",
... | Bind port to a network segment.
Provisioning request to Arista Hardware to plug a host
into appropriate network is done when the port is created
this simply tells the ML2 Plugin that we are binding the port | [
"Bind",
"port",
"to",
"a",
"network",
"segment",
"."
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/mechanism_arista.py#L361-L388 |
openstack/networking-arista | networking_arista/ml2/mechanism_arista.py | AristaDriver._try_to_release_dynamic_segment | def _try_to_release_dynamic_segment(self, context, migration=False):
"""Release dynamic segment if necessary
If this port was the last port using a segment and the segment was
allocated by this driver, it should be released
"""
if migration:
binding_levels = context.... | python | def _try_to_release_dynamic_segment(self, context, migration=False):
"""Release dynamic segment if necessary
If this port was the last port using a segment and the segment was
allocated by this driver, it should be released
"""
if migration:
binding_levels = context.... | [
"def",
"_try_to_release_dynamic_segment",
"(",
"self",
",",
"context",
",",
"migration",
"=",
"False",
")",
":",
"if",
"migration",
":",
"binding_levels",
"=",
"context",
".",
"original_binding_levels",
"else",
":",
"binding_levels",
"=",
"context",
".",
"binding_... | Release dynamic segment if necessary
If this port was the last port using a segment and the segment was
allocated by this driver, it should be released | [
"Release",
"dynamic",
"segment",
"if",
"necessary"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/mechanism_arista.py#L390-L418 |
matthewgilbert/mapping | mapping/mappings.py | bdom_roll_date | def bdom_roll_date(sd, ed, bdom, months, holidays=[]):
"""
Convenience function for getting business day data associated with
contracts. Usefully for generating business day derived 'contract_dates'
which can be used as input to roller(). Returns dates for a business day of
the month for months in m... | python | def bdom_roll_date(sd, ed, bdom, months, holidays=[]):
"""
Convenience function for getting business day data associated with
contracts. Usefully for generating business day derived 'contract_dates'
which can be used as input to roller(). Returns dates for a business day of
the month for months in m... | [
"def",
"bdom_roll_date",
"(",
"sd",
",",
"ed",
",",
"bdom",
",",
"months",
",",
"holidays",
"=",
"[",
"]",
")",
":",
"if",
"not",
"isinstance",
"(",
"bdom",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"\"'bdom' must be integer\"",
")",
"sd",
"=",... | Convenience function for getting business day data associated with
contracts. Usefully for generating business day derived 'contract_dates'
which can be used as input to roller(). Returns dates for a business day of
the month for months in months.keys() between the start date and end date.
Parameters
... | [
"Convenience",
"function",
"for",
"getting",
"business",
"day",
"data",
"associated",
"with",
"contracts",
".",
"Usefully",
"for",
"generating",
"business",
"day",
"derived",
"contract_dates",
"which",
"can",
"be",
"used",
"as",
"input",
"to",
"roller",
"()",
".... | train | https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/mappings.py#L18-L78 |
matthewgilbert/mapping | mapping/mappings.py | roller | def roller(timestamps, contract_dates, get_weights, **kwargs):
"""
Calculate weight allocations to tradeable instruments for generic futures
at a set of timestamps for a given root generic.
Paramters
---------
timestamps: iterable
Sorted iterable of of pandas.Timestamps to calculate wei... | python | def roller(timestamps, contract_dates, get_weights, **kwargs):
"""
Calculate weight allocations to tradeable instruments for generic futures
at a set of timestamps for a given root generic.
Paramters
---------
timestamps: iterable
Sorted iterable of of pandas.Timestamps to calculate wei... | [
"def",
"roller",
"(",
"timestamps",
",",
"contract_dates",
",",
"get_weights",
",",
"*",
"*",
"kwargs",
")",
":",
"timestamps",
"=",
"sorted",
"(",
"timestamps",
")",
"contract_dates",
"=",
"contract_dates",
".",
"sort_values",
"(",
")",
"_check_contract_dates",... | Calculate weight allocations to tradeable instruments for generic futures
at a set of timestamps for a given root generic.
Paramters
---------
timestamps: iterable
Sorted iterable of of pandas.Timestamps to calculate weights for
contract_dates: pandas.Series
Series with index of tra... | [
"Calculate",
"weight",
"allocations",
"to",
"tradeable",
"instruments",
"for",
"generic",
"futures",
"at",
"a",
"set",
"of",
"timestamps",
"for",
"a",
"given",
"root",
"generic",
"."
] | train | https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/mappings.py#L81-L141 |
matthewgilbert/mapping | mapping/mappings.py | aggregate_weights | def aggregate_weights(weights, drop_date=False):
"""
Transforms list of tuples of weights into pandas.DataFrame of weights.
Parameters:
-----------
weights: list
A list of tuples consisting of the generic instrument name,
the tradeable contract as a string, the weight on this contra... | python | def aggregate_weights(weights, drop_date=False):
"""
Transforms list of tuples of weights into pandas.DataFrame of weights.
Parameters:
-----------
weights: list
A list of tuples consisting of the generic instrument name,
the tradeable contract as a string, the weight on this contra... | [
"def",
"aggregate_weights",
"(",
"weights",
",",
"drop_date",
"=",
"False",
")",
":",
"dwts",
"=",
"pd",
".",
"DataFrame",
"(",
"weights",
",",
"columns",
"=",
"[",
"\"generic\"",
",",
"\"contract\"",
",",
"\"weight\"",
",",
"\"date\"",
"]",
")",
"dwts",
... | Transforms list of tuples of weights into pandas.DataFrame of weights.
Parameters:
-----------
weights: list
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.
... | [
"Transforms",
"list",
"of",
"tuples",
"of",
"weights",
"into",
"pandas",
".",
"DataFrame",
"of",
"weights",
"."
] | train | https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/mappings.py#L144-L171 |
matthewgilbert/mapping | mapping/mappings.py | static_transition | 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 thro... | python | 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 thro... | [
"def",
"static_transition",
"(",
"timestamp",
",",
"contract_dates",
",",
"transition",
",",
"holidays",
"=",
"None",
",",
"validate_inputs",
"=",
"True",
")",
":",
"if",
"validate_inputs",
":",
"# required for MultiIndex slicing",
"_check_static",
"(",
"transition",
... | 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 weight... | [
"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",... | train | https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/mappings.py#L174-L282 |
matthewgilbert/mapping | mapping/mappings.py | to_generics | 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... | python | 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... | [
"def",
"to_generics",
"(",
"instruments",
",",
"weights",
")",
":",
"if",
"not",
"isinstance",
"(",
"weights",
",",
"dict",
")",
":",
"weights",
"=",
"{",
"\"\"",
":",
"weights",
"}",
"allocations",
"=",
"[",
"]",
"unmapped_instr",
"=",
"instruments",
".... | 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 co... | [
"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... | train | https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/mappings.py#L315-L407 |
openstack/networking-arista | networking_arista/ml2/security_groups/security_group_sync.py | AristaSecurityGroupSyncWorker.synchronize_switch | def synchronize_switch(self, switch_ip, expected_acls, expected_bindings):
"""Update ACL config on a switch to match expected config
This is done as follows:
1. Get switch ACL config using show commands
2. Update expected bindings based on switch LAGs
3. Get commands to synchron... | python | def synchronize_switch(self, switch_ip, expected_acls, expected_bindings):
"""Update ACL config on a switch to match expected config
This is done as follows:
1. Get switch ACL config using show commands
2. Update expected bindings based on switch LAGs
3. Get commands to synchron... | [
"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"... | Update ACL config on a switch to match expected config
This is done as follows:
1. Get switch ACL config using show commands
2. Update expected bindings based on switch LAGs
3. Get commands to synchronize switch ACLs
4. Get commands to synchronize switch ACL bindings
5. ... | [
"Update",
"ACL",
"config",
"on",
"a",
"switch",
"to",
"match",
"expected",
"config"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/security_groups/security_group_sync.py#L63-L88 |
openstack/networking-arista | networking_arista/ml2/security_groups/security_group_sync.py | AristaSecurityGroupSyncWorker.synchronize | 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... | python | 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... | [
"def",
"synchronize",
"(",
"self",
")",
":",
"# Get expected ACLs and rules",
"expected_acls",
"=",
"self",
".",
"get_expected_acls",
"(",
")",
"# Get expected interface to ACL mappings",
"all_expected_bindings",
"=",
"self",
".",
"get_expected_bindings",
"(",
")",
"# Che... | Perform sync of the security groups between ML2 and EOS. | [
"Perform",
"sync",
"of",
"the",
"security",
"groups",
"between",
"ML2",
"and",
"EOS",
"."
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/security_groups/security_group_sync.py#L90-L107 |
openstack/networking-arista | networking_arista/ml2/rpc/arista_eapi.py | AristaRPCWrapperEapi.check_vlan_type_driver_commands | 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... | python | 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... | [
"def",
"check_vlan_type_driver_commands",
"(",
"self",
")",
":",
"cmd",
"=",
"[",
"'show openstack resource-pool vlan region %s uuid'",
"%",
"self",
".",
"region",
"]",
"try",
":",
"self",
".",
"_run_eos_cmds",
"(",
"cmd",
")",
"self",
".",
"cli_commands",
"[",
... | 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. | [
"Checks",
"the",
"validity",
"of",
"CLI",
"commands",
"for",
"Arista",
"s",
"VLAN",
"type",
"driver",
"."
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/rpc/arista_eapi.py#L125-L140 |
openstack/networking-arista | networking_arista/ml2/rpc/arista_eapi.py | AristaRPCWrapperEapi.get_vlan_assignment_uuid | def get_vlan_assignment_uuid(self):
"""Returns the UUID for the region's vlan assignment on CVX
:returns: string containing the region's vlan assignment UUID
"""
vlan_uuid_cmd = self.cli_commands['resource-pool']
if vlan_uuid_cmd:
return self._run_eos_cmds(commands=v... | python | def get_vlan_assignment_uuid(self):
"""Returns the UUID for the region's vlan assignment on CVX
:returns: string containing the region's vlan assignment UUID
"""
vlan_uuid_cmd = self.cli_commands['resource-pool']
if vlan_uuid_cmd:
return self._run_eos_cmds(commands=v... | [
"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",
... | Returns the UUID for the region's vlan assignment on CVX
:returns: string containing the region's vlan assignment UUID | [
"Returns",
"the",
"UUID",
"for",
"the",
"region",
"s",
"vlan",
"assignment",
"on",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/rpc/arista_eapi.py#L142-L150 |
openstack/networking-arista | networking_arista/ml2/rpc/arista_eapi.py | AristaRPCWrapperEapi.get_vlan_allocation | def get_vlan_allocation(self):
"""Returns the status of the region's VLAN pool in CVX
:returns: dictionary containg the assigned, allocated and available
VLANs for the region
"""
if not self.cli_commands['resource-pool']:
LOG.warning(_('The version of CVX y... | python | def get_vlan_allocation(self):
"""Returns the status of the region's VLAN pool in CVX
:returns: dictionary containg the assigned, allocated and available
VLANs for the region
"""
if not self.cli_commands['resource-pool']:
LOG.warning(_('The version of CVX y... | [
"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.'",
")",
")",
"els... | Returns the status of the region's VLAN pool in CVX
:returns: dictionary containg the assigned, allocated and available
VLANs for the region | [
"Returns",
"the",
"status",
"of",
"the",
"region",
"s",
"VLAN",
"pool",
"in",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/rpc/arista_eapi.py#L152-L170 |
openstack/networking-arista | networking_arista/ml2/rpc/arista_eapi.py | AristaRPCWrapperEapi._run_eos_cmds | 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.
... | python | 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.
... | [
"def",
"_run_eos_cmds",
"(",
"self",
",",
"commands",
",",
"commands_to_log",
"=",
"None",
")",
":",
"# Always figure out who is master (starting with the last known val)",
"try",
":",
"if",
"self",
".",
"_get_eos_master",
"(",
")",
"is",
"None",
":",
"msg",
"=",
... | 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 i... | [
"Execute",
"/",
"sends",
"a",
"CAPI",
"(",
"Command",
"API",
")",
"command",
"to",
"EOS",
"."
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/rpc/arista_eapi.py#L172-L213 |
openstack/networking-arista | networking_arista/ml2/rpc/arista_eapi.py | AristaRPCWrapperEapi._build_command | 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.
:... | 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.
:... | [
"def",
"_build_command",
"(",
"self",
",",
"cmds",
",",
"sync",
"=",
"False",
")",
":",
"region_cmd",
"=",
"'region %s'",
"%",
"self",
".",
"region",
"if",
"sync",
":",
"region_cmd",
"=",
"self",
".",
"cli_commands",
"[",
"const",
".",
"CMD_REGION_SYNC",
... | 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 bei... | [
"Build",
"full",
"EOS",
"s",
"openstack",
"CLI",
"command",
"."
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/rpc/arista_eapi.py#L215-L238 |
openstack/networking-arista | networking_arista/ml2/rpc/arista_eapi.py | AristaRPCWrapperEapi._run_openstack_cmds | def _run_openstack_cmds(self, commands, commands_to_log=None, sync=False):
"""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 exec... | python | def _run_openstack_cmds(self, commands, commands_to_log=None, sync=False):
"""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 exec... | [
"def",
"_run_openstack_cmds",
"(",
"self",
",",
"commands",
",",
"commands_to_log",
"=",
"None",
",",
"sync",
"=",
"False",
")",
":",
"full_command",
"=",
"self",
".",
"_build_command",
"(",
"commands",
",",
"sync",
"=",
"sync",
")",
"if",
"commands_to_log",... | 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_logs : This should be set to the command that ... | [
"Execute",
"/",
"sends",
"a",
"CAPI",
"(",
"Command",
"API",
")",
"command",
"to",
"EOS",
"."
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/rpc/arista_eapi.py#L240-L258 |
openstack/networking-arista | networking_arista/ml2/rpc/arista_eapi.py | AristaRPCWrapperEapi.get_baremetal_physnet | def get_baremetal_physnet(self, context):
"""Returns dictionary which contains mac to hostname mapping"""
port = context.current
host_id = context.host
cmd = ['show network physical-topology hosts']
try:
response = self._run_eos_cmds(cmd)
binding_profile =... | python | def get_baremetal_physnet(self, context):
"""Returns dictionary which contains mac to hostname mapping"""
port = context.current
host_id = context.host
cmd = ['show network physical-topology hosts']
try:
response = self._run_eos_cmds(cmd)
binding_profile =... | [
"def",
"get_baremetal_physnet",
"(",
"self",
",",
"context",
")",
":",
"port",
"=",
"context",
".",
"current",
"host_id",
"=",
"context",
".",
"host",
"cmd",
"=",
"[",
"'show network physical-topology hosts'",
"]",
"try",
":",
"response",
"=",
"self",
".",
"... | Returns dictionary which contains mac to hostname mapping | [
"Returns",
"dictionary",
"which",
"contains",
"mac",
"to",
"hostname",
"mapping"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/rpc/arista_eapi.py#L288-L311 |
openstack/networking-arista | networking_arista/ml2/rpc/arista_eapi.py | AristaRPCWrapperEapi.get_host_physnet | 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)
... | python | 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)
... | [
"def",
"get_host_physnet",
"(",
"self",
",",
"context",
")",
":",
"host_id",
"=",
"utils",
".",
"hostname",
"(",
"context",
".",
"host",
")",
"cmd",
"=",
"[",
"'show network physical-topology neighbors'",
"]",
"try",
":",
"response",
"=",
"self",
".",
"_run_... | Returns dictionary which contains physical topology information
for a given host_id | [
"Returns",
"dictionary",
"which",
"contains",
"physical",
"topology",
"information"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/rpc/arista_eapi.py#L313-L337 |
openstack/networking-arista | networking_arista/common/db_lib.py | filter_unnecessary_segments | def filter_unnecessary_segments(query):
"""Filter segments are not needed on CVX"""
segment_model = segment_models.NetworkSegment
network_model = models_v2.Network
query = (query
.join_if_necessary(network_model)
.join_if_necessary(segment_model)
.filter(network_mo... | python | def filter_unnecessary_segments(query):
"""Filter segments are not needed on CVX"""
segment_model = segment_models.NetworkSegment
network_model = models_v2.Network
query = (query
.join_if_necessary(network_model)
.join_if_necessary(segment_model)
.filter(network_mo... | [
"def",
"filter_unnecessary_segments",
"(",
"query",
")",
":",
"segment_model",
"=",
"segment_models",
".",
"NetworkSegment",
"network_model",
"=",
"models_v2",
".",
"Network",
"query",
"=",
"(",
"query",
".",
"join_if_necessary",
"(",
"network_model",
")",
".",
"j... | Filter segments are not needed on CVX | [
"Filter",
"segments",
"are",
"not",
"needed",
"on",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L59-L68 |
openstack/networking-arista | networking_arista/common/db_lib.py | filter_network_type | 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 | python | 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 | [
"def",
"filter_network_type",
"(",
"query",
")",
":",
"segment_model",
"=",
"segment_models",
".",
"NetworkSegment",
"query",
"=",
"(",
"query",
".",
"filter",
"(",
"segment_model",
".",
"network_type",
".",
"in_",
"(",
"utils",
".",
"SUPPORTED_NETWORK_TYPES",
"... | Filter unsupported segment types | [
"Filter",
"unsupported",
"segment",
"types"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L71-L78 |
openstack/networking-arista | networking_arista/common/db_lib.py | filter_unbound_ports | 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... | python | 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... | [
"def",
"filter_unbound_ports",
"(",
"query",
")",
":",
"# 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",
"quer... | Filter ports not bound to a host or network | [
"Filter",
"ports",
"not",
"bound",
"to",
"a",
"host",
"or",
"network"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L81-L95 |
openstack/networking-arista | networking_arista/common/db_lib.py | filter_by_device_owner | 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... | python | 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... | [
"def",
"filter_by_device_owner",
"(",
"query",
",",
"device_owners",
"=",
"None",
")",
":",
"port_model",
"=",
"models_v2",
".",
"Port",
"if",
"not",
"device_owners",
":",
"device_owners",
"=",
"utils",
".",
"SUPPORTED_DEVICE_OWNERS",
"supported_device_owner_filter",
... | 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 | [
"Filter",
"ports",
"by",
"device_owner"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L98-L117 |
openstack/networking-arista | networking_arista/common/db_lib.py | filter_by_device_id | def filter_by_device_id(query):
"""Filter ports attached to devices we don't care about
Currently used to filter DHCP_RESERVED ports
"""
port_model = models_v2.Port
unsupported_device_id_filter = [
port_model.device_id.notilike('%s%%' % id)
for id in utils.UNSUPPORTED_DEVICE_IDS]
... | python | def filter_by_device_id(query):
"""Filter ports attached to devices we don't care about
Currently used to filter DHCP_RESERVED ports
"""
port_model = models_v2.Port
unsupported_device_id_filter = [
port_model.device_id.notilike('%s%%' % id)
for id in utils.UNSUPPORTED_DEVICE_IDS]
... | [
"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",
".",
"UNS... | Filter ports attached to devices we don't care about
Currently used to filter DHCP_RESERVED ports | [
"Filter",
"ports",
"attached",
"to",
"devices",
"we",
"don",
"t",
"care",
"about"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L120-L131 |
openstack/networking-arista | networking_arista/common/db_lib.py | filter_by_vnic_type | def filter_by_vnic_type(query, vnic_type):
"""Filter ports by vnic_type (currently only used for baremetals)"""
port_model = models_v2.Port
binding_model = ml2_models.PortBinding
dst_binding_model = ml2_models.DistributedPortBinding
query = (query
.outerjoin_if_necessary(
... | python | def filter_by_vnic_type(query, vnic_type):
"""Filter ports by vnic_type (currently only used for baremetals)"""
port_model = models_v2.Port
binding_model = ml2_models.PortBinding
dst_binding_model = ml2_models.DistributedPortBinding
query = (query
.outerjoin_if_necessary(
... | [
"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",
"=",
"(",
"... | Filter ports by vnic_type (currently only used for baremetals) | [
"Filter",
"ports",
"by",
"vnic_type",
"(",
"currently",
"only",
"used",
"for",
"baremetals",
")"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L134-L149 |
openstack/networking-arista | networking_arista/common/db_lib.py | filter_unmanaged_physnets | 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... | python | 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... | [
"def",
"filter_unmanaged_physnets",
"(",
"query",
")",
":",
"config",
"=",
"cfg",
".",
"CONF",
".",
"ml2_arista",
"managed_physnets",
"=",
"config",
"[",
"'managed_physnets'",
"]",
"# Filter out ports bound to segments on physnets that we're not",
"# managing",
"segment_mod... | Filter ports managed by other ML2 plugins | [
"Filter",
"ports",
"managed",
"by",
"other",
"ML2",
"plugins"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L152-L165 |
openstack/networking-arista | networking_arista/common/db_lib.py | filter_inactive_ports | def filter_inactive_ports(query):
"""Filter ports that aren't in active status """
port_model = models_v2.Port
query = (query
.filter(port_model.status == n_const.PORT_STATUS_ACTIVE))
return query | python | def filter_inactive_ports(query):
"""Filter ports that aren't in active status """
port_model = models_v2.Port
query = (query
.filter(port_model.status == n_const.PORT_STATUS_ACTIVE))
return query | [
"def",
"filter_inactive_ports",
"(",
"query",
")",
":",
"port_model",
"=",
"models_v2",
".",
"Port",
"query",
"=",
"(",
"query",
".",
"filter",
"(",
"port_model",
".",
"status",
"==",
"n_const",
".",
"PORT_STATUS_ACTIVE",
")",
")",
"return",
"query"
] | Filter ports that aren't in active status | [
"Filter",
"ports",
"that",
"aren",
"t",
"in",
"active",
"status"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L168-L173 |
openstack/networking-arista | networking_arista/common/db_lib.py | filter_unnecessary_ports | 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()
... | python | 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()
... | [
"def",
"filter_unnecessary_ports",
"(",
"query",
",",
"device_owners",
"=",
"None",
",",
"vnic_type",
"=",
"None",
",",
"active",
"=",
"True",
")",
":",
"query",
"=",
"(",
"query",
".",
"filter_unbound_ports",
"(",
")",
".",
"filter_by_device_owner",
"(",
"d... | Filter out all ports are not needed on CVX | [
"Filter",
"out",
"all",
"ports",
"are",
"not",
"needed",
"on",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L176-L188 |
openstack/networking-arista | networking_arista/common/db_lib.py | get_tenants | def get_tenants(tenant_id=None):
"""Returns list of all project/tenant ids that may be relevant on CVX"""
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.qu... | python | def get_tenants(tenant_id=None):
"""Returns list of all project/tenant ids that may be relevant on CVX"""
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.qu... | [
"def",
"get_tenants",
"(",
"tenant_id",
"=",
"None",
")",
":",
"if",
"tenant_id",
"==",
"''",
":",
"return",
"[",
"]",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"project_ids",
"=",
"set",
"(",
")",
"with",
"session",
".",
"begin",
"(",... | Returns list of all project/tenant ids that may be relevant on CVX | [
"Returns",
"list",
"of",
"all",
"project",
"/",
"tenant",
"ids",
"that",
"may",
"be",
"relevant",
"on",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L204-L216 |
openstack/networking-arista | networking_arista/common/db_lib.py | get_networks | 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... | 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... | [
"def",
"get_networks",
"(",
"network_id",
"=",
"None",
")",
":",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"model",
"=",
"models_v2",
".",
"Network",
"networks",
"=",
"session",
".",
"query... | Returns list of all networks that may be relevant on CVX | [
"Returns",
"list",
"of",
"all",
"networks",
"that",
"may",
"be",
"relevant",
"on",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L219-L227 |
openstack/networking-arista | networking_arista/common/db_lib.py | get_segments | def get_segments(segment_id=None):
"""Returns list of all network segments that may be relevant on CVX"""
session = db.get_reader_session()
with session.begin():
model = segment_models.NetworkSegment
segments = session.query(model).filter_unnecessary_segments()
if segment_id:
... | python | def get_segments(segment_id=None):
"""Returns list of all network segments that may be relevant on CVX"""
session = db.get_reader_session()
with session.begin():
model = segment_models.NetworkSegment
segments = session.query(model).filter_unnecessary_segments()
if segment_id:
... | [
"def",
"get_segments",
"(",
"segment_id",
"=",
"None",
")",
":",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"model",
"=",
"segment_models",
".",
"NetworkSegment",
"segments",
"=",
"session",
"... | Returns list of all network segments that may be relevant on CVX | [
"Returns",
"list",
"of",
"all",
"network",
"segments",
"that",
"may",
"be",
"relevant",
"on",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L230-L238 |
openstack/networking-arista | networking_arista/common/db_lib.py | get_instances | def get_instances(device_owners=None, vnic_type=None, instance_id=None):
"""Returns filtered list of all instances in the neutron db"""
session = db.get_reader_session()
with session.begin():
port_model = models_v2.Port
binding_model = ml2_models.PortBinding
instances = (session
... | python | def get_instances(device_owners=None, vnic_type=None, instance_id=None):
"""Returns filtered list of all instances in the neutron db"""
session = db.get_reader_session()
with session.begin():
port_model = models_v2.Port
binding_model = ml2_models.PortBinding
instances = (session
... | [
"def",
"get_instances",
"(",
"device_owners",
"=",
"None",
",",
"vnic_type",
"=",
"None",
",",
"instance_id",
"=",
"None",
")",
":",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"port_model",
... | Returns filtered list of all instances in the neutron db | [
"Returns",
"filtered",
"list",
"of",
"all",
"instances",
"in",
"the",
"neutron",
"db"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L241-L258 |
openstack/networking-arista | networking_arista/common/db_lib.py | get_vm_instances | def get_vm_instances(instance_id=None):
"""Returns filtered list of vms that may be relevant on CVX"""
return get_instances(device_owners=[n_const.DEVICE_OWNER_COMPUTE_PREFIX],
vnic_type=portbindings.VNIC_NORMAL,
instance_id=instance_id) | python | def get_vm_instances(instance_id=None):
"""Returns filtered list of vms that may be relevant on CVX"""
return get_instances(device_owners=[n_const.DEVICE_OWNER_COMPUTE_PREFIX],
vnic_type=portbindings.VNIC_NORMAL,
instance_id=instance_id) | [
"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",
"=",... | Returns filtered list of vms that may be relevant on CVX | [
"Returns",
"filtered",
"list",
"of",
"vms",
"that",
"may",
"be",
"relevant",
"on",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L273-L277 |
openstack/networking-arista | networking_arista/common/db_lib.py | get_ports | def get_ports(device_owners=None, vnic_type=None, port_id=None, active=True):
"""Returns list of all ports in neutron the db"""
session = db.get_reader_session()
with session.begin():
port_model = models_v2.Port
ports = (session
.query(port_model)
.filter_un... | python | def get_ports(device_owners=None, vnic_type=None, port_id=None, active=True):
"""Returns list of all ports in neutron the db"""
session = db.get_reader_session()
with session.begin():
port_model = models_v2.Port
ports = (session
.query(port_model)
.filter_un... | [
"def",
"get_ports",
"(",
"device_owners",
"=",
"None",
",",
"vnic_type",
"=",
"None",
",",
"port_id",
"=",
"None",
",",
"active",
"=",
"True",
")",
":",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")... | Returns list of all ports in neutron the db | [
"Returns",
"list",
"of",
"all",
"ports",
"in",
"neutron",
"the",
"db"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L286-L296 |
openstack/networking-arista | networking_arista/common/db_lib.py | get_vm_ports | 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) | python | 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) | [
"def",
"get_vm_ports",
"(",
"port_id",
"=",
"None",
")",
":",
"return",
"get_ports",
"(",
"device_owners",
"=",
"[",
"n_const",
".",
"DEVICE_OWNER_COMPUTE_PREFIX",
",",
"t_const",
".",
"TRUNK_SUBPORT_OWNER",
"]",
",",
"vnic_type",
"=",
"portbindings",
".",
"VNIC... | Returns filtered list of vms that may be relevant on CVX | [
"Returns",
"filtered",
"list",
"of",
"vms",
"that",
"may",
"be",
"relevant",
"on",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L311-L315 |
openstack/networking-arista | networking_arista/common/db_lib.py | get_port_bindings | def get_port_bindings(binding_key=None):
"""Returns filtered list of port bindings that may be relevant on CVX
This query is a little complex as we need all binding levels for any
binding that has a single managed physnet, but we need to filter bindings
that have no managed physnets. In order to achiev... | python | def get_port_bindings(binding_key=None):
"""Returns filtered list of port bindings that may be relevant on CVX
This query is a little complex as we need all binding levels for any
binding that has a single managed physnet, but we need to filter bindings
that have no managed physnets. In order to achiev... | [
"def",
"get_port_bindings",
"(",
"binding_key",
"=",
"None",
")",
":",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"binding_level_model",
"=",
"ml2_models",
".",
"PortBindingLevel",
"aliased_blm",
... | Returns filtered list of port bindings that may be relevant on CVX
This query is a little complex as we need all binding levels for any
binding that has a single managed physnet, but we need to filter bindings
that have no managed physnets. In order to achieve this, we join to the
binding_level_model o... | [
"Returns",
"filtered",
"list",
"of",
"port",
"bindings",
"that",
"may",
"be",
"relevant",
"on",
"CVX"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L323-L399 |
openstack/networking-arista | networking_arista/common/db_lib.py | tenant_provisioned | def tenant_provisioned(tenant_id):
"""Returns true if any networks or ports exist for a tenant."""
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]
... | python | def tenant_provisioned(tenant_id):
"""Returns true if any networks or ports exist for a tenant."""
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]
... | [
"def",
"tenant_provisioned",
"(",
"tenant_id",
")",
":",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"res",
"=",
"any",
"(",
"session",
".",
"query",
"(",
"m",
")",
".",
"filter",
"(",
"m... | Returns true if any networks or ports exist for a tenant. | [
"Returns",
"true",
"if",
"any",
"networks",
"or",
"ports",
"exist",
"for",
"a",
"tenant",
"."
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L438-L446 |
openstack/networking-arista | networking_arista/common/db_lib.py | instance_provisioned | 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... | python | 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... | [
"def",
"instance_provisioned",
"(",
"device_id",
")",
":",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"port_model",
"=",
"models_v2",
".",
"Port",
"res",
"=",
"bool",
"(",
"session",
".",
"q... | Returns true if any ports exist for an instance. | [
"Returns",
"true",
"if",
"any",
"ports",
"exist",
"for",
"an",
"instance",
"."
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L449-L456 |
openstack/networking-arista | networking_arista/common/db_lib.py | port_provisioned | def port_provisioned(port_id):
"""Returns true if port still exists."""
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 | python | def port_provisioned(port_id):
"""Returns true if port still exists."""
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 | [
"def",
"port_provisioned",
"(",
"port_id",
")",
":",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"port_model",
"=",
"models_v2",
".",
"Port",
"res",
"=",
"bool",
"(",
"session",
".",
"query",... | Returns true if port still exists. | [
"Returns",
"true",
"if",
"port",
"still",
"exists",
"."
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L459-L466 |
openstack/networking-arista | networking_arista/common/db_lib.py | get_parent | def get_parent(port_id):
"""Get trunk subport's parent port"""
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).
filter(subport_mod... | python | def get_parent(port_id):
"""Get trunk subport's parent port"""
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).
filter(subport_mod... | [
"def",
"get_parent",
"(",
"port_id",
")",
":",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"res",
"=",
"dict",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"subport_model",
"=",
"trunk_models",
".",
"SubPort",
"trunk_model",
"... | Get trunk subport's parent port | [
"Get",
"trunk",
"subport",
"s",
"parent",
"port"
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L469-L484 |
openstack/networking-arista | networking_arista/common/db_lib.py | get_port_binding_level | def get_port_binding_level(filters):
"""Returns entries from PortBindingLevel based on the specified filters."""
session = db.get_reader_session()
with session.begin():
return (session.query(ml2_models.PortBindingLevel).
filter_by(**filters).
order_by(ml2_models.PortB... | python | def get_port_binding_level(filters):
"""Returns entries from PortBindingLevel based on the specified filters."""
session = db.get_reader_session()
with session.begin():
return (session.query(ml2_models.PortBindingLevel).
filter_by(**filters).
order_by(ml2_models.PortB... | [
"def",
"get_port_binding_level",
"(",
"filters",
")",
":",
"session",
"=",
"db",
".",
"get_reader_session",
"(",
")",
"with",
"session",
".",
"begin",
"(",
")",
":",
"return",
"(",
"session",
".",
"query",
"(",
"ml2_models",
".",
"PortBindingLevel",
")",
"... | Returns entries from PortBindingLevel based on the specified filters. | [
"Returns",
"entries",
"from",
"PortBindingLevel",
"based",
"on",
"the",
"specified",
"filters",
"."
] | train | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L487-L494 |
bastibe/SoundFile | soundfile.py | read | 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... | 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... | [
"def",
"read",
"(",
"file",
",",
"frames",
"=",
"-",
"1",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"None",
",",
"dtype",
"=",
"'float64'",
",",
"always_2d",
"=",
"False",
",",
"fill_value",
"=",
"None",
",",
"out",
"=",
"None",
",",
"samplerate",
... | Provide audio data from a sound file as NumPy array.
By default, the whole file is read from the beginning, but the
position to start reading can be specified with `start` and the
number of frames to read can be specified with `frames`.
Alternatively, a range can be specified with `start` and `stop`.
... | [
"Provide",
"audio",
"data",
"from",
"a",
"sound",
"file",
"as",
"NumPy",
"array",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L170-L260 |
bastibe/SoundFile | soundfile.py | write | 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:... | python | 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:... | [
"def",
"write",
"(",
"file",
",",
"data",
",",
"samplerate",
",",
"subtype",
"=",
"None",
",",
"endian",
"=",
"None",
",",
"format",
"=",
"None",
",",
"closefd",
"=",
"True",
")",
":",
"import",
"numpy",
"as",
"np",
"data",
"=",
"np",
".",
"asarray... | 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:`SoundFile` for details.
data : array_like
The data to write. Usually two-dimensional (frames... | [
"Write",
"data",
"to",
"a",
"sound",
"file",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L263-L316 |
bastibe/SoundFile | soundfile.py | blocks | 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... | python | 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... | [
"def",
"blocks",
"(",
"file",
",",
"blocksize",
"=",
"None",
",",
"overlap",
"=",
"0",
",",
"frames",
"=",
"-",
"1",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"None",
",",
"dtype",
"=",
"'float64'",
",",
"always_2d",
"=",
"False",
",",
"fill_value"... | Return a generator for block-wise reading.
By default, iteration starts at the beginning and stops at the end
of the file. Use `start` to start at a later position and `frames`
or `stop` to stop earlier.
If you stop iterating over the generator before it's exhausted,
the sound file is not closed.... | [
"Return",
"a",
"generator",
"for",
"block",
"-",
"wise",
"reading",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L319-L375 |
bastibe/SoundFile | soundfile.py | available_subtypes | 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... | python | 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... | [
"def",
"available_subtypes",
"(",
"format",
"=",
"None",
")",
":",
"subtypes",
"=",
"_available_formats_helper",
"(",
"_snd",
".",
"SFC_GET_FORMAT_SUBTYPE_COUNT",
",",
"_snd",
".",
"SFC_GET_FORMAT_SUBTYPE",
")",
"return",
"dict",
"(",
"(",
"subtype",
",",
"name",
... | 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 PCM',
'PCM_16': 'Signed 16 bit PCM',
... | [
"Return",
"a",
"dictionary",
"of",
"available",
"subtypes",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L462-L482 |
bastibe/SoundFile | soundfile.py | check_format | 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... | python | 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... | [
"def",
"check_format",
"(",
"format",
",",
"subtype",
"=",
"None",
",",
"endian",
"=",
"None",
")",
":",
"try",
":",
"return",
"bool",
"(",
"_format_int",
"(",
"format",
",",
"subtype",
",",
"endian",
")",
")",
"except",
"(",
"ValueError",
",",
"TypeEr... | 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 | [
"Check",
"if",
"the",
"combination",
"of",
"format",
"/",
"subtype",
"/",
"endian",
"is",
"valid",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L485-L500 |
bastibe/SoundFile | soundfile.py | _error_check | def _error_check(err, prefix=""):
"""Pretty-print a numerical error code if there is an error."""
if err != 0:
err_str = _snd.sf_error_number(err)
raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace')) | python | def _error_check(err, prefix=""):
"""Pretty-print a numerical error code if there is an error."""
if err != 0:
err_str = _snd.sf_error_number(err)
raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace')) | [
"def",
"_error_check",
"(",
"err",
",",
"prefix",
"=",
"\"\"",
")",
":",
"if",
"err",
"!=",
"0",
":",
"err_str",
"=",
"_snd",
".",
"sf_error_number",
"(",
"err",
")",
"raise",
"RuntimeError",
"(",
"prefix",
"+",
"_ffi",
".",
"string",
"(",
"err_str",
... | Pretty-print a numerical error code if there is an error. | [
"Pretty",
"-",
"print",
"a",
"numerical",
"error",
"code",
"if",
"there",
"is",
"an",
"error",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1353-L1357 |
bastibe/SoundFile | soundfile.py | _format_int | 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 ... | python | 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 ... | [
"def",
"_format_int",
"(",
"format",
",",
"subtype",
",",
"endian",
")",
":",
"result",
"=",
"_check_format",
"(",
"format",
")",
"if",
"subtype",
"is",
"None",
":",
"subtype",
"=",
"default_subtype",
"(",
"format",
")",
"if",
"subtype",
"is",
"None",
":... | Return numeric ID for given format|subtype|endian combo. | [
"Return",
"numeric",
"ID",
"for",
"given",
"format|subtype|endian",
"combo",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1360-L1389 |
bastibe/SoundFile | soundfile.py | _check_mode | 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... | 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... | [
"def",
"_check_mode",
"(",
"mode",
")",
":",
"if",
"not",
"isinstance",
"(",
"mode",
",",
"(",
"_unicode",
",",
"str",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid mode: {0!r}\"",
".",
"format",
"(",
"mode",
")",
")",
"mode_set",
"=",
"set",
"(... | Check if mode is valid and return its integer representation. | [
"Check",
"if",
"mode",
"is",
"valid",
"and",
"return",
"its",
"integer",
"representation",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1392-L1408 |
bastibe/SoundFile | soundfile.py | _create_info_struct | 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))
... | python | 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))
... | [
"def",
"_create_info_struct",
"(",
"file",
",",
"mode",
",",
"samplerate",
",",
"channels",
",",
"format",
",",
"subtype",
",",
"endian",
")",
":",
"original_format",
"=",
"format",
"if",
"format",
"is",
"None",
":",
"format",
"=",
"_get_format_from_filename",... | Check arguments and create SF_INFO struct. | [
"Check",
"arguments",
"and",
"create",
"SF_INFO",
"struct",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1411-L1435 |
bastibe/SoundFile | soundfile.py | _get_format_from_filename | 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... | python | 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... | [
"def",
"_get_format_from_filename",
"(",
"file",
",",
"mode",
")",
":",
"format",
"=",
"''",
"file",
"=",
"getattr",
"(",
"file",
",",
"'name'",
",",
"file",
")",
"try",
":",
"# This raises an exception if file is not a (Unicode/byte) string:",
"format",
"=",
"_os... | 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 object). | [
"Return",
"a",
"format",
"string",
"obtained",
"from",
"file",
"(",
"or",
"file",
".",
"name",
")",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1438-L1459 |
bastibe/SoundFile | soundfile.py | _format_str | 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' | python | 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' | [
"def",
"_format_str",
"(",
"format_int",
")",
":",
"for",
"dictionary",
"in",
"_formats",
",",
"_subtypes",
",",
"_endians",
":",
"for",
"k",
",",
"v",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"if",
"v",
"==",
"format_int",
":",
"return",
"k",
... | Return the string representation of a given numeric format. | [
"Return",
"the",
"string",
"representation",
"of",
"a",
"given",
"numeric",
"format",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1462-L1469 |
bastibe/SoundFile | soundfile.py | _format_info | def _format_info(format_int, format_flag=_snd.SFC_GET_FORMAT_INFO):
"""Return the ID and short description of a given format."""
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_INFO"... | python | def _format_info(format_int, format_flag=_snd.SFC_GET_FORMAT_INFO):
"""Return the ID and short description of a given format."""
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_INFO"... | [
"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",
... | Return the ID and short description of a given format. | [
"Return",
"the",
"ID",
"and",
"short",
"description",
"of",
"a",
"given",
"format",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1472-L1480 |
bastibe/SoundFile | soundfile.py | _available_formats_helper | def _available_formats_helper(count_flag, format_flag):
"""Helper for available_formats() and available_subtypes()."""
count = _ffi.new("int*")
_snd.sf_command(_ffi.NULL, count_flag, count, _ffi.sizeof("int"))
for format_int in range(count[0]):
yield _format_info(format_int, format_flag) | python | def _available_formats_helper(count_flag, format_flag):
"""Helper for available_formats() and available_subtypes()."""
count = _ffi.new("int*")
_snd.sf_command(_ffi.NULL, count_flag, count, _ffi.sizeof("int"))
for format_int in range(count[0]):
yield _format_info(format_int, format_flag) | [
"def",
"_available_formats_helper",
"(",
"count_flag",
",",
"format_flag",
")",
":",
"count",
"=",
"_ffi",
".",
"new",
"(",
"\"int*\"",
")",
"_snd",
".",
"sf_command",
"(",
"_ffi",
".",
"NULL",
",",
"count_flag",
",",
"count",
",",
"_ffi",
".",
"sizeof",
... | Helper for available_formats() and available_subtypes(). | [
"Helper",
"for",
"available_formats",
"()",
"and",
"available_subtypes",
"()",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1483-L1488 |
bastibe/SoundFile | soundfile.py | _check_format | def _check_format(format_str):
"""Check if `format_str` is valid and return format ID."""
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("... | python | def _check_format(format_str):
"""Check if `format_str` is valid and return format ID."""
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("... | [
"def",
"_check_format",
"(",
"format_str",
")",
":",
"if",
"not",
"isinstance",
"(",
"format_str",
",",
"(",
"_unicode",
",",
"str",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid format: {0!r}\"",
".",
"format",
"(",
"format_str",
")",
")",
"try",
"... | Check if `format_str` is valid and return format ID. | [
"Check",
"if",
"format_str",
"is",
"valid",
"and",
"return",
"format",
"ID",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1491-L1499 |
bastibe/SoundFile | soundfile.py | _has_virtual_io_attrs | 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... | python | 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... | [
"def",
"_has_virtual_io_attrs",
"(",
"file",
",",
"mode_int",
")",
":",
"readonly",
"=",
"mode_int",
"==",
"_snd",
".",
"SFM_READ",
"writeonly",
"=",
"mode_int",
"==",
"_snd",
".",
"SFM_WRITE",
"return",
"all",
"(",
"[",
"hasattr",
"(",
"file",
",",
"'seek... | Check if file has all the necessary attributes for virtual IO. | [
"Check",
"if",
"file",
"has",
"all",
"the",
"necessary",
"attributes",
"for",
"virtual",
"IO",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1502-L1511 |
bastibe/SoundFile | soundfile.py | SoundFile.extra_info | 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') | python | 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') | [
"def",
"extra_info",
"(",
"self",
")",
":",
"info",
"=",
"_ffi",
".",
"new",
"(",
"\"char[]\"",
",",
"2",
"**",
"14",
")",
"_snd",
".",
"sf_command",
"(",
"self",
".",
"_file",
",",
"_snd",
".",
"SFC_GET_LOG_INFO",
",",
"info",
",",
"_ffi",
".",
"s... | Retrieve the log string generated when opening the file. | [
"Retrieve",
"the",
"log",
"string",
"generated",
"when",
"opening",
"the",
"file",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L671-L676 |
bastibe/SoundFile | soundfile.py | SoundFile.seek | 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
... | python | 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
... | [
"def",
"seek",
"(",
"self",
",",
"frames",
",",
"whence",
"=",
"SEEK_SET",
")",
":",
"self",
".",
"_check_if_closed",
"(",
")",
"position",
"=",
"_snd",
".",
"sf_seek",
"(",
"self",
".",
"_file",
",",
"frames",
",",
"whence",
")",
"_error_check",
"(",
... | 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
the beginning of the file.
``w... | [
"Set",
"the",
"read",
"/",
"write",
"position",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L735-L774 |
bastibe/SoundFile | soundfile.py | SoundFile.read | 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 position. This advances the
read/write... | python | 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 position. This advances the
read/write... | [
"def",
"read",
"(",
"self",
",",
"frames",
"=",
"-",
"1",
",",
"dtype",
"=",
"'float64'",
",",
"always_2d",
"=",
"False",
",",
"fill_value",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"frames",
"=",
"self",
".... | 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 position. This advances the
read/write position by the same number of frames.
By default, all frames from the current read/write position to
... | [
"Read",
"from",
"the",
"file",
"and",
"return",
"data",
"as",
"NumPy",
"array",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L780-L873 |
bastibe/SoundFile | soundfile.py | SoundFile.buffer_read | def buffer_read(self, frames=-1, dtype=None):
"""Read from the file and return data as buffer object.
Reads the given number of `frames` in the given data format
starting at the current read/write position. This advances the
read/write position by the same number of frames.
By ... | python | def buffer_read(self, frames=-1, dtype=None):
"""Read from the file and return data as buffer object.
Reads the given number of `frames` in the given data format
starting at the current read/write position. This advances the
read/write position by the same number of frames.
By ... | [
"def",
"buffer_read",
"(",
"self",
",",
"frames",
"=",
"-",
"1",
",",
"dtype",
"=",
"None",
")",
":",
"frames",
"=",
"self",
".",
"_check_frames",
"(",
"frames",
",",
"fill_value",
"=",
"None",
")",
"ctype",
"=",
"self",
".",
"_check_dtype",
"(",
"dt... | Read from the file and return data as buffer object.
Reads the given number of `frames` in the given data format
starting at the current read/write position. This advances the
read/write position by the same number of frames.
By default, all frames from the current read/write position ... | [
"Read",
"from",
"the",
"file",
"and",
"return",
"data",
"as",
"buffer",
"object",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L875-L908 |
bastibe/SoundFile | soundfile.py | SoundFile.buffer_read_into | 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... | python | 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... | [
"def",
"buffer_read_into",
"(",
"self",
",",
"buffer",
",",
"dtype",
")",
":",
"ctype",
"=",
"self",
".",
"_check_dtype",
"(",
"dtype",
")",
"cdata",
",",
"frames",
"=",
"self",
".",
"_check_buffer",
"(",
"buffer",
",",
"ctype",
")",
"frames",
"=",
"se... | 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 the file is reached. This advances the read/write po... | [
"Read",
"from",
"the",
"file",
"into",
"a",
"given",
"buffer",
"object",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L910-L941 |
bastibe/SoundFile | soundfile.py | SoundFile.write | def write(self, data):
"""Write audio data from a NumPy array to the file.
Writes a number of frames at the read/write position to the
file. This also advances the read/write position by the same
number of frames and enlarges the file if necessary.
Note that writing int values ... | python | def write(self, data):
"""Write audio data from a NumPy array to the file.
Writes a number of frames at the read/write position to the
file. This also advances the read/write position by the same
number of frames and enlarges the file if necessary.
Note that writing int values ... | [
"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 audio data from a NumPy array to the file.
Writes a number of frames at the read/write position to the
file. This also advances the read/write position by the same
number of frames and enlarges the file if necessary.
Note that writing int values to a float file will *not* scale
... | [
"Write",
"audio",
"data",
"from",
"a",
"NumPy",
"array",
"to",
"the",
"file",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L943-L994 |
bastibe/SoundFile | soundfile.py | SoundFile.buffer_write | 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... | python | 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... | [
"def",
"buffer_write",
"(",
"self",
",",
"data",
",",
"dtype",
")",
":",
"ctype",
"=",
"self",
".",
"_check_dtype",
"(",
"dtype",
")",
"cdata",
",",
"frames",
"=",
"self",
".",
"_check_buffer",
"(",
"data",
",",
"ctype",
")",
"written",
"=",
"self",
... | 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 file if necessary.
Parameters
---... | [
"Write",
"audio",
"data",
"from",
"a",
"buffer",
"/",
"bytes",
"object",
"to",
"the",
"file",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L996-L1021 |
bastibe/SoundFile | soundfile.py | SoundFile.blocks | 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 a given `overlap`) until the end of the file
... | python | 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 a given `overlap`) until the end of the file
... | [
"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 a given `overlap`) until the end of the file
is reached; `frames` can be used to stop earlier.
Parameters
----------
blocksize : int
The number... | [
"Return",
"a",
"generator",
"for",
"block",
"-",
"wise",
"reading",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1023-L1113 |
bastibe/SoundFile | soundfile.py | SoundFile.truncate | 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... | python | 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... | [
"def",
"truncate",
"(",
"self",
",",
"frames",
"=",
"None",
")",
":",
"if",
"frames",
"is",
"None",
":",
"frames",
"=",
"self",
".",
"tell",
"(",
")",
"err",
"=",
"_snd",
".",
"sf_command",
"(",
"self",
".",
"_file",
",",
"_snd",
".",
"SFC_FILE_TRU... | 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 deleted.
If not specified, the ... | [
"Truncate",
"the",
"file",
"to",
"a",
"given",
"number",
"of",
"frames",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1115-L1135 |
bastibe/SoundFile | soundfile.py | SoundFile.close | 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) | python | 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) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"closed",
":",
"# be sure to flush data to disk before closing the file",
"self",
".",
"flush",
"(",
")",
"err",
"=",
"_snd",
".",
"sf_close",
"(",
"self",
".",
"_file",
")",
"self",
".",
"_f... | Close the file. Can be called multiple times. | [
"Close",
"the",
"file",
".",
"Can",
"be",
"called",
"multiple",
"times",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1151-L1158 |
bastibe/SoundFile | soundfile.py | SoundFile._open | def _open(self, file, mode_int, closefd):
"""Call the appropriate sf_open*() function from libsndfile."""
if isinstance(file, (_unicode, bytes)):
if _os.path.isfile(file):
if 'x' in self.mode:
raise OSError("File exists: {0!r}".format(self.name))
... | python | def _open(self, file, mode_int, closefd):
"""Call the appropriate sf_open*() function from libsndfile."""
if isinstance(file, (_unicode, bytes)):
if _os.path.isfile(file):
if 'x' in self.mode:
raise OSError("File exists: {0!r}".format(self.name))
... | [
"def",
"_open",
"(",
"self",
",",
"file",
",",
"mode_int",
",",
"closefd",
")",
":",
"if",
"isinstance",
"(",
"file",
",",
"(",
"_unicode",
",",
"bytes",
")",
")",
":",
"if",
"_os",
".",
"path",
".",
"isfile",
"(",
"file",
")",
":",
"if",
"'x'",
... | Call the appropriate sf_open*() function from libsndfile. | [
"Call",
"the",
"appropriate",
"sf_open",
"*",
"()",
"function",
"from",
"libsndfile",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1160-L1192 |
bastibe/SoundFile | soundfile.py | SoundFile._init_virtual_io | 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)... | python | 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)... | [
"def",
"_init_virtual_io",
"(",
"self",
",",
"file",
")",
":",
"@",
"_ffi",
".",
"callback",
"(",
"\"sf_vio_get_filelen\"",
")",
"def",
"vio_get_filelen",
"(",
"user_data",
")",
":",
"curr",
"=",
"file",
".",
"tell",
"(",
")",
"file",
".",
"seek",
"(",
... | Initialize callback functions for sf_open_virtual(). | [
"Initialize",
"callback",
"functions",
"for",
"sf_open_virtual",
"()",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1194-L1243 |
bastibe/SoundFile | soundfile.py | SoundFile._check_frames | 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):
... | python | 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):
... | [
"def",
"_check_frames",
"(",
"self",
",",
"frames",
",",
"fill_value",
")",
":",
"if",
"self",
".",
"seekable",
"(",
")",
":",
"remaining_frames",
"=",
"self",
".",
"frames",
"-",
"self",
".",
"tell",
"(",
")",
"if",
"frames",
"<",
"0",
"or",
"(",
... | Reduce frames to no more than are available in the file. | [
"Reduce",
"frames",
"to",
"no",
"more",
"than",
"are",
"available",
"in",
"the",
"file",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1262-L1271 |
bastibe/SoundFile | soundfile.py | SoundFile._check_buffer | def _check_buffer(self, data, ctype):
"""Convert buffer to cdata and check for valid size."""
assert ctype in _ffi_types.values()
if not isinstance(data, bytes):
data = _ffi.from_buffer(data)
frames, remainder = divmod(len(data),
self.channe... | python | def _check_buffer(self, data, ctype):
"""Convert buffer to cdata and check for valid size."""
assert ctype in _ffi_types.values()
if not isinstance(data, bytes):
data = _ffi.from_buffer(data)
frames, remainder = divmod(len(data),
self.channe... | [
"def",
"_check_buffer",
"(",
"self",
",",
"data",
",",
"ctype",
")",
":",
"assert",
"ctype",
"in",
"_ffi_types",
".",
"values",
"(",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"data",
"=",
"_ffi",
".",
"from_buffer",
"(",
"d... | Convert buffer to cdata and check for valid size. | [
"Convert",
"buffer",
"to",
"cdata",
"and",
"check",
"for",
"valid",
"size",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1273-L1282 |
bastibe/SoundFile | soundfile.py | SoundFile._create_empty_array | def _create_empty_array(self, frames, always_2d, dtype):
"""Create an empty array with appropriate shape."""
import numpy as np
if always_2d or self.channels > 1:
shape = frames, self.channels
else:
shape = frames,
return np.empty(shape, dtype, order='C') | python | def _create_empty_array(self, frames, always_2d, dtype):
"""Create an empty array with appropriate shape."""
import numpy as np
if always_2d or self.channels > 1:
shape = frames, self.channels
else:
shape = frames,
return np.empty(shape, dtype, order='C') | [
"def",
"_create_empty_array",
"(",
"self",
",",
"frames",
",",
"always_2d",
",",
"dtype",
")",
":",
"import",
"numpy",
"as",
"np",
"if",
"always_2d",
"or",
"self",
".",
"channels",
">",
"1",
":",
"shape",
"=",
"frames",
",",
"self",
".",
"channels",
"e... | Create an empty array with appropriate shape. | [
"Create",
"an",
"empty",
"array",
"with",
"appropriate",
"shape",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1284-L1291 |
bastibe/SoundFile | soundfile.py | SoundFile._check_dtype | def _check_dtype(self, dtype):
"""Check if dtype string is valid and return ctype string."""
try:
return _ffi_types[dtype]
except KeyError:
raise ValueError("dtype must be one of {0!r} and not {1!r}".format(
sorted(_ffi_types.keys()), dtype)) | python | def _check_dtype(self, dtype):
"""Check if dtype string is valid and return ctype string."""
try:
return _ffi_types[dtype]
except KeyError:
raise ValueError("dtype must be one of {0!r} and not {1!r}".format(
sorted(_ffi_types.keys()), dtype)) | [
"def",
"_check_dtype",
"(",
"self",
",",
"dtype",
")",
":",
"try",
":",
"return",
"_ffi_types",
"[",
"dtype",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"dtype must be one of {0!r} and not {1!r}\"",
".",
"format",
"(",
"sorted",
"(",
"_ffi_typ... | Check if dtype string is valid and return ctype string. | [
"Check",
"if",
"dtype",
"string",
"is",
"valid",
"and",
"return",
"ctype",
"string",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1293-L1299 |
bastibe/SoundFile | soundfile.py | SoundFile._array_io | def _array_io(self, action, array, frames):
"""Check array and call low-level IO function."""
if (array.ndim not in (1, 2) or
array.ndim == 1 and self.channels != 1 or
array.ndim == 2 and array.shape[1] != self.channels):
raise ValueError("Invalid shape: {0!r}... | python | def _array_io(self, action, array, frames):
"""Check array and call low-level IO function."""
if (array.ndim not in (1, 2) or
array.ndim == 1 and self.channels != 1 or
array.ndim == 2 and array.shape[1] != self.channels):
raise ValueError("Invalid shape: {0!r}... | [
"def",
"_array_io",
"(",
"self",
",",
"action",
",",
"array",
",",
"frames",
")",
":",
"if",
"(",
"array",
".",
"ndim",
"not",
"in",
"(",
"1",
",",
"2",
")",
"or",
"array",
".",
"ndim",
"==",
"1",
"and",
"self",
".",
"channels",
"!=",
"1",
"or"... | Check array and call low-level IO function. | [
"Check",
"array",
"and",
"call",
"low",
"-",
"level",
"IO",
"function",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1301-L1312 |
bastibe/SoundFile | soundfile.py | SoundFile._cdata_io | def _cdata_io(self, action, data, ctype, frames):
"""Call one of libsndfile's read/write functions."""
assert ctype in _ffi_types.values()
self._check_if_closed()
if self.seekable():
curr = self.tell()
func = getattr(_snd, 'sf_' + action + 'f_' + ctype)
frames... | python | def _cdata_io(self, action, data, ctype, frames):
"""Call one of libsndfile's read/write functions."""
assert ctype in _ffi_types.values()
self._check_if_closed()
if self.seekable():
curr = self.tell()
func = getattr(_snd, 'sf_' + action + 'f_' + ctype)
frames... | [
"def",
"_cdata_io",
"(",
"self",
",",
"action",
",",
"data",
",",
"ctype",
",",
"frames",
")",
":",
"assert",
"ctype",
"in",
"_ffi_types",
".",
"values",
"(",
")",
"self",
".",
"_check_if_closed",
"(",
")",
"if",
"self",
".",
"seekable",
"(",
")",
":... | Call one of libsndfile's read/write functions. | [
"Call",
"one",
"of",
"libsndfile",
"s",
"read",
"/",
"write",
"functions",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1314-L1325 |
bastibe/SoundFile | soundfile.py | SoundFile._update_frames | def _update_frames(self, written):
"""Update self.frames after writing."""
if self.seekable():
curr = self.tell()
self._info.frames = self.seek(0, SEEK_END)
self.seek(curr, SEEK_SET)
else:
self._info.frames += written | python | def _update_frames(self, written):
"""Update self.frames after writing."""
if self.seekable():
curr = self.tell()
self._info.frames = self.seek(0, SEEK_END)
self.seek(curr, SEEK_SET)
else:
self._info.frames += written | [
"def",
"_update_frames",
"(",
"self",
",",
"written",
")",
":",
"if",
"self",
".",
"seekable",
"(",
")",
":",
"curr",
"=",
"self",
".",
"tell",
"(",
")",
"self",
".",
"_info",
".",
"frames",
"=",
"self",
".",
"seek",
"(",
"0",
",",
"SEEK_END",
")... | Update self.frames after writing. | [
"Update",
"self",
".",
"frames",
"after",
"writing",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1327-L1334 |
bastibe/SoundFile | soundfile.py | SoundFile._prepare_read | def _prepare_read(self, start, stop, frames):
"""Seek to start frame and calculate length."""
if start != 0 and not self.seekable():
raise ValueError("start is only allowed for seekable files")
if frames >= 0 and stop is not None:
raise TypeError("Only one of {frames, sto... | python | def _prepare_read(self, start, stop, frames):
"""Seek to start frame and calculate length."""
if start != 0 and not self.seekable():
raise ValueError("start is only allowed for seekable files")
if frames >= 0 and stop is not None:
raise TypeError("Only one of {frames, sto... | [
"def",
"_prepare_read",
"(",
"self",
",",
"start",
",",
"stop",
",",
"frames",
")",
":",
"if",
"start",
"!=",
"0",
"and",
"not",
"self",
".",
"seekable",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"start is only allowed for seekable files\"",
")",
"if",
... | Seek to start frame and calculate length. | [
"Seek",
"to",
"start",
"frame",
"and",
"calculate",
"length",
"."
] | train | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1336-L1350 |
bioidiap/bob.bio.spear | bob/bio/spear/utils/__init__.py | ensure_dir | def ensure_dir(dirname):
""" Creates the directory dirname if it does not already exist,
taking into account concurrent 'creation' on the grid.
An exception is thrown if a file (rather than a directory) already
exists. """
try:
# Tries to create the directory
os.makedirs(dirname)
except ... | python | def ensure_dir(dirname):
""" Creates the directory dirname if it does not already exist,
taking into account concurrent 'creation' on the grid.
An exception is thrown if a file (rather than a directory) already
exists. """
try:
# Tries to create the directory
os.makedirs(dirname)
except ... | [
"def",
"ensure_dir",
"(",
"dirname",
")",
":",
"try",
":",
"# Tries to create the directory",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"except",
"OSError",
":",
"# Check that the directory exists",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dirname",
")",
... | Creates the directory dirname if it does not already exist,
taking into account concurrent 'creation' on the grid.
An exception is thrown if a file (rather than a directory) already
exists. | [
"Creates",
"the",
"directory",
"dirname",
"if",
"it",
"does",
"not",
"already",
"exist",
"taking",
"into",
"account",
"concurrent",
"creation",
"on",
"the",
"grid",
".",
"An",
"exception",
"is",
"thrown",
"if",
"a",
"file",
"(",
"rather",
"than",
"a",
"dir... | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/__init__.py#L26-L37 |
bioidiap/bob.bio.spear | bob/bio/spear/utils/__init__.py | probes_used_generate_vector | def probes_used_generate_vector(probe_files_full, probe_files_model):
"""Generates boolean matrices indicating which are the probes for each model"""
import numpy as np
C_probesUsed = np.ndarray((len(probe_files_full),), 'bool')
C_probesUsed.fill(False)
c=0
for k in sorted(probe_files_full.keys()):
if p... | python | def probes_used_generate_vector(probe_files_full, probe_files_model):
"""Generates boolean matrices indicating which are the probes for each model"""
import numpy as np
C_probesUsed = np.ndarray((len(probe_files_full),), 'bool')
C_probesUsed.fill(False)
c=0
for k in sorted(probe_files_full.keys()):
if p... | [
"def",
"probes_used_generate_vector",
"(",
"probe_files_full",
",",
"probe_files_model",
")",
":",
"import",
"numpy",
"as",
"np",
"C_probesUsed",
"=",
"np",
".",
"ndarray",
"(",
"(",
"len",
"(",
"probe_files_full",
")",
",",
")",
",",
"'bool'",
")",
"C_probesU... | Generates boolean matrices indicating which are the probes for each model | [
"Generates",
"boolean",
"matrices",
"indicating",
"which",
"are",
"the",
"probes",
"for",
"each",
"model"
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/__init__.py#L66-L75 |
bioidiap/bob.bio.spear | bob/bio/spear/utils/__init__.py | probes_used_extract_scores | def probes_used_extract_scores(full_scores, same_probes):
"""Extracts a matrix of scores for a model, given a probes_used row vector of boolean"""
if full_scores.shape[1] != same_probes.shape[0]: raise "Size mismatch"
import numpy as np
model_scores = np.ndarray((full_scores.shape[0],np.sum(same_probes)), 'floa... | python | def probes_used_extract_scores(full_scores, same_probes):
"""Extracts a matrix of scores for a model, given a probes_used row vector of boolean"""
if full_scores.shape[1] != same_probes.shape[0]: raise "Size mismatch"
import numpy as np
model_scores = np.ndarray((full_scores.shape[0],np.sum(same_probes)), 'floa... | [
"def",
"probes_used_extract_scores",
"(",
"full_scores",
",",
"same_probes",
")",
":",
"if",
"full_scores",
".",
"shape",
"[",
"1",
"]",
"!=",
"same_probes",
".",
"shape",
"[",
"0",
"]",
":",
"raise",
"\"Size mismatch\"",
"import",
"numpy",
"as",
"np",
"mode... | Extracts a matrix of scores for a model, given a probes_used row vector of boolean | [
"Extracts",
"a",
"matrix",
"of",
"scores",
"for",
"a",
"model",
"given",
"a",
"probes_used",
"row",
"vector",
"of",
"boolean"
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/__init__.py#L77-L88 |
bioidiap/bob.bio.spear | bob/bio/spear/utils/__init__.py | read | def read(filename):
"""Read audio file"""
# Depricated: use load() function from bob.bio.spear.database.AudioBioFile
#TODO: update xbob.sox first. This will enable the use of formats like NIST sphere and other
#import xbob.sox
#audio = xbob.sox.reader(filename)
#(rate, data) = audio.load()
# We consider t... | python | def read(filename):
"""Read audio file"""
# Depricated: use load() function from bob.bio.spear.database.AudioBioFile
#TODO: update xbob.sox first. This will enable the use of formats like NIST sphere and other
#import xbob.sox
#audio = xbob.sox.reader(filename)
#(rate, data) = audio.load()
# We consider t... | [
"def",
"read",
"(",
"filename",
")",
":",
"# Depricated: use load() function from bob.bio.spear.database.AudioBioFile",
"#TODO: update xbob.sox first. This will enable the use of formats like NIST sphere and other",
"#import xbob.sox",
"#audio = xbob.sox.reader(filename)",
"#(rate, data) = audio... | Read audio file | [
"Read",
"audio",
"file"
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/__init__.py#L91-L105 |
bioidiap/bob.bio.spear | bob/bio/spear/utils/__init__.py | normalize_std_array | def normalize_std_array(vector):
"""Applies a unit mean and variance normalization to an arrayset"""
# Initializes variables
length = 1
n_samples = len(vector)
mean = numpy.ndarray((length,), 'float64')
std = numpy.ndarray((length,), 'float64')
mean.fill(0)
std.fill(0)
# Computes mean and variance
... | python | def normalize_std_array(vector):
"""Applies a unit mean and variance normalization to an arrayset"""
# Initializes variables
length = 1
n_samples = len(vector)
mean = numpy.ndarray((length,), 'float64')
std = numpy.ndarray((length,), 'float64')
mean.fill(0)
std.fill(0)
# Computes mean and variance
... | [
"def",
"normalize_std_array",
"(",
"vector",
")",
":",
"# Initializes variables",
"length",
"=",
"1",
"n_samples",
"=",
"len",
"(",
"vector",
")",
"mean",
"=",
"numpy",
".",
"ndarray",
"(",
"(",
"length",
",",
")",
",",
"'float64'",
")",
"std",
"=",
"num... | Applies a unit mean and variance normalization to an arrayset | [
"Applies",
"a",
"unit",
"mean",
"and",
"variance",
"normalization",
"to",
"an",
"arrayset"
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/__init__.py#L109-L134 |
bioidiap/bob.bio.spear | bob/bio/spear/utils/__init__.py | smoothing | def smoothing(labels, smoothing_window):
""" Applies a smoothing on VAD"""
if numpy.sum(labels)< smoothing_window:
return labels
segments = []
for k in range(1,len(labels)-1):
if labels[k]==0 and labels[k-1]==1 and labels[k+1]==1 :
labels[k]=1
for k in range(1,len(labels)-1):
if labels[k]==... | python | def smoothing(labels, smoothing_window):
""" Applies a smoothing on VAD"""
if numpy.sum(labels)< smoothing_window:
return labels
segments = []
for k in range(1,len(labels)-1):
if labels[k]==0 and labels[k-1]==1 and labels[k+1]==1 :
labels[k]=1
for k in range(1,len(labels)-1):
if labels[k]==... | [
"def",
"smoothing",
"(",
"labels",
",",
"smoothing_window",
")",
":",
"if",
"numpy",
".",
"sum",
"(",
"labels",
")",
"<",
"smoothing_window",
":",
"return",
"labels",
"segments",
"=",
"[",
"]",
"for",
"k",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"l... | Applies a smoothing on VAD | [
"Applies",
"a",
"smoothing",
"on",
"VAD"
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/__init__.py#L137-L198 |
bioidiap/bob.bio.spear | bob/bio/spear/preprocessor/External.py | External._conversion | def _conversion(self, input_signal, vad_file):
"""
Converts an external VAD to follow the Spear convention.
Energy is used in order to avoind out-of-bound array indexes.
"""
e = bob.ap.Energy(rate_wavsample[0], self.win_length_ms, self.win_shift_ms)
energy_array = e(rate_wavsample[1])
... | python | def _conversion(self, input_signal, vad_file):
"""
Converts an external VAD to follow the Spear convention.
Energy is used in order to avoind out-of-bound array indexes.
"""
e = bob.ap.Energy(rate_wavsample[0], self.win_length_ms, self.win_shift_ms)
energy_array = e(rate_wavsample[1])
... | [
"def",
"_conversion",
"(",
"self",
",",
"input_signal",
",",
"vad_file",
")",
":",
"e",
"=",
"bob",
".",
"ap",
".",
"Energy",
"(",
"rate_wavsample",
"[",
"0",
"]",
",",
"self",
".",
"win_length_ms",
",",
"self",
".",
"win_shift_ms",
")",
"energy_array",
... | Converts an external VAD to follow the Spear convention.
Energy is used in order to avoind out-of-bound array indexes. | [
"Converts",
"an",
"external",
"VAD",
"to",
"follow",
"the",
"Spear",
"convention",
".",
"Energy",
"is",
"used",
"in",
"order",
"to",
"avoind",
"out",
"-",
"of",
"-",
"bound",
"array",
"indexes",
"."
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/preprocessor/External.py#L65-L75 |
bioidiap/bob.bio.spear | bob/bio/spear/preprocessor/Mod_4Hz.py | Mod_4Hz.mod_4hz | def mod_4hz(self, rate_wavsample):
"""Computes and returns the 4Hz modulation energy features for the given input wave file"""
# Set parameters
wl = self.win_length_ms
ws = self.win_shift_ms
nf = self.n_filters
f_min = self.f_min
f_max = self.f_max
pre = self.pre_emphasis_coef
c = ... | python | def mod_4hz(self, rate_wavsample):
"""Computes and returns the 4Hz modulation energy features for the given input wave file"""
# Set parameters
wl = self.win_length_ms
ws = self.win_shift_ms
nf = self.n_filters
f_min = self.f_min
f_max = self.f_max
pre = self.pre_emphasis_coef
c = ... | [
"def",
"mod_4hz",
"(",
"self",
",",
"rate_wavsample",
")",
":",
"# Set parameters",
"wl",
"=",
"self",
".",
"win_length_ms",
"ws",
"=",
"self",
".",
"win_shift_ms",
"nf",
"=",
"self",
".",
"n_filters",
"f_min",
"=",
"self",
".",
"f_min",
"f_max",
"=",
"s... | Computes and returns the 4Hz modulation energy features for the given input wave file | [
"Computes",
"and",
"returns",
"the",
"4Hz",
"modulation",
"energy",
"features",
"for",
"the",
"given",
"input",
"wave",
"file"
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/preprocessor/Mod_4Hz.py#L168-L194 |
bioidiap/bob.bio.spear | bob/bio/spear/extractor/CQCCFeatures.py | CQCCFeatures.read_matlab_files | def read_matlab_files(self, biofile, directory, extension):
"""
Read pre-computed CQCC Matlab features here
"""
import bob.io.matlab
# return the numpy array read from the data_file
data_path = biofile.make_path(directory, extension)
return bob.io.base.load(data_p... | python | def read_matlab_files(self, biofile, directory, extension):
"""
Read pre-computed CQCC Matlab features here
"""
import bob.io.matlab
# return the numpy array read from the data_file
data_path = biofile.make_path(directory, extension)
return bob.io.base.load(data_p... | [
"def",
"read_matlab_files",
"(",
"self",
",",
"biofile",
",",
"directory",
",",
"extension",
")",
":",
"import",
"bob",
".",
"io",
".",
"matlab",
"# return the numpy array read from the data_file",
"data_path",
"=",
"biofile",
".",
"make_path",
"(",
"directory",
"... | Read pre-computed CQCC Matlab features here | [
"Read",
"pre",
"-",
"computed",
"CQCC",
"Matlab",
"features",
"here"
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/extractor/CQCCFeatures.py#L45-L52 |
bioidiap/bob.bio.spear | bob/bio/spear/preprocessor/Base.py | Base.write_data | def write_data(self, data, data_file, compression=0):
"""Writes the given *preprocessed* data to a file with the given name.
"""
f = bob.io.base.HDF5File(data_file, 'w')
f.set("rate", data[0], compression=compression)
f.set("data", data[1], compression=compression)
f.set("labels", data[2], compr... | python | def write_data(self, data, data_file, compression=0):
"""Writes the given *preprocessed* data to a file with the given name.
"""
f = bob.io.base.HDF5File(data_file, 'w')
f.set("rate", data[0], compression=compression)
f.set("data", data[1], compression=compression)
f.set("labels", data[2], compr... | [
"def",
"write_data",
"(",
"self",
",",
"data",
",",
"data_file",
",",
"compression",
"=",
"0",
")",
":",
"f",
"=",
"bob",
".",
"io",
".",
"base",
".",
"HDF5File",
"(",
"data_file",
",",
"'w'",
")",
"f",
".",
"set",
"(",
"\"rate\"",
",",
"data",
"... | Writes the given *preprocessed* data to a file with the given name. | [
"Writes",
"the",
"given",
"*",
"preprocessed",
"*",
"data",
"to",
"a",
"file",
"with",
"the",
"given",
"name",
"."
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/preprocessor/Base.py#L18-L24 |
bioidiap/bob.bio.spear | bob/bio/spear/script/baselines.py | command_line_arguments | def command_line_arguments(command_line_parameters):
"""Defines the command line parameters that are accepted."""
# create parser
parser = argparse.ArgumentParser(description='Execute baseline algorithms with default parameters', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# add parameters
# - t... | python | def command_line_arguments(command_line_parameters):
"""Defines the command line parameters that are accepted."""
# create parser
parser = argparse.ArgumentParser(description='Execute baseline algorithms with default parameters', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# add parameters
# - t... | [
"def",
"command_line_arguments",
"(",
"command_line_parameters",
")",
":",
"# create parser",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Execute baseline algorithms with default parameters'",
",",
"formatter_class",
"=",
"argparse",
".",
"A... | Defines the command line parameters that are accepted. | [
"Defines",
"the",
"command",
"line",
"parameters",
"that",
"are",
"accepted",
"."
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/script/baselines.py#L38-L78 |
bioidiap/bob.bio.spear | bob/bio/spear/preprocessor/Energy_2Gauss.py | Energy_2Gauss._compute_energy | def _compute_energy(self, rate_wavsample):
"""retreive the speech / non speech labels for the speech sample given by the tuple (rate, wave signal)"""
e = bob.ap.Energy(rate_wavsample[0], self.win_length_ms, self.win_shift_ms)
energy_array = e(rate_wavsample[1])
labels = self._voice_activity_detection(e... | python | def _compute_energy(self, rate_wavsample):
"""retreive the speech / non speech labels for the speech sample given by the tuple (rate, wave signal)"""
e = bob.ap.Energy(rate_wavsample[0], self.win_length_ms, self.win_shift_ms)
energy_array = e(rate_wavsample[1])
labels = self._voice_activity_detection(e... | [
"def",
"_compute_energy",
"(",
"self",
",",
"rate_wavsample",
")",
":",
"e",
"=",
"bob",
".",
"ap",
".",
"Energy",
"(",
"rate_wavsample",
"[",
"0",
"]",
",",
"self",
".",
"win_length_ms",
",",
"self",
".",
"win_shift_ms",
")",
"energy_array",
"=",
"e",
... | retreive the speech / non speech labels for the speech sample given by the tuple (rate, wave signal) | [
"retreive",
"the",
"speech",
"/",
"non",
"speech",
"labels",
"for",
"the",
"speech",
"sample",
"given",
"by",
"the",
"tuple",
"(",
"rate",
"wave",
"signal",
")"
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/preprocessor/Energy_2Gauss.py#L122-L132 |
bioidiap/bob.bio.spear | bob/bio/spear/utils/extraction.py | calc_mean | def calc_mean(c0, c1=[]):
""" Calculates the mean of the data."""
if c1 != []:
return (numpy.mean(c0, 0) + numpy.mean(c1, 0)) / 2.
else:
return numpy.mean(c0, 0) | python | def calc_mean(c0, c1=[]):
""" Calculates the mean of the data."""
if c1 != []:
return (numpy.mean(c0, 0) + numpy.mean(c1, 0)) / 2.
else:
return numpy.mean(c0, 0) | [
"def",
"calc_mean",
"(",
"c0",
",",
"c1",
"=",
"[",
"]",
")",
":",
"if",
"c1",
"!=",
"[",
"]",
":",
"return",
"(",
"numpy",
".",
"mean",
"(",
"c0",
",",
"0",
")",
"+",
"numpy",
".",
"mean",
"(",
"c1",
",",
"0",
")",
")",
"/",
"2.",
"else"... | Calculates the mean of the data. | [
"Calculates",
"the",
"mean",
"of",
"the",
"data",
"."
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/extraction.py#L32-L37 |
bioidiap/bob.bio.spear | bob/bio/spear/utils/extraction.py | calc_std | def calc_std(c0, c1=[]):
""" Calculates the variance of the data."""
if c1 == []:
return numpy.std(c0, 0)
prop = float(len(c0)) / float(len(c1))
if prop < 1:
p0 = int(math.ceil(1 / prop))
p1 = 1
else:
p0 = 1
p1 = int(math.ceil(prop))
return numpy.std(numpy... | python | def calc_std(c0, c1=[]):
""" Calculates the variance of the data."""
if c1 == []:
return numpy.std(c0, 0)
prop = float(len(c0)) / float(len(c1))
if prop < 1:
p0 = int(math.ceil(1 / prop))
p1 = 1
else:
p0 = 1
p1 = int(math.ceil(prop))
return numpy.std(numpy... | [
"def",
"calc_std",
"(",
"c0",
",",
"c1",
"=",
"[",
"]",
")",
":",
"if",
"c1",
"==",
"[",
"]",
":",
"return",
"numpy",
".",
"std",
"(",
"c0",
",",
"0",
")",
"prop",
"=",
"float",
"(",
"len",
"(",
"c0",
")",
")",
"/",
"float",
"(",
"len",
"... | Calculates the variance of the data. | [
"Calculates",
"the",
"variance",
"of",
"the",
"data",
"."
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/extraction.py#L40-L51 |
bioidiap/bob.bio.spear | bob/bio/spear/utils/extraction.py | calc_mean_std | def calc_mean_std(c0, c1=[], nonStdZero=False):
""" Calculates both the mean of the data. """
mi = calc_mean(c0, c1)
std = calc_std(c0, c1)
if (nonStdZero):
std[std == 0] = 1
return mi, std | python | def calc_mean_std(c0, c1=[], nonStdZero=False):
""" Calculates both the mean of the data. """
mi = calc_mean(c0, c1)
std = calc_std(c0, c1)
if (nonStdZero):
std[std == 0] = 1
return mi, std | [
"def",
"calc_mean_std",
"(",
"c0",
",",
"c1",
"=",
"[",
"]",
",",
"nonStdZero",
"=",
"False",
")",
":",
"mi",
"=",
"calc_mean",
"(",
"c0",
",",
"c1",
")",
"std",
"=",
"calc_std",
"(",
"c0",
",",
"c1",
")",
"if",
"(",
"nonStdZero",
")",
":",
"st... | Calculates both the mean of the data. | [
"Calculates",
"both",
"the",
"mean",
"of",
"the",
"data",
"."
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/extraction.py#L59-L66 |
bioidiap/bob.bio.spear | bob/bio/spear/utils/extraction.py | vad_filter_features | def vad_filter_features(vad_labels, features, filter_frames="trim_silence"):
""" Trim the spectrogram to remove silent head/tails from the speech sample.
Keep all remaining frames or either speech or non-speech only
@param: filter_frames: the value is either 'silence_only' (keep the speech, remove everythin... | python | def vad_filter_features(vad_labels, features, filter_frames="trim_silence"):
""" Trim the spectrogram to remove silent head/tails from the speech sample.
Keep all remaining frames or either speech or non-speech only
@param: filter_frames: the value is either 'silence_only' (keep the speech, remove everythin... | [
"def",
"vad_filter_features",
"(",
"vad_labels",
",",
"features",
",",
"filter_frames",
"=",
"\"trim_silence\"",
")",
":",
"if",
"not",
"features",
".",
"size",
":",
"raise",
"ValueError",
"(",
"\"vad_filter_features(): data sample is empty, no features extraction is possib... | Trim the spectrogram to remove silent head/tails from the speech sample.
Keep all remaining frames or either speech or non-speech only
@param: filter_frames: the value is either 'silence_only' (keep the speech, remove everything else),
'speech_only' (only keep the silent parts), 'trim_silence' (trim silent ... | [
"Trim",
"the",
"spectrogram",
"to",
"remove",
"silent",
"head",
"/",
"tails",
"from",
"the",
"speech",
"sample",
".",
"Keep",
"all",
"remaining",
"frames",
"or",
"either",
"speech",
"or",
"non",
"-",
"speech",
"only"
] | train | https://github.com/bioidiap/bob.bio.spear/blob/9f5d13d2e52d3b0c818f4abaa07cda15f62a34cd/bob/bio/spear/utils/extraction.py#L69-L120 |
jtambasco/modesolverpy | modesolverpy/mode_solver.py | _ModeSolver.solve_sweep_structure | def solve_sweep_structure(
self,
structures,
sweep_param_list,
filename="structure_n_effs.dat",
plot=True,
x_label="Structure number",
fraction_mode_list=[],
):
"""
Find the modes of many structures.
Args:
structures (list)... | python | def solve_sweep_structure(
self,
structures,
sweep_param_list,
filename="structure_n_effs.dat",
plot=True,
x_label="Structure number",
fraction_mode_list=[],
):
"""
Find the modes of many structures.
Args:
structures (list)... | [
"def",
"solve_sweep_structure",
"(",
"self",
",",
"structures",
",",
"sweep_param_list",
",",
"filename",
"=",
"\"structure_n_effs.dat\"",
",",
"plot",
"=",
"True",
",",
"x_label",
"=",
"\"Structure number\"",
",",
"fraction_mode_list",
"=",
"[",
"]",
",",
")",
... | Find the modes of many structures.
Args:
structures (list): A list of `Structures` to find the modes
of.
sweep_param_list (list): A list of the parameter-sweep sweep
that was used. This is for plotting purposes only.
filename (str): The nomin... | [
"Find",
"the",
"modes",
"of",
"many",
"structures",
"."
] | train | https://github.com/jtambasco/modesolverpy/blob/85254a13b5aed2404187c52ac93b9b3ce99ee3a3/modesolverpy/mode_solver.py#L92-L192 |
jtambasco/modesolverpy | modesolverpy/mode_solver.py | _ModeSolver.solve_sweep_wavelength | def solve_sweep_wavelength(
self,
structure,
wavelengths,
filename="wavelength_n_effs.dat",
plot=True,
):
"""
Solve for the effective indices of a fixed structure at
different wavelengths.
Args:
structure (Slabs): The target struct... | python | def solve_sweep_wavelength(
self,
structure,
wavelengths,
filename="wavelength_n_effs.dat",
plot=True,
):
"""
Solve for the effective indices of a fixed structure at
different wavelengths.
Args:
structure (Slabs): The target struct... | [
"def",
"solve_sweep_wavelength",
"(",
"self",
",",
"structure",
",",
"wavelengths",
",",
"filename",
"=",
"\"wavelength_n_effs.dat\"",
",",
"plot",
"=",
"True",
",",
")",
":",
"n_effs",
"=",
"[",
"]",
"for",
"w",
"in",
"tqdm",
".",
"tqdm",
"(",
"wavelength... | Solve for the effective indices of a fixed structure at
different wavelengths.
Args:
structure (Slabs): The target structure to solve
for modes.
wavelengths (list): A list of wavelengths to sweep
over.
filename (str): The nominal filen... | [
"Solve",
"for",
"the",
"effective",
"indices",
"of",
"a",
"fixed",
"structure",
"at",
"different",
"wavelengths",
"."
] | train | https://github.com/jtambasco/modesolverpy/blob/85254a13b5aed2404187c52ac93b9b3ce99ee3a3/modesolverpy/mode_solver.py#L194-L243 |
jtambasco/modesolverpy | modesolverpy/mode_solver.py | _ModeSolver.solve_ng | def solve_ng(self, structure, wavelength_step=0.01, filename="ng.dat"):
r"""
Solve for the group index, :math:`n_g`, of a structure at a particular
wavelength.
Args:
structure (Structure): The target structure to solve
for modes.
wavelength_step (... | python | def solve_ng(self, structure, wavelength_step=0.01, filename="ng.dat"):
r"""
Solve for the group index, :math:`n_g`, of a structure at a particular
wavelength.
Args:
structure (Structure): The target structure to solve
for modes.
wavelength_step (... | [
"def",
"solve_ng",
"(",
"self",
",",
"structure",
",",
"wavelength_step",
"=",
"0.01",
",",
"filename",
"=",
"\"ng.dat\"",
")",
":",
"wl_nom",
"=",
"structure",
".",
"_wl",
"self",
".",
"solve",
"(",
"structure",
")",
"n_ctrs",
"=",
"self",
".",
"n_effs"... | r"""
Solve for the group index, :math:`n_g`, of a structure at a particular
wavelength.
Args:
structure (Structure): The target structure to solve
for modes.
wavelength_step (float): The step to take below and
above the nominal wavelength.... | [
"r",
"Solve",
"for",
"the",
"group",
"index",
":",
"math",
":",
"n_g",
"of",
"a",
"structure",
"at",
"a",
"particular",
"wavelength",
"."
] | train | https://github.com/jtambasco/modesolverpy/blob/85254a13b5aed2404187c52ac93b9b3ce99ee3a3/modesolverpy/mode_solver.py#L245-L288 |
jtambasco/modesolverpy | modesolverpy/mode_solver.py | ModeSolverSemiVectorial.write_modes_to_file | def write_modes_to_file(self, filename="mode.dat", plot=True, analyse=True):
"""
Writes the mode fields to a file and optionally plots them.
Args:
filename (str): The nominal filename to use for the saved
data. The suffix will be automatically be changed to
... | python | def write_modes_to_file(self, filename="mode.dat", plot=True, analyse=True):
"""
Writes the mode fields to a file and optionally plots them.
Args:
filename (str): The nominal filename to use for the saved
data. The suffix will be automatically be changed to
... | [
"def",
"write_modes_to_file",
"(",
"self",
",",
"filename",
"=",
"\"mode.dat\"",
",",
"plot",
"=",
"True",
",",
"analyse",
"=",
"True",
")",
":",
"modes_directory",
"=",
"\"./modes_semi_vec/\"",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"modes_direc... | Writes the mode fields to a file and optionally plots them.
Args:
filename (str): The nominal filename to use for the saved
data. The suffix will be automatically be changed to
identifiy each mode number. Default is 'mode.dat'
plot (bool): `True` if plo... | [
"Writes",
"the",
"mode",
"fields",
"to",
"a",
"file",
"and",
"optionally",
"plots",
"them",
"."
] | train | https://github.com/jtambasco/modesolverpy/blob/85254a13b5aed2404187c52ac93b9b3ce99ee3a3/modesolverpy/mode_solver.py#L548-L610 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.