Parse R transform expression to Hive equivalent

@param RExps : e.g: "foobar = arrtime - crsarrtime, speed = distance / airtime"
@return "(arrtime - crsarrtime) as foobar, (distance / airtime) as speed
352141
public static String RToSqlUdf(List<String> RExps, List<String> selectedColumns, List<Column> existingColumns) {
    List<String> udfs = Lists.newArrayList();
    Map<String, String> newColToDef = new HashMap<String, String>();
    boolean updateOnConflict = (selectedColumns == null || selectedColumns.isEmpty());
    String dupColExp = "%s duplicates another column name";

    if (updateOnConflict) {
      if (existingColumns != null && !existingColumns.isEmpty()) {
        for (Column c : existingColumns) {
          udfs.add(c.getName());
        }
      }
    }
    else {
      for (String c : selectedColumns) {
        udfs.add(c);
      }
    }

    Set<String> newColsInRExp = new HashSet<String>();
    for (String str : RExps) {
      int index = str.indexOf("=") >  str.indexOf("~")
          ? str.indexOf("=")
          : str.indexOf("~");
      String[] udf = new String[2];
      if (index == -1) {
        udf[0] = str;
      } else {
        udf[0] = str.substring(0,index);
        udf[1] = str.substring(index + 1);
      }

      // String[] udf = str.split("[=~](?![^()]*+\\))");
      String newCol = (index != -1) ?
        udf[0].trim().replaceAll("\\W", "") :
        udf[0].trim();
      if (newColsInRExp.contains(newCol)) {
        throw new RuntimeException(String.format(dupColExp, newCol));
      }
      String newDef = (index != -1) ? udf[1].trim() : null;
      if (!udfs.contains(newCol)) {
        udfs.add(newCol);
      }
      else if (!updateOnConflict) {
        throw new RuntimeException(String.format(dupColExp,newCol));
      }

      if (newDef != null && !newDef.isEmpty()) {
        newColToDef.put(newCol.replaceAll("\\W", ""), newDef);
      }
      newColsInRExp.add(newCol);
    }

    String selectStr = "";
    for (String udf : udfs) {
      String exp = newColToDef.containsKey(udf) ?
        String.format("%s as %s", newColToDef.get(udf), udf) :
        String.format("%s", udf);
      selectStr += (exp + ",");
    }

    return selectStr.substring(0, selectStr.length() - 1);
  }
812938
public String translate(final Values values) {
        final ArrayList<Values.Row> rows = new ArrayList<>(values.getRows());
        final String[] aliases = values.getAliases();

        // If aliases does not exist, throw an exception.
        // Otherwise, apply them to the columns.
        if (aliases == null || aliases.length == 0) {
            throw new DatabaseEngineRuntimeException("Values requires aliases to avoid ambiguous columns names.");
        } else {
            rows.forEach(row -> {
                final List<Expression> expressions = row.getExpressions();
                for (int i = 0; i < expressions.size() && i < aliases.length; i++) {
                    // DISCLAIMER : May have side-effects because will change the state of the row's expressions.
                    expressions.get(i).alias(aliases[i]);
                }
            });
        }

        // Put each row on a select for union operator to work.
        final List<Expression> rowsWithSelect = rows.stream()
                .map(SqlBuilder::select)
                .collect(Collectors.toList());

        // By default, use UNION ALL to express VALUES.
        // This way, only engines that support VALUES will implement it.
        // Since the amount of values can be quite large, a linear UNION can cause Stack Overflow.
        // To avoid it, we model this UNION as a binary tree.
        final Union union = rowsToUnion(rowsWithSelect);

        if (values.isEnclosed()) {
            union.enclose();
        }

        return translate(union);
    }
693937
public static <T extends Geometry> JTSGeometryExpression<T> setSRID(Expression<T> expr, int srid) {
        return geometryOperation(expr.getType(), SpatialOps.SET_SRID,
                expr, ConstantImpl.create(srid));
    }
306646
private void matchX509CRLs(CRLSelector selector, Collection<CRL> matches) {
        for (Object obj : crlIssuers.values()) {
            if (obj instanceof X509CRL) {
                X509CRL crl = (X509CRL)obj;
                if (selector.match(crl)) {
                    matches.add(crl);
                }
            } else {
                // See crlIssuers javadoc.
                @SuppressWarnings("unchecked")
                List<X509CRL> list = (List<X509CRL>)obj;
                for (X509CRL crl : list) {
                    if (selector.match(crl)) {
                        matches.add(crl);
                    }
                }
            }
        }
    }
765972
public List<Map<String, Object>> convertAllToMaps(ResultSet rs) throws SQLException{
		return convertAllToMaps(rs, null);
	}
229214
@Override
    public ZMatrixRMaj getR(ZMatrixRMaj R, boolean compact) {
        if( compact )
            R = UtilDecompositons_ZDRM.checkZerosLT(R,minLength,numCols);
        else
            R = UtilDecompositons_ZDRM.checkZerosLT(R,numRows,numCols);

        for( int i = 0; i < R.numRows; i++ ) {
            for( int j = i; j < R.numCols; j++ ) {
                int index = QR.getIndex(j,i);
                R.set(i,j,QR.data[index],QR.data[index+1]);
            }
        }

        return R;
    }
