Convert value for display purpose
18159
def value_to_display(value, minmax=False, level=0):
    """"""
    # To save current Numpy printoptions
    np_printoptions = FakeObject

    try:
        numeric_numpy_types = (int64, int32, int16, int8,
                               uint64, uint32, uint16, uint8,
                               float64, float32, float16,
                               complex128, complex64, bool_)
        if ndarray is not FakeObject:
            # Save printoptions
            np_printoptions = get_printoptions()
            # Set max number of elements to show for Numpy arrays
            # in our display
            set_printoptions(threshold=10)
        if isinstance(value, recarray):
            if level == 0:
                fields = value.names
                display = 'Field names: ' + ', '.join(fields)
            else:
                display = 'Recarray'
        elif isinstance(value, MaskedArray):
            display = 'Masked array'
        elif isinstance(value, ndarray):
            if level == 0:
                if minmax:
                    try:
                        display = 'Min: %r\nMax: %r' % (value.min(), value.max())
                    except (TypeError, ValueError):
                        if value.dtype.type in numeric_numpy_types:
                            display = str(value)
                        else:
                            display = default_display(value)
                elif value.dtype.type in numeric_numpy_types:
                    display = str(value)
                else:
                    display = default_display(value)
            else:
                display = 'Numpy array'
        elif any([type(value) == t for t in [list, set, tuple, dict]]):
            display = collections_display(value, level+1)
        elif isinstance(value, Image):
            if level == 0:
                display = '%s  Mode: %s' % (address(value), value.mode)
            else:
                display = 'Image'
        elif isinstance(value, DataFrame):
            if level == 0:
                cols = value.columns
                if PY2 and len(cols) > 0:
                    # Get rid of possible BOM utf-8 data present at the
                    # beginning of a file, which gets attached to the first
                    # column header when headers are present in the first
                    # row.
                    # Fixes Issue 2514
                    try:
                        ini_col = to_text_string(cols[0], encoding='utf-8-sig')
                    except:
                        ini_col = to_text_string(cols[0])
                    cols = [ini_col] + [to_text_string(c) for c in cols[1:]]
                else:
                    cols = [to_text_string(c) for c in cols]
                display = 'Column names: ' + ', '.join(list(cols))
            else:
                display = 'Dataframe'
        elif isinstance(value, NavigableString):
            # Fixes Issue 2448
            display = to_text_string(value)
            if level > 0:
                display = u"'" + display + u"'"
        elif isinstance(value, Index):
            if level == 0:
                try:
                    display = value._summary()
                except AttributeError:
                    display = value.summary()
            else:
                display = 'Index'
        elif is_binary_string(value):
            # We don't apply this to classes that extend string types
            # See issue 5636
            if is_type_text_string(value):
                try:
                    display = to_text_string(value, 'utf8')
                    if level > 0:
                        display = u"'" + display + u"'"
                except:
                    display = value
                    if level > 0:
                        display = b"'" + display + b"'"
            else:
                display = default_display(value)
        elif is_text_string(value):
            # We don't apply this to classes that extend string types
            # See issue 5636
            if is_type_text_string(value):
                display = value
                if level > 0:
                    display = u"'" + display + u"'"
            else:
                display = default_display(value)
        elif (isinstance(value, datetime.date) or
              isinstance(value, datetime.timedelta)):
            display = str(value)
        elif (isinstance(value, NUMERIC_TYPES) or
              isinstance(value, bool) or
              isinstance(value, numeric_numpy_types)):
            display = repr(value)
        else:
            if level == 0:
                display = default_display(value)
            else:
                display = default_display(value, with_module=False)
    except:
        display = default_display(value)

    # Truncate display at 70 chars to avoid freezing Spyder
    # because of large displays
    if len(display) > 70:
        if is_binary_string(display):
            ellipses = b' ...'
        else:
            ellipses = u' ...'
        display = display[:70].rstrip() + ellipses

    # Restore Numpy printoptions
    if np_printoptions is not FakeObject:
        set_printoptions(**np_printoptions)

    return display
