This function is mostly re-written for the fix of ENG-6511. --yzhang
481695
private static Index findBestMatchIndexForMatviewMinOrMax(MaterializedViewInfo matviewinfo,
            Table srcTable, List<AbstractExpression> groupbyExprs, AbstractExpression minMaxAggExpr) {
        CatalogMap<Index> allIndexes = srcTable.getIndexes();
        StmtTableScan tableScan = new StmtTargetTableScan(srcTable);

        // Candidate index. If we can find an index covering both group-by columns and aggExpr (optimal) then we will
        // return immediately.
        // If the index found covers only group-by columns (sub-optimal), we will first cache it here.
        Index candidate = null;
        for (Index index : allIndexes) {
            // indexOptimalForMinMax == true if the index covered both the group-by columns and the min/max aggExpr.
            boolean indexOptimalForMinMax = false;
            // If minMaxAggExpr is not null, the diff can be zero or one.
            // Otherwise, for a usable index, its number of columns must agree with that of the group-by columns.
            final int diffAllowance = minMaxAggExpr == null ? 0 : 1;

            // Get all indexed exprs if there is any.
            String expressionjson = index.getExpressionsjson();
            List<AbstractExpression> indexedExprs = null;
            if ( ! expressionjson.isEmpty() ) {
                try {
                    indexedExprs = AbstractExpression.fromJSONArrayString(expressionjson, tableScan);
                } catch (JSONException e) {
                    e.printStackTrace();
                    assert(false);
                    return null;
                }
            }
            // Get source table columns.
            List<Column> srcColumnArray = CatalogUtil.getSortedCatalogItems(srcTable.getColumns(), "index");
            MatViewIndexMatchingGroupby matchingCase = null;

            if (groupbyExprs == null) {
                // This means group-by columns are all simple columns.
                // It also means we can only access the group-by columns by colref.
                List<ColumnRef> groupbyColRefs =
                    CatalogUtil.getSortedCatalogItems(matviewinfo.getGroupbycols(), "index");
                if (indexedExprs == null) {
                    matchingCase = MatViewIndexMatchingGroupby.GB_COL_IDX_COL;

                    // All the columns in the index are also simple columns, EASY! colref vs. colref
                    List<ColumnRef> indexedColRefs =
                        CatalogUtil.getSortedCatalogItems(index.getColumns(), "index");
                    // The number of columns in index can never be less than that in the group-by column list.
                    // If minMaxAggExpr == null, they must be equal (diffAllowance == 0)
                    // Otherwise they may be equal (sub-optimal) or
                    // indexedColRefs.size() == groupbyColRefs.size() + 1 (optimal, diffAllowance == 1)
                    if (isInvalidIndexCandidate(indexedColRefs.size(), groupbyColRefs.size(), diffAllowance)) {
                        continue;
                    }

                    if (! isGroupbyMatchingIndex(matchingCase, groupbyColRefs, null, indexedColRefs, null, null)) {
                        continue;
                    }
                    if (isValidIndexCandidateForMinMax(indexedColRefs.size(), groupbyColRefs.size(), diffAllowance)) {
                        if(! isIndexOptimalForMinMax(matchingCase, minMaxAggExpr, indexedColRefs, null, srcColumnArray)) {
                            continue;
                        }
                        indexOptimalForMinMax = true;
                    }
                }
                else {
                    matchingCase = MatViewIndexMatchingGroupby.GB_COL_IDX_EXP;
                    // In this branch, group-by columns are simple columns, but the index contains complex columns.
                    // So it's only safe to access the index columns from indexedExprs.
                    // You can still get something from indexedColRefs, but they will be inaccurate.
                    // e.g.: ONE index column (a+b) will get you TWO separate entries {a, b} in indexedColRefs.
                    // In order to compare columns: for group-by columns: convert colref => col
                    //                              for    index columns: convert    tve => col
                    if (isInvalidIndexCandidate(indexedExprs.size(), groupbyColRefs.size(), diffAllowance)) {
                        continue;
                    }

                    if (! isGroupbyMatchingIndex(matchingCase, groupbyColRefs, null, null, indexedExprs, srcColumnArray)) {
                        continue;
                    }
                    if (isValidIndexCandidateForMinMax(indexedExprs.size(), groupbyColRefs.size(), diffAllowance)) {
                        if(! isIndexOptimalForMinMax(matchingCase, minMaxAggExpr, null, indexedExprs, null)) {
                            continue;
                        }
                        indexOptimalForMinMax = true;
                    }
                }
            }
            else {
                matchingCase = MatViewIndexMatchingGroupby.GB_EXP_IDX_EXP;
                // This means group-by columns have complex columns.
                // It's only safe to access the group-by columns from groupbyExprs.
                // AND, indexedExprs must not be null in this case. (yeah!)
                if ( indexedExprs == null ) {
                    continue;
                }
                if (isInvalidIndexCandidate(indexedExprs.size(), groupbyExprs.size(), diffAllowance)) {
                    continue;
                }

                if (! isGroupbyMatchingIndex(matchingCase, null, groupbyExprs, null, indexedExprs, null)) {
                    continue;
                }

                if (isValidIndexCandidateForMinMax(indexedExprs.size(), groupbyExprs.size(), diffAllowance)) {
                    if (! isIndexOptimalForMinMax(matchingCase, minMaxAggExpr, null, indexedExprs, null)) {
                        continue;
                    }
                    indexOptimalForMinMax = true;
                }
            }

            // NOW index at least covered all group-by columns (sub-optimal candidate)
            if (!index.getPredicatejson().isEmpty()) {
                // Additional check for partial indexes to make sure matview WHERE clause
                // covers the partial index predicate
                List<AbstractExpression> coveringExprs = new ArrayList<>();
                List<AbstractExpression> exactMatchCoveringExprs = new ArrayList<>();
                try {
                    String encodedPredicate = matviewinfo.getPredicate();
                    if (!encodedPredicate.isEmpty()) {
                        String predicate = Encoder.hexDecodeToString(encodedPredicate);
                        AbstractExpression matViewPredicate = AbstractExpression.fromJSONString(predicate, tableScan);
                        coveringExprs.addAll(ExpressionUtil.uncombineAny(matViewPredicate));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    assert(false);
                    return null;
                }
                String predicatejson = index.getPredicatejson();
                if ( ! predicatejson.isEmpty() &&
                        ! SubPlanAssembler.isPartialIndexPredicateCovered(
                                tableScan, coveringExprs,
                                predicatejson, exactMatchCoveringExprs)) {
                    // the partial index predicate does not match the MatView's
                    // where clause -- give up on this index
                    continue;
                }
            }
            // if the index already covered group by columns and the aggCol/aggExpr,
            // it is already the best index we can get, return immediately.
            if (indexOptimalForMinMax) {
                return index;
            }
            // otherwise wait to see if we can find something better!
            candidate = index;
        }
        return candidate;
    }
1313284
function fixBrokenCode(text)
  {
    // make sure we ignore `&shy;` - which gets inserted
    // by the forum's code formatter
    text = text.replace(/\u00AD/g,'');
    // replace quotes that get auto-replaced by Google Docs and other editors
    text = text.replace(/[\u201c\u201d]/g,'"');
    text = text.replace(/[\u2018\u2019]/g,'\'');

    return text;
  }
261864
def fix_e713(self, result):
        """"""
        (line_index, offset, target) = get_index_offset_contents(result,
                                                                 self.source)

        # to convert once 'not in' -> 'in'
        before_target = target[:offset]
        target = target[offset:]
        match_notin = COMPARE_NEGATIVE_REGEX_THROUGH.search(target)
        notin_pos_start, notin_pos_end = 0, 0
        if match_notin:
            notin_pos_start = match_notin.start(1)
            notin_pos_end = match_notin.end()
            target = '{}{} {}'.format(
                target[:notin_pos_start], 'in', target[notin_pos_end:])

        # fix 'not in'
        match = COMPARE_NEGATIVE_REGEX.search(target)
        if match:
            if match.group(3) == 'in':
                pos_start = match.start(1)
                new_target = '{5}{0}{1} {2} {3} {4}'.format(
                    target[:pos_start], match.group(2), match.group(1),
                    match.group(3), target[match.end():], before_target)
                if match_notin:
                    # revert 'in' -> 'not in'
                    pos_start = notin_pos_start + offset
                    pos_end = notin_pos_end + offset - 4     # len('not ')
                    new_target = '{}{} {}'.format(
                        new_target[:pos_start], 'not in', new_target[pos_end:])
                self.source[line_index] = new_target
983415
function yy_r101(){
    $this->_retvalue = $this->yystack[$this->yyidx + -6]->minor.' ? '. $this->compileVariable("'".$this->yystack[$this->yyidx + -2]->minor."'") . ' : '.$this->yystack[$this->yyidx + 0]->minor;
    }
700783
def fix_e712(self, result):
        """"""
        (line_index, offset, target) = get_index_offset_contents(result,
                                                                 self.source)

        # Handle very easy "not" special cases.
        if re.match(r'^\s*if [\w."\'\[\]]+ == False:$', target):
            self.source[line_index] = re.sub(r'if ([\w."\'\[\]]+) == False:',
                                             r'if not \1:', target, count=1)
        elif re.match(r'^\s*if [\w."\'\[\]]+ != True:$', target):
            self.source[line_index] = re.sub(r'if ([\w."\'\[\]]+) != True:',
                                             r'if not \1:', target, count=1)
        else:
            right_offset = offset + 2
            if right_offset >= len(target):
                return []

            left = target[:offset].rstrip()
            center = target[offset:right_offset]
            right = target[right_offset:].lstrip()

            # Handle simple cases only.
            new_right = None
            if center.strip() == '==':
                if re.match(r'\bTrue\b', right):
                    new_right = re.sub(r'\bTrue\b *', '', right, count=1)
            elif center.strip() == '!=':
                if re.match(r'\bFalse\b', right):
                    new_right = re.sub(r'\bFalse\b *', '', right, count=1)

            if new_right is None:
                return []

            if new_right[0].isalnum():
                new_right = ' ' + new_right

            self.source[line_index] = left + new_right
571667
function yy_r105()
    {
        self::$prefix_number ++;
        if ($this->yystack[ $this->yyidx + - 2 ]->minor[ 'var' ] == '\'smarty\'') {
            $this->compiler->prefix_code[] = '<?php $_tmp' . self::$prefix_number . ' = ' .
                $this->compiler->compileTag('private_special_variable', array(),
                                            $this->yystack[ $this->yyidx + - 2 ]->minor[ 'smarty_internal_index' ]) .
                ';?>';
        } else {
            $this->compiler->prefix_code[] = '<?php $_tmp' . self::$prefix_number . ' = ' .
                $this->compiler->compileVariable($this->yystack[ $this->yyidx + - 2 ]->minor[ 'var' ]) .
                $this->yystack[ $this->yyidx + - 2 ]->minor[ 'smarty_internal_index' ] . ';?>';
        }
        $this->_retvalue = '$_tmp' . self::$prefix_number . '::' . $this->yystack[ $this->yyidx + 0 ]->minor[ 0 ] .
            $this->yystack[ $this->yyidx + 0 ]->minor[ 1 ];
    }
209821
function multMod_(x, y, n) {
  var i;
  if (s0.length!=2*x.length)
    s0=new Array(2*x.length);
  copyInt_(s0, 0);
  for (i=0; i<y.length; i++)
    if (y[i])
      linCombShift_(s0, x, y[i], i);   //s0=1*s0+y[i]*(x<<(i*bpe))
  mod_(s0, n);
  copy_(x, s0);
}
1314053
def fix_e401(self, result):
        """"""
        line_index = result['line'] - 1
        target = self.source[line_index]
        offset = result['column'] - 1

        if not target.lstrip().startswith('import'):
            return []

        indentation = re.split(pattern=r'\bimport\b',
                               string=target, maxsplit=1)[0]
        fixed = (target[:offset].rstrip('\t ,') + '\n' +
                 indentation + 'import ' + target[offset:].lstrip('\t ,'))
        self.source[line_index] = fixed
210066
function modifiedGramSchmidt (m) {
  const n = m.dimension;

  const v0 = m.getColumn(0);
  const u0 = v0;
  const v1 = m.getColumn(1);
  const u1 = v1.clone().sub(proj(u0, v1));
  if (n === 2) {
    m.setColumns(v0, v1);
    return;
  }
  const v2 = m.getColumn(2);
  const u2t = v2.clone().sub(proj(u0, v2));
  const u2 = u2t.sub(proj(u1, u2t));
  if (n === 3) {
    m.setColumns(u0, u1, u2);
    // return;
  }
}
601952
function yy_r40(){
    $this->_retvalue = '<?php ob_start();?>'.$this->compiler->compileTag($this->yystack[$this->yyidx + -2]->minor,$this->yystack[$this->yyidx + 0]->minor).'<?php echo ';
    $this->_retvalue .= $this->compiler->compileTag('private_modifier',array(),array('modifierlist'=>$this->yystack[$this->yyidx + -1]->minor,'value'=>'ob_get_clean()')).'?>';
    }
726909
private void fixN0c(BracketData bd, int openingIndex, int newPropPosition, byte newProp) {
        /* This function calls itself recursively */
        IsoRun pLastIsoRun = bd.isoRuns[bd.isoRunLast];
        Opening qOpening;
        int k, openingPosition, closingPosition;
        for (k = openingIndex+1; k < pLastIsoRun.limit; k++) {
            qOpening = bd.openings[k];
            if (qOpening.match >= 0)    /* not an N0c match */
                continue;
            if (newPropPosition < qOpening.contextPos)
                break;
            if (newPropPosition >= qOpening.position)
                continue;
            if (newProp == qOpening.contextDir)
                break;
            openingPosition = qOpening.position;
            dirProps[openingPosition] = newProp;
            closingPosition = -(qOpening.match);
            dirProps[closingPosition] = newProp;
            qOpening.match = 0;                                 /* prevent further changes */
            fixN0c(bd, k, openingPosition, newProp);
            fixN0c(bd, k, closingPosition, newProp);
        }
    }
620340
function yy_r175(){ 
    if ($this->yystack[$this->yyidx + 0]->minor instanceof Stmt\VariablePlaceholder) {
        $this->_retvalue = $this->yystack[$this->yyidx + 0]->minor;
    } else if (is_array($this->yystack[$this->yyidx + 0]->minor)) {
        $this->_retvalue = new Stmt\Expr('column', $this->yystack[$this->yyidx + 0]->minor[0], $this->yystack[$this->yyidx + 0]->minor[1]); 
    } else {
        $this->_retvalue = new Stmt\Expr('column', $this->yystack[$this->yyidx + 0]->minor);
    }
    }
22087
function yy_r155()
    {
        if ($this->security) {
            $this->compiler->trigger_template_error(self::Err2);
        }
        self::$prefix_number ++;
        $this->compiler->prefix_code[] = '<?php $_tmp' . self::$prefix_number . '=' .
            $this->compiler->compileVariable('\'' . substr($this->yystack[ $this->yyidx + - 3 ]->minor, 1) . '\'') .
            ';?>';
        $this->_retvalue =
            '$_tmp' . self::$prefix_number . '(' . implode(',', $this->yystack[ $this->yyidx + - 1 ]->minor) . ')';
    }
863632
function yy_r167(){
    $this->_retvalue = '$'.$this->yystack[$this->yyidx + -1]->minor.$this->yystack[$this->yyidx + 0]->minor;
    }
1152459
function yy_r127(){
    $this->_retvalue = '(is_array($tmp = $_smarty_tpl->getConfigVariable(\''. $this->yystack[$this->yyidx + -2]->minor .'\')) ? $tmp'.$this->yystack[$this->yyidx + 0]->minor.' :null)';
    }
988896
def fix_e712(self, result):
        """"""
        (line_index, offset, target) = get_index_offset_contents(result,
                                                                 self.source)

        # Handle very easy "not" special cases.
        if re.match(r'^\s*if [\w.]+ == False:$', target):
            self.source[line_index] = re.sub(r'if ([\w.]+) == False:',
                                             r'if not \1:', target, count=1)
        elif re.match(r'^\s*if [\w.]+ != True:$', target):
            self.source[line_index] = re.sub(r'if ([\w.]+) != True:',
                                             r'if not \1:', target, count=1)
        else:
            right_offset = offset + 2
            if right_offset >= len(target):
                return []

            left = target[:offset].rstrip()
            center = target[offset:right_offset]
            right = target[right_offset:].lstrip()

            # Handle simple cases only.
            new_right = None
            if center.strip() == '==':
                if re.match(r'\bTrue\b', right):
                    new_right = re.sub(r'\bTrue\b *', '', right, count=1)
            elif center.strip() == '!=':
                if re.match(r'\bFalse\b', right):
                    new_right = re.sub(r'\bFalse\b *', '', right, count=1)

            if new_right is None:
                return []

            if new_right[0].isalnum():
                new_right = ' ' + new_right

            self.source[line_index] = left + new_right
1151072
def fix_e251(self, result):
        """"""
        line_index = result['line'] - 1
        target = self.source[line_index]

        # This is necessary since pycodestyle sometimes reports columns that
        # goes past the end of the physical line. This happens in cases like,
        # foo(bar\n=None)
        c = min(result['column'] - 1,
                len(target) - 1)

        if target[c].strip():
            fixed = target
        else:
            fixed = target[:c].rstrip() + target[c:].lstrip()

        # There could be an escaped newline
        #
        #     def foo(a=\
        #             1)
        if fixed.endswith(('=\\\n', '=\\\r\n', '=\\\r')):
            self.source[line_index] = fixed.rstrip('\n\r \t\\')
            self.source[line_index + 1] = self.source[line_index + 1].lstrip()
            return [line_index + 1, line_index + 2]  # Line indexed at 1

        self.source[result['line'] - 1] = fixed