Get the strain for a single ifo when using the multi-detector CLI
978902
def from_cli_single_ifo(opt, ifo, **kwargs):
    
    single_det_opt = copy_opts_for_single_ifo(opt, ifo)
    return from_cli(single_det_opt, **kwargs)
368849
def from_multi_ifo_interface(cls, opt, ifo, column, column_types, **kwds):
        
        opt = copy.deepcopy(opt)
        opt_dict = vars(opt)
        for arg, value in opt_dict.items():
            if isinstance(value, dict):
                setattr(opt, arg, getattr(opt, arg)[ifo])
        return cls(opt, column, column_types, **kwds)
690330
def parse(self, ifconfig=None):  # noqa: max-complexity=12
        
        if not ifconfig:
            ifconfig, __, __ = exec_cmd(self.get_command())
        self.ifconfig_data = ifconfig
        cur = None
        patterns = self.get_patterns()
        for line in self.ifconfig_data.splitlines():
            for pattern in patterns:
                m = re.match(pattern, line)
                if not m:
                    continue
                groupdict = m.groupdict()
                # Special treatment to trigger which interface we're
                # setting for if 'device' is in the line.  Presumably the
                # device of the interface is within the first line of the
                # device block.
                if 'device' in groupdict:
                    cur = groupdict['device']
                    self.add_device(cur)
                elif cur is None:
                    raise RuntimeError(
                        "Got results that don't belong to a device"
                    )

                for k, v in groupdict.items():
                    if k in self._interfaces[cur]:
                        if self._interfaces[cur][k] is None:
                            self._interfaces[cur][k] = v
                        elif hasattr(self._interfaces[cur][k], 'append'):
                            self._interfaces[cur][k].append(v)
                        elif self._interfaces[cur][k] == v:
                            # Silently ignore if the it's the same value as last. Example: Multiple
                            # inet4 addresses, result in multiple netmasks. Cardinality mismatch
                            continue
                        else:
                            raise RuntimeError(
                                "Tried to add {}={} multiple times to {}, it was already: {}".format(
                                    k,
                                    v,
                                    cur,
                                    self._interfaces[cur][k]
                                )
                            )
                    else:
                        self._interfaces[cur][k] = v

        # Copy the first 'inet4' ip address to 'inet' for backwards compatibility
        for device, device_dict in self._interfaces.items():
            if len(device_dict['inet4']) > 0:
                device_dict['inet'] = device_dict['inet4'][0]

        # fix it up
        self._interfaces = self.alter(self._interfaces)
90910
def _make_pull_imethod_resp(objs, eos, context_id):
        
        eos_tup = (u'EndOfSequence', None, eos)
        enum_ctxt_tup = (u'EnumerationContext', None, context_id)

        return [("IRETURNVALUE", {}, objs), enum_ctxt_tup, eos_tup]
464659
def _parse_bridge_opts(opts, iface):
    '''
    
    '''
    config = {}

    if 'ports' in opts:
        if isinstance(opts['ports'], list):
            opts['ports'] = ' '.join(opts['ports'])
        config.update({'ports': opts['ports']})

    for opt in ['ageing', 'fd', 'gcint', 'hello', 'maxage']:
        if opt in opts:
            try:
                float(opts[opt])
                config.update({opt: opts[opt]})
            except ValueError:
                _raise_error_iface(iface, opt, ['float'])

    for opt in ['bridgeprio', 'maxwait']:
        if opt in opts:
            if isinstance(opts[opt], int):
                config.update({opt: opts[opt]})
            else:
                _raise_error_iface(iface, opt, ['integer'])

    if 'hw' in opts:
        # match 12 hex digits with either : or - as separators between pairs
        if re.match('[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$',
                    opts['hw'].lower()):
            config.update({'hw': opts['hw']})
        else:
            _raise_error_iface(iface, 'hw', ['valid MAC address'])

    for opt in ['pathcost', 'portprio']:
        if opt in opts:
            try:
                port, cost_or_prio = opts[opt].split()
                int(cost_or_prio)
                config.update({opt: '{0} {1}'.format(port, cost_or_prio)})
            except ValueError:
                _raise_error_iface(iface, opt, ['interface integer'])

    if 'stp' in opts:
        if opts['stp'] in _CONFIG_TRUE:
            config.update({'stp': 'on'})
        elif opts['stp'] in _CONFIG_FALSE:
            config.update({'stp': 'off'})
        else:
            _raise_error_iface(iface, 'stp', _CONFIG_TRUE + _CONFIG_FALSE)

    if 'waitport' in opts:
        if isinstance(opts['waitport'], int):
            config.update({'waitport': opts['waitport']})
        else:
            values = opts['waitport'].split()
            waitport_time = values.pop(0)
            if waitport_time.isdigit() and values:
                config.update({
                    'waitport': '{0} {1}'.format(
                        waitport_time, ' '.join(values)
                    )
                })
            else:
                _raise_error_iface(iface, opt, ['integer [interfaces]'])

    return config
