/*
This function wraps WebPage.evaluate, and offers the possibility to pass
parameters into the webpage function. The PhantomJS issue is here:

http://code.google.com/p/phantomjs/issues/detail?id=132

This is from comment #43.
505611
function evaluate(page, func) {
    var args = [].slice.call(arguments, 2);
    var fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}";
    return page.evaluate(fn);
}
116230
public function evaluateWebPage() {
    try {
      $renderer = new PageRenderer($this->webPage, $this->uriVariables);
      $this->response = $renderer->evaluatePage();
      $this->rawRequestBody = $this->response->getResult();
    } catch (WebException $e) {
      // FIXME this is ugly
      $this->thrownWebException = $e;
      $this->rawRequestBody = $this->createRequestBodyFromException();
    } finally {
      $this->evaluated = true;
    }
  }
191432
public static Object evalNotNull(String tagName,
                                     String attributeName,
                                     String expression,
                                     Class expectedType,
                                     Tag tag,
                                     PageContext pageContext)
            throws JspException {
        if (expression != null) {
            Object r = ExpressionEvaluatorManager.evaluate(
                    attributeName, expression, expectedType, tag, pageContext);
            if (r == null) {
                throw new NullAttributeException(tagName, attributeName);
            }
            return r;
        } else {
            return null;
        }
    }
231336
function(param) {

			/**
			 * Reference the instance
			 */
			var rInstance = this;

			if (typeof param !== "undefined") {
				rInstance.text = param.text;
				rInstance.scopes = [].concat(param.scope);
			}


			/**
			 * The required regexp computed using delims in settings
			 * @type {RegExp}
			 */
			var re = new RegExp(['{%(.+?)%}|', this.delimStart, '(.+?)', this.delimEnd].join(''), 'g');

			/**
			 * Save the raw text
			 * @type {String}
			 */
			rInstance.raw = rInstance.text;

			/**
			 * Compute and assign to compiledText property of the same object
			 * @param  {String} _  Matched string
			 * @param  {String} $1 Content of first match group
			 * @param  {String} $2 Content of second match group
			 * @return {String}    Interpolated string
			 */

			rInstance.text = rInstance.text.replace(re, function(_, $1, $2) {
				var computed;

				/**
				 * If escaped value is found, interpolation will not happen
				 */
				if ($1) {
					computed = $1;
				}

				/**
				 * Matched content, let's interpolate
				 */
				if ($2) {

					/**
					 * Break out scope variables out of scope's box and evaluate the expr expression
					 */
					var scopeBox = function(expr, localScope) {
						var variables = '';

						/**
						 * If scope is a window object, no need to scopebox it
						 */
						if (typeof window !== "undefined" ? localScope !== window : true) {
							for(var i in localScope) {
								variables += 'var ' + i + ' = localScope.' + i + '; ';
							}
						}
						var unbox = '(function() { ' + variables + ' try { return eval(expr);} catch(e) {} })()';
						return eval(unbox);
					};

					if (rInstance.scopes.length) {
						var numScopes = rInstance.scopes.length;
						for (var i=0;i<numScopes;i++) {
							/**
							 * Current Scope
							 * @type {String}
							 */
							var scope = rInstance.scopes[i];

							/**
							 * Get the computation
							 * @type {Any}
							 */
							computed = scopeBox($2, scope);

							/**
							 * If the computed property is a function, execute it in the context of the current scope
							 * @type {Unknown}
							 */
							if (typeof computed === "function") {
								computed = computed.call(scope);
							}

							/**
							 * If the computed property is an object, get the string
							 */
							if (typeof computed === "object") {
								computed = computed.toString();
							}
								
							/**
							 * Found what we were looking for, now break the loop
							 */
							if (computed !== undefined)
								break;
						}
					} else {
						/**
						 * If no scope is passed, let us assume the global scope
						 * @type {Any}
						 */
						computed = scopeBox($2, (typeof window !== "undefined" ? window : {}));
					}

					/**
					 * If no computations were found, we return the raw matched value back
					 * @type {String}
					 */
					computed = computed !== undefined ? computed : _;
				}

				/**
				 * Final computed value returned
				 */
				return computed;
			});
			
			/**
			 * Return self for chaining
			 */
			return rInstance;
		}
623074
function (msg) {
            console.log("Runtime.evaluate");
            var result = eval(msg.params.expression);
            MessageBroker.respond(msg, {
                result: JSON.stringify(result) // TODO: in original protocol this is an object handle
            });
        }