56173
function formatValue(value) {
		
		var out;
		var type = util.sType(value);
		
		// if there is a type, check all sub items for types
		if (_.has(value, 'attributes.type') && _.has(value, '$value') && _.keys(value).length === 2) {
			out = util.moRef(value);
		}
		else if (type) {
			if (util.isArray(value)) {
				out = [];
				
				var subtype = type;
				
				if (subtype.match(/^ArrayOf/)) {
					subtype = subtype.replace(/^ArrayOf/, '');

					if (!Array.isArray(_.get(value, subtype)) && value[subtype]) {
						value[subtype] = [value[subtype]];
					}
				}
				
				_.forEach(value[_.keys(value)[1]], function(obj) {
					out.push(formatValue(obj));
				});
			}
			else if (util.isBoolean(value)) {
				
				// check for valid true values, otherwise false
				if (_.includes(['1', 'true'], _.lowerCase(value.$value))) {
					out = true;
				}
				else {
					out = false;
				}
			}
			else if (util.isInt(value)) {
				out = Number(value.$value);
			}
			else if (_.has(value, '$value')) {
				out = value.$value;
			}
			else {
				out = formatValue(_.omit(value, 'attributes'));
			}
			
		}
		else if (Array.isArray(value)) {
			out = [];
			_.forEach(value, function(val) {
				if (util.sType(val) || util.isArray(val) || util.hasKeys(val)) {
					out.push(formatValue(val));
				}
				else {
					out.push(cast(val));
				}
			});
		}
		else if (util.hasKeys(value)) {
			out = {};
			_.forEach(value, function(val, key) {
				if (util.sType(val) || util.isArray(val) || util.hasKeys(val)) {
					out[key] = formatValue(val);
				}
				else {
					out[key] = cast(val);
				}
			});
		}
		else {
			out = cast(value);
		}
		return out;
	}
927829
private static Object convert(Class<?> clazz, String value) {
      /* TODO create a new Converter class and move this method there for reuse */

        if (Integer.class.equals(clazz) || int.class.equals(clazz)) {
            return Integer.valueOf(value);
        } else if (Double.class.equals(clazz) || double.class.equals(clazz)) {
            return Double.valueOf(value);
        } else if (Long.class.equals(clazz) || long.class.equals(clazz)) {
            return Long.valueOf(value);
        } else if (Boolean.class.equals(clazz) || boolean.class.equals(clazz)) {
            return Boolean.valueOf(value);
        }

        return value;
    }
1032189
function convertPropToPixels(propName, propValue, maxScroll, offset = 0) {
  let propValueInPx = propValue;
  const isElement = propValue instanceof HTMLElement;
  const keyCodes = {
    ZERO: 48,
    NINE: 57,
  };

  if (typeof propValue === 'number') {
    propValueInPx = propValue;
  } else if (START_END_DURATION_REGEX.test(propValue)) {
    propValueInPx = getValueInPx(propValue, maxScroll);
  } else if (
    isElement ||
    typeof propValue === 'string' &&
    (propValue.charCodeAt(0) < keyCodes.ZERO || propValue.charCodeAt(0) > keyCodes.NINE)
  ) {
    const element = isElement ? propValue : document.querySelector(propValue);

    if (!element) {
      console.warn(`Plx, ERROR: ${ propName } selector matches no elements: "${ propValue }"`); // eslint-disable-line
      return null;
    }

    if (propName === 'start' || propName === 'end') {
      // START or END
      // Element enters the viewport
      propValueInPx = getElementTop(element) - window.innerHeight;
    } else if (propName === 'duration') {
      // DURATION
      // Height of the element
      propValueInPx = element.offsetHeight;
    }
  } else {
    console.warn(`Plx, ERROR: "${ propValue }" is not a valid ${ propName } value, check documenation`); // eslint-disable-line
    return null;
  }

  // Transform offset to px
  let offsetInPx = 0;

  if (typeof offset === 'number') {
    offsetInPx = offset;
  } else if (START_END_DURATION_REGEX.test(offset)) {
    offsetInPx = getValueInPx(offset, maxScroll);
  }
  // Add offset
  propValueInPx += offsetInPx;

  if (propValueInPx < 0) {
    propValueInPx = 0;
  }

  return propValueInPx;
}
972588
def ConvertToWireFormat(self, value):
    """"""
    # Is it a protobuf-based value?
    if hasattr(value.__class__, "protobuf"):
      if value.__class__.protobuf:
        type_name = ("type.googleapis.com/%s" %
                     value.__class__.protobuf.__name__)
      else:
        type_name = value.__class__.__name__
      data = value.SerializeToString()
    # Is it a primitive value?
    elif hasattr(value.__class__, "data_store_type"):
      wrapper_cls = self.__class__.WRAPPER_BY_TYPE[
          value.__class__.data_store_type]
      wrapped_data = wrapper_cls()
      wrapped_data.value = value.SerializeToDataStore()

      type_name = ("type.googleapis.com/google.protobuf.%s" %
                   wrapper_cls.__name__)
      data = wrapped_data.SerializeToString()
    else:
      raise ValueError("Can't convert value %s to an protobuf.Any value." %
                       value)

    any_value = AnyValue(type_url=type_name, value=data)
    output = _SerializeEntries(_GetOrderedEntries(any_value.GetRawData()))

    return (self.encoded_tag, VarintEncode(len(output)), output)
1082645
def _ConvertFloat(value):
  """"""
  if value == 'nan':
    raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.')
  try:
    # Assume Python compatible syntax.
    return float(value)
  except ValueError:
    # Check alternative spellings.
    if value == _NEG_INFINITY:
      return float('-inf')
    elif value == _INFINITY:
      return float('inf')
    elif value == _NAN:
      return float('nan')
    else:
      raise ParseError('Couldn\'t parse float: {0}.'.format(value))