451228
def low_frequency_cutoff_from_cli(opts):
    
    # FIXME: this just uses the same frequency cutoff for every instrument for
    # now. We should allow for different frequency cutoffs to be used; that
    # will require (minor) changes to the Likelihood class
    instruments = opts.instruments if opts.instruments is not None else []
    return {ifo: opts.low_frequency_cutoff for ifo in instruments}
1087505
def get_signals(signal_array, frame, root_or_cache, ns, multiplex_id, float_factory):
    # type: (typing.Sequence[_Element], canmatrix.Frame, _DocRoot, str, _MultiplexId, typing.Callable) -> None
    """"""
    global signal_rxs
    group_id = 1
    if signal_array is None:  # Empty signalarray - nothing to do
        return
    for signal in signal_array:
        compu_method = None
        motorola = get_child(signal, "PACKING-BYTE-ORDER", root_or_cache, ns)
        start_bit = get_child(signal, "START-POSITION", root_or_cache, ns)

        isignal = get_child(signal, "SIGNAL", root_or_cache, ns)
        if isignal is None:
            isignal = get_child(signal, "I-SIGNAL", root_or_cache, ns)
        if isignal is None:
            isignal = get_child(signal, "I-SIGNAL-GROUP", root_or_cache, ns)
            if isignal is not None:
                logger.debug("get_signals: found I-SIGNAL-GROUP ")

                isignal_array = find_children_by_path(isignal, "I-SIGNAL", root_or_cache, ns)
                get_sys_signals(isignal, isignal_array, frame, group_id, ns)
                group_id = group_id + 1
                continue
        if isignal is None:
            logger.debug(
                'Frame %s, no isignal for %s found',
                frame.name, get_child(signal, "SHORT-NAME", root_or_cache, ns).text)

        base_type = get_child(isignal, "BASE-TYPE", root_or_cache, ns)
        signal_name = None  # type: typing.Optional[str]
        signal_name_elem = get_child(isignal, "LONG-NAME", root_or_cache, ns)
        if signal_name_elem is not None:
            signal_name_elem = get_child(signal_name_elem, "L-4", root_or_cache, ns)
            if signal_name_elem is not None:
                signal_name = signal_name_elem.text
        system_signal = get_child(isignal, "SYSTEM-SIGNAL", root_or_cache, ns)
        if system_signal is None:
            logger.debug('Frame %s, signal %s has no system-signal', frame.name, isignal.tag)

        if "SYSTEM-SIGNAL-GROUP" in system_signal.tag:
            system_signals = find_children_by_path(system_signal, "SYSTEM-SIGNAL-REFS/SYSTEM-SIGNAL", root_or_cache, ns)
            get_sys_signals(system_signal, system_signals, frame, group_id, ns)
            group_id = group_id + 1
            continue

        length = get_child(isignal, "LENGTH", root_or_cache, ns)
        if length is None:
            length = get_child(system_signal, "LENGTH", root_or_cache, ns)

        name = get_child(system_signal, "SHORT-NAME", root_or_cache, ns)
        unit_element = get_child(isignal, "UNIT", root_or_cache, ns)
        display_name = get_child(unit_element, "DISPLAY-NAME", root_or_cache, ns)
        if display_name is not None:
            signal_unit = display_name.text
        else:
            signal_unit = ""

        signal_min = None  # type: canmatrix.types.OptionalPhysicalValue
        signal_max = None  # type: canmatrix.types.OptionalPhysicalValue
        receiver = []  # type: typing.List[str]

        signal_description = get_element_desc(system_signal, root_or_cache, ns)

        datatype = get_child(system_signal, "DATA-TYPE", root_or_cache, ns)
        if datatype is None:  # AR4?
            data_constr = None
            compu_method = None
            base_type = None
            for test_signal in [isignal, system_signal]:
                if data_constr is None:
                    data_constr = get_child(test_signal, "DATA-CONSTR", root_or_cache, ns)
                if compu_method is None:
                    compu_method = get_child(test_signal, "COMPU-METHOD", root_or_cache, ns)
                if base_type is None:
                    base_type = get_child(test_signal, "BASE-TYPE", root_or_cache, ns)



            lower = get_child(data_constr, "LOWER-LIMIT", root_or_cache, ns)
            upper = get_child(data_constr, "UPPER-LIMIT", root_or_cache, ns)
            encoding = None  # TODO - find encoding in AR4
        else:
            lower = get_child(datatype, "LOWER-LIMIT", root_or_cache, ns)
            upper = get_child(datatype, "UPPER-LIMIT", root_or_cache, ns)
            encoding = get_child(datatype, "ENCODING", root_or_cache, ns)

        if encoding is not None and (encoding.text == "SINGLE" or encoding.text == "DOUBLE"):
            is_float = True
        else:
            is_float = False
        
        if lower is not None and upper is not None:
            signal_min = float_factory(lower.text)
            signal_max = float_factory(upper.text)

        datdefprops = get_child(datatype, "SW-DATA-DEF-PROPS", root_or_cache, ns)

        if compu_method is None:
            compu_method = get_child(datdefprops, "COMPU-METHOD", root_or_cache, ns)
        if compu_method is None:  # AR4
            compu_method = get_child(isignal, "COMPU-METHOD", root_or_cache, ns)
            base_type = get_child(isignal, "BASE-TYPE", root_or_cache, ns)
            encoding = get_child(base_type, "BASE-TYPE-ENCODING", root_or_cache, ns)
            if encoding is not None and encoding.text == "IEEE754":
                is_float = True
        if compu_method is None:
            logger.debug('No Compmethod found!! - try alternate scheme 1.')
            networkrep = get_child(isignal, "NETWORK-REPRESENTATION-PROPS", root_or_cache, ns)
            data_def_props_var = get_child(networkrep, "SW-DATA-DEF-PROPS-VARIANTS", root_or_cache, ns)
            data_def_props_cond = get_child(data_def_props_var, "SW-DATA-DEF-PROPS-CONDITIONAL", root_or_cache, ns)
            if data_def_props_cond is not None:
                try:
                    compu_method = get_child(data_def_props_cond, "COMPU-METHOD", root_or_cache, ns)
                except:
                    logger.debug('No valid compu method found for this - check ARXML file!!')
                    compu_method = None
        #####################################################################################################
        # no found compu-method fuzzy search in systemsignal:
        #####################################################################################################
        if compu_method is None:
            logger.debug('No Compmethod found!! - fuzzy search in syssignal.')
            compu_method = get_child(system_signal, "COMPU-METHOD", root_or_cache, ns)

        # decode compuMethod:
        (values, factor, offset, unit_elem, const) = decode_compu_method(compu_method, root_or_cache, ns, float_factory)

        if signal_min is not None:
            signal_min *= factor
            signal_min += offset
        if signal_max is not None:
            signal_max *= factor
            signal_max += offset

        if base_type is None:
            base_type = get_child(datdefprops, "BASE-TYPE", root_or_cache, ns)
        if base_type is not None:
            type_name = get_element_name(base_type, ns)
            if type_name[0] == 'u':
                is_signed = False  # unsigned
            else:
                is_signed = True  # signed
        else:
            is_signed = True  # signed

        if unit_elem is not None:
            longname = get_child(unit_elem, "LONG-NAME", root_or_cache, ns)
        #####################################################################################################
        # Modification to support obtaining the Signals Unit by DISPLAY-NAME. 07June16
        #####################################################################################################
            display_name = None
            try:
                display_name = get_child(unit_elem, "DISPLAY-NAME", root_or_cache, ns)
            except:
                logger.debug('No Unit Display name found!! - using long name')
            if display_name is not None:
                signal_unit = display_name.text
            else:
                l4 = get_child(longname, "L-4", root_or_cache, ns)
                if l4 is not None:
                    signal_unit = l4.text

        init_list = find_children_by_path(system_signal, "INIT-VALUE/VALUE", root_or_cache, ns)

        if not init_list:
            init_list = find_children_by_path(isignal, "INIT-VALUE/NUMERICAL-VALUE-SPECIFICATION/VALUE", root_or_cache, ns)  # #AR4.2
        if init_list:
            initvalue = init_list[0]
        else:
            initvalue = None

        is_little_endian = False
        if motorola is not None:
            if motorola.text == 'MOST-SIGNIFICANT-BYTE-LAST':
                is_little_endian = True
        else:
            logger.debug('no name byte order for signal' + name.text)

        if name is None:
            logger.debug('no name for signal given')
        if start_bit is None:
            logger.debug('no startBit for signal given')
        if length is None:
            logger.debug('no length for signal given')

        if start_bit is not None:
            new_signal = canmatrix.Signal(
                name.text,
                start_bit=int(start_bit.text),
                size=int(length.text),
                is_little_endian=is_little_endian,
                is_signed=is_signed,
                factor=factor,
                offset=offset,
                unit=signal_unit,
                receivers=receiver,
                multiplex=multiplex_id,
                comment=signal_description,
                is_float=is_float)

            if signal_min is not None:
                new_signal.min = signal_min
            if signal_max is not None:
                new_signal.max = signal_max

            if new_signal.is_little_endian == 0:
                # startbit of motorola coded signals are MSB in arxml
                new_signal.set_startbit(int(start_bit.text), bitNumbering=1)

            # save signal, to determin receiver-ECUs for this signal later
            signal_rxs[system_signal] = new_signal

            if base_type is not None:
                temp = get_child(base_type, "SHORT-NAME", root_or_cache, ns)
                if temp is not None and "boolean" == temp.text:
                    new_signal.add_values(1, "TRUE")
                    new_signal.add_values(0, "FALSE")

            if initvalue is not None and initvalue.text is not None:
                initvalue.text = canmatrix.utils.guess_value(initvalue.text)
                new_signal._initValue = float_factory(initvalue.text)
                new_signal.add_attribute("GenSigStartValue", str(new_signal._initValue))
            else:
                new_signal._initValue = 0

            for key, value in list(values.items()):
                new_signal.add_values(key, value)
            if signal_name is not None:
                new_signal.add_attribute("LongName", signal_name)
            frame.add_signal(new_signal)
