Guess the correct LLS class for a given payload
335851
def _LLSGuessPayloadClass(p, **kargs):
    

    cls = conf.raw_layer
    if len(p) >= 3:
        typ = struct.unpack("!H", p[0:2])[0]
        clsname = _OSPF_LLSclasses.get(typ, "LLS_Generic_TLV")
        cls = globals()[clsname]
    return cls(p, **kargs)
322772
def get_permissible_wcs(classname, f):
    """
    # these are the problematic sectors
    classes = ['cu', 'db', 'sb', 'sd', 'mue', 'mutau', 'taue', 'dF0']
    if classname not in classes or f == 5:
        # for 5-flavour WET, nothing to do.
        # Neither for other classes (I, II, ...) because they exist either all
        # or not at all in WET-3 and WET-4 (they have specific flavours).
        return 'all'
    if f not in [3, 4]:
        raise ValueError("f must be 3, 4, or 5.")
    if classname == 'dF0':
        sector = 'dF=0'
    else:
        sector = classname
    perm_keys = wcxf.Basis['WET-{}'.format(f), 'JMS'].sectors[sector].keys()
    all_keys = coeffs[sector]
    return [i for i, c in enumerate(all_keys) if c in perm_keys]
31281
def get_suitable_vis_classes(obj):
    """"""

    ret = []
    for class_ in classes_vis():
        if isinstance(obj, class_.input_classes):
            ret.append(class_)
    return ret
749102
def _match_class_pos(self):
        """"""
        # TODO: add notfitted warnings
        if self.kernel.classes_.shape[0] != 2:
            raise ValueError("Number of classes is {}, expected 2.".format(
                self.kernel.classes_.shape[0]))

        # # get the position of match probabilities
        # classes = list(self.kernel.classes_)
        # return classes.index(1)

        return 1
616888
def decode_payload_as(self,cls):
        """"""
        s = bytes(self.payload)
        self.payload = cls(s, _internal=1, _underlayer=self)
        pp = self
        while pp.underlayer is not None:
            pp = pp.underlayer
        self.payload.dissection_done(pp)
191754
def str_to_class(s):
    """"""
    lst = s.split(".")
    klass = lst[-1]
    mod_list = lst[:-1]
    module = ".".join(mod_list)
    try:
        mod = __import__(module)
        if hasattr(mod, klass):
            return getattr(mod, klass)
        else:
            return None
    except ImportError:
        return None
101216
def ls(obj=None):
    """"""
    if obj is None:
        
        import builtins
        all = builtins.__dict__.copy()
        all.update(globals())
        objlst = sorted(conf.layers, key=lambda x:x.__name__)
        for o in objlst:
            print("%-10s : %s" %(o.__name__,o.name))
    else:
        if isinstance(obj, type) and issubclass(obj, Packet):
            for f in obj.fields_desc:
                print("%-10s : %-20s = (%s)" % (f.name, f.__class__.__name__,  repr(f.default)))
        elif isinstance(obj, Packet):
            for f in obj.fields_desc:
                print("%-10s : %-20s = %-15s (%s)" % (f.name, f.__class__.__name__, repr(getattr(obj,f.name)), repr(f.default)))
            if not isinstance(obj.payload, NoPayload):
                print("--")
                ls(obj.payload)
                

        else:
            print("Not a packet class. Type 'ls()' to list packet classes.")
67497
def __findout_decl_type(match_class, **keywds):
        """"""
        if 'decl_type' in keywds:
            return keywds['decl_type']

        matcher_args = keywds.copy()
        del matcher_args['function']
        del matcher_args['recursive']
        if 'allow_empty' in matcher_args:
            del matcher_args['allow_empty']

        decl_matcher = match_class(**matcher_args)
        if decl_matcher.decl_type:
            return decl_matcher.decl_type
        return None
31264
def guess_cls(self):
        """"""

        # Get the data link type
        try:
            ret = fcntl.ioctl(self.ins, BIOCGDLT, struct.pack('I', 0))
            ret = struct.unpack('I', ret)[0]
        except IOError:
            cls = conf.default_l2
            warning("BIOCGDLT failed: unable to guess type. Using %s !",
                    cls.name)
            return cls

        # Retrieve the corresponding class
        try:
            return conf.l2types[ret]
        except KeyError:
            cls = conf.default_l2
            warning("Unable to guess type (type %i). Using %s", ret, cls.name)
175760
def lcsr(s1, s2):
    '''
    '''
    if s1 == s2:
        return 1.0
    return llcs(s1, s2) / max(1, len(s1), len(s2))
887268
function checkClass(i) {
  let l;

  if (i >= tokensLength) return 0;

  if (tokens[i].class_l) return tokens[i].class_l;

  if (tokens[i++].type === TokenType.FullStop) {
    if (l = checkInterpolatedVariable(i)) tokens[i].class_child = 1;
    else if (l = checkIdent(i)) tokens[i].class_child = 2;
    else return 0;

    tokens[i].class_l = l + 1;
    return l + 1;
  }

  return 0;
}
1152386
def calculate_payload_hash(payload, algorithm, content_type):
    """"""
    p_hash = hashlib.new(algorithm)

    parts = []
    parts.append('hawk.' + str(HAWK_VER) + '.payload\n')
    parts.append(parse_content_type(content_type) + '\n')
    parts.append(payload or '')
    parts.append('\n')

    for i, p in enumerate(parts):
        # Make sure we are about to hash binary strings.
        if not isinstance(p, six.binary_type):
            p = p.encode('utf8')
        p_hash.update(p)
        parts[i] = p

    log.debug('calculating payload hash from:\n{parts}'
              .format(parts=pprint.pformat(parts)))

    return b64encode(p_hash.digest())
199550
def _class(self):
        """"""
        try:
            self._project_name()
        except ValueError:
            return MalformedReq
        if self._is_satisfied():
            return SatisfiedReq
        if not self._expected_hashes():
            return MissingReq
        if self._actual_hash() not in self._expected_hashes():
            return MismatchedReq
        return InstallableReq
867284
def find_class(self):
        """"""
        classes = {1: InstructionGotoTable, 2: InstructionWriteMetadata,
                   3: InstructionWriteAction, 4: InstructionApplyAction,
                   5: InstructionClearAction, 6: InstructionMeter}
        return classes.get(self.value, None)
689386
def _get_xsitype(pyclass):
    '''
    '''
    if hasattr(pyclass,'type') and type(pyclass.type) in _seqtypes:
        return pyclass.type
    elif hasattr(pyclass,'type') and hasattr(pyclass, 'schema'):
        return (pyclass.schema, pyclass.type)

    return (None,None)
709215
def _getSuitableClasses(self, data):
        """"""
        classes = None
        if data[EI.CLASS] == ELFCLASS.BITS_32:
            if data[EI.DATA] == ELFDATA.LSB:
                classes = LSB_32
            elif data[EI.DATA] == ELFDATA.MSB:
                classes = MSB_32

        elif data[EI.CLASS] == ELFCLASS.BITS_64:
            if data[EI.DATA] == ELFDATA.LSB:
                classes = LSB_64
            elif data[EI.DATA] == ELFDATA.MSB:
                classes = MSB_64

        return classes
1127192
def parse_as_header(class_, f):
        
        (version, previous_block_hash, merkle_root, timestamp,
            difficulty, nonce) = parse_struct("L##LLL", f)
        return class_(version, previous_block_hash, merkle_root, timestamp, difficulty, nonce)