<commit_before>require 'open3'

class Asp::Solver
  attr_reader :models

  GROUNDER    = "gringo"
  SOLVER      = "clasp"
  SOLVER_OPTS = ["0", "--outf=2","--quiet=0","--verbose=0"]

  def initialize
    @models = []
  end

  def solve(problem)

    # TODO: try not to use Tempfile
    t = Tempfile.new("asp_solving_temp")
    begin
      t.write(problem)
      t.rewind
      cmd = "#{GROUNDER} #{t.path}"


      stdout_str, stderr_str, status = Open3.capture3(cmd)
      status.success? or return

      Open3.pipeline_r(["echo", stdout_str], [SOLVER, *SOLVER_OPTS]) do |stdout, wait_thr|
        json = JSON.parse(stdout.read)
        witnesses = json["Call"][0]["Witnesses"]
        witnesses.each do |w|
          @models << Asp::Model.new(w)
        end
      end
    ensure
    t.close
    t.unlink
    end
  end


end<commit_msg>refactoring to avoid echo piping<commit_after>require 'open3'

class Asp::Solver
  attr_reader :models

  GROUNDER    = "gringo"
  SOLVER      = "clasp"
  SOLVER_OPTS = ["0", "--outf=2","--quiet=0","--verbose=0"]

  def initialize
    @models = []
  end

  def solve(problem)

    # TODO: try not to use Tempfile
    t = Tempfile.new("asp_solving_temp")
    begin
      t.write(problem)
      t.rewind
      cmd = "#{GROUNDER} #{t.path}"

      grounded_program, stderr_str, status = Open3.capture3(cmd)
      status.success? or return

      Open3.popen3(SOLVER, *SOLVER_OPTS) do |stdin, stdout, stderr, wait_thr|
        stdin.puts grounded_program
        stdin.close
        json = JSON.parse(stdout.read)
        witnesses = json["Call"][0]["Witnesses"]
        witnesses.each do |w|
          @models << Asp::Model.new(w)
        end
      end
    ensure
    t.close
    t.unlink
    end
    true
  end


end
{'fraction_non_alphanumeric': 0.1324200913242009, 'fraction_numerical': 0.010844748858447488, 'mean_word_length': 2.384169884169884, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '4522246', 'n_tokens_mistral': 663, 'n_tokens_neox': 624, 'n_words': 135}