If auto_convert, then all values will be converted to string format, otherwise
    remain the orignal value
764735
def make_view_field(field, obj=None, types_convert_map=None, fields_convert_map=None, 
    value=__default_value__, auto_convert=True):
    
    from uliweb.utils.textconvert import text2html
    from uliweb.core.html import Tag
    
    old_value = value

    types_convert_map = types_convert_map or {}
    fields_convert_map = fields_convert_map or {}
    default_convert_map = {orm.TextProperty:lambda v,o:text2html(v)}
    
    if isinstance(field, dict):
        if 'prop' in field and field.get('prop'):
            prop = field['prop']
        else:
            prop = field
        name = field.get('name')
    else:
        prop = field
        name = prop.property_name
        
    #not real Property instance, then return itself, so if should return
    #just like {'label':xxx, 'value':xxx, 'display':xxx}
    if not isinstance(prop, orm.Property):  
        if old_value is __default_value__:
            value = prop.get('value', '')
        display = prop.get('display', value)
        label = prop.get('label', '') or prop.get('verbose_name', '')
        convert = prop.get('convert', None)
    else:
        if old_value is __default_value__:
            if isinstance(obj, Model):
                value = prop.get_value_for_datastore(obj)
                if value is Lazy:
                    getattr(obj, prop.property_name)
                    value = prop.get_value_for_datastore(obj)
            else:
                value = obj[name]
        if auto_convert or prop.choices:
            display = prop.get_display_value(value)
        else:
            display = value
        
        if isinstance(field, dict):
            initial = field.get('verbose_name', None)
        else:
            initial = ''
        label = initial or prop.verbose_name or name
        
    if name in fields_convert_map:
        convert = fields_convert_map.get(name, None)
    else:
        if isinstance(prop, orm.Property):
            convert = types_convert_map.get(prop.__class__, None)
            if not convert:
                convert = default_convert_map.get(prop.__class__, None)
    
    convert_result = None
    if convert:
        convert_result = convert(value, obj)
    
    if convert_result is None:
        if value is not None:
            if isinstance(prop, orm.ManyToMany):
                s = []
                #support value parameter, the old value is already stored in "old_value" variable
                if old_value is not __default_value__:
                    if prop.reference_fieldname == 'id':
                        query = []
                        for _id in old_value:
                            _v = functions.get_cached_object(prop.reference_class, _id)
                            query.append(_v)
                    else:
                        query = prop.reference_class.filter(prop.reference_class.c[prop.reversed_fieldname].in_(old_value))
                else:
                    if prop.reference_fieldname == 'id':
                        query = []
                        _ids = prop.get_value_for_datastore(obj, cached=True)
                        for _id in _ids:
                            _v = functions.get_cached_object(prop.reference_class, _id)
                            if not _v:
                                log.debug("Can't find object %s:%d" % (prop.reference_class.__name__, _id))
                                _v = _id
                            query.append(_v)
                    else:
                        query = getattr(obj, prop.property_name).all()
                        
                for x in query:
                    if isinstance(x, orm.Model):
                        s.append(get_obj_url(x))
                    else:
                        s.append(str(x))
                display = ' '.join(s)
            elif isinstance(prop, orm.ReferenceProperty) or isinstance(prop, orm.OneToOne):
                try:
                    if old_value is not __default_value__:
                        d = prop.reference_class.c[prop.reference_fieldname]
                        if prop.reference_fieldname == 'id':
                            v = functions.get_cached_object(prop.reference_class, old_value)
                        else:
                            v = prop.reference_class.get(d==old_value)
                    if not isinstance(obj, Model):
                        d = prop.reference_class.c[prop.reference_fieldname]
                        if prop.reference_fieldname == 'id':
                            v = functions.get_cached_object(prop.reference_class, value)
                        else:
                            v = prop.reference_class.get(d==value)
                    else:
                        if prop.reference_fieldname == 'id':
                            v = functions.get_cached_object(prop.reference_class, obj.get_datastore_value(prop.property_name))
                        else:
                            v = functions.get_cached_object(prop.reference_class,
                                    condition=prop.reference_class.c[prop.reference_fieldname]==obj.get_datastore_value(prop.property_name))
                except orm.Error:
                    display = prop.get_datastore_value(obj) or ''
                    v = None
                if isinstance(v, Model):
                    display = get_obj_url(v)
                else:
                    display = str(v if v is not None else '')
            elif isinstance(prop, orm.FileProperty):
                url = functions.get_href(value)
                if url:
                    display = str(Tag('a', value, href=url))
                else:
                    display = ''
