When SQLAlchemy gets the string representation from a ReprObjType
        column, it converts it to the python equivalent via exec.
324717
def process_result_value(self, value, dialect):
        
        if value is not None:
            cmd = "value = {}".format(value)
            exec(cmd)
        return value
1147220
def get_datatype(cls,
                     db: DATABASE_SUPPORTER_FWD_REF,
                     table: str,
                     column: str) -> str:
        """"""
        raise RuntimeError(_MSG_NO_FLAVOUR)
128296
def db_exec_literal(self, sql: str) -> int:
        """"""
        self.ensure_db_open()
        cursor = self.db.cursor()
        debug_sql(sql)
        try:
            cursor.execute(sql)
            return cursor.rowcount
        except:  # nopep8
            log.exception("db_exec_literal: SQL was: " + sql)
            raise
460327
def rows_to_columns(data, schema=None):
    
    if not schema:
        schema = SchemaTree()
    all_schema = schema
    all_leaves = schema.leaves
    values = {full_name: [] for full_name in all_leaves}
    reps = {full_name: [] for full_name in all_leaves}
    defs = {full_name: [] for full_name in all_leaves}

    def _none_to_column(schema, path, rep_level, def_level):
        for full_path in all_schema.leaves:
            if startswith_field(full_path, path):
                reps[full_path].append(rep_level)
                defs[full_path].append(def_level)

    def _value_to_column(value, schema, path, counters, def_level):
        ptype = type(value)
        ntype, dtype, ltype, jtype, itype, byte_width = python_type_to_all_types[ptype]

        if jtype is NESTED:
            if schema.element.repetition_type != REPEATED:
                Log.error("Expecting {{path|quote}} to be repeated", path=path)

            new_path = path
            if not value:
                _none_to_column(schema, new_path, get_rep_level(counters), def_level)
            else:
                try:
                    new_schema = schema.more.get('.')

                    if not new_schema:
                        if schema.locked:
                            # DEFAULT TO REQUIRED ENTRIES
                            new_schema = schema
                            schema.element.repetition_type = REQUIRED
                        else:
                            new_path = path
                            new_value = value[0]
                            ptype = type(new_value)
                            new_schema = schema.add(
                                new_path,
                                OPTIONAL,
                                ptype
                            )
                            if new_value is None or python_type_to_json_type[ptype] in PRIMITIVE:
                                values[new_path] = []
                                reps[new_path] = [0] * counters[0]
                                defs[new_path] = [0] * counters[0]
                    for k, new_value in enumerate(value):
                        new_counters = counters + (k,)
                        _value_to_column(new_value, new_schema, new_path, new_counters, def_level+1)
                finally:
                    schema.element.repetition_type = REPEATED
        elif jtype is OBJECT:
            if value is None:
                if schema.element.repetition_type == REQUIRED:
                    Log.error("{{path|quote}} is required", path=path)
                _none_to_column(schema, path, get_rep_level(counters), def_level)
            else:
                if schema.element.repetition_type == REPEATED:
                    Log.error("Expecting {{path|quote}} to be repeated", path=path)

                if schema.element.repetition_type == REQUIRED:
                    new_def_level = def_level
                else:
                    counters = counters + (0,)
                    new_def_level = def_level+1

                for name, sub_schema in schema.more.items():
                    new_path = concat_field(path, name)
                    new_value = value.get(name, None)
                    _value_to_column(new_value, sub_schema, new_path, counters, new_def_level)

                for name in set(value.keys()) - set(schema.more.keys()):
                    if schema.locked:
                        Log.error("{{path}} is not allowed in the schema", path=path)
                    new_path = concat_field(path, name)
                    new_value = value.get(name, None)
                    ptype = type(new_value)
                    sub_schema = schema.add(
                        new_path,
                        REPEATED if isinstance(new_value, list) else OPTIONAL,
                        ptype
                    )
                    if python_type_to_json_type[ptype] in PRIMITIVE:
                        values[new_path] = []
                        reps[new_path] = [0] * counters[0]
                        defs[new_path] = [0] * counters[0]
                    _value_to_column(new_value, sub_schema, new_path, counters, new_def_level)
        else:
            if jtype is STRING:
                value = value.encode('utf8')
            merge_schema(schema, path, value)
            values[path].append(value)
            if schema.element.repetition_type == REQUIRED:
                reps[path].append(get_rep_level(counters))
                defs[path].append(def_level)
            else:
                reps[path].append(get_rep_level(counters))
                defs[path].append(def_level + 1)

    for rownum, new_value in enumerate(data):
        try:
            _value_to_column(new_value, schema, '.', (rownum,), 0)
        except Exception as e:
            Log.error("can not encode {{row|json}}", row=new_value, cause=e)

    return Table(values, reps, defs, len(data), schema)