1327466
def _read_temp_ifaces(iface, data):
    '''
    
    '''
    try:
        template = JINJA.get_template('debian_eth.jinja')
    except jinja2.exceptions.TemplateNotFound:
        log.error('Could not load template debian_eth.jinja')
        return ''

    ifcfg = template.render({'name': iface, 'data': data})
    # Return as an array so the difflib works
    return [item + '\n' for item in ifcfg.split('\n')]
482241
def operator_si(u):
    """"""
    global _aux
    if np.ndim(u) == 2:
        P = _P2
    elif np.ndim(u) == 3:
        P = _P3
    else:
        raise ValueError("u has an invalid number of dimensions "
                         "(should be 2 or 3)")
    
    if u.shape != _aux.shape[1:]:
        _aux = np.zeros((len(P),) + u.shape)
    
    for _aux_i, P_i in zip(_aux, P):
        _aux_i[:] = binary_erosion(u, P_i)
    
    return _aux.max(0)
224261
def _parse_ethtool_opts(opts, iface):
    '''
    
    '''
    config = {}

    if 'autoneg' in opts:
        if opts['autoneg'] in _CONFIG_TRUE:
            config.update({'autoneg': 'on'})
        elif opts['autoneg'] in _CONFIG_FALSE:
            config.update({'autoneg': 'off'})
        else:
            _raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE)

    if 'duplex' in opts:
        valid = ['full', 'half']
        if opts['duplex'] in valid:
            config.update({'duplex': opts['duplex']})
        else:
            _raise_error_iface(iface, 'duplex', valid)

    if 'speed' in opts:
        valid = ['10', '100', '1000', '10000']
        if six.text_type(opts['speed']) in valid:
            config.update({'speed': opts['speed']})
        else:
            _raise_error_iface(iface, opts['speed'], valid)

    valid = _CONFIG_TRUE + _CONFIG_FALSE
    for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'):
        if option in opts:
            if opts[option] in _CONFIG_TRUE:
                config.update({option: 'on'})
            elif opts[option] in _CONFIG_FALSE:
                config.update({option: 'off'})
            else:
                _raise_error_iface(iface, option, valid)

    return config