#            if isinstance(prop, orm.Property) and prop.choices is not None:
#                display = prop.get_display_value(value)
            if prop.__class__ is orm.TextProperty:
                display = text2html(value)
       
    else:
        display = convert_result
        
    if isinstance(display, unicode):
        display = display.encode('utf-8')
    if display is None:
        display = ''
        
    return Storage({'label':label, 'value':value, 'display':display, 'name':name})
745899
def as_strings(self):
        """"""
        if self.value == '' or self.value is None:
            return '{0};\n'.format(self.name)
        if '"' not in self.value and (';' in self.value or '#' in self.value):
            return '{0} "{1}";\n'.format(self.name, self.value)
        return '{0} {1};\n'.format(self.name, self.value)
644130
def as_string(value):
    
    if six.PY2:
        buffer_types = buffer, memoryview  # noqa: F821
    else:
        buffer_types = memoryview

    if value is None:
        return u''
    elif isinstance(value, buffer_types):
        return bytes(value).decode('utf8', 'ignore')
    elif isinstance(value, bytes):
        return value.decode('utf8', 'ignore')
    else:
        return six.text_type(value)
1097318
def safe_trim(qty_as_string):
    '''
    
    '''
    qty_formatted = qty_as_string
    if '.' in qty_as_string:
        # only affect numbers with decimals
        while True:
            if qty_formatted[-1] == '0' and qty_formatted[-2] != '.':
                qty_formatted = qty_formatted[:-1]
            else:
                break

    return qty_formatted
19960
def value_to_db(self, value):
        
        if isinstance(value, six.string_types):
            value = value.encode("utf_8")
        return value
790433
def ConvertToWireFormat(self, value):
    """"""
    data = value.SerializeToString()
    return (self.encoded_tag, VarintEncode(len(data)), data)
78370
def value_convert(self, value, value_type):
        
        CONVERSION_OPTIONS = {
            "str": str,
            "int": int,
            "float": float,
            # Treat booleans specially
            "bool": (lambda val: val.lower() in ("true", "1")),
            # Auto-guess the type
            "auto": self.make_value,
        }

        try:
            return CONVERSION_OPTIONS[value_type](value)
        except (TypeError, ValueError):
            self.notify_user("Bad type conversion")
            return None
526957
function strToBool(input, defaultValue = false) {
  const value = String(input)
    .trim()
    .toLowerCase()
  if (['1', 'true', 'on', 'yes'].includes(value)) return true
  if (['0', 'false', 'off', 'no'].includes(value)) return false
  return defaultValue
}
1166874
private static function _numberToString($price, $numbersScript, $sex, $forms, $saveFloat) {
        $result             = array();
        $tmp                = explode('.', str_replace(',','.', $price));

        $integerPart        = number_format($tmp[0], 0, '','-');
        if ($integerPart == 0) {
            $result[] = $numbersScript['0'];
        }

        $fractionalPart     = isset($tmp[1]) ? substr(str_pad($tmp[1], 2, '0', STR_PAD_RIGHT), 0, 2) : '00';
        $segments           = explode('-', $integerPart);
        $offset             = sizeof($segments);

        if ((int)$integerPart == 0) {
            $result[] = $numbersScript['0'];
            $result[] = self::_getMorphed(0, $forms[1][0], $forms[1][1], $forms[1][2]);
        } else {
            foreach ($segments as $segment) {
                $currentSex = (int) $forms[$offset][3];
                $ri         = (int) $segment;
                if ($ri== 0 && $offset>1) {
                    $offset--;
                    continue;
                }

                $ri         = str_pad($ri, 3, '0', STR_PAD_LEFT);

                $r1         = (int)substr($ri, 0, 1);
                $r2         = (int)substr($ri, 1, 1);
                $r3         = (int)substr($ri, 2, 1);
                $r22        = (int)$r2.$r3;

                if ($ri > 99) {
                    $result[] = $numbersScript[100][$r1];
                }
                if ($r22 > 20) {
                    $result[] = $numbersScript[10][$r2];
                    $result[] = $sex[$currentSex][$r3];
                } elseif ($r22 > 9) {
                    $result[] = $numbersScript[11][$r22-9];
                } elseif ($r22 > 0) {
                    $result[] = $sex[$currentSex][$r3];
                }

                $result[]   = self::_getMorphed($ri, $forms[$offset][0], $forms[$offset][1], $forms[$offset][2]);
                $offset--;
            }
        }

        if ($saveFloat) {
            $result[] = $fractionalPart;
            $result[] = self::_getMorphed($fractionalPart, $forms[0][0], $forms[0][1], $forms[0][2]);
        }
        return preg_replace("#\s{2,}#", ' ', implode(' ',$result));
    }
