Add a window clause to be applied to downstream analytic expressions
357594
def over(self, window):
        
        return GroupedTableExpr(
            self.table,
            self.by,
            having=self._having,
            order_by=self._order_by,
            window=window,
        )
333191
public static void onLogicalExpression(Expression expression, EntityMetadata m, KunderaMetadata kunderaMetadata,
            KunderaQuery kunderaQuery)
    {
        if (expression instanceof OrExpression)
        {
            kunderaQuery.addFilterClause("(");
        }

        traverse(((LogicalExpression) expression).getLeftExpression(), m, kunderaMetadata, kunderaQuery, false);

        if (expression instanceof OrExpression)
        {
            kunderaQuery.addFilterClause(")");
        }

        kunderaQuery.addFilterClause(((LogicalExpression) expression).getIdentifier());

        if (expression instanceof OrExpression)
        {
            kunderaQuery.addFilterClause("(");
        }

        traverse(((LogicalExpression) expression).getRightExpression(), m, kunderaMetadata, kunderaQuery, false);

        if (expression instanceof OrExpression)
        {
            kunderaQuery.addFilterClause(")");
        }
    }
1068963
void addIndexCondition(Expression[] exprList, Index index, int colCount,
                           boolean isJoin) {
// VoltDB extension
        if (rangeIndex == index && isJoinIndex && (!isJoin) &&
                (multiColumnCount > 0) && (colCount == 0)) {
            // This is one particular set of conditions which broke the classification of
            // ON and WHERE clauses.
            return;
        }
// End of VoltDB extension
        rangeIndex  = index;
        isJoinIndex = isJoin;

        for (int i = 0; i < colCount; i++) {
            Expression e = exprList[i];

            indexEndCondition =
                ExpressionLogical.andExpressions(indexEndCondition, e);
        }

        if (colCount == 1) {
            indexCondition = exprList[0];
        } else {
            findFirstExpressions = exprList;
            isMultiFindFirst     = true;
            multiColumnCount     = colCount;
        }
    }
659031
private AbstractExpression parseWindowedAggregationExpression(VoltXMLElement exprNode) {
        int id = Integer.parseInt(exprNode.attributes.get("id"));
        String optypeName = exprNode.attributes.get("optype");
        ExpressionType optype = ExpressionType.get(optypeName);
        if (optype == ExpressionType.INVALID) {
            throw new PlanningErrorException("Undefined windowed function call " + optypeName);
        }

        // If this is not in the display column list, and the id is not the id of
        // the windowed expression, then this is an error.
        if (!m_parsingInDisplayColumns) {
            if (m_windowFunctionExpressions.size() > 0) {
                WindowFunctionExpression we = m_windowFunctionExpressions.get(0);
                if (we.getXMLID() == id) {
                    // This is the same as a windowed expression we saw in the
                    // display list.  This can happen if we see an alias for
                    // a display list element in the order by expressions.  If
                    // this happens we just want to return the TVE we squirreled
                    // away in the windowed expression.
                    return we.getDisplayListExpression();
                }
            }
            throw new PlanningErrorException("Windowed function call expressions can only appear in the selection list of a query or subquery.");
        }
        // Parse individual aggregate expressions
        List<AbstractExpression> partitionbyExprs = new ArrayList<>();
        List<AbstractExpression> orderbyExprs = new ArrayList<>();
        List<SortDirectionType>  orderbyDirs  = new ArrayList<>();
        List<AbstractExpression> aggParams    = new ArrayList<>();

        for (VoltXMLElement childEle : exprNode.children) {
            if (childEle.name.equals("winspec")) {
                for (VoltXMLElement ele : childEle.children) {
                    if (ele.name.equals("partitionbyList")) {
                        for (VoltXMLElement childNode : ele.children) {
                            AbstractExpression expr = parseExpressionNode(childNode);
                            if (expr.hasSubquerySubexpression()) {
                                throw new PlanningErrorException(
                                        "SQL window functions cannot be partitioned by subquery expression arguments.");
                            }
                            ExpressionUtil.finalizeValueTypes(expr);
                            partitionbyExprs.add(expr);
                        }
                    }
                    else if (ele.name.equals("orderbyList")) {
                        for (VoltXMLElement childNode : ele.children) {
                            SortDirectionType sortDir =
                                    Boolean.valueOf(childNode.attributes.get("descending")) ?
                                    SortDirectionType.DESC :
                                    SortDirectionType.ASC;

                            AbstractExpression expr = parseExpressionNode(childNode.children.get(0));
                            if (expr.hasSubquerySubexpression()) {
                                throw new PlanningErrorException(
                                        "SQL window functions cannot be ordered by subquery expression arguments.");
                            }
                            ExpressionUtil.finalizeValueTypes(expr);
                            orderbyExprs.add(expr);
                            orderbyDirs.add(sortDir);
                        }
                    }
                }
            }
            else {
                AbstractExpression aggParam = parseExpressionNode(childEle);
                if (aggParam != null) {
                    aggParam.finalizeValueTypes();
                    aggParams.add(aggParam);
                }
            }
        }

        String alias = WINDOWED_AGGREGATE_COLUMN_NAME;
        if (exprNode.attributes.containsKey("alias")) {
            alias = exprNode.attributes.get("alias");
        }
        WindowFunctionExpression rankExpr = new WindowFunctionExpression(optype,
                                                             partitionbyExprs,
                                                             orderbyExprs,
                                                             orderbyDirs,
                                                             aggParams,
                                                             id);
        ExpressionUtil.finalizeValueTypes(rankExpr);
        // Only offset 0 is useful.  But we keep the index anyway.
        int offset = m_windowFunctionExpressions.size();
        m_windowFunctionExpressions.add(rankExpr);
        TupleValueExpression tve = new TupleValueExpression(
                TEMP_TABLE_NAME, TEMP_TABLE_NAME,
                alias, alias,
                rankExpr, offset);
        // This tve does not ever need a differentiator.
        tve.setNeedsNoDifferentiation();
        rankExpr.setDisplayListExpression(tve);
        return tve;
    }
