Convert list/tuple of list/tuples to bytecode
    _names_ contains a list of name objects
497355
def list2bytecode(l, opc, varnames, consts):
    
    bc = []
    for i, opcodes in enumerate(l):
        opname = opcodes[0]
        operands = opcodes[1:]
        if opname not in opc.opname:
            raise TypeError(
                "error at item %d [%s, %s], opcode not valid" %
                (i, opname, operands))
        opcode = opc.opmap[opname]
        bc.append(opcode)
        print(opname, operands)
        gen = (j for j in operands if operands)
        for j in gen:
            k = (consts if opcode in opc.CONST_OPS else varnames).index(j)
            if k == -1:
                raise TypeError(
                    "operand %s [%s, %s], not found in names" %
                    (i, opname, operands))
            else:
                bc += num2code(k)
                pass
            pass
        pass
    if opc.python_version < 3.0:
        return reduce(lambda a, b: a + chr(b), bc, '')
    else:
        if PYTHON3:
            return bytes(bc)
        else:
            return bytes(bytearray(bc))
400376
def _serialize_iterable(obj):
    
    if isinstance(obj, (tuple, set)):
        # make a tuple assignable by casting it to list
        obj = list(obj)
    for item in obj:
        obj[obj.index(item)] = serialize_obj(item)
    return obj
132387
def _named_tuple_converter(tuple_type):
    # type: (Type[Tuple]) -> _AggregateConverter
    """"""
    def _from_dict(dict_value):
        if dict_value:
            return tuple_type(**dict_value)

        # Cannot construct a namedtuple value from an empty dictionary
        return None

    def _to_dict(value):
        if value:
            return value._asdict()

        return {}

    converter = _AggregateConverter(from_dict=_from_dict, to_dict=_to_dict)
    return converter
130080
def coerce_to_list(val):
    
    if val:
        if not isinstance(val, (list, tuple)):
            val = [val]
    else:
        val = []
    return val
406217
def maybe_cast_list(value, types):
    
    if not isinstance(value, list):
        return value

    if type(types) not in (list, tuple):
        types = (types,)

    for list_type in types:
        if issubclass(list_type, list):
            try:
                return list_type(value)
            except (TypeError, ValueError):
                pass
    return value
1336691
def named_objs(objlist, namesdict=None):
    
    objs = OrderedDict()

    if namesdict is not None:
        objtoname = {hashable(v): k for k, v in namesdict.items()}

    for obj in objlist:
        if namesdict is not None and hashable(obj) in objtoname:
            k = objtoname[hashable(obj)]
        elif hasattr(obj, "name"):
            k = obj.name
        elif hasattr(obj, '__name__'):
            k = obj.__name__
        else:
            k = as_unicode(obj)
        objs[k] = obj
    return objs
736678
def tuple(data, field_name):
    
    if isinstance(data, Cube):
        Log.error("not supported yet")

    if isinstance(data, FlatList):
        Log.error("not supported yet")

    if is_data(field_name) and "value" in field_name:
        # SIMPLIFY {"value":value} AS STRING
        field_name = field_name["value"]

    # SIMPLE PYTHON ITERABLE ASSUMED
    if is_text(field_name):
        if len(split_field(field_name)) == 1:
            return [(d[field_name],) for d in data]
        else:
            path = split_field(field_name)
            output = []
            flat_list._tuple1(data, path, 0, output)
            return output
    elif is_list(field_name):
        paths = [_select_a_field(f) for f in field_name]
        output = FlatList()
        _tuple((), unwrap(data), paths, 0, output)
        return output
    else:
        paths = [_select_a_field(field_name)]
        output = FlatList()
        _tuple((), data, paths, 0, output)
        return output
1267356
def toList(self):
        
        if self.getNumCols() > 1:
            return [
                tuple(self.getRowByIndex(i))
                for i in range(self.getNumRows())
            ]
        else:
            return [
                self.getRowByIndex(i)[0]
                for i in range(self.getNumRows())
            ]
813654
def as_named_tuple(self):
        
        keys = list(self.entities.keys())
        replaced = []
        for i, k in enumerate(keys):
            if iskeyword(k):
                replaced.append(k)
                keys[i] = '%s_' % k
        if replaced:
            safe = ['%s_' % k for k in replaced]
            warnings.warn("Entity names cannot be reserved keywords when "
                          "representing a File as a namedtuple. Replacing "
                          "entities %s with safe versions %s." % (keys, safe))
        entities = dict(zip(keys, self.entities.values()))
        _File = namedtuple('File', 'filename ' + ' '.join(entities.keys()))
        return _File(filename=self.path, **entities)
718555
def _hack_namedtuple(cls):
    
    name = cls.__name__
    fields = cls._fields

    def __reduce__(self):
        return (_restore, (name, fields, tuple(self)))
    cls.__reduce__ = __reduce__
    cls._is_namedtuple_ = True
    return cls