800812
def _evaluate_one(caller, svtype, size_range, ensemble, truth, data):
    
    def cnv_matches(name):
        return cnv_to_event(name, data) == svtype
    def is_breakend(name):
        return name.startswith("BND")
    def in_size_range(max_buffer=0):
        def _work(feat):
            minf, maxf = size_range
            buffer = min(max_buffer, int(((maxf + minf) / 2.0) / 10.0))
            size = feat.end - feat.start
            return size >= max([0, minf - buffer]) and size < maxf + buffer
        return _work
    def is_caller_svtype(feat):
        for name in feat.name.split(","):
            if ((name.startswith(svtype) or cnv_matches(name) or is_breakend(name))
                  and (caller == "sv-ensemble" or name.endswith(caller))):
                return True
        return False
    minf, maxf = size_range
    efeats = pybedtools.BedTool(ensemble).filter(in_size_range(0)).filter(is_caller_svtype).saveas().sort().merge()
    tfeats = pybedtools.BedTool(truth).filter(in_size_range(0)).sort().merge().saveas()
    etotal = efeats.count()
    ttotal = tfeats.count()
    match = efeats.intersect(tfeats, u=True).sort().merge().saveas().count()
    return {"sensitivity": _stat_str(match, ttotal),
            "precision": _stat_str(match, etotal)}