902994
def addExpression(self, datafields):
        
        self._expressionValueList.append(datafields)
        if len(self._expressionValueList) >= self._batchSize:
            self.batchAddExpression()
57847
public static <T extends Number> WindowOver<T> avg(Expression<T> expr) {
        return new WindowOver<T>(expr.getType(), Ops.AggOps.AVG_AGG, expr);
    }
668654
function executeExpression(expressionToExecute, callback) {
    var receivedData = "";
    var hadDataSinceTimeout = false;

    function getProcessInfo(expressionToExecute, callback) {
      var prevReader = Espruino.Core.Serial.startListening(function (readData) {
        var bufView = new Uint8Array(readData);
        for(var i = 0; i < bufView.length; i++) {
          receivedData += String.fromCharCode(bufView[i]);
        }
        // check if we got what we wanted
        var startProcess = receivedData.indexOf("< <<");
        var endProcess = receivedData.indexOf(">> >", startProcess);
        if(startProcess >= 0 && endProcess > 0){
          // All good - get the data!
          var result = receivedData.substring(startProcess + 4,endProcess);
          console.log("Got "+JSON.stringify(receivedData));
          // strip out the text we found
          receivedData = receivedData.substr(0,startProcess) + receivedData.substr(endProcess+4);
          // Now stop time timeout
          if (timeout) clearInterval(timeout);
          timeout = "cancelled";
          // Do the next stuff
          nextStep(result);
        } else if (startProcess >= 0) {
          // we got some data - so keep waiting...
          hadDataSinceTimeout = true;
        }
      });

      // when we're done...
      var nextStep = function(result) {
        // start the previous reader listing again
        Espruino.Core.Serial.startListening(prevReader);
        // forward the original text to the previous reader
        if(prevReader) prevReader(receivedData);
        // run the callback
        callback(result);
      };

      var timeout = undefined;
      // Don't Ctrl-C, as we've already got ourselves a prompt with Espruino.Core.Utils.getEspruinoPrompt
      Espruino.Core.Serial.write('\x10print("<","<<",JSON.stringify('+expressionToExecute+'),">>",">")\n',
                                 undefined, function() {
        // now it's sent, wait for data
        var maxTimeout = 10; // seconds - how long we wait if we're getting data
        var minTimeout = 2; // seconds - how long we wait if we're not getting data
        var pollInterval = 500; // milliseconds
        var timeoutSeconds = 0;
        if (timeout != "cancelled")
          timeout = setInterval(function onTimeout(){
          timeoutSeconds += pollInterval/1000;
          // if we're still getting data, keep waiting for up to 10 secs
          if (hadDataSinceTimeout && timeoutSeconds<maxTimeout) {
            hadDataSinceTimeout = false;
          } else if (timeoutSeconds > minTimeout) {
            // No data yet...
            // OR we keep getting data for > maxTimeout seconds
            clearInterval(timeout);
            console.warn("No result found for "+JSON.stringify(expressionToExecute)+" - just got "+JSON.stringify(receivedData));
            nextStep(undefined);
          }
        }, pollInterval);
      });
    }

    if(Espruino.Core.Serial.isConnected()){
      Espruino.Core.Utils.getEspruinoPrompt(function() {
        getProcessInfo(expressionToExecute, callback);
      });
    } else {
      console.error("executeExpression called when not connected!");
      callback(undefined);
    }
  }
