Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

280
LINES

< > BotCompany Repo | #1003684 // "Random" v5 (with "quick scores")

JavaX source code [tags: use-pretranspiled] - run with: x30.jar

Libraryless. Click here for Pure Java version (4205L/29K/102K).

!759

static JTable table;
static JTextArea chat;
static JTextField input;
static File logFile;
static new L<S> log;
static L<S> recommendations;

static int listDelay = 2000, listMakingTimeout = 2000;
static int maxListLength = 100;

static Bool thinking;
static bool updateOnce = true;
static new Thinker thinker;

static S systemPrefix = "[system]";

p-awt {
  //substanceLAF("EmeraldDusk"); // Too dark!
  substanceLAF("ChallengerDeep");
  loadLog();

  thinker.startUp(log);
  
  table = tableWithTooltips();
  chat = autoScroll(wordWrapTextArea());
  chat.setText(joinLines(log));
  input = new JTextField;
  JFrame frame = showFrame(vgrid(centerAndSouth(chat, input), table));
  //setFrameIconLater(frame, "#1003593");
  
  onEnter(input, r {
    post();
  });
  
  onDoubleClick(table, voidfunc(int row) {
    chooseSuggestion(row);
  });
  
  for (int i = 1; i <= 12; i++) {
    final int _i = i;
    registerFunctionKey(frame, i, r {
      chooseSuggestion(_i-1);
    });
  }
  
  fillList();
  
  input.requestFocus();
}

static S getInput() {
  ret joinLines(" # ", input.getText().trim());
}

static void post() {
  S i = getInput();
  if (inputAllowedByUser(i))
    post(i);
}

svoid chooseSuggestion(int row) {
  L<S> line = getTableLine(table, row);
  if (line == null) ret;
  S s = line.get(0);
  if (empty(s)) ret;
  input.setText(s);
  post();
}

static bool inputAllowedByUser(S i) {
  ret !swic(i, systemPrefix);
}

static void postSystemMessage(S msg) {
  post(systemPrefix + " " + msg);
}

static void post(S i) {
  S s = i + "\n";
  chat.append(s);
  appendToFile(logFile, "[" + chatTime() + "] " + s);
  synchronized(mc()) {
    log.add(i);
  }
  input.selectAll();
  updateOnce = true;
  action(i);
}

static void action(S s) {
  if (!s.startsWith("!")) ret;
  s = dropPrefix("!", s);
  new Matches m;
  if "start program *" {
    S progID = m.fsi(0);
    S title = getSnippetTitle(progID);
    // TODO: Show author!
    S msg = "Run program " + progID + " - " + title + "?";
    if (confirmOKCancel(chat, msg)) {
      postSystemMessage("Starting program " + progID + " - " + quote(title));
      nohupJavax(progID);
    } else
      postSystemMessage("Program start cancelled by user (was: " + progID + ")");
  }
}

static void fillList() {
  bool t = shouldUpdateList() || updateOnce;
  updateOnce = false;
  if (neq(t, thinking)) {
    thinking = t;
    setFrameIcon(table, t ? "#1003603" : "#1003593");
  }
  
  if (!t)
    againl8r();
  else thread "Fill List" {
    final new L<S> data;
    thinker.makeListData(data);
    
    dataToTable_uneditable(table, data);
    againl8r();
  }
}

static void againl8r() {
  swingAfter(table, listDelay, r { fillList(); });
}

static bool shouldUpdateList() {
  ret getFrame(table).isFocused()
    && !mouseInComponent(table);
}

// also called from outside
static L<S> loadLog() {
  if (logFile == null)
    logFile = getProgramFile("log.txt");
  for (S s : toLines(loadTextFile(logFile))) pcall {
    log.add(substring(s, s.indexOf(']')+1).trim());
  }
  ret log;
}

!include #1003606 // GenTesting

