Helper function to convert python data structures to R equivalents

    TODO: a single model for transforming to r to handle
    * function args
    * lists as function args
197953
def _to_r(o, as_data=False, level=0):
    
    if o is None:
        return "NA"
    if isinstance(o, basestring):
        return o
    if hasattr(o, "r"):
        # bridge to @property r on GGStatement(s)
        return o.r
    elif isinstance(o, bool):
        return "TRUE" if o else "FALSE"
    elif isinstance(o, (list, tuple)):
        inner = ",".join([_to_r(x, True, level+1) for x in o])
        return "c({})".format(inner) if as_data else inner
    elif isinstance(o, dict):
        inner = ",".join(["{}={}".format(k, _to_r(v, True, level+1))
                         for k, v in sorted(o.iteritems(), key=lambda x: x[0])])
        return "list({})".format(inner) if as_data else inner
    return str(o)
358179
def _AsList(arg):
    """"""
    if (isinstance(arg, string_types) or
        not isinstance(arg, collections.Iterable)):
      return [arg]
    else:
      return list(arg)
1146511
def bracketedList(l, r, sep, expr, allow_missing_close=False):
  
  # We may need to backtrack for lists, because of list comprehension, but not for
  # any of the other lists
  strict = l != '['
  closer = sym(r) if not allow_missing_close else p.Optional(sym(r))
  if strict:
    return sym(l) - listMembers(sep, expr) - closer
  else:
    return sym(l) + listMembers(sep, expr) + closer