205906
def auto_convert_string_cell(flagable, cell_str, position, worksheet, flags,
                             units, parens_as_neg=True):
    '''
    
    '''
    conversion = cell_str.strip()

    # Wrapped?
    if re.search(allregex.control_wrapping_regex, cell_str):
        # Drop the wrapping characters
        stripped_cell = cell_str.strip()
        mod_cell_str = stripped_cell[1:][:-1].strip()
        neg_mult = False
        # If the wrapping characters are '(' and ')' and the interior is a number,
        # then the number should be interpreted as a negative value
        if (stripped_cell[0] == '(' and stripped_cell[-1] == ')' and
                re.search(allregex.contains_numerical_regex, mod_cell_str)):
            # Flag for conversion to negative
            neg_mult = True
        flagable.flag_change(flags, 'interpreted', position, worksheet,
                            flagable.FLAGS['removed-wrapping'])
        # Try again without wrapping
        converted_value = auto_convert_cell(flagable, mod_cell_str, position,
                                            worksheet, flags, units)
        neg_mult = neg_mult and check_cell_type(converted_value, get_cell_type(0))
        if neg_mult and parens_as_neg:
            flagable.flag_change(flags, 'interpreted', position, worksheet,
                                 flagable.FLAGS['converted-wrapping-to-neg'])
        return -converted_value if neg_mult else converted_value
    # Is a string containing numbers?
    elif re.search(allregex.contains_numerical_regex, cell_str):
        conversion = auto_convert_numeric_string_cell(flagable, conversion, position,
                                                      worksheet, flags, units)
    elif re.search(allregex.bool_regex, cell_str):
        flagable.flag_change(flags, 'interpreted', position, worksheet,
                             flagable.FLAGS['bool-to-int'])
        conversion = 1 if re.search(allregex.true_bool_regex, cell_str) else 0

    return conversion
677728
def ConvertToWireFormat(self, value):
    """"""
    value = value.encode("utf8")
    return (self.encoded_tag, VarintEncode(len(value)), value)
23522
def format_string(m, l, capture, is_bytes):
    """"""

    for fmt_type, value in capture[1:]:
        if fmt_type == FMT_ATTR:
            # Attribute
            l = getattr(l, value)
        elif fmt_type == FMT_INDEX:
            # Index
            l = l[value]
        elif fmt_type == FMT_CONV:
            if is_bytes:
                # Conversion
                if value in ('r', 'a'):
                    l = repr(l).encode('ascii', 'backslashreplace')
                elif value == 's':
                    # If the object is not string or byte string already
                    l = _to_bstr(l)
            else:
                # Conversion
                if value == 'a':
                    l = ascii(l)
                elif value == 'r':
                    l = repr(l)
                elif value == 's':
                    # If the object is not string or byte string already
                    l = str(l)
        elif fmt_type == FMT_SPEC:
            # Integers and floats don't have an explicit 's' format type.
            if value[3] and value[3] == 's':
                if isinstance(l, int):  # pragma: no cover
                    raise ValueError("Unknown format code 's' for object of type 'int'")
                if isinstance(l, float):  # pragma: no cover
                    raise ValueError("Unknown format code 's' for object of type 'float'")

            # Ensure object is a byte string
            l = _to_bstr(l) if is_bytes else str(l)

            spec_type = value[1]
            if spec_type == '^':
                l = l.center(value[2], value[0])
            elif spec_type == ">":
                l = l.rjust(value[2], value[0])
            else:
                l = l.ljust(value[2], value[0])

    # Make sure the final object is a byte string
    return _to_bstr(l) if is_bytes else str(l)