sclass Thinker {
  new MultiSet<S> scores;
  new MultiSet<S> quickScores;
  int quickAnalysisDepth = 100;
  int logLengthSeen;
  
  void startUp(L<S> log) {
    final L<S> _log = cloneList(log); // Clone to be safe
    
    thread "Full Scoring!" {
      scores = makeGT().scoreGenerators(_log);
    }
  }
  
  GenTesting makeGT() {
    ret new GenTesting(voidfunc(L<Gen> gens, L<S> log) { makeGenerators(gens, log); });
  }
  
  void updateQuickScores() {
    if (l(log) > logLengthSeen) {
      logLengthSeen = l(log);
      quickScores = makeGT().scoreGenerators(getLastFromLog(quickAnalysisDepth));
    }
  }

  // also called from outside
  void recommendSolver(S solverID) {
    if (!isRecommendedSolver(solverID = fsi(solverID))) {
      print("Adding recommended solver: " + solverID);
      logQuoted("recommendations.txt", solverID);
    } else
      print("Solver already recommended: " + solverID);
  }
  
  bool isRecommendedSolver(S solverID) {
    ret contains(scanLog("recommendations.txt"), fsI(solverID));
  }
  
  // Scoring formula!
  int formula(S genName) {
    ret quickScores.get(genName)+scores.get(genName);
  }
  
  L<Gen> sortGenerators(L<Gen> gens, final MultiSet<S> scores) {
    ret sortedList(gens, func(Gen a, Gen b) {
      formula(b.name)-formula(a.name)
    });
  }

  void makeListData(L l) {
    try {
      updateQuickScores();
      new L<Gen> gens;
      makeGenerators(gens, log);
      gens = sortGenerators(gens, scores);
      if (empty(gens)) {
        l.add(ll("No generators"));
        ret;
      }
      
      long timeout = now() + listMakingTimeout;
      int i = -1;
      new HashSet<S> seen;
      while (now() < timeout && l(l) < maxListLength && nempty(gens)) {
        i = (i+1) % l(gens);
        Gen gen = gens.get(i);
        try {
          S s = cast callF(gen.func);
          if (empty(s) || seen.contains(s))
            gens.remove(i);
          else {
            seen.add(s);
            int k = l(l)+1;
            S key = k <= 12 ? "F" + k : null;
            l.add(litorderedmap("Suggestion", s, "Suggester", gen.name, "Key", key));
          }
        } catch {
          gens.remove(i);
        }
      }
    } catch e {
      printStackTrace(e);
      l.add(e.toString());
    }
  }
}

// CREATIVE PART!

// put func {}'s returning a string in there
static void makeGenerators(L<Gen> l, final L<S> log) {
  gen(l, "hello random", func { "Hello " + randomID(10) });
  gen(l, quine(func { last(log) }));
  gen(l, quine(func { oneOf(log) }));
  gen(l, "1 assoc", oneAssoc(log));
  gen(l, "most popular", mostPopular(log));
  addLoadedSolvers(l);
}

svoid addLoadedSolvers(L<Gen> l) {
  if (recommendations == null) { 
    recommendations = new L;
    for (S s : scanLog("recommendations.txt"))
      if (isSnippetID(s))
        recommendations.add(s);
  }
    
  for (final S solverID : recommendations)
    gen(l, solverID, func {
      O c = hotwireCached(solverID);
      ret call(c, "calc", log);
    });
}

static O oneAssoc(final L<S> log) {
  ret func {
    for (int i = l(log)-2; i >= 0; i--)
      if (eqic(log.get(i), last(log)))
        ret log.get(i+1);
    null;
  };
}

static O mostPopular(final L<S> log) {
  ret func {
    ret new MultiHashSet<S>(log).getMostPopularEntry();
  };
}

synchronized static L<S> getLastFromLog(int n) {
  ret cloneList(getLast(log, n));
}

Author comment

Began life as a copy of #1003678

download  show line numbers  debug dex  old transpilations   

Travelled to 15 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1003684
Snippet name: "Random" v5 (with "quick scores")
Eternal ID of this version: #1003684/1
Text MD5: 5861b7c6e426c9e20e178aac1e3a53a7
Transpilation MD5: ab1af3bb49220884da1cfb3deb39c5b5
Author: stefan
Category: javax / talking robots
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-07-25 21:41:20
Source code size: 6711 bytes / 280 lines
Pitched / IR pitched: No / No
Views / Downloads: 520 / 631
Referenced in: #1003695 - "Random" v6 (with !hotwire)