Warning : session_start(): open(/var/lib/php/sessions/sess_3qr1ks9ho2qllnkvkjbkd0lnlg, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.fail;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import static x30_pkg.x30_util.asList;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.IConceptIndex;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.Derefable;
import loadableUtils.utils.ImageSurfaceSelector;
import loadableUtils.utils.SimpleCRUD;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import loadableUtils.utils.DynImageSurface;
import loadableUtils.utils.DynCalculatedList;
import java.text.NumberFormat;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.nio.file.Files;
import java.nio.file.Path;
class main {
public static class Interpretable {
public String text;
public String ruleID;
public Interpretable() {
}
public Interpretable(String text, String ruleID) {
this.ruleID = ruleID;
this.text = text;
}
}
public static class Entry {
public long msgID;
public String originalLine;
public String interpretableText;
public String ruleID;
public static String _fieldOrder = "msgID originalLine interpretableText";
}
public static boolean _moduleClass_InterpretableTest;
public static class InterpretableTest extends DynObjectTable {
public void start() {
super.start();
addCountToName();
startThread(new Runnable() {
public void run() {
try {
scan();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "scan();";
}
});
}
public JComponent visualize() {
return withCenteredButtons(super.visualize(), "Scan", runnableThread(new Runnable() {
public void run() {
try {
scan();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "scan();";
}
}));
}
public void scan() {
AutoCloseable __6 = enter();
try {
List list = new ArrayList();
Flag interrupted = new Flag();
AutoCloseable action = dm_currentAction("Scanning chat", rRaiseFlag(interrupted));
try {
F0 contextMaker = new GazelleContextCache_v2().fill();
List lines = dm_discord_allLines();
int i = 0;
for (GazelleLine line : reversed(lines)) {
++i;
if (!licensed() || interrupted.get())
break;
Collection l = getInterpretables(line, "contextMaker", contextMaker);
for (Interpretable intp : l) list.add(nu(Entry.class, "originalLine", line.text, "msgID", line.msgID, "interpretableText", intp.text, "ruleID", intp.ruleID));
call(action, "setText", "Found " + n2(list, "interpretable") + ", scanned " + i + "/" + n2(lines, "line"));
}
setList(list);
} finally {
_close(action);
}
} finally {
_close(__6);
}
}
public Collection getInterpretables(GazelleLine line, Object... __) {
Set texts = litCISet(line.text);
List interpretables = new ArrayList();
RuleEngine2 engine = ((F0) optPar("contextMaker", __)).get().engine;
for (RuleEngine2.SimplifyWithRule rule : engine.splitterRules()) {
try {
for (String out : gazelle_executeSplitterRule(engine, rule, line.text)) if (texts.add(out))
interpretables.add(new Interpretable(out, rule.globalID));
} catch (Throwable __e) {
_handleException(__e);
}
}
for (GazelleTree t : dm_gazelle_reasonAboutChatInput_v2(null, line.text, paramsPlus(__, "skipSplitters", true, "acceptablePurposes", litset("preprocess")))) if (texts.add(t.line))
interpretables.add(new Interpretable(t.line, t.ruleID()));
return interpretables;
}
}
public static Object callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
return x30_util.callF(f, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A callF(F0 f) {
return f == null ? null : f.get();
}
public static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
public static C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
public static void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
public static Object callMC(String method, Object... args) {
return call(mc(), method, args);
}
public static Object call(Object o) {
return callF(o);
}
public static Object call(Object o, String method, Object... args) {
return x30_util.call(o, method, args);
}
public static void _onLoad_initUtils() {
utils.__javax = javax();
}
public static void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
public Class get(String name) {
try {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (startsWith(name, "main$"))
return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + substring(name, 4));
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Class c = findClass_fullName(name);\r\n if (c != null) ret c;\r\n if (start...";
}
});
}
public static String programID() {
return getProgramID();
}
public static String programID(Object o) {
return getProgramID(o);
}
public static volatile StringBuffer local_log = new StringBuffer();
public static volatile Appendable print_log = local_log;
public static volatile int print_log_max = 1024 * 1024;
public static volatile int local_log_max = 100 * 1024;
public static boolean print_silent;
public static Object print_byThread_lock = new Object();
public static volatile ThreadLocal print_byThread;
public static volatile Object print_allThreads;
public static void print() {
print("");
}
public static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
public static A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
public static void print_noNewLine(String s) {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
print_raw(s);
}
public static void print_raw(String s) {
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
public static Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
public static Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
public static Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
public static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
public static JPanel withCenteredButtons(JComponent center, Object... params) {
return centerAndSouth(center, withMargin(jcenteredbuttons(params)));
}
public static Runnable runnableThread(final Runnable r) {
return new Runnable() {
public void run() {
try {
startThread(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startThread(r)";
}
};
}
public static AutoCloseable dm_currentAction(String text, Runnable cancelMe) {
return (AutoCloseable) dm_callModule(dm_makeOrShowModule("#1019874/CurrentAction"), "showAction", text, cancelMe);
}
public static Runnable rRaiseFlag(final Flag flag) {
return flag == null ? null : new Runnable() {
public void run() {
try {
flag.raise();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "flag.raise()";
}
};
}
public static List dm_discord_allLines() {
return map("dm_discord_importLine", (List) dm_call(dm_gazelle_linesCRUD(), "concepts"));
}
public static List reversed(Collection l) {
return reversedList(l);
}
public static List reversed(A[] l) {
return reversedList(asList(l));
}
public static String reversed(String s) {
return reversedString(s);
}
public static volatile boolean licensed_yes = true;
public static boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
public static void licensed_off() {
licensed_yes = false;
}
public static A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
public static String n2(long l) {
return formatWithThousands(l);
}
public static String n2(Collection l) {
return n2(l(l));
}
public static String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
public static String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
public static String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
public static String n2(Collection l, String singular) {
return n2(l(l), singular);
}
public static String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
public static String n2(Map m, String singular) {
return n2(l(m), singular);
}
public static String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
public static String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
public static String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
public static void _close(AutoCloseable c) {
if (c != null)
try {
c.close();
} catch (Throwable e) {
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else
throw rethrow(e);
}
}
public static TreeSet litCISet(String... items) {
return litciset(items);
}
public static A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
public static A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
public static Object optPar(Object[] params, String name) {
return optParam(params, name);
}
public static Object optPar(String name, Object[] params) {
return optParam(params, name);
}
public static A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
public static A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
public static Collection gazelle_executeSplitterRule(RuleEngine2 engine, RuleEngine2.SimplifyWithRule rule, String input) {
Object f = rule.function();
Collection out = (Collection) ((f instanceof String ? callF(engine.callFunctionOnString, (String) f, input) : callF(f, input)));
return out;
}
public static volatile PersistableThrowable _handleException_lastException;
public static List _handleException_onException = synchroList(ll("printStackTrace2"));
public static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3);
}
}
public static List dm_gazelle_reasonAboutChatInput_v2(String userName, String content, Object... __) {
boolean debug = boolPar("debug", __);
List preContext = (List) (optPar("preContext", __));
GazelleEvalContext ctx = (GazelleEvalContext) (optPar("ctx", __));
F0 contextMaker = (F0) (optPar("contextMaker", __));
if (ctx == null && contextMaker != null)
ctx = contextMaker.get();
if (ctx == null)
ctx = dm_gazelle_stdEvalContext(dm_gazelle_allRulesWithComment(optPar("requiredComment", __, "discord")));
Set acceptablePurposes = (Set) (optPar("acceptablePurposes", __));
if (debug)
print(" == PROCESSING INPUT: " + content);
ctx.engine.dropRulesWhere(r -> cicOneOf(r.comments, "in 1 = statement", "in = statement", "disable"));
if (acceptablePurposes != null) {
if (debug)
print("Purposes: " + acceptablePurposes);
ctx.engine.dropRulesWhere(r -> !acceptablePurposes.contains(unnull(r.purpose)));
if (debug)
print("Retaining " + n2(ctx.engine.rules, "rule"));
}
if (debug)
print("Have rules: " + collect("globalID", ctx.engine.rules));
gazelle_addHelpers(ctx, __);
Object[] params = litparams("firstConditionOnly", true, "dialogHistory", preContext, "debug", debug, "badComments", optPar("badComments", __), "acceptablePurposes", optPar("acceptablePurposes", __), "respondingToHuman", optPar("respondingToHuman", __), "skipSplitters", optPar("skipSplitters", __));
GazelleTree tree1 = (GazelleTree) (optPar("tree", __));
if (tree1 == null)
tree1 = new GazelleTree(ctx, content);
List l = dm_gazelle_getChildren(tree1, params);
Map inputMap = gazelle_inputMapFromLineAndHistory(content, listPlus(preContext, content));
if (debug)
print("reasonAbout inputMap=" + sfu(asTreeMap(inputMap)));
dm_gazelle_matchAdditionalInput3(l, inputMap, __);
if (nempty(userName) && !boolPar("skipUserName", __)) {
GazelleTree tree2 = new GazelleTree(ctx, optCurly(userName) + " says: " + content);
if (debug)
print("Tree2: " + tree2);
l.addAll(dm_gazelle_getChildren(tree2, paramsPlus(__, "tree2", true)));
}
Long userID = (Long) (optPar("userID", __));
if (userID != null && userID != 0 && !boolPar("skipUserID", __)) {
GazelleTree tree3 = new GazelleTree(ctx, "user with id " + userID + " says: " + content);
l.addAll(dm_gazelle_getChildren(tree3, paramsPlus(__, "tree3", true)));
}
if (boolPar("skipBad", __, true))
l = filter(l, new F1() {
public Boolean get(GazelleTree t) {
try {
return neq(t.prediction, "bad");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "neq(t.prediction, \"bad\")";
}
});
gazelle_sortChildren(l);
dm_gazelle_matchStatements_v2(l, passParams(__, "debug", "dm_gazelle_matchStatementsDebug"));
for (GazelleTree t : l) t.flush();
int n = l(l);
l = gazelle_dropUnsatisfiedEntries(l);
if (debug)
print("Filtered out " + (n - l(l)) + " unsatisfied entries (keeping " + l(l) + ")");
gazelle_dropMatchedDefaultRules(l);
return l;
}
public static Object[] paramsPlus(Object[] a1, Object... a2) {
if (a2 == null || l(a2) == 2 && a2[0] == null)
return a1;
if (a1 == null)
return a2;
assertEvenLength(a1);
assertEvenLength(a2);
Map map = paramsToOrderedMap(a1);
int n = l(a2);
for (int i = 0; i < n; i += 2) {
Object key = a2[i];
if (key != null)
map.put(key, a2[i + 1]);
}
return mapToParams(map);
}
public static HashSet litset(A... items) {
return lithashset(items);
}
public static Class mc() {
return main.class;
}
public static Class javax() {
return getJavaX();
}
public static void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
public static HashMap findClass_fullName_cache = new HashMap();
public static Class findClass_fullName(String name) {
synchronized (findClass_fullName_cache) {
if (findClass_fullName_cache.containsKey(name))
return findClass_fullName_cache.get(name);
Class c;
try {
c = Class.forName(name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_fullName_cache.put(name, c);
return c;
}
}
public static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
public static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
public static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
m.m = new String[] { substring(a, strL(b)) };
return true;
}
public static boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
public static String substring(String s, int x) {
return substring(s, x, strL(s));
}
public static String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
if (x >= s.length())
return "";
if (y < x)
y = x;
if (y > s.length())
y = s.length();
return s.substring(x, y);
}
public static List splitAtEllipsis(String s) {
return splitAtTokens(javaTokWithBrackets(s), ".", "", ".", "", ".");
}
public static Throwable printStackTrace2(Throwable e) {
print(getStackTrace2(e));
return e;
}
public static void printStackTrace2() {
printStackTrace2(new Throwable());
}
public static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
public static Object _defaultClassFinder_value;
public static Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
public static String programID;
public static String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
public static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
public static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
public static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
public static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
public static Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
public static A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
public static ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
public static boolean isFalse(Object o) {
return eq(false, o);
}
public static String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0)
return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i + 1 < l && s.charAt(i + 1) == '\n')
++i;
}
}
return out.toString();
}
public static void print_append(Appendable _buf, String s, int max) {
try {
synchronized (_buf) {
_buf.append(s);
if (!(_buf instanceof StringBuilder))
return;
StringBuilder buf = (StringBuilder) _buf;
max /= 2;
if (buf.length() > max)
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String defaultThreadName_name;
public static String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
public static Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
public static Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
public static Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
public static Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
public static Runnable toRunnable(final Object o) {
if (o instanceof Runnable)
return (Runnable) o;
return new Runnable() {
public void run() {
try {
callF(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(o)";
}
};
}
public static Map _registerThread_threads;
public static Object _onRegisterThread;
public static Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
public static void _registerThread() {
_registerThread(Thread.currentThread());
}
public static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
public static JPanel centerAndSouth(final Component c, final Component s) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
if (s != null)
panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT...";
}
});
}
public static int withMargin_defaultWidth = 6;
public static JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
public static JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
public static JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
public static JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static JPanel jcenteredbuttons(Object... params) {
List l = new ArrayList();
for (int i = 0; i < l(params); i += 2) if (params[i] != null)
if (params[i] instanceof JComponent)
l.add((JComponent) params[i--]);
else
l.add(jbutton((String) params[i], params[i + 1]));
return jcenteredline(l);
}
public static Object dm_callModule(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __943 = dm_enter(mod);
try {
return call(mod, method, args);
} finally {
_close(__943);
}
}
public static String dm_makeOrShowModule(String moduleLibID) {
return (String) callCreator("makeOrShowModule", moduleLibID);
}
public static List map(Iterable l, Object f) {
return map(f, l);
}
public static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) x.add(callF(f, o));
return x;
}
public static List map(Iterable l, F1 f) {
return map(f, l);
}
public static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(callF(f, o));
return x;
}
public static List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
public static List map(Object f, Object[] l) {
return map(f, asList(l));
}
public static List map(Object[] l, Object f) {
return map(f, l);
}
public static List map(Object f, Map map) {
return map(map, f);
}
public static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
public static GazelleLine dm_discord_importLine(Object lineConcept) {
return lineConcept == null ? null : nu(GazelleLine.class, "timestamp", _get("created", lineConcept), "user", call(lineConcept, "userName"), "bot", _get("bot", lineConcept), "text", _get("text", lineConcept), "msgID", getLong("msgID", lineConcept), "reactions", map(getList(lineConcept, "reactions"), new F1() {
public GazelleReaction get(Object r) {
try {
return nu(GazelleReaction.class, "userID", getLong((Object) getOpt("user", r), "userID"), "created", _get("created", r), "emoji", _get("emoji", r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "nu GazelleReaction(\r\n userID := getLong((O) getOpt user(r), 'userID),\r...";
}
}));
}
public static Object dm_call(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __39 = dm_enter(mod);
try {
return call_withVarargs(mod, method, args);
} finally {
_close(__39);
}
}
public static String dm_gazelle_linesCRUD() {
return dm_require("#1021628/GLines");
}
public static List reversedList(Collection l) {
List x = cloneList(l);
Collections.reverse(x);
return x;
}
public static String reversedString(String s) {
return reverseString(s);
}
public static Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A nuObject(Class c, Object... args) {
try {
if (args.length == 0)
return nuObjectWithoutArguments(c);
Constructor m = nuObject_findConstructor(c, args);
m.setAccessible(true);
return (A) m.newInstance(args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
public static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
public static void setAll(Object o, Map fields) {
if (fields == null)
return;
for (String field : keys(fields)) set(o, field, fields.get(field));
}
public static void setAll(Object o, Object... values) {
failIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
set(o, field, value);
}
}
public static String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
public static double fraction(double d) {
return d % 1;
}
public static String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
public static String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
public static String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
public static String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
public static String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
public static TreeSet litciset(String... items) {
TreeSet set = caseInsensitiveSet();
for (String a : items) set.add(a);
return set;
}
public static A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
public static A optParam(ThreadLocal tl) {
return optPar(tl);
}
public static A optParam(Object[] opt, String name, A defaultValue) {
if (!even(l(opt)))
throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name))
return (A) opt[i + 1];
return defaultValue;
}
public static Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
public static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
public static List synchroList(List l) {
return Collections.synchronizedList(l);
}
public static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
public static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
public static Throwable innerException(Throwable e) {
return getInnerException(e);
}
public static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || b != null && a.equals(b);
}
public static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
public static ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
public static boolean boolPar(ThreadLocal tl) {
return boolOptParam(tl);
}
public static boolean boolPar(Object[] __, String name) {
return boolOptParam(__, name);
}
public static boolean boolPar(String name, Object[] __) {
return boolOptParam(__, name);
}
public static boolean boolPar(String name, Object[] params, boolean defaultValue) {
return optParam(params, name, defaultValue);
}
public static GazelleEvalContext dm_gazelle_stdEvalContext() {
return dm_gazelle_stdEvalContext(dm_allRulesFromRulesModuleWithCommentsAndIDs());
}
public static GazelleEvalContext dm_gazelle_stdEvalContext(List> rules, Object... __) {
GazelleEvalContext ctx = gazelle_stdEvalContext_v2(rules, __);
ctx.engine.callFunctionOnString = new F2() {
public Object get(String function, String s) {
try {
return dm_callFunctionOnString(function, s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_callFunctionOnString(function, s)";
}
};
return ctx;
}
public static List> dm_gazelle_allRulesWithComment(final String comment) {
List> l = dm_allRulesFromRulesModuleWithCommentsAndIDs();
return empty(comment) ? l : filter(l, new F1, Boolean>() {
public Boolean get(T3 t) {
try {
return cic(tlft(t.b), comment);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cic(tlft(t.b), comment)";
}
});
}
public static boolean cicOneOf(String s, String... l) {
for (String x : l) if (cic(s, x))
return true;
return false;
}
public static boolean cicOneOf(Collection l, String... bla) {
for (String x : unnull(l)) if (eqicOneOf(x, bla))
return true;
return false;
}
public static String unnull(String s) {
return s == null ? "" : s;
}
public static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
public static List unnull(List l) {
return l == null ? emptyList() : l;
}
public static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
public static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
public static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
public static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
public static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
public static List collect(Collection c, String field) {
return collectField(c, field);
}
public static List collect(String field, Collection c) {
return collectField(c, field);
}
public static void gazelle_addHelpers(GazelleEvalContext ctx, Object... __) {
if (ctx.engine.hasHelpers)
return;
print("Adding helpers");
ctx.engine.hasHelpers = true;
gazelle_addHelperTablesToRules(ctx.engine);
gazelle_addVarSplittersToRules(ctx.engine, __);
gazelle_addVarDiscriminators(ctx.engine, __);
gazelle_addVarConvertersToRules(ctx.engine, __);
gazelle_addCalculationFunctionsToRules(ctx.engine, __);
gazelle_addRespondToHumanOnlyHelpers(ctx.engine, __);
gazelle_addForbiddenBindingHelpers(ctx.engine, __);
}
public static Object[] litparams(Object... l) {
int n = 0, n1 = l(l);
for (int i = 0; i < n1; i += 2) if (l[i] != null && l[i + 1] != null)
++n;
if (n == 0)
return null;
Object[] params = new Object[n * 2];
int j = 0;
for (int i = 0; i < n1; i += 2) {
Object key = l[i], value = l[i + 1];
if (key != null && value != null) {
params[j++] = key;
params[j++] = value;
}
}
return params;
}
public static List dm_gazelle_getChildren(GazelleTree tree, Object... __) {
return gazelle_getChildren(tree, paramsPlus(__, "makeEvalContext", "dm_gazelle_stdEvalContext"));
}
public static Map gazelle_inputMapFromLineAndHistory(String line, List history) {
Map inputMap = litmap("standard", line);
for (int i = 0; i < l(history); i++) inputMap.put("history-" + (l(history) - i), history.get(i));
return inputMap;
}
public static List listPlus(Collection l, A... more) {
return concatLists(l, asList(more));
}
public static String sfu(Object o) {
return structureForUser(o);
}
public static TreeMap asTreeMap(Map map) {
return map instanceof TreeMap ? (TreeMap) map : new TreeMap(map);
}
public static void dm_gazelle_matchAdditionalInput3(List l, Map inputsByType, Object... __) {
for (GazelleTree t : l) if (t.rule() != null) {
RuleEngine2_MatchedRule mr = t.mr;
List insWithType = t.rule().insWithType;
while (licensed()) {
int iCond = t.mr.iCond;
TextAndType next = get(insWithType, iCond);
if (next == null || !startsWith(next.type, "history-"))
break;
if (ai_ruleEngine2_matchStep(t.mr, inputsByType, true, __)) {
print("Input match OK. new map: " + t.mr.map + ". Updating prediction.");
gazelle_addPredictionToTreeNode(t);
} else {
print("Input match failed");
break;
}
}
}
}
public static boolean nempty(Collection c) {
return !empty(c);
}
public static boolean nempty(CharSequence s) {
return !empty(s);
}
public static boolean nempty(Object[] o) {
return !empty(o);
}
public static boolean nempty(byte[] o) {
return !empty(o);
}
public static boolean nempty(int[] o) {
return !empty(o);
}
public static boolean nempty(Map m) {
return !empty(m);
}
public static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
public static boolean nempty(Object o) {
return !empty(o);
}
public static String optCurly(String s) {
return curlyBraceOptIfMoreThanOneToken(s);
}
public static List filter(Iterable c, Object pred) {
if (pred instanceof F1)
return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null)
for (Object o : c) if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
public static List filter(Object pred, Iterable c) {
return filter(c, pred);
}
public static List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o).booleanValue())
x.add(o);
return x;
}
public static List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
public static List filter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o).booleanValue())
x.add(o);
return x;
}
public static List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
public static boolean neq(Object a, Object b) {
return !eq(a, b);
}
public static void gazelle_sortChildren(GazelleTree tree) {
if (tree == null)
return;
gazelle_sortChildren(tree.children);
}
public static void gazelle_sortChildren(List children) {
if (children != null)
sortByCalculatedFieldDesc(children, new F1() {
public Integer get(GazelleTree c) {
try {
return ai_goodBadToInt(c.prediction);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ai_goodBadToInt(c.prediction)";
}
});
}
public static void dm_gazelle_matchStatements_v2(List l, Object... __) {
boolean debug = boolPar("debug", __) || boolPar("matchStatementsDebug", __);
for (GazelleTree t : l) {
if (t.rule() == null)
continue;
RuleEngine2_MatchedRule mr = t.mr;
List in = t.rule().in;
int iCond = t.mr.iCond;
if (debug)
print("matchStatements: iCond=" + iCond + " in " + in);
if (iCond >= l(in))
continue;
List conditions = dropFirst(iCond, in);
if (debug)
print("Remaining conditions for " + t.ruleID() + " with " + t.mr.map + ": " + conditions);
Matches m = new Matches();
if (!matchAny("in " + (iCond + 1) + " = statement *", t.rule().comments, m))
continue;
String subRuleID = m.unq(0);
if (debug)
print("Found subrule: " + subRuleID);
List fulfillments = dm_gazelle_fulfillmentsForRule(subRuleID);
Lowest> bestMap = new Lowest();
if (debug)
print("Have " + n2(fulfillments, "fulfillment") + ".");
for (Object f : fulfillments) {
Map varMap = asCIMap(safeUnstructMap(getString("varMap", f)));
printIndent(sfu(varMap));
boolean selfVarsFix = boolPar("selfVarsFix", __, true);
if (selfVarsFix) {
String cond = first(conditions);
for (String x : identifiersOnly(codeTokens(mr.tokenize(cond)))) if (!varMap.containsKey(x)) {
if (debug)
print("Self-linking " + x);
varMap.put(x, x);
}
}
if (debug)
print("Original map: " + t.mr.map);
Map newMap = mergeMapsStrictlyIC(asCIMap(t.mr.map), varMap);
if (newMap == null) {
if (debug)
printIndent("Can't merge maps");
continue;
}
if (debug)
printIndent("Maps merged! => " + sfu(newMap));
newMap = ciMapWithoutKeysEqualToValues(newMap);
if (debug)
printIndent("Map simplified => " + sfu(newMap));
bestMap.put(newMap, l(newMap));
}
Map newMap = bestMap.get();
if (newMap == null) {
if (debug)
print("No matching statement found");
continue;
}
t.mr.map = newMap;
t.mr.iCond++;
t.mr.remainingConditions = dropFirst(t.mr.remainingConditions);
t.mr.remainingConditionsWithType = dropFirst(t.mr.remainingConditionsWithType);
t.mr.out = null;
t.line = t.mr.outText();
if (debug)
print("Rewrote " + t.mr.rule.out + " to: " + t.line);
break;
}
}
public static Object[] passParams(Object[] __, String... params) {
Map map = paramsToMap(__);
List l = new ArrayList();
int n = l(l) - 1;
for (String key : params) if (map.containsKey(key)) {
l.add(key);
l.add(map.get(key));
}
return empty(l) ? null : toObjectArray(l);
}
public static List gazelle_dropUnsatisfiedEntries(List l) {
return antiFilter(l, t -> t.mr != null && t.mr.moreConditions());
}
public static void gazelle_dropMatchedDefaultRules(List l) {
List defaults = filter(l, new F1() {
public Boolean get(GazelleTree t) {
try {
return cic(t.ruleComments(), "default");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cic(t.ruleComments(), \"default\")";
}
});
if (nempty(defaults) && l(defaults) < l(l))
l.removeAll(defaults);
}
public static Object[] assertEvenLength(Object[] a) {
assertTrue(even(l(a)));
return a;
}
public static LinkedHashMap paramsToOrderedMap(Object... params) {
return paramsToMap(params);
}
public static Object[] mapToParams(Map map) {
return mapToObjectArray(map);
}
public static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
public static Class __javax;
public static Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
public static int strL(String s) {
return s == null ? 0 : s.length();
}
public static int listL(Collection l) {
return l == null ? 0 : l.size();
}
public static List splitAtTokens(String s, List tokens) {
return splitAtTokens(javaTok(s), tokens);
}
public static List splitAtTokens(List tok, List tokens) {
List l = new ArrayList();
int i = 0;
while (i < l(tok)) {
int j = indexOfSubList(tok, tokens, i);
if (i >= l(tok))
break;
if (j < 0)
j = l(tok);
l.add(trimJoin(tok.subList(i, j)));
i = j + l(tokens);
}
return l;
}
public static List splitAtTokens(List tok, String... tokens) {
List l = new ArrayList();
int i = 0;
while (i < l(tok)) {
int j = indexOfSubList(tok, tokens, i);
if (i >= l(tok))
break;
if (j < 0)
j = l(tok);
l.add(trimJoin(tok.subList(i, j)));
i = j + l(tokens);
}
return l;
}
public static List javaTokWithBrackets(String s) {
return javaTokPlusBrackets(s);
}
public static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
public static String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
public static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
public static String formatSnippetID(long id) {
return "#" + id;
}
public static Class getMainClass() {
return mc();
}
public static Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static volatile boolean ping_pauseAll;
public static int ping_sleep = 100;
public static volatile boolean ping_anyActions;
public static Map ping_actions = newWeakHashMap();
public static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
public static boolean ping() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
public static boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty())
ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Runnable _topLevelErrorHandling(final Runnable runnable) {
final Object info = _threadInfo();
return new Runnable() {
public void run() {
try {
try {
_threadInheritInfo(info);
runnable.run();
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }";
}
};
}
public static WeakReference weakRef(A a) {
return newWeakReference(a);
}
public static Object swing(Object f) {
return swingAndWait(f);
}
public static A swing(F0 f) {
return (A) swingAndWait(f);
}
public static Component wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
public static Component wrap_2(Object swingable) {
if (swingable == null)
return null;
Component c;
if (swingable instanceof Component)
c = (Component) swingable;
else
c = (Component) callOpt(swingable, "swing");
if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
public static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
public static JButton jbutton(String text) {
return newButton(text, null);
}
public static JButton jbutton(Action action) {
return swingNu(JButton.class, action);
}
public static JPanel jcenteredline(final Component... components) {
return swing(new F0() {
public JPanel get() {
try {
return jFullCenter(hstackWithSpacing(components));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret jFullCenter(hstackWithSpacing(components));";
}
});
}
public static JPanel jcenteredline(List extends Component> components) {
return jcenteredline(asArray(Component.class, components));
}
public static Object dm_getModule(Object moduleOrID) {
if (moduleOrID == null || eq(moduleOrID, ""))
return null;
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
return dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
public static AutoCloseable dm_enter(Object mod) {
return (AutoCloseable) callOpt(dm_getModule(mod), "enter");
}
public static Object callCreator(String functionName, Object... args) {
return call(creator(), functionName, args);
}
public static ArrayList emptyList() {
return new ArrayList();
}
public static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
public static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
public static ArrayList emptyList(Class c) {
return new ArrayList();
}
public static A _get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
public static Object _get(Object o, String field) {
return get(o, field);
}
public static Object _get(String field, Object o) {
return get(o, field);
}
public static A _get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
public static Android3 bot(String greeting) {
return makeAndroid3(greeting);
}
public static Android3 bot(Android3 a) {
return makeBot(a);
}
public static Android3 bot(String greeting, Object responder) {
return makeBot(greeting, responder);
}
public static Android3 bot() {
return makeBot();
}
public static long getLong(Object o, String field) {
return toLong(getOpt(o, field));
}
public static long getLong(String field, Object o) {
return getLong(o, field);
}
public static List getList(Map map, Object key) {
return map == null ? null : (List) map.get(key);
}
public static List getList(List l, int idx) {
return (List) get(l, idx);
}
public static List getList(Object o, Object key) {
if (o instanceof Map)
return getList((Map) o, key);
if (key instanceof String)
return (List) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
public static Object call_withVarargs(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me == null) {
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
if ((me.getModifiers() & Modifier.STATIC) == 0)
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not static");
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String dm_require(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
public static String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
public static Map classForName_cache = synchroHashMap();
public static Class classForName(String name) {
try {
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = Class.forName(name));
return c;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
public static Object nuObjectWithoutArguments(String className) {
try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A nuObjectWithoutArguments(Class c) {
try {
if (nuObjectWithoutArguments_cache == null)
return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
Constructor m = nuObjectWithoutArguments_cache.get(c);
if (m == null)
nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
return (A) m.newInstance();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
m.setAccessible(true);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
public static List getClasses(Object[] array) {
List l = new ArrayList();
for (Object o : array) l.add(_getClass(o));
return l;
}
public static boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class)
return arg instanceof Boolean;
if (type == int.class)
return arg instanceof Integer;
if (type == long.class)
return arg instanceof Long;
if (type == float.class)
return arg instanceof Float;
if (type == short.class)
return arg instanceof Short;
if (type == char.class)
return arg instanceof Character;
if (type == byte.class)
return arg instanceof Byte;
if (type == double.class)
return arg instanceof Double;
return type.isInstance(arg);
}
public static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
public static Set keys(Object map) {
return keys((Map) map);
}
public static Set keys(MultiSet ms) {
return ms.keySet();
}
public static Set keys(MultiMap mm) {
return mm.keySet();
}
public static void set(Object o, String field, Object value) {
if (o == null)
return;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
f.setAccessible(true);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
f.setAccessible(true);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
public static Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
public static void failIfOddCount(Object... list) {
if (odd(l(list)))
throw fail("Odd list size: " + list);
}
public static String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
public static String trim(String s) {
return s == null ? null : s.trim();
}
public static String trim(StringBuilder buf) {
return buf.toString().trim();
}
public static String trim(StringBuffer buf) {
return buf.toString().trim();
}
public static TreeSet caseInsensitiveSet() {
return new TreeSet(caseInsensitiveComparator());
}
public static TreeSet caseInsensitiveSet(Collection c) {
return toCaseInsensitiveSet(c);
}
public static TreeSet treeSet() {
return new TreeSet();
}
public static boolean even(int i) {
return (i & 1) == 0;
}
public static boolean even(long i) {
return (i & 1) == 0;
}
public static Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
public static Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
public static String str(Object o) {
return o == null ? "null" : o.toString();
}
public static String str(char[] c) {
return new String(c);
}
public static Object collectionMutex(Object o) {
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
public static boolean boolOptParam(ThreadLocal tl) {
return isTrue(optPar(tl));
}
public static boolean boolOptParam(Object[] __, String name) {
return isTrue(optParam(__, name));
}
public static boolean boolOptParam(String name, Object[] __) {
return boolOptParam(__, name);
}
public static List> dm_allRulesFromRulesModuleWithCommentsAndIDs() {
return collectThreeFieldsAsTriple("text", "comments", "globalID", (List) dm_call(dm_gazelle_rulesModule(), "concepts"));
}
public static GazelleEvalContext gazelle_stdEvalContext_v2(List> rules, Object... __) {
long startTime = sysNow();
GazelleEvalContext ctx = new GazelleEvalContext();
ctx.engine = new RuleEngine2();
ctx.engine.addRules2(rules);
gazelle_changeInTypesForRulesWithMultipleInputs(ctx.engine);
MultiSet statements = dm_gazelle_statementsFromAppliedRules_multiSet();
ctx.dataByRule = new HashMap();
Map> statementsByRule = ai_gazelle_indexStatementsByRule_multiSet(statements);
for (String ruleID : keys(statementsByRule)) {
MultiSet statements2 = statementsByRule.get(ruleID);
ctx.dataByRule.put(ruleID, ai_gazelle_analyzeStatementsForRule_multiSet(statements2));
}
ctx.predictor = dm_gazelle_standardPredictor(__);
done2(startTime, "Making engine with " + n2(rules, "rule"));
return ctx;
}
public static Object dm_callFunctionOnString(String code, String s) {
return callF(dm_codeWithHintsToFunctionOnString(code), s);
}
public static boolean empty(Collection c) {
return c == null || c.isEmpty();
}
public static boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
public static boolean empty(Map map) {
return map == null || map.isEmpty();
}
public static boolean empty(Object[] o) {
return o == null || o.length == 0;
}
public static boolean empty(Object o) {
if (o instanceof Collection)
return empty((Collection) o);
if (o instanceof String)
return empty((String) o);
if (o instanceof Map)
return empty((Map) o);
if (o instanceof Object[])
return empty((Object[]) o);
if (o instanceof byte[])
return empty((byte[]) o);
if (o == null)
return true;
throw fail("unknown type for 'empty': " + getType(o));
}
public static boolean empty(float[] a) {
return a == null || a.length == 0;
}
public static boolean empty(int[] a) {
return a == null || a.length == 0;
}
public static boolean empty(long[] a) {
return a == null || a.length == 0;
}
public static boolean empty(byte[] a) {
return a == null || a.length == 0;
}
public static boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
public static boolean empty(File f) {
return getFileSize(f) == 0;
}
public static boolean cic(Collection l, String s) {
return containsIgnoreCase(l, s);
}
public static boolean cic(String[] l, String s) {
return containsIgnoreCase(l, s);
}
public static boolean cic(String s, char c) {
return containsIgnoreCase(s, c);
}
public static boolean cic(String a, String b) {
return containsIgnoreCase(a, b);
}
public static List tlft(String s) {
return toLinesFullTrim(s);
}
public static List tlft(File f) {
return toLinesFullTrim(f);
}
public static boolean eqicOneOf(String s, String... l) {
for (String x : l) if (eqic(s, x))
return true;
return false;
}
public static Map emptyMap() {
return new HashMap();
}
public static List collectField(Collection c, String field) {
List l = new ArrayList();
if (c != null)
for (Object a : c) l.add(getOpt(a, field));
return l;
}
public static List collectField(String field, Collection c) {
return collectField(c, field);
}
public static class gazelle_addHelperTablesToRules_Massager {
public List> helperTable;
public Map> helperIndex;
public gazelle_addHelperTablesToRules_Massager() {
}
public gazelle_addHelperTablesToRules_Massager(List> helperTable, Map> helperIndex) {
this.helperIndex = helperIndex;
this.helperTable = helperTable;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
for (String t : codeTokens(matched.tokenize(matched.rule.out))) {
if (map.containsKey(t))
continue;
Pair idx = helperIndex.get(t);
if (idx == null)
continue;
{
final Map __742 = cloneMap(map);
for (String key : keys(__742)) {
String val = __742.get(key);
int idx2 = indexOfIC(helperTable.get(idx.a), key);
if (idx2 < 0)
continue;
Pair idxVal = helperIndex.get(val);
if (idxVal == null)
continue;
String out = _get(_get(helperTable, idxVal.a), idx.b);
print("Massaged: " + t + " <-> " + key + " => " + out);
mapPut(map, t, out);
}
}
}
return map;
}
}
public static void gazelle_addHelperTablesToRules(RuleEngine2 engine) {
Matches m = new Matches();
for (final RuleEngine2.Rule r : engine.rules) {
{
if (!(matchAny("use helper table mech list *", r.comments, m)))
continue;
}
List entries = mL(m.unq(0));
{
if (empty(entries))
continue;
}
final List> helperTable = map("tok_splitAtCommaOrDoubleArrow", entries);
final Map> helperIndex = indexTwoDArrayIC(helperTable);
r.addMapMassager(new gazelle_addHelperTablesToRules_Massager(helperTable, helperIndex));
}
}
public static class gazelle_addVarSplittersToRules_VarSplitter {
public String var;
public boolean debug;
public gazelle_addVarSplittersToRules_VarSplitter() {
}
public gazelle_addVarSplittersToRules_VarSplitter(String var, boolean debug) {
this.debug = debug;
this.var = var;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
String value = getOrKeep(map, curly(var));
List tok1 = matched.tokenize(var);
List tok2 = matched.tokenize(uncurly(value));
if (debug)
print("VarSplitter: " + tok1 + " / " + tok2);
if (l(tok1) != l(tok2))
return null;
int oldSize = l(map);
for (int i = 1; i < l(tok1); i += 2) if (!strictPutIC(map, tok1.get(i), tok2.get(i)))
return null;
if (debug)
print("VarSplitter done => " + map);
matched.nPossibleVars = matched.nPossibleVars() + l(map) - oldSize;
return map;
}
}
public static void gazelle_addVarSplittersToRules(RuleEngine2 engine, Object... __) {
Matches m = new Matches();
boolean debug = boolPar("debug", __);
for (final RuleEngine2.Rule r : engine.rules) {
{
if (!(jmatchAny("split *", r.comments, m) && isQuoted(m.get(0))))
continue;
}
String var = m.unq(0);
if (debug)
print("Made splitter for: " + var);
r.addMapMassager(new gazelle_addVarSplittersToRules_VarSplitter(var, debug));
}
}
public static class gazelle_addVarDiscriminators_VarDiscriminator {
public String var;
public Object discriminator;
public boolean debug;
public gazelle_addVarDiscriminators_VarDiscriminator() {
}
public gazelle_addVarDiscriminators_VarDiscriminator(String var, Object discriminator, boolean debug) {
this.debug = debug;
this.discriminator = discriminator;
this.var = var;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
String value = map.get(var);
if (value != null && !isTrue(callAndMake_orF1(discriminator, value))) {
if (debug)
print("Rejecting var: " + var + " -> " + value + " because of " + discriminator);
return null;
}
return map;
}
}
public static void gazelle_addVarDiscriminators(RuleEngine2 engine, Object... __) {
boolean debug = boolPar("debug", __);
for (final RuleEngine2.Rule r : engine.rules) for (Matches m : getJMatches_all("var * should satisfy *", r.comments)) {
String var = m.unq(0), discriminator = m.unq(1);
if (debug)
print("Made discriminator for: " + var);
r.addMapMassager(new gazelle_addVarDiscriminators_VarDiscriminator(var, discriminator, debug));
}
}
public static class gazelle_addVarConvertersToRules_VarConverter {
public String var1, var2;
public Object converter;
public boolean debug;
public gazelle_addVarConvertersToRules_VarConverter() {
}
public gazelle_addVarConvertersToRules_VarConverter(String var1, String var2, Object converter, boolean debug) {
this.debug = debug;
this.converter = converter;
this.var2 = var2;
this.var1 = var1;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
String value = map.get(var1);
if (value == null)
return map;
String value2 = (String) callAndMake_orF1(converter, value);
if (debug)
print("VarConverter: " + value + " => " + value2);
if (!strictPutIC(map, var2, value2))
return null;
return map;
}
}
public static void gazelle_addVarConvertersToRules(RuleEngine2 engine, Object... __) {
boolean debug = boolPar("debug", __) || boolPar("varConverterDebug", __);
for (final RuleEngine2.Rule r : engine.rules) for (Matches m : getJMatches_all("convert var * to * with *", r.comments)) r.addMapMassager(new gazelle_addVarConvertersToRules_VarConverter(m.unq(0), m.unq(1), m.unq(2), debug));
}
public static class gazelle_addCalculationFunctionsToRules_Calculator {
public String var1, var2, var3;
public Object function;
public boolean debug;
public gazelle_addCalculationFunctionsToRules_Calculator() {
}
public gazelle_addCalculationFunctionsToRules_Calculator(String var1, String var2, String var3, Object function, boolean debug) {
this.debug = debug;
this.function = function;
this.var3 = var3;
this.var2 = var2;
this.var1 = var1;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
double result;
try {
String value1 = getOrKeep(map, var1), value2 = getOrKeep(map, var2);
result = (double) callAndMake_orF2(function, parseDouble(value1), parseDouble(value2));
} catch (Throwable _e) {
return null;
}
if (!strictPutIC(map, var3, str(iround(result))))
return null;
return map;
}
}
public static void gazelle_addCalculationFunctionsToRules(RuleEngine2 engine, Object... __) {
boolean debug = boolPar("debug", __) || boolPar("calcDebug", __);
for (final RuleEngine2.Rule r : engine.rules) for (Matches m : getJMatches_all("compute var * from * and * using *", r.comments)) {
r.addMapMassager(new gazelle_addCalculationFunctionsToRules_Calculator(m.unq(1), m.unq(2), m.unq(0), m.unq(3), debug));
if (debug)
print("Calculator made");
}
}
public static class gazelle_addRespondToHumanOnlyHelpers_Check {
public boolean debug;
public gazelle_addRespondToHumanOnlyHelpers_Check() {
}
public gazelle_addRespondToHumanOnlyHelpers_Check(boolean debug) {
this.debug = debug;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
if (debug)
print("humanOnlyHelper for " + matched.ruleID() + ": " + matched.inputsByType);
if (!eq("true", matched.inputsByType.get("_respondingToHuman")))
return null;
return map;
}
}
public static void gazelle_addRespondToHumanOnlyHelpers(RuleEngine2 engine, Object... __) {
boolean debug = boolPar("debug", __) || boolPar("humanOnlyDebug", __);
for (final RuleEngine2.Rule r : engine.rules) if (cic(r.comments, "only answer to human")) {
if (debug)
print("Made human-only helper");
r.addMapMassager(new gazelle_addRespondToHumanOnlyHelpers_Check(debug));
}
}
public static class gazelle_addForbiddenBindingHelpers_Blocker {
public String var, value;
public boolean debug;
public gazelle_addForbiddenBindingHelpers_Blocker() {
}
public gazelle_addForbiddenBindingHelpers_Blocker(String var, String value, boolean debug) {
this.debug = debug;
this.value = value;
this.var = var;
}
public Map get(Map map, List tokC, List tokI, RuleEngine2_MatchedRule matched) {
if (map == null)
return null;
if (eqic(value, map.get(var)))
return null;
return map;
}
}
public static void gazelle_addForbiddenBindingHelpers(RuleEngine2 engine, Object... __) {
boolean debug = boolPar("debug", __) || boolPar("forbiddenBindingsDebug", __);
for (final RuleEngine2.Rule r : engine.rules) for (Matches m : getJMatches_all("don't change * to *", r.comments)) r.addMapMassager(new gazelle_addForbiddenBindingHelpers_Blocker(m.unq(0), m.unq(1), debug));
}
public static List gazelle_getChildren(GazelleTree tree, Object... __) {
if (tree == null)
return null;
if (tree.children != null)
return tree.children;
tree.children = new ArrayList();
double qualityCutOff = optPar("qualityCutOff", __, -0.75);
List dialogHistory = (List) (optPar("dialogHistory", __));
boolean debug = boolPar("debug", __);
if (tree.ctx == null)
tree.setContext(assertNotNull("evalContext", (GazelleEvalContext) callF(assertNotNull("makeEvalContext", (Object) optPar("makeEvalContext", __)))));
GazelleEvalContext ctx = tree.ctx;
RuleEngine2 engine = ctx.engine;
Map inputMap = gazelle_inputMapFromLineAndHistory(tree.line, concatLists(dialogHistory, tree.history()));
if (boolPar("respondingToHuman", __))
inputMap.put("_respondingToHuman", "true");
if (debug)
print("inputMap=" + sfu(asTreeMap(inputMap)));
if (!boolPar("skipSplitters", __))
for (RuleEngine2.SimplifyWithRule rule : engine.splitterRules()) {
try {
Collection out = gazelle_executeSplitterRule(engine, rule, tree.line);
GazelleTree child = new GazelleTree(joinWithVBar(out));
child.ctx = ctx;
child.isSplitNode = true;
tree.add(child);
for (String line : out) child.add(new GazelleTree(line));
} catch (Throwable __e) {
_handleException(__e);
}
}
boolean firstConditionOnly = boolPar("firstConditionOnly", __);
Object[] params = litobjectarray("debug", optPar("debug", __), "tree", tree);
List l = sortByMethodDesc("qualitySum", firstConditionOnly ? ai_ruleEngine2_rulesForInput_5(engine, inputMap, params) : ai_ruleEngine2_rulesForInput_5_allConditions(engine, inputMap, params));
for (RuleEngine2_MatchedRule r : l) {
double quality = r.relativeQuality();
if (quality < qualityCutOff) {
if (debug)
print("Match under quality (" + quality + "/" + qualityCutOff + "): " + r);
continue;
}
String line = r.outText();
GazelleTree child = new GazelleTree(line);
child.ctx = ctx;
child.mr = r;
if (r.rule != null)
child.lineType = r.rule.outType;
gazelle_addPredictionToTreeNode(child);
tree.add(child);
}
gazelle_sortChildren(tree);
return tree.children;
}
public static HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
public static void litmap_impl(Map map, Object... x) {
for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
map.put(x[i], x[i + 1]);
}
public static List concatLists(Collection ... lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
public static List concatLists(Collection extends Collection > lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
public static String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
public static boolean ai_ruleEngine2_matchStep(final RuleEngine2_MatchedRule matched, Map inputsByType, boolean fillRemainingConditions, Object... __) {
boolean debug = boolPar("debug", __);
RuleEngine2.Rule rule = matched.rule;
TextAndType in = rule.insWithType.get(matched.iCond);
String input = inputsByType.get(in.type);
if (input == null)
return false;
Object inputMassager = get(rule.inputMassagers, matched.iCond);
Object checkerFunction = get(rule.checkerFunctions, matched.iCond);
List tokC = null, tokI = null;
Map map;
if (inputMassager != null) {
input = (String) callF(inputMassager, input);
if (debug)
print("Massaged input to: " + input);
if (input == null)
return false;
}
if (checkerFunction != null)
map = (Map) callF(checkerFunction, input);
else {
String cond = in.text;
String tokenize = matched.tokenizationFunction;
tokC = (List) callAndMake(tokenize, cond);
tokI = (List) callAndMake(tokenize, input);
if (debug)
print("matchStep inputsByType=" + sfu(asTreeMap(inputsByType)));
if (debug)
print("matchStep in=" + in + ", iCond=" + matched.iCond + ", insWithType: " + rule.insWithType);
if (debug)
print("matchStep tokI/tokC: " + codeTokens(tokI) + " / " + codeTokens(tokC));
if (contains(cond, "{}"))
tokI = ai_applyWordSplitPattern1(tokC, tokI);
map = zipTwoListsToCIMap_strict_withoutEquals(tokC, tokI);
}
if (debug)
print("matchStep for rule " + rule.globalID + " map: " + map);
if (!gazelle_addMatch(matched, map, tokC, tokI, __)) {
if (debug)
print("addMatch failed - " + strWithIdentityHashCode(matched));
return false;
}
if (debug)
print("matchStep succeeded. " + matched);
matched.matchedLines.add(pair(tokC, tokI));
if (fillRemainingConditions) {
matched.remainingConditions = nullIfEmpty(map(dropFirst(matched.iCond, rule.in), new F1() {
public String get(String s) {
try {
return matched.applyMappingTo(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "matched.applyMappingTo(s)";
}
}));
matched.remainingConditionsWithType = nullIfEmpty(map(dropFirst(matched.iCond, rule.insWithType), new F1() {
public TextAndType get(TextAndType in) {
try {
return new TextAndType(matched.applyMappingTo(in.text), in.type);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "TextAndType(matched.applyMappingTo(in.text), in.type)";
}
}));
}
Map, Integer> qualities = ai_ruleEngine2_mappingQualities(rule);
for (String a : keys(map)) {
String b = map.get(a);
mapPut(matched.mappingQuality, a, qualities.get(pair(a, b)));
}
matched.iCond++;
if (debug)
print("iCond now=" + matched.iCond + ", next input: " + get(matched.rule.insWithType, matched.iCond));
return true;
}
public static void gazelle_addPredictionToTreeNode(GazelleTree child, Object... __) {
boolean debug = boolPar("debug", __);
Set badComments = (Set) (optPar("badComments", __));
Set acceptablePurposes = (Set) (optPar("acceptablePurposes", __));
RuleEngine2_MatchedRule r = child.mr;
GazelleEvalContext ctx = child.ctx;
if (containsAny(r.rule.comments, badComments) || acceptablePurposes != null && !acceptablePurposes.contains(unnull(r.rule.purpose))) {
if (debug)
print("prediction=bad for various reasons");
child.prediction = "bad";
} else {
if (ctx.predictor == null)
child.prediction = null;
else {
child.prediction = ctx.predictor.get(ctx, r);
if (debug)
print("Prediction=" + child.prediction + " for " + r + " (" + (r.moreConditions() ? "unsatisfied" : "satisfied") + ") by " + ctx.predictor);
}
}
}
public static String curlyBraceOptIfMoreThanOneToken(String s) {
return !isCurlyBraced(s) && numberOfJavaTokens(s) > 1 ? curlyBrace(s) : s;
}
public static List sortByCalculatedFieldDesc(Collection c, final Object f) {
return sortByCalculatedFieldDesc_inPlace(cloneList(c), f);
}
public static List sortByCalculatedFieldDesc(Object f, Collection c) {
return sortByCalculatedFieldDesc(c, f);
}
public static int ai_goodBadToInt(String s) {
if (eq(s, "good"))
return 1;
if (eq(s, "bad"))
return -1;
return 0;
}
public static String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
public static String[] dropFirst(String[] a) {
return drop(1, a);
}
public static Object[] dropFirst(Object[] a) {
return drop(1, a);
}
public static List dropFirst(List l) {
return dropFirst(1, l);
}
public static List dropFirst(int n, Iterable i) {
return dropFirst(n, toList(i));
}
public static List dropFirst(Iterable i) {
return dropFirst(toList(i));
}
public static List dropFirst(int n, List l) {
return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
public static List dropFirst(List l, int n) {
return dropFirst(n, l);
}
public static String dropFirst(int n, String s) {
return substring(s, n);
}
public static String dropFirst(String s) {
return substring(s, 1);
}
public static boolean matchAny(Collection patterns, String s, Matches m) {
for (String pattern : patterns) if (match(pattern, s, m))
return true;
return false;
}
public static boolean matchAny(Collection patterns, String s) {
return matchAny(patterns, s, null);
}
public static boolean matchAny(String pat, Iterable l) {
return matchAny(pat, l, null);
}
public static boolean matchAny(String pat, Iterable l, Matches m) {
if (l != null)
for (String s : l) if (match(pat, s, m))
return true;
return false;
}
public static List dm_gazelle_fulfillmentsForRule(String ruleID) {
return (List) dm_call(dm_gazelle_fulfillmentsCRUD(), "entriesForRule", ruleID);
}
public static TreeMap asCIMap(Map map) {
return asCaseInsensitiveMap(map);
}
public static Map safeUnstructMap(String s) {
return safeUnstructureMap(s);
}
public static String getString(Map map, Object key) {
return map == null ? null : (String) map.get(key);
}
public static String getString(List l, int idx) {
return (String) get(l, idx);
}
public static String getString(Object o, Object key) {
if (o instanceof Map)
return getString((Map) o, key);
if (key instanceof String)
return (String) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
public static String getString(String key, Object o) {
return getString(o, (Object) key);
}
public static A printIndent(A o) {
print(indentx(str(o)));
return o;
}
public static A printIndent(String indent, A o) {
print(indentx(indent, str(o)));
return o;
}
public static void printIndent(int indent, Object o) {
print(indentx(indent, str(o)));
}
public static Object first(Object list) {
return first((Iterable) list);
}
public static A first(List list) {
return empty(list) ? null : list.get(0);
}
public static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
public static A first(IterableIterator i) {
return first((Iterator ) i);
}
public static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
public static A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
public static Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
public static A first(Pair p) {
return p == null ? null : p.a;
}
public static A first(T3 t) {
return t == null ? null : t.a;
}
public static List identifiersOnly(Collection l) {
List out = new ArrayList();
for (String a : unnull(l)) if (isIdentifier(a))
out.add(a);
return out;
}
public static List codeTokens(List tok) {
return codeTokensOnly(tok);
}
public static Map mergeMapsStrictlyIC(Map map1, Map map2) {
if (map2 == null)
return map1;
if (map1 == null)
return map2;
if (!canPutAllStrictlyIC(map1, map2))
return null;
return mergeMaps(map1, map2);
}
public static Map ciMapWithoutKeysEqualToValues(Map map) {
if (map == null)
return null;
Map map2 = ciMap();
for (String key : keys(map)) {
String value = map.get(key);
if (!eqic(key, value))
map2.put(key, value);
}
return map2;
}
public static LinkedHashMap paramsToMap(Object... params) {
LinkedHashMap map = new LinkedHashMap();
for (int i = 0; i + 1 < l(params); i += 2) mapPut(map, params[i], params[i + 1]);
return map;
}
public static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
public static List antiFilter(Iterable c, Object pred) {
if (pred instanceof F1)
return antiFilter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null)
for (Object o : c) if (!isTrue(callF(pred, o)))
x.add(o);
return x;
}
public static List antiFilter(Object pred, Iterable c) {
return antiFilter(c, pred);
}
public static List antiFilter(Object pred, Object[] c) {
return antiFilter(pred, wrapArrayAsList(c));
}
public static List antiFilter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (!pred.get(o).booleanValue())
x.add(o);
return x;
}
public static List antiFilter(F1 pred, Iterable c) {
return antiFilter(c, pred);
}
public static List antiFilter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (!pred.get(o).booleanValue())
x.add(o);
return x;
}
public static List antiFilter(IF1 pred, Iterable c) {
return antiFilter(c, pred);
}
public static Object[] mapToObjectArray(Map map) {
List l = new ArrayList();
for (Object o : keys(map)) {
l.add(o);
l.add(map.get(o));
}
return toObjectArray(l);
}
public static int javaTok_n, javaTok_elements;
public static boolean javaTok_opt;
public static List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') {
++j;
break;
} else if (c2 == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
public static List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
public static int indexOfSubList(List x, List y) {
return indexOfSubList(x, y, 0);
}
public static int indexOfSubList(List x, List y, int i) {
outer: for (; i + l(y) <= l(x); i++) {
for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y.get(j)))
continue outer;
return i;
}
return -1;
}
public static int indexOfSubList(List x, A[] y, int i) {
outer: for (; i + l(y) <= l(x); i++) {
for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y[j]))
continue outer;
return i;
}
return -1;
}
public static String trimJoin(List s) {
return trim(join(s));
}
public static List javaTokPlusBrackets(String s) {
return tok_combineRoundOrCurlyBrackets_keep(javaTok(s));
}
public static String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
public static String hideCredentials(String url) {
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
public static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
public static String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
public static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
public static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
public static Throwable unwrapTrivialExceptionWraps(Throwable e) {
if (e == null)
return e;
while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause();
return e;
}
public static String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix))
return s;
return replacement + substring(s, l(prefix));
}
public static Throwable innerException2(Throwable e) {
if (e == null)
return null;
while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
return e;
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
public static boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
public static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
public static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
public static Thread currentThread() {
return Thread.currentThread();
}
public static WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
public static void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
public static A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
return c;
}
public static JScrollPane jscroll(final Component c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret new JScrollPane(c);";
}
});
}
public static JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
public static JLabel jlabel() {
return jlabel(" ");
}
public static boolean newButton_autoToolTip = true;
public static JButton newButton(final String text, final Object action) {
return swing(new F0() {
public JButton get() {
try {
String text2 = dropPrefix("[disabled] ", text);
final JButton btn = new JButton(text2);
if (l(text2) < l(text))
btn.setEnabled(false);
if (newButton_autoToolTip) {
btn.setToolTipText(btn.getText());
}
if (action != null)
btn.addActionListener(actionListener(action, btn));
return btn;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S text2 = dropPrefix(\"[disabled] \", text);\r\n final JButton btn = new JButt...";
}
});
}
public static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
public static JPanel jFullCenter(final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(c);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new GridBagLayout);\r\n panel.add(c);\r\n ret panel;";
}
});
}
public static int hstackWithSpacing_spacing = 10;
public static JPanel hstackWithSpacing(Object... parts) {
parts = flattenArray2(parts);
int spacing = hstackWithSpacing_spacing;
int i = 0;
if (first(parts) instanceof Integer) {
spacing = toInt(first(parts));
++i;
}
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.gridheight = GridBagConstraints.REMAINDER;
for (; i < l(parts); i++) {
if (i != 0)
panel.add(javax.swing.Box.createRigidArea(new Dimension(spacing, 0)), gbc);
panel.add(wrapForSmartAdd(parts[i]), gbc);
}
gbc.weightx = 1;
panel.add(jrigid(), gbc);
return panel;
}
public static Object[] asArray(List l) {
return toObjectArray(l);
}
public static A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
public static boolean isString(Object o) {
return o instanceof String;
}
public static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
public static Object dm_getService(String serviceName) {
return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName)));
}
public static boolean isStringOrIntOrLong(Object o) {
return o instanceof String || o instanceof Integer || o instanceof Long;
}
public static Object dm_callOS(String functionName, Object... args) {
return call(dm_os(), functionName, args);
}
public static Object dm_resolveModule(Object moduleOrStem) {
return dm_callOS("resolveModule", moduleOrStem);
}
public static WeakReference creator_class;
public static Object creator() {
return creator_class == null ? null : creator_class.get();
}
public static int max(int a, int b) {
return Math.max(a, b);
}
public static int max(int a, int b, int c) {
return max(max(a, b), c);
}
public static long max(int a, long b) {
return Math.max((long) a, b);
}
public static long max(long a, long b) {
return Math.max(a, b);
}
public static double max(int a, double b) {
return Math.max((double) a, b);
}
public static float max(float a, float b) {
return Math.max(a, b);
}
public static double max(double a, double b) {
return Math.max(a, b);
}
public static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
public static double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
public static float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
public static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
public static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
public static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
public static boolean makeAndroid3_disable;
public static class Android3 {
public String greeting;
public boolean publicOverride;
public int startPort = 5000;
public Responder responder;
public boolean console = true;
public boolean quiet;
public boolean daemon = false;
public boolean incomingSilent = false;
public int incomingPrintLimit = 200;
public boolean useMultiPort = true;
public boolean recordHistory;
public boolean verbose;
public int answerPrintLimit = 500;
public boolean newLineAboveAnswer, newLineBelowAnswer;
public int port;
public long vport;
public DialogHandler handler;
public ServerSocket server;
public Android3(String greeting) {
this.greeting = greeting;
}
public Android3() {
}
public synchronized void dispose() {
if (server != null) {
try {
server.close();
} catch (IOException e) {
print("[internal] " + e);
}
server = null;
}
if (vport != 0) {
try {
print("Disposing " + this);
removeFromMultiPort(vport);
vport = 0;
} catch (Throwable __e) {
_handleException(__e);
}
}
}
public String toString() {
return "Bot: " + greeting + " [vport " + vport + "]";
}
}
public abstract static class Responder {
public abstract String answer(String s, List history);
}
public static Android3 makeAndroid3(final String greeting) {
return makeAndroid3(new Android3(greeting));
}
public static Android3 makeAndroid3(final String greeting, Responder responder) {
Android3 android = new Android3(greeting);
android.responder = responder;
return makeAndroid3(android);
}
public static Android3 makeAndroid3(final Android3 a) {
if (makeAndroid3_disable)
return a;
if (a.responder == null)
a.responder = new Responder() {
public String answer(String s, List history) {
return callStaticAnswerMethod(s, history);
}
};
if (!a.quiet)
print("[bot] " + a.greeting);
if (a.console && (readLine_noReadLine || makeAndroid3_consoleInUse()))
a.console = false;
record(a);
if (a.useMultiPort)
a.vport = addToMultiPort(a.greeting, makeAndroid3_verboseResponder(a));
if (a.console)
makeAndroid3_handleConsole(a);
if (a.useMultiPort)
return a;
a.handler = makeAndroid3_makeDialogHandler(a);
if (a.quiet)
startDialogServer_quiet.set(true);
try {
a.port = a.daemon ? startDialogServerOnPortAboveDaemon(a.startPort, a.handler) : startDialogServerOnPortAbove(a.startPort, a.handler);
} finally {
startDialogServer_quiet.set(null);
}
a.server = startDialogServer_serverSocket;
return a;
}
public static void makeAndroid3_handleConsole(final Android3 a) {
if (!a.quiet)
print("You may also type on this console.");
startThread(new Runnable() {
public void run() {
try {
List history = new ArrayList();
while (licensed()) {
String line;
try {
line = readLine();
} catch (Throwable e) {
print(getInnerMessage(e));
break;
}
if (line == null)
break;
{
history.add(line);
history.add(makeAndroid3_getAnswer(line, history, a));
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "List history = new ArrayList();\r\n while (licensed()) {\r\n Stri...";
}
});
}
public static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) {
return new DialogHandler() {
public void run(final DialogIO io) {
if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) {
io.sendLine("Sorry, not allowed");
return;
}
String dialogID = randomID(8);
io.sendLine(a.greeting + " / Your ID: " + dialogID);
List history = new ArrayList();
while (io.isStillConnected()) {
if (io.waitForLine()) {
final String line = io.readLineNoBlock();
String s = dialogID + " at " + now() + ": " + quote(line);
if (!a.incomingSilent)
print(shorten(s, a.incomingPrintLimit));
if (eq(line, "bye")) {
io.sendLine("bye stranger");
return;
}
Matches m = new Matches();
if (a.recordHistory)
history.add(line);
String answer;
if (match3("this is a continuation of talk *", s, m) || match3("hello bot! this is a continuation of talk *", s, m)) {
dialogID = unquote(m.m[0]);
answer = "ok";
} else
try {
makeAndroid3_io.set(io);
answer = makeAndroid3_getAnswer(line, history, a);
} finally {
makeAndroid3_io.set(null);
}
if (a.recordHistory)
history.add(answer);
io.sendLine(answer);
}
}
}
};
}
public static String makeAndroid3_getAnswer(String line, List history, Android3 a) {
String answer, originalAnswer;
try {
originalAnswer = a.responder.answer(line, history);
answer = makeAndroid3_fallback(line, history, originalAnswer);
} catch (Throwable e) {
e = getInnerException(e);
printStackTrace(e);
originalAnswer = answer = e.toString();
}
if (!a.incomingSilent) {
if (originalAnswer == null)
originalAnswer = "?";
if (a.newLineAboveAnswer)
print();
print(">" + dropFirst(indentx(2, shorten(rtrim(originalAnswer), a.answerPrintLimit))));
if (a.newLineBelowAnswer)
print();
}
return answer;
}
public static String makeAndroid3_fallback(String s, List history, String answer) {
if (answer == null && match3("what is your pid", s))
return getPID();
if (answer == null && match3("what is your program id", s))
return getProgramID();
if (match3("get injection id", s))
return getInjectionID();
if (answer == null)
answer = "?";
if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
answer = quote(answer);
return answer;
}
public static boolean makeAndroid3_consoleInUse() {
if (isTrue(vm_generalMap_get("consoleInUse")))
return true;
for (Object o : record_list) if (o instanceof Android3 && ((Android3) o).console)
return true;
return false;
}
public static Responder makeAndroid3_verboseResponder(final Android3 a) {
return new Responder() {
public String answer(String s, List history) {
if (a.verbose)
print("> " + shorten(s, a.incomingPrintLimit));
String answer = a.responder.answer(s, history);
if (a.verbose)
print("< " + shorten(answer, a.incomingPrintLimit));
return answer;
}
};
}
public static ThreadLocal makeAndroid3_io = new ThreadLocal();
public static Android3 makeAndroid3() {
return makeAndroid3(getProgramTitle() + ".");
}
public static int makeBot(String greeting) {
return makeAndroid3(greeting).port;
}
public static Android3 makeBot(Android3 a) {
makeAndroid3(a);
return a;
}
public static Android3 makeBot(String greeting, Object responder) {
Android3 a = new Android3(greeting);
a.responder = makeResponder(responder);
makeBot(a);
return a;
}
public static Android3 makeBot() {
return makeAndroid3(defaultBotName());
}
public static long toLong(Object o) {
if (o instanceof Number)
return ((Number) o).longValue();
if (o instanceof String)
return parseLong((String) o);
return 0;
}
public static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
public static final Map callOpt_cache = newDangerousWeakHashMap();
public static Object callOpt_cached(Object o, String methodName, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null)
return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static _MethodCache callOpt_getCache(Class c) {
synchronized (callOpt_cache) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
}
public static String joinWithComma(Collection c) {
return join(", ", c);
}
public static String joinWithComma(String... c) {
return join(", ", c);
}
public static String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
public static List classNames(Collection l) {
return getClassNames(l);
}
public static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
public static Object invokeMethod(Method m, Object o, Object... args) {
try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = args.length;
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
Object[] varArgs = arrayOfType(varArgType, nArgs - n);
arraycopy(args, n, varArgs, 0, nArgs - n);
newArgs[n] = varArgs;
return newArgs;
}
public static String dm_makeModule(String moduleLibID) {
return (String) callCreator("makeModule", moduleLibID);
}
public static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
public static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
public static Class _getClass(Object o) {
return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
}
public static Class _getClass(Object realm, String name) {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
public static void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
if (type == int.class && value instanceof Long)
value = ((Long) value).intValue();
if (type == LinkedHashMap.class && value instanceof Map) {
f.set(o, asLinkedHashMap((Map) value));
return;
}
try {
if (f.getType() == Concept.Ref.class) {
f.set(o, ((Concept) o).new Ref((Concept) value));
return;
}
if (o instanceof Concept.Ref) {
f.set(o, ((Concept.Ref) o).get());
return;
}
} catch (Throwable _e) {
}
throw e;
}
}
public static boolean odd(int i) {
return (i & 1) != 0;
}
public static boolean odd(long i) {
return (i & 1) != 0;
}
public static boolean odd(BigInteger i) {
return odd(toInt(i));
}
public static Comparator caseInsensitiveComparator() {
return betterCIComparator();
}
public static TreeSet toCaseInsensitiveSet(Iterable c) {
if (isCISet(c))
return (TreeSet) c;
TreeSet set = caseInsensitiveSet();
addAll(set, c);
return set;
}
public static TreeSet