644434
def visitAdditionOrSubtractionExpression(self, ctx):
        
        is_add = ctx.PLUS() is not None
        arg1 = self.visit(ctx.expression(0))
        arg2 = self.visit(ctx.expression(1))

        # first try as decimals
        try:
            _arg1 = conversions.to_decimal(arg1, self._eval_context)
            _arg2 = conversions.to_decimal(arg2, self._eval_context)
            return _arg1 + _arg2 if is_add else _arg1 - _arg2
        except EvaluationError:
            pass

        # then as date + something
        try:
            _arg1 = conversions.to_date_or_datetime(arg1, self._eval_context)

            if isinstance(arg2, datetime.time):
                # upgrade our date to datetime
                _arg1 = conversions.to_datetime(_arg1, self._eval_context)

                # convert time value to a duration
                _arg2 = datetime.timedelta(hours=arg2.hour, minutes=arg2.minute, seconds=arg2.second, microseconds=arg2.microsecond)
            else:
                _arg2 = datetime.timedelta(days=conversions.to_integer(arg2, self._eval_context))

            return _arg1 + _arg2 if is_add else _arg1 - _arg2

        except EvaluationError as ex:
            raise EvaluationError("Expression could not be evaluated as decimal or date arithmetic", ex)
12767
public static <T extends Number> WindowOver<T> varPop(Expression<T> expr) {
        return new WindowOver<T>(expr.getType(), SQLOps.VARPOP, expr);
    }
273075
function(expression) {
			var pastedExpression = new Expression();
			var key = this._getKey();

			pastedExpression.fromJson(json.parse(localStorage[key]));
			var newExpression;
			if (expression) {
				var expressionClone = new Expression({
					operator : 'and',
					expressionList : [expression, pastedExpression]
				}).toJson();
				//converting the same instance
				expression.fromJson(expressionClone);
				newExpression = expression;
			} else {
				newExpression = pastedExpression;
			}

			var parentBuilder = this.get('filterBuilder');

			parentBuilder.set('expression', newExpression, true /* preventChange Undo State
			 * */);
		}
886256
def add_clause(self, clause, no_return=True):
        

        if self.glucose:
            res = pysolvers.glucose3_add_cl(self.glucose, clause)

            if res == False:
                self.status = False

            if not no_return:
                return res
773909
function (clause) {
            var cond = argsToArray(arguments).slice(1), cb;
            if (cond.length && isFunction(cond[cond.length - 1])) {
                cb = cond.pop();
            }
            cond = cond.length === 1 ? cond[0] : cond;
            if ((cond == null || cond === undefined || cond === "") || (Array.isArray(cond) && cond.length === 0 && !cb) || (isObject(cond) && isEmpty(cond) && !cb)) {
                return this.mergeOptions();
            } else {
                cond = this._filterExpr(cond, cb);
                var cl = this.__opts[clause];
                cl && (cond = new BooleanExpression("AND", cl, cond));
                var opts = {};
                opts[clause] = cond;
                return this.mergeOptions(opts);
            }
        }