1344379
def _ex_type_str(exobj):
    """"""
    regexp = re.compile(r"<(?:\bclass\b|\btype\b)\s+'?([\w|\.]+)'?>")
    exc_type = str(exobj)
    if regexp.match(exc_type):
        exc_type = regexp.match(exc_type).groups()[0]
        exc_type = exc_type[11:] if exc_type.startswith("exceptions.") else exc_type
    if "." in exc_type:
        exc_type = exc_type.split(".")[-1]
    return exc_type
1221869
def tostring(element, *args, **kwargs):
    
    global modules

    _bootstrap()
    t = _get_type(element)

    etree = modules.get(t, None)

    if not etree:
        raise RuntimeError('Unable to find the etree implementation related '
            'to %r (type %r)' % (element, t))

    return etree.tostring(element, *args, **kwargs)
1188469
def parse_type_str(expected_base=None, with_arrlist=False):
    
    def decorator(old_from_type_str):
        @functools.wraps(old_from_type_str)
        def new_from_type_str(cls, type_str, registry):
            normalized_type_str = normalize(type_str)
            abi_type = parse(normalized_type_str)

            type_str_repr = repr(type_str)
            if type_str != normalized_type_str:
                type_str_repr = '{} (normalized to {})'.format(
                    type_str_repr,
                    repr(normalized_type_str),
                )

            if expected_base is not None:
                if not isinstance(abi_type, BasicType):
                    raise ValueError(
                        'Cannot create {} for non-basic type {}'.format(
                            cls.__name__,
                            type_str_repr,
                        )
                    )
                if abi_type.base != expected_base:
                    raise ValueError(
                        'Cannot create {} for type {}: expected type with '
                        "base '{}'".format(
                            cls.__name__,
                            type_str_repr,
                            expected_base,
                        )
                    )

            if not with_arrlist and abi_type.arrlist is not None:
                raise ValueError(
                    'Cannot create {} for type {}: expected type with '
                    'no array dimension list'.format(
                        cls.__name__,
                        type_str_repr,
                    )
                )
            if with_arrlist and abi_type.arrlist is None:
                raise ValueError(
                    'Cannot create {} for type {}: expected type with '
                    'array dimension list'.format(
                        cls.__name__,
                        type_str_repr,
                    )
                )

            # Perform general validation of default solidity types
            abi_type.validate()

            return old_from_type_str(cls, abi_type, registry)

        return classmethod(new_from_type_str)

    return decorator
693800
def value_to_db(self, value):
        
        assert isinstance(value, six.integer_types)
        return str(value).encode("utf_8")
594412
def str_to_python_object(input_str):
    
    if not input_str:
        return None
    if six.PY3 and isinstance(input_str, six.binary_type):
        input_str = to_str(input_str)
    if not isinstance(input_str, six.string_types):
        # gosh, we didn't get a string, we can't convert anything but strings
        # we're going to assume that what we got is actually what was wanted
        # as the output
        return input_str
    input_str = str_quote_stripper(input_str)
    if '.' not in input_str and input_str in known_mapping_str_to_type:
        return known_mapping_str_to_type[input_str]
    parts = [x.strip() for x in input_str.split('.') if x.strip()]
    try:
        try:
            # first try as a complete module
            package = __import__(input_str)
        except ImportError:
            # it must be a class from a module
            if len(parts) == 1:
                # since it has only one part, it must be a class from __main__
                parts = ('__main__', input_str)
            package = __import__('.'.join(parts[:-1]), globals(), locals(), [])
        obj = package
        for name in parts[1:]:
            obj = getattr(obj, name)
        return obj
    except AttributeError as x:
        raise CannotConvertError("%s cannot be found" % input_str)
    except ImportError as x:
        raise CannotConvertError(str(x))
