Decorator to help PEG functions handle value conversions.
502745
def valuemap(f):
    
    @wraps(f)
    def wrapper(*args, **kwargs):
        if 'value' in kwargs:
            val = kwargs['value']
            del kwargs['value']
            _f = f(*args, **kwargs)
            def valued_f(*args, **kwargs):
                result = _f(*args, **kwargs)
                s, obj, span = result
                if callable(val):
                    return PegreResult(s, val(obj), span)
                else:
                    return PegreResult(s, val, span)
            return valued_f
        else:
            return f(*args, **kwargs)
    return wrapper
556247
def _inject_conversion(self, value, conversion):
        
        t = type(value)
        return value[:-1] + t(u'!') + conversion + t(u'}')
812255
def ensure_dtype(core, dtype, dtype_):
    """"""
    core = core.copy()
    if dtype is None:
        dtype = dtype_

    if dtype_ == dtype:
        return core, dtype

    for key, val in {
            int: chaospy.poly.typing.asint,
            float: chaospy.poly.typing.asfloat,
            np.float32: chaospy.poly.typing.asfloat,
            np.float64: chaospy.poly.typing.asfloat,
    }.items():

        if dtype == key:
            converter = val
            break
    else:
        raise ValueError("dtype not recognised (%s)" % str(dtype))

    for key, val in core.items():
        core[key] = converter(val)
    return core, dtype
1324278
def converts_values(self):
        """"""
        return self.convert_value is not Formatter.convert_value or \
               self.convert_column is not Formatter.convert_column
420516
def convert(self, value):
        
        if self._type is str:
            return str(value)
        elif self._type is int:
            try:
                return int(value)
            except (UnicodeError, ValueError):
                raise WorkflowArgumentError('Cannot convert {} to int'.format(value))
        elif self._type is float:
            try:
                return float(value)
            except (UnicodeError, ValueError):
                raise WorkflowArgumentError('Cannot convert {} to float'.format(value))
        elif self._type is bool:
            if isinstance(value, bool):
                return bool(value)
            value = value.lower()
            if value in ('true', '1', 'yes', 'y'):
                return True
            elif value in ('false', '0', 'no', 'n'):
                return False
            raise WorkflowArgumentError('Cannot convert {} to bool'.format(value))
        else:
            return value
1060436
def _normalize(self, key, value):
        

        # None value should not be converted by normalizer
        if value is None:
            return None

        normalize_func = getattr(self, 'normalize_{0}'.format(key),
                                 lambda x: x)

        return normalize_func(value)
811144
def value_check(arg_name, pos, allowed_values):
    

    def decorator(fn):

        # brevity compromised in favour of readability
        def logic(*args, **kwargs):
            arg_count = len(args)
            if arg_count:
                if pos < arg_count:
                    if args[pos] in allowed_values:
                        return fn(*args, **kwargs)
                    else:
                        raise ValueError(
                            "'{0}' at position {1} not in allowed values {2}".format(args[pos], pos, allowed_values))
                else:
                    if arg_name in kwargs:
                        value = kwargs[arg_name]
                        if value in allowed_values:
                            return fn(*args, **kwargs)
                        else:
                            raise ValueError("'{0}' is not an allowed kwarg".format(arg_name))
                    else:
                        # partially applied functions because of incomplete args, let python handle this
                        return fn(*args, **kwargs)
            else:
                if arg_name in kwargs:
                    value = kwargs[arg_name]
                    if value in allowed_values:
                        return fn(*args, **kwargs)
                else:
                    raise ValueError("'{0}' is not an allowed kwarg".format(arg_name))

        return logic

    return decorator
776389
def normalizeX(value):
    
    if not isinstance(value, (int, float)):
        raise TypeError("X coordinates must be instances of "
                        ":ref:`type-int-float`, not %s."
                        % type(value).__name__)
    return value