431205
private void translatePreconditionMacros(WyilFile.Decl.FunctionOrMethod declaration) {
		Tuple<WyilFile.Expr> invariants = declaration.getRequires();
		//
		for (int i = 0; i != invariants.size(); ++i) {
			// Construct fresh environment for this macro. This is necessary to
			// avoid name clashes with subsequent macros.
			GlobalEnvironment globalEnvironment = new GlobalEnvironment(declaration);
			LocalEnvironment localEnvironment = new LocalEnvironment(globalEnvironment);
			WyalFile.VariableDeclaration[] type = generatePreconditionParameters(declaration, localEnvironment);
			// Translate expression itself
			WyalFile.Stmt.Block clause = translateAsBlock(invariants.get(i), localEnvironment);
			// Capture any free variables. This is necessary to deal with any
			// variable aliases introduced by type test operators.
			clause = captureFreeVariables(declaration, globalEnvironment, clause);
			//
			Name ident = convert(declaration.getQualifiedName(), "_requires_" + i, declaration.getName());
			WyalFile.Declaration md = new WyalFile.Declaration.Named.Macro(ident, type, clause);
			allocate(md, invariants.get(i).getParent(WyilFile.Attribute.Span.class));
		}
	}
994495
private void fromWindow(PatternDescrBuilder<?> pattern) throws RecognitionException {
        String window = "";

        match(input,
                DRL6Lexer.ID,
                DroolsSoftKeywords.WINDOW,
                null,
                DroolsEditorType.KEYWORD);
        if (state.failed)
            return;

        Token id = match(input,
                DRL6Lexer.ID,
                null,
                null,
                DroolsEditorType.IDENTIFIER);
        if (state.failed)
            return;
        window = id.getText();

        if (state.backtracking == 0) {
            pattern.from().window(window);
            if (input.LA(1) != DRL6Lexer.EOF) {
                helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION);
            }
        }
    }