952643
function evalModel(currentScope, scopeDefinition, partialModel, partialName) {
    if (!partialModel) { return; }

    var user = currentScope && currentScope.user;
    var activeUser = user ? {
        _id: user._id,
        name: user.username,
        role: user.role,
        user: user
    } : {};

    var opts = { dependencies: { currentScope: currentScope, activeUser: activeUser }};
    var me = this;

    // if its a function, then its our injection point
    if (_.isFunction(partialModel)) {
        updateScope(this.pancakes.cook(partialModel, opts), scopeDefinition, currentScope, partialName);
    }
    // else if its an object, we want to loop through the object values
    else if (_.isObject(partialModel)) {
        _.each(partialModel, function (partialModelVal, partialModelName) {

            // if the name is in the scope definition, throw error because it means we are trying to modify a parent scope value in the model
            if (scopeDefinition[partialModelName]) {
                throw new Error(partialName + 'mode() value ' + partialModelName + ' is from the parent scope and should not be modified in the mode().');
            }

            // any function in the object is an injection point
            if (_.isFunction(partialModelVal)) {
                updateScope(me.pancakes.cook(partialModelVal, opts), scopeDefinition, currentScope, partialName, partialModelName);
            }
            // else just set the value on the scope
            else {
                currentScope[partialModelName] = partialModelVal;
            }
        });
    }
    else {
        throw new Error(partialName + ' invalid model() format');
    }
}
1194727
func (p *WebPage) EvaluateJavaScript(script string) (interface{}, error) {
	var resp struct {
		ReturnValue interface{} `json:"returnValue"`
	}
	if err := p.ref.process.doJSON("POST", "/webpage/EvaluateJavaScript", map[string]interface{}{"ref": p.ref.id, "script": script}, &resp); err != nil {
		return nil, err
	}
	return resp.ReturnValue, nil
}
985765
public function evaluatePage() {
    if ($this->webPage == null) {
      throw new HttpNotFound();
    }

    $requestMethod = Server::getRequestMethod();
    $reflectionObject = new \ReflectionObject($this->webPage);

    if (!$reflectionObject->hasMethod($requestMethod)) {
      throw new HttpMethodNotAllowed();
    }

    $this->evaluatePermissions();

    // initialize the page
    $initializeParameters = $this->getParametersForMethod($reflectionObject->getMethod(self::INITIALIZE_FUNCTION));
    call_user_func_array([$this->webPage, self::INITIALIZE_FUNCTION], $initializeParameters);

    $renderParameters = $this->getParametersForMethod($reflectionObject->getMethod(self::FALLBACK_FUNCTION));
    try {
      $result = call_user_func_array([$this->webPage, self::FALLBACK_FUNCTION], $renderParameters);
      if (!($result instanceof Response)) {
        throw new HttpInternalServerError("The result of initialize has to be of type 'Response'");
      }
      return $result;
    } catch (HttpMethodNotAllowed $exc) {
      // empty on purpose (try render first, if its not overridden, fall through)
    }

    $requestMethodParameters = $this->getParametersForMethod($reflectionObject->getMethod($requestMethod));
    $result = call_user_func_array([$this->webPage, $requestMethod], $requestMethodParameters);
    if (!($result instanceof Response)) {
      throw new HttpInternalServerError("The result of $requestMethod has to be of type 'Response'");
    }
    return $result;
  }
307845
function createPagination(req) {
  return function createPagination(pages, page, liClass, anchorClass) {
    var params = qs.parse(url.parse(req.url).query);
    var str = '';

    params.page = 1;
    var clas = (page == 1 && 'active') || '';

    for (var p = 1; p <= pages; p++) {
      params.page = p;
      clas = (page == p && 'active') || '';

      var href = '?' + qs.stringify(params);

      str += `<li class="${liClass} ${clas}"><a class="${anchorClass}" href="${href}">${p}</a></li>`;
    }

    return str;
  };
}
3722
function (separator, page, args) {

        // By default, we return page name without arguments.
        var ret = page;
        if (typeof args !== 'undefined') {
            if (args && args.length) {
                // Some arguments have been provided, add them.
                if (args.length !== 0) {
                    ret = page + separator + args.join(separator);
                }
            } else {
                // Argument isn't an array, add it.
                ret = page + separator + args;
            }
        }
        return ret;
    }