1171891
def convert(self, *args, **kwargs):
        

        if args:
            raise NotImplementedError
        by_item = kwargs.get('by_item', True)

        new_inputs = ['coerce', 'datetime', 'numeric', 'timedelta']
        new_style = False
        for kw in new_inputs:
            new_style |= kw in kwargs

        if new_style:
            fn = soft_convert_objects
            fn_inputs = new_inputs
        else:
            fn = maybe_convert_objects
            fn_inputs = ['convert_dates', 'convert_numeric',
                         'convert_timedeltas']
        fn_inputs += ['copy']

        fn_kwargs = {key: kwargs[key] for key in fn_inputs if key in kwargs}

        # operate column-by-column
        def f(m, v, i):
            shape = v.shape
            values = fn(v.ravel(), **fn_kwargs)
            try:
                values = values.reshape(shape)
                values = _block_shape(values, ndim=self.ndim)
            except (AttributeError, NotImplementedError):
                pass

            return values

        if by_item and not self._is_single_block:
            blocks = self.split_and_operate(None, f, False)
        else:
            values = f(None, self.values.ravel(), None)
            blocks = [make_block(values, ndim=self.ndim,
                                 placement=self.mgr_locs)]

        return blocks
215841
def _implicit_convert(cls, arg):
        """"""

        # ints, long and floats mix freely with BigFloats, and are
        # converted exactly.
        if isinstance(arg, six.integer_types) or isinstance(arg, float):
            return cls.exact(arg)
        elif isinstance(arg, BigFloat):
            return arg
        else:
            raise TypeError("Unable to convert argument %s of type %s "
                            "to BigFloat" % (arg, type(arg)))
541799
def convert_float(value, parameter):
    '''
    
    '''
    value = _check_default(value, parameter, ( '', '-', None ))
    if value is None or isinstance(value, float):
        return value
    try:
        return float(value)
    except Exception as e:
        raise ValueError(str(e))
669165
def _convert_value(self, column, value):
        ''''''

        if isinstance(value, GObject.Value):
            return value
        return GObject.Value(self.get_column_type(column), value)
347739
def convert_values(self):
        
        def stringify(value):
            if self.encoding is not None:
                encoder = partial(pprint_thing_encoded,
                                  encoding=self.encoding)
            else:
                encoder = pprint_thing
            return encoder(value)

        lhs, rhs = self.lhs, self.rhs

        if is_term(lhs) and lhs.is_datetime and is_term(rhs) and rhs.is_scalar:
            v = rhs.value
            if isinstance(v, (int, float)):
                v = stringify(v)
            v = Timestamp(_ensure_decoded(v))
            if v.tz is not None:
                v = v.tz_convert('UTC')
            self.rhs.update(v)

        if is_term(rhs) and rhs.is_datetime and is_term(lhs) and lhs.is_scalar:
            v = lhs.value
            if isinstance(v, (int, float)):
                v = stringify(v)
            v = Timestamp(_ensure_decoded(v))
            if v.tz is not None:
                v = v.tz_convert('UTC')
            self.lhs.update(v)
1291059
def convert_values(args_list):
    
    rate_map = get_rates(map(itemgetter(1, 2), args_list))
    value_map = {}
    for value, source, target in args_list:
        args = (value, source, target)
        if source == target:
            value_map[args] = value
        else:
            value_map[args] = value * rate_map[(source, target)]

    return value_map
1279970
def _value_wrapper(self, value):
        '''  
        '''
        if isinstance(value, (int, float,)):
            return '=%s' % value
        elif isinstance(value, (str, unicode)):
            value = value.strip()
            # LIKE
            if RE_LIKE.match(value):
                return ' LIKE %s' % repr(RE_LIKE.match(value).group('RE_LIKE'))
            # REGEXP
            elif RE_REGEXP.match(value):
                return ' REGEXP %s' % repr(RE_REGEXP.search(value).group('RE_REGEXP'))
            else:            
                return '=%s' % repr(value)
        elif value is None:
            return ' ISNULL'
136780
def _value(obj):
    
    # TODO: this is ugly and makes everything ugly
    # can we handle this with a clean decorator or just requiring that only floats be passed??
    if hasattr(obj, 'value'):
        return obj.value
    elif isinstance(obj, np.ndarray):
        return np.array([o.value for o in obj])
    elif hasattr(obj, '__iter__'):
        return [_value(o) for o in obj]
    return obj
1172188
def encode(cls, value):
        
        try:
            if float(value) + 0 == value:
                return repr(value)
        except (TypeError, ValueError):
            pass

        raise InvalidValue('not a float')