244749
public static Iterator<ResidueNumber> multiIterator(AtomPositionMap map, List<? extends ResidueRange> rrs) {
		ResidueRange[] ranges = new ResidueRange[rrs.size()];
		for (int i = 0; i < rrs.size(); i++) {
			ranges[i] = rrs.get(i);
		}
		return multiIterator(map, ranges);
	}
724803
final public TregexPattern Node(Relation r) throws ParseException {
  TregexPattern node;
    switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
    case 12:
      jj_consume_token(12);
      node = SubNode(r);
      jj_consume_token(13);
      break;
    case IDENTIFIER:
    case BLANK:
    case REGEX:
    case 14:
    case 15:
    case 18:
    case 19:
      node = ModDescription(r);
      break;
    default:
      jj_la1[0] = jj_gen;
      jj_consume_token(-1);
      throw new ParseException();
    }
    {if (true) return node;}
    throw new Error("Missing return statement in function");
  }
779581
def _extract_rsnap_isteps(rproffile):
    """"""
    step_regex = re.compile(r'^\*+step:\s*(\d+) ; time =\s*(\S+)')
    isteps = []  # list of (istep, time, nz)
    rows_to_del = set()
    line = ' '
    with rproffile.open() as stream:
        while line[0] != '*':
            line = stream.readline()
        match = step_regex.match(line)
        istep = int(match.group(1))
        time = float(match.group(2))
        nlines = 0
        iline = 0
        for line in stream:
            if line[0] == '*':
                isteps.append((istep, time, nlines))
                match = step_regex.match(line)
                istep = int(match.group(1))
                time = float(match.group(2))
                nlines = 0
                # remove useless lines produced when run is restarted
                nrows_to_del = 0
                while isteps and istep <= isteps[-1][0]:
                    nrows_to_del += isteps.pop()[-1]
                rows_to_del = rows_to_del.union(
                    range(iline - nrows_to_del, iline))
            else:
                nlines += 1
                iline += 1
        isteps.append((istep, time, nlines))
    return isteps, rows_to_del
331390
private QueryParameters convertResultSetCurrentLine(ResultSet rs) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        int cols = rsmd.getColumnCount();
        String columnName = null;
        QueryParameters result = new QueryParameters();

        for (int i = 1; i <= cols; i++) {

            columnName = rsmd.getColumnLabel(i);
            if (null == columnName || 0 == columnName.length()) {
                columnName = rsmd.getColumnName(i);
            }

            result.set(columnName, rs.getObject(i));
            result.updatePosition(columnName, i - 1);
        }

        if (result != null) {
            result = typeHandler.processOutput(stmt, result);
        }

        return result;
    }
710833
function parseExpr(source) {
    if (!source) {
        return;
    }

    if (typeof source === 'object' && source.type) {
        return source;
    }

    var expr = readTertiaryExpr(new Walker(source));
    expr.raw = source;
    return expr;
}
1198269
def regex(r):
    
    if isinstance(r, stringtypes):
        p = re.compile(r)
    else:
        p = r
    msg = 'Expected to match: {}'.format(p.pattern)
    def match_regex(s, grm=None, pos=0):
        m = p.match(s)
        if m is not None:
            start, end = m.span()
            data = m.groupdict() if p.groupindex else m.group()
            return PegreResult(s[m.end():], data, (pos+start, pos+end))
        raise PegreError(msg, pos)
    return match_regex
540218
def parse_multirsp(self, tup_tree):
        # pylint: disable=unused-argument
        
        raise CIMXMLParseError(
            _format("Internal Error: Parsing support for element {0!A} is not "
                    "implemented", name(tup_tree)),
            conn_id=self.conn_id)
818692
public Map<String, Object> convertToMap(ResultSet rs) throws SQLException{
		return convertToMap(rs, null);
	}
548582
private AbstractExpression parseVectorExpression(VoltXMLElement exprNode) {
        ArrayList<AbstractExpression> args = new ArrayList<>();
        for (VoltXMLElement argNode : exprNode.children) {
            assert(argNode != null);
            // recursively parse each argument subtree (could be any kind of expression).
            AbstractExpression argExpr = parseExpressionNode(argNode);
            assert(argExpr != null);
            args.add(argExpr);
        }

        VectorValueExpression vve = new VectorValueExpression();
        vve.setValueType(VoltType.VOLTTABLE);
        vve.setArgs(args);
        return vve;
    }
1043199
def rex(expr):
    
    r = re.compile(expr)
    return lambda key: isinstance(key, six.string_types) and r.match(key)
242863
public List<?> convertAllToDynamicBeans(ResultSet rs) throws SQLException{
		ResultSetMetaData rsmd = rs.getMetaData();
		
		Map<String, ColumnMetaData> columnToPropertyMappings = createColumnToPropertyMappings(rsmd);
		
		Class<?> beanClass = reuseOrBuildBeanClass(rsmd, columnToPropertyMappings);
		BeanProcessor beanProcessor = new BeanProcessor(simpleColumnToPropertyMappings(columnToPropertyMappings));
		return beanProcessor.toBeanList(rs, beanClass);
	}