1076067
function loadpage(path, vars, user, newvalue) {
  // __dirname = path.resolve(); // If in the REPL
  if(typeof vars != "object") vars = {};
  var serverFileContent = readServerFile();
  var env = {
      googleClientId: googleClientId,
      vars: vars,
      user: toLeoQuery(user || {}),
      defaultOptions: toLeoQuery(defaultOptions),
      path: path,
      fileOperations: [] };
  
  if(typeof newvalue == "undefined") {
    return [evaluateToHtml(path, env, serverFileContent), vars];
  } else { // We update the page and re-render it.
    var newVal = sns.nativeToVal(newvalue);
    console.log("Started to update...");
    var result = sns.objEnv.string.update(env)(serverFileContent)(newVal);
    console.log("Update finished (first solution)");
    if(result.ctor == "Ok") {
      var allSolutions = result._0;
      // Instead of iterating through all the solutions, just detect if there is an ambiguity.
      var solution = getOneSolution(path, serverFileContent, allSolutions);
      if(solution === false) {
        return [{ctor: "Err", _0: "Empty list of solutions"}];
      } else {
        console.log("Checking for ambiguities");
        var allSolutionsTail = sns.lazyList.tail(allSolutions);
        var solution2 = getOneSolution(path, serverFileContent, allSolutionsTail);
        if(solution2 === false) { // No ambiguity, we can immediately process the change.
          console.log("No ambiguity");
          return solution;
        } else {
          console.log("Ambiguity found");
          var solutionKey = uniqueKey();
          var cachedSolution = {
              timestamp: (+ new Date()),
              computed: [solution, solution2],
              remaining: allSolutionsTail,
              path: path,
              serverFileContent: serverFileContent
          }
          cachedSolutions[solutionKey] = cachedSolution;
          return solution.concat(solutionKey);
        }
      }
    } else return [result];
  }
}
1057770
function evalExpression(sourceUrl$$1, ctx, vars) {
    var /** @type {?} */ fnBody = ctx.toSource() + "\n//# sourceURL=" + sourceUrl$$1;
    var /** @type {?} */ fnArgNames = [];
    var /** @type {?} */ fnArgValues = [];
    for (var /** @type {?} */ argName in vars) {
        fnArgNames.push(argName);
        fnArgValues.push(vars[argName]);
    }
    if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["t" /* isDevMode */])()) {
        // using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise
        // E.g. ```
        // function anonymous(a,b,c
        // /**/) { ... }```
        // We don't want to hard code this fact, so we auto detect it via an empty function first.
        var /** @type {?} */ emptyFn = new (Function.bind.apply(Function, [void 0].concat(fnArgNames.concat('return null;'))))().toString();
        var /** @type {?} */ headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1;
        fnBody += "\n" + ctx.toSourceMapGenerator(sourceUrl$$1, sourceUrl$$1, headerLines).toJsComment();
    }
    return new (Function.bind.apply(Function, [void 0].concat(fnArgNames.concat(fnBody))))().apply(void 0, fnArgValues);
}
313187
@Override
	public void eval(String javascript) throws WidgetException {
		WebElement element = findElement(false);
		WebDriver wd = getGUIDriver().getWrappedDriver();
		try {
			((JavascriptExecutor) wd).executeScript(javascript, element);
		} catch (Exception e) {
			long time = System.currentTimeMillis() + 2000;
			boolean success = false;
			while (!success && System.currentTimeMillis() < time) {
				try {
					((JavascriptExecutor) wd).executeScript(javascript, element);
					success = true;
				} catch (Exception e2) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e1) {
						// Ignore
					}
					e = e2;
				}
			}

			if (!success) {
				throw new RuntimeException(e);
			}
		}
	}