678276
def pixels(self, value: int) -> 'Gap':
        """"""
        raise_not_number(value)
        self.gap = '{}px'.format(value)
        return self
285105
function writeOnDisplay(value) {
    dothat.lcd.clear();
    dothat.lcd.setCursorPosition(0, 1);
    dothat.lcd.write(value);
}
173480
def convert(self, value, param, ctx):  # pylint: disable=inconsistent-return-statements
        """"""
        matches = MEMORY_RE.match(value.lower())
        if matches is None:
            self.fail('%s is not a valid value for memory amount' % value, param, ctx)
        amount_str, unit = matches.groups()
        amount = int(amount_str)
        if unit in [None, 'm', 'mb']:
            # Assume the user intends gigabytes if they specify a number < 1024
            if amount < 1024:
                return amount * 1024
            else:
                if amount % 1024 != 0:
                    self.fail('%s is not an integer that is divisable by 1024' % value, param, ctx)
                return amount
        elif unit in ['g', 'gb']:
            return amount * 1024
1101539
function convertColorToString(color) {
  const {type, values} = color

  // Only convert the first 3 values to int (i.e. not alpha)
  if (type.indexOf('rgb') > -1)
    for (let i = 0; i < 3; i++) values[i] = parseInt(values[i])

  let colorString

  if (type.indexOf('hsl') > -1)
    colorString = `${color.type}(${values[0]}, ${values[1]}%, ${values[2]}%`
  else colorString = `${color.type}(${values[0]}, ${values[1]}, ${values[2]}`

  if (values.length === 4) colorString += `, ${color.values[3].toFixed(2)})`
  else colorString += ')'

  return colorString
}
1113840
def convert_value(self, v):
        

        def stringify(value):
            if self.encoding is not None:
                encoder = partial(pprint_thing_encoded,
                                  encoding=self.encoding)
            else:
                encoder = pprint_thing
            return encoder(value)

        kind = _ensure_decoded(self.kind)
        meta = _ensure_decoded(self.meta)
        if kind == 'datetime64' or kind == 'datetime':
            if isinstance(v, (int, float)):
                v = stringify(v)
            v = _ensure_decoded(v)
            v = Timestamp(v)
            if v.tz is not None:
                v = v.tz_convert('UTC')
            return TermValue(v, v.value, kind)
        elif kind == 'timedelta64' or kind == 'timedelta':
            v = Timedelta(v, unit='s').value
            return TermValue(int(v), v, kind)
        elif meta == 'category':
            metadata = com.values_from_object(self.metadata)
            result = metadata.searchsorted(v, side='left')

            # result returns 0 if v is first element or if v is not in metadata
            # check that metadata contains v
            if not result and v not in metadata:
                result = -1
            return TermValue(result, result, 'integer')
        elif kind == 'integer':
            v = int(float(v))
            return TermValue(v, v, kind)
        elif kind == 'float':
            v = float(v)
            return TermValue(v, v, kind)
        elif kind == 'bool':
            if isinstance(v, str):
                v = not v.strip().lower() in ['false', 'f', 'no',
                                              'n', 'none', '0',
                                              '[]', '{}', '']
            else:
                v = bool(v)
            return TermValue(v, v, kind)
        elif isinstance(v, str):
            # string quoting
            return TermValue(v, stringify(v), 'string')
        else:
            raise TypeError("Cannot compare {v} of type {typ} to {kind} column"
                            .format(v=v, typ=type(v), kind=kind))
1138668
def to_gui
      return to_standard_hex if hexadecimal?
      return Convert.xterm_to_hex(@value) if cterm?
      return :NONE if none?

      raise ColorError.new "can't convert \"#{ @value }\" to gui"
    end
1086315
def pixels(self, value: float) -> 'Size':
        """"""
        raise_not_number(value)
        self.maximum = '{}px'.format(value)
        return self
339035
def convert(self, value):
        """"""
        try:
            return convert_to_format(value, self._format)
        except (ValueError, TypeError):
            return value
670562
def _value_to_color(value, cmap):
    """"""
    cm = plt.get_cmap(cmap)
    rgba = cm(value)
    return [int(round(255*v)) for v in rgba[0:3]]
306757
def default_display(value, with_module=True):
    """"""
    object_type = type(value)
    try:
        name = object_type.__name__
        module = object_type.__module__
        if with_module:
            return name + ' object of ' + module + ' module'
        else:
            return name
    except:
        type_str = to_text_string(object_type)
        return type_str[1:-1]
115277
def _convert_number(self, number):
        """"""

        number = float(number)
        return int(number) if number.is_integer() else float(number)