22053
def associate_psds_to_multi_ifo_segments(opt, fd_segments, gwstrain, flen,
                                         delta_f, flow, ifos,
                                         dyn_range_factor=1., precision=None):
    
    for ifo in ifos:
        if gwstrain is not None:
            strain = gwstrain[ifo]
        else:
            strain = None

        if fd_segments is not None:
            segments = fd_segments[ifo]
        else:
            segments = None

        associate_psds_to_single_ifo_segments(opt, segments, strain, flen,
                delta_f, flow, ifo, dyn_range_factor=dyn_range_factor,
                precision=precision)
452062
def _guess_iface_name(netif):
    
    with os.popen('%s -l' % conf.prog.ifconfig) as fdesc:
        ifaces = fdesc.readline().strip().split(' ')
    matches = [iface for iface in ifaces if iface.startswith(netif)]
    if len(matches) == 1:
        return matches[0]
    return None
383962
def get_interface(iface):
    '''
    
    '''

    adapters = _parse_interfaces()
    if iface in adapters:
        try:
            if iface == 'source':
                template = JINJA.get_template('debian_source.jinja')
            else:
                template = JINJA.get_template('debian_eth.jinja')
        except jinja2.exceptions.TemplateNotFound:
            log.error('Could not load template debian_eth.jinja')
            return ''

        ifcfg = template.render({'name': iface, 'data': adapters[iface]})

        # ensure lines in list end with newline, so difflib works
        return [item + '\n' for item in ifcfg.split('\n')]
    else:
        return []
630670
def from_cli(cls, opt, strain):
        
        return cls(strain, segment_length=opt.segment_length,
                   segment_start_pad=opt.segment_start_pad,
                   segment_end_pad=opt.segment_end_pad,
                   trigger_start=opt.trig_start_time,
                   trigger_end=opt.trig_end_time,
                   filter_inj_only=opt.filter_inj_only,
                   injection_window=opt.injection_window,
                   allow_zero_padding=opt.allow_zero_padding)
567999
def scan(iface, style=None):
    '''
    
    '''
    if not _valid_iface(iface):
        raise SaltInvocationError(
            'The interface specified is not valid'
        )

    out = __salt__['cmd.run']('iwlist {0} scan'.format(iface))
    if 'Network is down' in out:
        __salt__['cmd.run']('ip link set {0} up'.format(iface))
        out = __salt__['cmd.run']('iwlist {0} scan'.format(iface))
    ret = {}
    tmp = {}
    for line in out.splitlines():
        if not line.strip():
            continue
        if 'Scan completed' in line:
            continue
        if line.strip().startswith('Cell'):
            comps = line.split(' - ')
            line = comps[1]
            if tmp:
                ret[tmp['Address']] = tmp
                tmp = {}
        comps = line.split(':')
        if comps[0].strip() == 'Address':
            # " is a valid character in SSIDs, but iwlist likes to wrap SSIDs in them
            comps[1] = comps[1].lstrip('"').rstrip('"')
        if comps[0].strip() == 'IE':
            if 'IE' not in tmp:
                tmp['IE'] = []
            tmp['IE'].append(':'.join(comps[1:]).strip())
        else:
            tmp[comps[0].strip()] = ':'.join(comps[1:]).strip()

    ret[tmp['Address']] = tmp

    if style == 'list':
        return ret.keys()

    return ret
518512
def from_cli_single_ifo(cls, opt, strain, ifo):
        
        return cls(strain, segment_length=opt.segment_length[ifo],
                   segment_start_pad=opt.segment_start_pad[ifo],
                   segment_end_pad=opt.segment_end_pad[ifo],
                   trigger_start=opt.trig_start_time[ifo],
                   trigger_end=opt.trig_end_time[ifo],
                   filter_inj_only=opt.filter_inj_only,
                   allow_zero_padding=opt.allow_zero_padding)