60961
function PDFPageProxy_render(params) {
      var stats = this.stats;
      stats.time('Overall');

      // If there was a pending destroy cancel it so no cleanup happens during
      // this call to render.
      this.pendingDestroy = false;

      var renderingIntent = (params.intent === 'print' ? 'print' : 'display');

      if (!this.intentStates[renderingIntent]) {
        this.intentStates[renderingIntent] = {};
      }
      var intentState = this.intentStates[renderingIntent];

      // If there's no displayReadyCapability yet, then the operatorList
      // was never requested before. Make the request and create the promise.
      if (!intentState.displayReadyCapability) {
        intentState.receivingOperatorList = true;
        intentState.displayReadyCapability = createPromiseCapability();
        intentState.operatorList = {
          fnArray: [],
          argsArray: [],
          lastChunk: false
        };

        this.stats.time('Page Request');
        this.transport.messageHandler.send('RenderPageRequest', {
          pageIndex: this.pageNumber - 1,
          intent: renderingIntent
        });
      }

      var internalRenderTask = new InternalRenderTask(complete, params,
                                                      this.objs,
                                                      this.commonObjs,
                                                      intentState.operatorList,
                                                      this.pageNumber);
      internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
      if (!intentState.renderTasks) {
        intentState.renderTasks = [];
      }
      intentState.renderTasks.push(internalRenderTask);
      var renderTask = internalRenderTask.task;

      // Obsolete parameter support
      if (params.continueCallback) {
        renderTask.onContinue = params.continueCallback;
      }

      var self = this;
      intentState.displayReadyCapability.promise.then(
        function pageDisplayReadyPromise(transparency) {
          if (self.pendingDestroy) {
            complete();
            return;
          }
          stats.time('Rendering');
          internalRenderTask.initalizeGraphics(transparency);
          internalRenderTask.operatorListChanged();
        },
        function pageDisplayReadPromiseError(reason) {
          complete(reason);
        }
      );

      function complete(error) {
        var i = intentState.renderTasks.indexOf(internalRenderTask);
        if (i >= 0) {
          intentState.renderTasks.splice(i, 1);
        }

        if (self.cleanupAfterRender) {
          self.pendingDestroy = true;
        }
        self._tryDestroy();

        if (error) {
          internalRenderTask.capability.reject(error);
        } else {
          internalRenderTask.capability.resolve();
        }
        stats.timeEnd('Rendering');
        stats.timeEnd('Overall');
      }

      return renderTask;
    }
966390
@JavaScriptMethod
    public HttpResponse render() {
        return new HttpResponse() {
            public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
                try {
                    new DefaultScriptInvoker() {
                        @Override
                        protected JellyContext createContext(StaplerRequest req, StaplerResponse rsp, Script script, Object it) {
                            JellyContext context = super.createContext(req, rsp, script, it);
                            for (int i=bodyStack.length-1; i>0; i--) {// exclude bodyStack[0]
                                context = new JellyContext(context);
                                context.setVariable("org.apache.commons.jelly.body",bodyStack[i]);
                            }
                            try {
                                AdjunctsInPage.get().assumeIncluded(adjuncts);
                            } catch (IOException | SAXException e) {
                                LOGGER.log(Level.WARNING, "Failed to resurrect adjunct context",e);
                            }
                            return context;
                        }

                        @Override
                        protected void exportVariables(StaplerRequest req, StaplerResponse rsp, Script script, Object it, JellyContext context) {
                            super.exportVariables(req, rsp, script, it, context);
                            context.setVariables(variables);
                            req.setAttribute("currentDescriptorByNameUrl",currentDescriptorByNameUrl);
                        }
                    }.invokeScript(req,rsp,bodyStack[0],null);
                } catch (JellyTagException e) {
                    LOGGER.log(Level.WARNING, "Failed to evaluate the template closure", e);
                    throw new IOException("Failed to evaluate the template closure",e);
                }
            }
        };
    }
817883
function (vars, method) {
/*Line 73 - 'AtomEvaluator.js' */            var k = vars.join("-") + ":" + method;
/*Line 74 - 'AtomEvaluator.js' */            var e = this.ecache[k];
/*Line 75 - 'AtomEvaluator.js' */            if (e)
/*Line 76 - 'AtomEvaluator.js' */                return e;
    
/*Line 78 - 'AtomEvaluator.js' */            vars.push("Atom");
/*Line 79 - 'AtomEvaluator.js' */            vars.push("AtomPromise");
/*Line 80 - 'AtomEvaluator.js' */            vars.push("$x");
    
/*Line 82 - 'AtomEvaluator.js' */            e = new Function(vars,method);
/*Line 83 - 'AtomEvaluator.js' */            this.ecache[k] = e;
/*Line 84 - 'AtomEvaluator.js' */            return e;
/*Line 85 - 'AtomEvaluator.js' */        }
1153594
public Object evaluate(Object pContext,
                           VariableResolver pResolver,
                           Map functions,
                           String defaultPrefix,
                           Logger pLogger)
            throws ELException {
        return mValue;
    }