708593
def extern_store_tuple(self, context_handle, vals_ptr, vals_len):
    """"""
    c = self._ffi.from_handle(context_handle)
    return c.to_value(tuple(c.from_value(val[0]) for val in self._ffi.unpack(vals_ptr, vals_len)))
1051333
private Name getNameObject(List<? extends Name> list, double probability) {
        int index = Collections.binarySearch(list, new Name(null, probability), locateNameByCumulativeProbability);
        if (index >= 0) {
            return list.get(index);
        } else if (-index > list.size()) {
            throw new RuntimeException("Invalid probability provided - (" + probability +
                    "). Max allowed for this list is " + getMax(list));
        } else {
            return list.get((-index) - 1);
        }
    }
953353
def _namedtupleload(l: Loader, value: Dict[str, Any], type_) -> Tuple:
    
    if not hasattr(type_, '__dataclass_fields__'):
        fields = set(type_._fields)
        optional_fields = set(getattr(type_, '_field_defaults', {}).keys())
        type_hints = type_._field_types
    else:
        #dataclass
        import dataclasses
        fields = set(type_.__dataclass_fields__.keys())
        optional_fields = {k for k,v in type_.__dataclass_fields__.items() if not (isinstance(getattr(v, 'default', dataclasses._MISSING_TYPE()), dataclasses._MISSING_TYPE) and isinstance(getattr(v, 'default_factory', dataclasses._MISSING_TYPE()), dataclasses._MISSING_TYPE))}
        type_hints = {k: v.type for k,v in type_.__dataclass_fields__.items()}

        #Name mangling

        # Prepare the list of the needed name changes
        transforms = []  # type: List[Tuple[str, str]]
        for field in fields:
            if type_.__dataclass_fields__[field].metadata:
                name = type_.__dataclass_fields__[field].metadata.get('name')
                if name:
                    transforms.append((field, name))
        # Do the needed name changes
        if transforms:
            value = value.copy()
            for pyname, dataname in transforms:
                if dataname in value:
                    tmp = value[dataname]
                    del value[dataname]
                    value[pyname] = tmp

    necessary_fields = fields.difference(optional_fields)
    try:
        vfields = set(value.keys())
    except AttributeError as e:
        raise TypedloadAttributeError(str(e), value=value, type_=type_)

    if necessary_fields.intersection(vfields) != necessary_fields:
        raise TypedloadValueError(
            'Value does not contain fields: %s which are necessary for type %s' % (
                necessary_fields.difference(vfields),
                type_
            ),
            value=value,
            type_=type_,
        )

    fieldsdiff = vfields.difference(fields)
    if l.failonextra and len(fieldsdiff):
        extra = ', '.join(fieldsdiff)
        raise TypedloadValueError(
            'Dictionary has unrecognized fields: %s and cannot be loaded into %s' % (extra, type_),
            value=value,
            type_=type_,
        )

    params = {}
    for k, v in value.items():
        if k not in fields:
            continue
        params[k] = l.load(
            v,
            type_hints[k],
            annotation=Annotation(AnnotationType.FIELD, k),
        )
    return type_(**params)
319138
def args_as_tuple(self):
        """"""
        if "," in self.arguments["header-names"]:
            result = tuple(tools.to_list(self.arguments["header-names"]))
        else:
            result = (self.arguments["header-names"].strip('"'),)
        result = result + (self.arguments["match-type"],)
        if "," in self.arguments["key-list"]:
            result = result + tuple(
                tools.to_list(self.arguments["key-list"], unquote=False))
        else:
            result = result + (self.arguments["key-list"].strip('"'),)
        return result
355100
def namedlist(objname, fieldnames):
    ''
    class NamedListTemplate(list):
        __name__ = objname
        _fields = fieldnames

        def __init__(self, L=None, **kwargs):
            if L is None:
                L = [None]*len(fieldnames)
            super().__init__(L)
            for k, v in kwargs.items():
                setattr(self, k, v)

        @classmethod
        def length(cls):
            return len(cls._fields)

    for i, attrname in enumerate(fieldnames):
        # create property getter/setter for each field
        setattr(NamedListTemplate, attrname, property(operator.itemgetter(i), itemsetter(i)))

    return NamedListTemplate
1279375
def concat_namedtuples(*tup, **kwargs):
    '''
    
    '''
    name = kwargs['name'] if 'name' in kwargs else None

    # filter out empty elements
    filtered = [i for i in filter(None, tup)]
    if filtered:
        if len(filtered) == 1:
            return filtered[0]
        else:
            fields = chain(*(t._fields for t in filtered))
            values = chain(*(t for t in filtered))
            if not name:
                name = 'SDMXNamedTuple'
            ConcatType = namedtuple_factory(name, fields)
            return ConcatType(*values)
    else:
        return ()
467113
def as_list(self):
        
        self._sanitise()
        l = []
        for name in self.names:
            l.append(getattr(self, name))
        return l