357100
public function convertToUtf()
    {
        $dbHandler = $this->getDbHandler();

        $rs = $dbHandler->query(
            "SELECT oxvarname, oxvartype, DECODE( oxvarvalue, '{$this->getConfigKey()}') AS oxvarvalue
                       FROM oxconfig
                       WHERE oxvartype IN ('str', 'arr', 'aarr')"
        );

        while ( (false !== $rs) && ($aRow = $rs->fetch())) {
            if ($aRow['oxvartype'] == 'arr' || $aRow['oxvartype'] == 'aarr') {
                $aRow['oxvarvalue'] = unserialize($aRow['oxvarvalue']);
            }
            if (!empty($aRow['oxvarvalue']) && !is_int($aRow['oxvarvalue'])) {
                $this->updateConfigValue($aRow['oxid'], $this->stringToUtf($aRow['oxvarvalue']));
            }
        }

        // Change currencies value to same as after 4.6 setup because previous encoding break it.
        $shopId = 1;

        $query = "REPLACE INTO `oxconfig` (`OXID`, `OXSHOPID`, `OXMODULE`, `OXVARNAME`, `OXVARTYPE`, `OXVARVALUE`) VALUES
            ('3c4f033dfb8fd4fe692715dda19ecd28', $shopId, '', 'aCurrencies', 'arr', 0x4dbace2972e14bf2cbd3a9a45157004422e928891572b281961cdebd1e0bbafe8b2444b15f2c7b1cfcbe6e5982d87434c3b19629dacd7728776b54d7caeace68b4b05c6ddeff2df9ff89b467b14df4dcc966c504477a9eaeadd5bdfa5195a97f46768ba236d658379ae6d371bfd53acd9902de08a1fd1eeab18779b191f3e31c258a87b58b9778f5636de2fab154fc0a51a2ecc3a4867db070f85852217e9d5e9aa60507);";

        $dbHandler->query($query);
    }
1328340
function arrayToStr(key, value) {
  if (isString(value) || isNumber(value)) return `${key}=${value}`;
  if (isString(value[0])) return `${key}=${value.join(':')}`;
  if (value && value.toString) return `${key}=${value.toString()}`;

  return value.map(val => arrayToStr(key, val));
}
345813
function(value) {
  if (value && value._bsontype) {
    if (_.includes([ 'Decimal128', 'Long' ], value._bsontype)) {
      return value.toString();
    }
    if (_.includes([ 'Double', 'Int32' ], value._bsontype)) {
      return String(value.value);
    }
  }
  if (_.isString(value)) {
    return value;
  }
  return String(value);
}
65764
function formatValues(values) {
  var formatted = {};
  for (var key in values) {
    if (values.hasOwnProperty(key)) {
      if (typeof values[key] === 'boolean') {
        var position = key.indexOf('{');
        if (position !== -1) {
          if (values[key] === true) {
            // Each options of SelectWidget are stored as boolean and grouped using '{' and '}'
            // eg:
            // gender{male} = true
            // gender{female} = false
            var newKey = key.substr(0, position);
            var newValue = key.substr(position);
            newValue = newValue.replace('{', '');
            newValue = newValue.replace('}', '');
            if (!Array.isArray(formatted[newKey])) {
              formatted[newKey] = [];
            }
            formatted[newKey].push(newValue);
          }
        } else {
          formatted[key] = values[key];
        }
      } else {
        if (typeof values[key] === 'string') {
          formatted[key] = values[key].trim();
        } else {
          formatted[key] = values[key];
        }
      }
    }
  }
  return formatted;
}
30995
def stringify(self, value, **opts):
        
        if self._is_null(value):
            return None
        try:
            opts_ = self.opts.copy()
            opts_.update(opts)
            return self._stringify(value, **opts_)
        except Exception as e:
            if not isinstance(e, ConverterError):
                e = ConverterError(None, exc=e)
            e.converter = self.__class__
            raise e