1361592
def _ls2ar(inp, strinp):
    """

    # Check if input is 1 or 3 elements (float, list, tuple, array)
    if np.size(inp) == 1:
        start = np.squeeze(inp)
        stop = start+1
        num = 1
    elif np.size(inp) == 3:
        start = inp[0]
        stop = inp[1]
        num = inp[2]
    else:
        print("* ERROR   :: <"+strinp+"> must be a float or a tuple of 3 " +
              "elements (start, stop, num); <"+strinp+" provided: " + str(inp))
        raise ValueError(strinp)

    # Re-arrange it to be compatible with np.arange/slice for brute
    if num < 2 or start == stop:
        stop = start
        step = 1
    else:
        step = (stop-start)/(num-1)
    return (start, stop+step/2, step)
1085154
def mapstr_to_list(mapstr):
    
    maplist = []

    with StringIO(mapstr) as infile:
        for row in infile:
            maplist.append(row.strip())

    return maplist
574642
def beta_r(self, r, kwargs):
        
        if self._type == 'const':
            return self.const_beta(kwargs)
        elif self._type == 'r_ani':
            return self.beta_r_ani(r, kwargs)
        else:
            raise ValueError('anisotropy type %s not supported!' % self._type)
868594
def ndarray_to_list_in_structure(item, squeeze=True):
    
    tp = type(item)

    if tp == np.ndarray:
        if squeeze:
            item = item.squeeze()
        item = item.tolist()
    elif tp == list:
        for i in range(len(item)):
            item[i] = ndarray_to_list_in_structure(item[i])
    elif tp == dict:
        for lab in item:
            item[lab] = ndarray_to_list_in_structure(item[lab])

    return item
1373003
def lossless_float_to_int(funcname, func, argname, arg):
    
    if not isinstance(arg, float):
        return arg

    arg_as_int = int(arg)
    if arg == arg_as_int:
        warnings.warn(
            "{f} expected an int for argument {name!r}, but got float {arg}."
            " Coercing to int.".format(
                f=funcname,
                name=argname,
                arg=arg,
            ),
        )
        return arg_as_int

    raise TypeError(arg)
309571
def transform_array_to_list(array):
    ''' 

    '''
    if (array.dtype.kind in ('u', 'i', 'f') and (~np.isfinite(array)).any()):
        transformed = array.astype('object')
        transformed[np.isnan(array)] = 'NaN'
        transformed[np.isposinf(array)] = 'Infinity'
        transformed[np.isneginf(array)] = '-Infinity'
        return transformed.tolist()
    elif (array.dtype.kind == 'O' and pd and pd.isnull(array).any()):
        transformed = array.astype('object')
        transformed[pd.isnull(array)] = 'NaN'
        return transformed.tolist()
    return array.tolist()
1298604
function listToArray(list) {
  if(isFunction(list)) {
    return function(x) {
      const m = list(x)

      if(!isSameType(List, m)) {
        throw new TypeError('listToArray: List returning function required')
      }

      return m.toArray()
    }
  }

  if(isSameType(List, list)) {
    return list.toArray()
  }

  throw new TypeError('listToArray: List or List returning function required')
}
316045
def rsi(arg, n):
    
    if isinstance(arg, pd.DataFrame):
        cols = [(name, rsi(arg[name], n)) for name in arg.columns]
        return pd.DataFrame.from_items(cols)
    else:
        assert isinstance(arg, pd.Series)
        n = int(n)
        converted = arg.dropna()
        change = converted.diff()
        gain = change.apply(lambda c: c > 0 and c or 0)
        avgGain = wilderma(gain, n)
        loss = change.apply(lambda c: c < 0 and abs(c) or 0)
        avgLoss = wilderma(loss, n)

        result = avgGain / avgLoss
        result[result == np.inf] = 100.  # divide by zero
        result = 100. - (100. / (1. + result))
        return pd.Series(result, index=converted.index).reindex(arg.index)
579687
def make_rw(obj: Any):
    

    if isinstance(obj, RoDict):
        return {k: make_rw(v) for k, v in obj.items()}
    elif isinstance(obj, RoList):
        return [make_rw(x) for x in obj]
    else:
        return obj
195180
def list_updater(*args):
    
    neg_index = [i for v,i in izip(args, itertools.count()) if v is not None and v < 0]
    if len(neg_index) > 1:
        raise ValueError("Cannot use negative values more than once")
    if not neg_index:
        slice_list = []
        size = 0
        for arg in args:
            if arg is None:
                slice_list.append(size)
                size += 1
            else:
                slice_list.append(slice(size, size + arg))
                size += arg
    else:
        sep = neg_index[0]
        slice_list = []
        size = 0
        for arg in args[:sep]:
            if arg is None:
                slice_list.append(size)
                size += 1
            else:
                slice_list.append(slice(size, size + arg))
                size += arg
        rslice_list = []
        rsize = 0
        for arg in args[:sep:-1]:
            if arg is None:
                rslice_list.append(-1-rsize)
                rsize += 1
            else:
                rslice_list.append(slice(None if not rsize else -rsize, -(rsize + arg)))
                rsize += arg
        slice_list.append(slice(size, rsize))
        slice_list.extend(reversed(rslice_list))
    def inner_wrapper(f):
        @functools.wraps(f)
        def wrapped_updater(keys, values):
            result = f(*[values[s] for s in slice_list])
            return (keys[:len(result)], result)
        return wrapped_updater
    return inner_wrapper
584605
def rm(args):
    
    p = OptionParser(rm.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    store, = args
    contents = glob_s3(store)
    for c in contents:
        rm_s3(c)
286211
def table(self,x,*args,**kwargs):
        
        reduce_func = kwargs.get('reduce',lambda x: x)
        data = []
        for i,d in enumerate(self.generate(*args)):
            if len(d) > 0:
                data.append(reduce_func(d[x]))
            else:
                data.append(0)
        try:
            return np.reshape(data,[len(self.space(a)) for a in args])
        except:
            return np.reshape(data,[-1]+[len(self.space(a)) for a in args])
1207483
def str_to_list(
    input_str,
    item_converter=lambda x: x,
    item_separator=',',
    list_to_collection_converter=None,
):
    
    if not isinstance(input_str, six.string_types):
        raise ValueError(input_str)
    input_str = str_quote_stripper(input_str)
    result = [
        item_converter(x.strip())
        for x in input_str.split(item_separator) if x.strip()
    ]
    if list_to_collection_converter is not None:
        return list_to_collection_converter(result)
    return result
857380
def toList(value):
        
        if type(value) == list:
            return value
        elif type(value) in [np.ndarray, tuple, xrange, array.array]:
            return list(value)
        elif isinstance(value, Vector):
            return list(value.toArray())
        else:
            raise TypeError("Could not convert %s to list" % value)