740397
def transform(self, value, **kwargs):
        
        if value is None:
            return None

        objid = id(value)
        if objid in self.context:
            return '<...>'
        self.context.add(objid)

        try:
            for serializer in self.serializers:
                try:
                    if serializer.can(value):
                        return serializer.serialize(value, **kwargs)
                except Exception as e:
                    logger.exception(e)
                    return text_type(type(value))

            # if all else fails, lets use the repr of the object
            try:
                return repr(value)
            except Exception as e:
                logger.exception(e)
                # It's common case that a model's __unicode__ definition
                # may try to query the database which if it was not
                # cleaned up correctly, would hit a transaction aborted
                # exception
                return text_type(type(value))
        finally:
            self.context.remove(objid)
836335
def _encode_dbref(name, value, check_keys, opts):
    """"""
    buf = bytearray(b"\x03" + name + b"\x00\x00\x00\x00")
    begin = len(buf) - 4

    buf += _name_value_to_bson(b"$ref\x00",
                               value.collection, check_keys, opts)
    buf += _name_value_to_bson(b"$id\x00",
                               value.id, check_keys, opts)
    if value.database is not None:
        buf += _name_value_to_bson(
            b"$db\x00", value.database, check_keys, opts)
    for key, val in iteritems(value._DBRef__kwargs):
        buf += _element_to_bson(key, val, check_keys, opts)

    buf += b"\x00"
    buf[begin:begin + 4] = _PACK_INT(len(buf) - begin)
    return bytes(buf)
533918
def parse_column_key_value(table_schema, setting_string):
        
        if ':' in setting_string:
            # splits <column>:<key>=<value> into <column> and <key>=<value>
            column, value = setting_string.split(':', 1)
        elif '=' in setting_string:
            # splits <column>=<value> into <column> and <value>
            column, value = setting_string.split('=', 1)
        else:
            # stores <column> and <value>=None
            column = setting_string
            value = None

        if value is not None:
            type_ = table_schema.columns[column].type
            value = datum_from_string(type_, value)

        return column, value
956357
def restore_type(self, type):
        

        # All dialects
        mapping = {
            ARRAY: 'array',
            sa.Boolean: 'boolean',
            sa.Date: 'date',
            sa.DateTime: 'datetime',
            sa.Float: 'number',
            sa.Integer: 'integer',
            JSONB: 'object',
            JSON: 'object',
            sa.Numeric: 'number',
            sa.Text: 'string',
            sa.Time: 'time',
            sa.VARCHAR: 'string',
            UUID: 'string',
        }

        # Get field type
        field_type = None
        for key, value in mapping.items():
            if isinstance(type, key):
                field_type = value

        # Not supported
        if field_type is None:
            message = 'Type "%s" is not supported'
            raise tableschema.exceptions.StorageError(message % type)

        return field_type
1179268
private String pythonify(String n) {
    if (n == null || name.toLowerCase().contains("confusion")) return n;
    StringBuilder sb = new StringBuilder();
    String [] modified = n.split("[\\s_]+");
    for (int i=0; i<modified.length; ++i) {
      if (i!=0) sb.append("_");
      String s = modified[i];
//      if (!s.matches("^[A-Z]{2,3}$")) {
        sb.append(s.toLowerCase()); //everything goes lowercase
//      } else {
//        sb.append(s);
//      }
    }
    String newString = sb.toString().replaceAll("[^\\w]", "");
//    if (!newString.equals(name)) {
//      Log.warn("Turning column description into field name: " + name + " --> " + newString);
//    }
    return newString;
  }
287852
def convert_numpy_type(cls, dtype):
        

        m = {
            'int64': cls.DATATYPE_INTEGER64,
            'float64': cls.DATATYPE_FLOAT,
            'object': cls.DATATYPE_TEXT  # Hack. Pandas makes strings into object.
        }

        t = m.get(dtype.name, None)

        if not t:
            raise TypeError(
                "Failed to convert numpy type: '{}' ".format(
                    dtype.name))

        return t
1056445
def serialize(expr):
    """"""

    result = None

    if isinstance(expr, string_types):
        result = expr

    elif expr is not None:
        result = '=py:{0}'.format(expr)

    return result
182052
def reverse_transform(self, column):
        
        self.check_data_type()

        return pd.DataFrame({self.col_name: np.log(column[self.col_name])})