<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
  * This code is based on code org.apache.spark.repl.SparkILoop released under Apache 2.0"
  * Link on Github: https://github.com/apache/spark/blob/master/repl/scala-2.11/src/main/scala/org/apache/spark/repl/SparkILoop.scala
  * Author: <NAME>
  */
package ai.h2o.sparkling.repl

import ai.h2o.sparkling.utils.SparkSessionUtils
import org.apache.spark.SparkContext
import org.apache.spark.expose.Logging

import scala.Predef.{println => _}
import scala.annotation.tailrec
import scala.collection.mutable
import scala.language.{existentials, implicitConversions, postfixOps}
import scala.tools.nsc._
import scala.tools.nsc.interpreter.{Results => IR, _}

/**
  * H2O Interpreter which is use to interpret scala code. This class is base class for H2O Interpreter
  *
  * @param sparkContext spark context
  * @param sessionId    session ID for interpreter
  */
private[repl] abstract class BaseH2OInterpreter(val sparkContext: SparkContext, var sessionId: Int) extends Logging {
  private val valuesExtractor = new ValuesExtractor
  private val ContinueString = "     | "
  private val consoleStream = new IntpConsoleStream()
  protected val responseWriter = new IntpResponseWriter()
  private var replExecutionStatus = CodeResults.Success
  protected var settings: Settings = _
  protected var intp: H2OIMain = _
  private var in: InteractiveReader = _
  private[repl] var pendingThunks: List[() => Unit] = Nil

  def closeInterpreter() {
    if (intp ne null) {
      intp.reporter.flush()
    }
  }

  def extractValue(term: String): Option[Any] = {
    intp.beSilentDuring {
      intp.interpret(s"""_valuesExtractor.values.put("$term", $term)""")
    }
    valuesExtractor.values.get(term)
  }

  /**
    * Get response of interpreter
    *
    * @return
    */
  def interpreterResponse: String = {
    responseWriter.content
  }

  /**
    * Redirected printed output coming from commands written in the interpreter
    *
    * @return
    */
  def consoleOutput: String = {
    consoleStream.content
  }

  def valueOfTerm(term: String): Option[Any] = {
    intp.valueOfTerm(term)
  }

  /**
    * Run scala code in a string
    *
    * @param code Code to be compiled end executed
    * @return
    */
  def runCode(code: String): CodeResults.Value = BaseH2OInterpreter.savingContextClassloader {
    initBeforeRunningCode(code)
    // Redirect output from console to our own stream
    scala.Console.withOut(consoleStream) {
      try loop()
      catch AbstractOrMissingHandler()
    }

    if (exceptionOccurred()) {
      CodeResults.Exception
    } else {
      replExecutionStatus
    }
  }

  private def initializeInterpreter(): Unit = {
    settings = createSettings()
    intp = createInterpreter()
    val spark = SparkSessionUtils.active
    addThunk(intp.beQuietDuring {
      intp.bind("sc", "org.apache.spark.SparkContext", sparkContext, List("@transient"))
      intp.bind("spark", "org.apache.spark.sql.SparkSession", spark, List("@transient"))
      intp.bind("sqlContext", "org.apache.spark.sql.SQLContext", spark.sqlContext, List("@transient", "implicit"))
      intp.bind("_valuesExtractor", "ai.h2o.sparkling.repl.ValuesExtractor", valuesExtractor, List("@transient"))
      command("""
            @transient val h2oContext = {
              val _h2oContext = org.apache.spark.h2o.H2OContext.get().getOrElse(throw new RuntimeException(
              "H2OContext has to be started in order to use H2O REPL"))
              _h2oContext
            }
          """)

      command("import org.apache.spark.SparkContext._")
      command("import org.apache.spark.sql.{DataFrame, Row, SQLContext}")<commit_msg>[SW-2211] Use ensure method in BaseH2oInterpreter<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
  * This code is based on code org.apache.spark.repl.SparkILoop released under Apache 2.0"
  * Link on Github: https://github.com/apache/spark/blob/master/repl/scala-2.11/src/main/scala/org/apache/spark/repl/SparkILoop.scala
  * Author: <NAME>
  */
package ai.h2o.sparkling.repl

import ai.h2o.sparkling.utils.SparkSessionUtils
import org.apache.spark.SparkContext
import org.apache.spark.expose.Logging

import scala.Predef.{println => _}
import scala.annotation.tailrec
import scala.collection.mutable
import scala.language.{existentials, implicitConversions, postfixOps}
import scala.tools.nsc._
import scala.tools.nsc.interpreter.{Results => IR, _}

/**
  * H2O Interpreter which is use to interpret scala code. This class is base class for H2O Interpreter
  *
  * @param sparkContext spark context
  * @param sessionId    session ID for interpreter
  */
private[repl] abstract class BaseH2OInterpreter(val sparkContext: SparkContext, var sessionId: Int) extends Logging {
  private val valuesExtractor = new ValuesExtractor
  private val ContinueString = "     | "
  private val consoleStream = new IntpConsoleStream()
  protected val responseWriter = new IntpResponseWriter()
  private var replExecutionStatus = CodeResults.Success
  protected var settings: Settings = _
  protected var intp: H2OIMain = _
  private var in: InteractiveReader = _
  private[repl] var pendingThunks: List[() => Unit] = Nil

  def closeInterpreter() {
    if (intp ne null) {
      intp.reporter.flush()
    }
  }

  def extractValue(term: String): Option[Any] = {
    intp.beSilentDuring {
      intp.interpret(s"""_valuesExtractor.values.put("$term", $term)""")
    }
    valuesExtractor.values.get(term)
  }

  /**
    * Get response of interpreter
    *
    * @return
    */
  def interpreterResponse: String = {
    responseWriter.content
  }

  /**
    * Redirected printed output coming from commands written in the interpreter
    *
    * @return
    */
  def consoleOutput: String = {
    consoleStream.content
  }

  def valueOfTerm(term: String): Option[Any] = {
    intp.valueOfTerm(term)
  }

  /**
    * Run scala code in a string
    *
    * @param code Code to be compiled end executed
    * @return
    */
  def runCode(code: String): CodeResults.Value = BaseH2OInterpreter.savingContextClassloader {
    initBeforeRunningCode(code)
    // Redirect output from console to our own stream
    scala.Console.withOut(consoleStream) {
      try loop()
      catch AbstractOrMissingHandler()
    }

    if (exceptionOccurred()) {
      CodeResults.Exception
    } else {
      replExecutionStatus
    }
  }

  private def initializeInterpreter(): Unit = {
    settings = createSettings()
    intp = createInterpreter()
    val spark = SparkSessionUtils.active
    addThunk(intp.beQuietDuring {
      intp.bind("sc", "org.apache.spark.SparkContext", sparkContext, List("@transient"))
      intp.bind("spark", "org.apache.spark.sql.SparkSession", spark, List("@transient"))
      intp.bind("sqlContext", "org.apache.spark.sql.SQLContext", spark.sqlContext, List("@transient", "implicit"))
      intp.bind("_valuesExtractor", "ai.h2o.sparkling.repl.ValuesExtractor", valuesExtractor, List("@transient"))
      command(
        """
            @transient val h2oContext = {
              val _h2oContext = org.apache.spark.h2o.H2OContext.ensure("H2OContext has to be started in order to use H2O REPL")
              _h2oContext
            }
          """)

      command("import org.apache.spark.SparkContext._")
      command("import org.apache.spark.sql.{DataFrame, Row, SQLContext}")
{'fraction_non_alphanumeric': 0.1008648770077502, 'fraction_numerical': 0.00595304953386499, 'mean_word_length': 3.4743718592964825, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 11, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3140300', 'n_tokens_mistral': 2693, 'n_tokens_neox': 2617, 'n_words': 741}