1204082
function(sel) {
  var filter = []
    , comb = combinators.noop
    , qname
    , cap
    , op
    , len;

  // add implicit universal selectors
  sel = sel.replace(/(^|\s)(:|\[|\.|#)/g, '$1*$2');

  while (cap = /\s*((?:\w+|\*)(?:[.#:][^\s]+|\[[^\]]+\])*)\s*$/.exec(sel)) {
    len = sel.length - cap[0].length;
    cap = cap[1].split(/(?=[\[:.#])/);
    if (!qname) qname = cap[0];
    filter.push(comb(parse(cap)));
    if (len) {
      op = sel[len - 1];
      // if the combinator doesn't exist, 
      // assume it was a whitespace.
      comb = combinators[op] || combinators[op = ' '];
      sel = sel.substring(0, op !== ' ' ? --len : len);
    } else {
      break;
    }
  }

  // compile to a single function
  filter = make(filter);

  // optimize the first qname
  filter.qname = qname;

  return filter;
}
817244
StatementDMQL compileCallStatement(RangeVariable[] outerRanges,
                                       boolean isStrictlyProcedure) {

        read();

        if (isIdentifier()) {
            checkValidCatalogName(token.namePrePrefix);

            RoutineSchema routineSchema =
                (RoutineSchema) database.schemaManager.findSchemaObject(
                    token.tokenString,
                    session.getSchemaName(token.namePrefix),
                    SchemaObject.PROCEDURE);

            if (routineSchema != null) {
                read();

                HsqlArrayList list = new HsqlArrayList();

                readThis(Tokens.OPENBRACKET);

                if (token.tokenType == Tokens.CLOSEBRACKET) {
                    read();
                } else {
                    while (true) {
                        Expression e = XreadValueExpression();

                        list.add(e);

                        if (token.tokenType == Tokens.COMMA) {
                            read();
                        } else {
                            readThis(Tokens.CLOSEBRACKET);

                            break;
                        }
                    }
                }

                Expression[] arguments = new Expression[list.size()];

                list.toArray(arguments);

                Routine routine =
                    routineSchema.getSpecificRoutine(arguments.length);
                HsqlList unresolved = null;

                for (int i = 0; i < arguments.length; i++) {
                    Expression e = arguments[i];

                    if (e.isParam()) {
                        e.setAttributesAsColumn(
                            routine.getParameter(i),
                            routine.getParameter(i).isWriteable());
                    } else {
                        int paramMode =
                            routine.getParameter(i).getParameterMode();

                        unresolved =
                            arguments[i].resolveColumnReferences(outerRanges,
                                unresolved);

                        if (paramMode
                                != SchemaObject.ParameterModes.PARAM_IN) {
                            if (e.getType() != OpTypes.VARIABLE) {
                                throw Error.error(ErrorCode.X_42603);
                            }
                        }
                    }
                }

                ExpressionColumn.checkColumnsResolved(unresolved);

                for (int i = 0; i < arguments.length; i++) {
                    arguments[i].resolveTypes(session, null);
                }

                StatementDMQL cs = new StatementProcedure(session, routine,
                    arguments, compileContext);

                return cs;
            }
        }

        if (isStrictlyProcedure) {
            throw Error.error(ErrorCode.X_42501, token.tokenString);
        }

        Expression expression = this.XreadValueExpression();
        HsqlList unresolved = expression.resolveColumnReferences(outerRanges,
            null);

        ExpressionColumn.checkColumnsResolved(unresolved);
        expression.resolveTypes(session, null);

//        expression.paramMode = PARAM_OUT;
        StatementDMQL cs = new StatementProcedure(session, expression,
            compileContext);

        return cs;
    }
1119985
def rewrite_binary_composition_inside_ternary_conditional(ir_blocks):
    """"""
    def visitor_fn(expression):
        """Expression visitor function."""
        # MATCH queries do not allow BinaryComposition inside a TernaryConditional's true/false
        # value blocks, since OrientDB cannot produce boolean values for comparisons inside them.
        # We transform any structures that resemble the following:
        #    TernaryConditional(predicate, X, Y), with X or Y of type BinaryComposition
        # into the following:
        # - if X is of type BinaryComposition, and Y is not,
        #    BinaryComposition(
        #        u'=',
        #        TernaryConditional(
        #            predicate,
        #            TernaryConditional(X, true, false),
        #            Y
        #        ),
        #        true
        #    )
        # - if Y is of type BinaryComposition, and X is not,
        #    BinaryComposition(
        #        u'=',
        #        TernaryConditional(
        #            predicate,
        #            X,
        #            TernaryConditional(Y, true, false),
        #        ),
        #        true
        #    )
        # - if both X and Y are of type BinaryComposition,
        #    BinaryComposition(
        #        u'=',
        #        TernaryConditional(
        #            predicate,
        #            TernaryConditional(X, true, false),
        #            TernaryConditional(Y, true, false)
        #        ),
        #        true
        #    )
        if not isinstance(expression, TernaryConditional):
            return expression

        if_true = expression.if_true
        if_false = expression.if_false

        true_branch_rewriting_necessary = isinstance(if_true, BinaryComposition)
        false_branch_rewriting_necessary = isinstance(if_false, BinaryComposition)

        if not (true_branch_rewriting_necessary or false_branch_rewriting_necessary):
            # No rewriting is necessary.
            return expression

        if true_branch_rewriting_necessary:
            if_true = TernaryConditional(if_true, TrueLiteral, FalseLiteral)

        if false_branch_rewriting_necessary:
            if_false = TernaryConditional(if_false, TrueLiteral, FalseLiteral)

        ternary = TernaryConditional(expression.predicate, if_true, if_false)
        return BinaryComposition(u'=', ternary, TrueLiteral)

    new_ir_blocks = [
        block.visit_and_update_expressions(visitor_fn)
        for block in ir_blocks
    ]

    return new_ir_blocks