Warning : session_start(): open(/var/lib/php/sessions/sess_7uf94en8k9df8vo3a3k8ihat8l, 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.loadPage_utf8;
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.componentPopupMenu_initForComponent;
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.imageio.metadata.*;
import javax.imageio.stream.*;
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 GRawBot extends DynPrintLog {
public boolean debug;
public transient GazelleContextCache_v2 contextCache = new GazelleContextCache_v2();
public void start() {
super.start();
ownResource(contextCache.listenToMessages());
contextCache.alwaysFullRefresh();
dm_vmBus_onMessage("gazelleActionableLine", new VF1() {
public void get(String a) {
try {
processLine(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "processLine(a)";
}
});
}
public void processLine(final String lineID) {
dm_q(new Runnable() {
public void run() {
try {
print("Processing line: " + lineID);
GazelleLine line = gazelle_lineForGlobalID(lineID);
if (line == null) {
print("Line not found");
return;
}
String content = line.text;
print("Text: " + content);
List preContext = null;
Object[] params = litmapparams("preContext", preContext, "badComments", mechCISet("Knock-out rule comments"), "respondingToHuman", !line.bot, "debug", debug, "contextMaker", contextCache);
List l = gazelle_reason_repeat(content, params);
pnl(l);
print();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "print(\"Processing line: \" + lineID);\r\n GazelleLine line = gazelle_lineForG...";
}
});
}
}
public static boolean _moduleClass_GRawBot;
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 call_withVarargs(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 volatile Object print_preprocess;
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) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, 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 void ownResource(AutoCloseable c) {
_registerAutoCloseable(c);
}
public static AutoCloseable dm_vmBus_onMessage(final String msg, final VF1 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
public static AutoCloseable dm_vmBus_onMessage(String msg, final VF2 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
public static AutoCloseable dm_vmBus_onMessage(String msg, Runnable onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
public static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
public static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
public static Q dm_q() {
return dm_current_mandatory().q();
}
public static void dm_q(Runnable r) {
dm_inQ(r);
}
public static void dm_q(DynModule module, Runnable r) {
module.q().add(r);
}
public static GazelleLine gazelle_lineForGlobalID(String globalID) {
return dm_discord_importLine(dm_call(dm_gazelle_linesCRUD(), "lineForGlobalID", globalID));
}
public static Object[] litmapparams(Object... l) {
return new Object[] { litmap(l) };
}
public static MechListDependentCaches> mechCISet_cache = new MechListDependentCaches(new F1>() {
public TreeSet get(String text) {
try {
return asCISet(tlft(text));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "asCISet(tlft(text))";
}
});
public static TreeSet mechCISet(String name) {
return mechCISet_cache.get(name);
}
public static List gazelle_reason_repeat(String input, Object... __) {
List out = new ArrayList();
int steps = 0, max = 10;
while (steps++ < max) {
addAll(out, (List) callF(optPar("sendToModules", __), input));
List l = gazelle_reasonWithPreAndPost(input, paramsMinus(__, "sendToModules"));
if (empty(l))
break;
gazelle_sortBeforeCommit(l, __);
GazelleTree t = first(l);
if (boolPar("debug", __) || boolPar("debugCommit", __))
print("Committing to: " + t.line + " (out of " + l(l) + ")");
List lines = tok_splitAtPlusAtBeginningOfLine(t.line);
if (l(lines) == 2 && t.rule() != null && contains(t.rule().comments, "out 2 = process")) {
print("splitting!");
t.line = first(lines);
out.add(t);
input = second(lines);
continue;
}
out.add(t);
break;
}
return out;
}
public static A pnl(A l) {
printNumberedLines(l);
return l;
}
public static void pnl(Map map) {
printNumberedLines(map);
}
public static void pnl(Object[] a) {
printNumberedLines(a);
}
public static void pnl(String s) {
printNumberedLines(lines(s));
}
public static Class mc() {
return main.class;
}
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.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
{
if (!(isStaticMethod(m)))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} 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 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 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 Set _registerAutoCloseable_set = synchroHashSet();
public static void _registerAutoCloseable(AutoCloseable c) {
addIfNotNull(_registerAutoCloseable_set, c);
}
public static void cleanMeUp__registerAutoCloseable() {
closeAutoCloseables(getAndClearList(_registerAutoCloseable_set));
}
public static AutoCloseable dm_ownResource(AutoCloseable resource) {
dm_currentModuleMandatory().ownResource(resource);
return resource;
}
public static AutoCloseable vmBus_onMessage(final String msg, final VF1 onMessage) {
Map map = vm_busListenersByMessage_live();
synchronized (map) {
Set listeners = map.get(msg);
if (listeners == null)
map.put(msg, listeners = syncIdentityHashSet());
return tempAdd(listeners, new VF2() {
public void get(String _msg, Object arg) {
try {
callF(onMessage, arg);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, arg)";
}
});
}
}
public static AutoCloseable vmBus_onMessage(String msg, final VF2 onMessage) {
return vmBus_onMessage(msg, new VF1() {
public void get(Object[] o) {
try {
callF(onMessage, first(o), second(o));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, first(o), second(o));";
}
});
}
public static AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) {
return vmBus_onMessage(msg, runnableToVF1(onMessage));
}
public static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
public static void dm_inQ(Runnable r) {
dm_q().add(r);
}
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), "context", _get("context", 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 __65 = dm_enter(mod);
try {
return call_withVarargs(mod, method, args);
} finally {
_close(__65);
}
}
public static String dm_gazelle_linesCRUD() {
return dm_require("#1021628/GLines");
}
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 TreeSet asCISet(Iterable c) {
return toCaseInsensitiveSet(c);
}
public static TreeSet asCISet(String... x) {
return toCaseInsensitiveSet(x);
}
public static List tlft(String s) {
return toLinesFullTrim(s);
}
public static List tlft(File f) {
return toLinesFullTrim(f);
}
public static void addAll(Collection c, Iterable b) {
if (c != null && b != null)
for (A a : b) c.add(a);
}
public static boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
public static boolean addAll(Collection c, B... b) {
return c != null && c.addAll(Arrays.asList(b));
}
public static void addAll(Collector c, Iterable b) {
if (c != null && b != null)
for (A a : b) c.add(a);
}
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 List gazelle_reasonWithPreAndPost(String input, Object... __) {
return gazelle_postprocess(gazelle_reasonWithPreprocessing(input, __), __);
}
public static Object[] paramsMinus(Object[] a1, Object... keys) {
return paramsWithout(a1, keys);
}
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 void gazelle_sortBeforeCommit(List l, Object... __) {
boolean debug = boolPar("debugSorting", __);
sort(l, new Comparator() {
public int compare(GazelleTree a, GazelleTree b) {
if (debug)
print("sorting: " + a.line + " / " + b.line);
int c = ai_goodBadToInt(b.prediction) - ai_goodBadToInt(a.prediction);
if (debug)
print(" " + c);
if (c != 0)
return c;
c = gazelle_historyLevelRequired(b.rule()) - gazelle_historyLevelRequired(a.rule());
if (debug)
print(" " + c);
return c;
}
});
}
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 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 List tok_splitAtPlusAtBeginningOfLine(String s) {
List indices = new ArrayList();
List tok = javaTokWithAllBrackets(s);
for (int i = 1; i < l(tok); i += 2) if (eqGet(tok, i, "+") && containsNewLine(get(tok, i - 1)))
indices.add(i);
return splitAtTokenIndices(tok, indices);
}
public static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
public static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
public static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
public static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
public static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
public static A second(List l) {
return get(l, 1);
}
public static A second(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
if (!it.hasNext())
return null;
it.next();
return it.hasNext() ? it.next() : null;
}
public static A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
public static B second(Pair p) {
return p == null ? null : p.b;
}
public static B second(T3 t) {
return t == null ? null : t.b;
}
public static A second(Producer p) {
if (p == null)
return null;
if (p.next() == null)
return null;
return p.next();
}
public static List printNumberedLines(List l) {
printNumberedLines((Collection ) l);
return l;
}
public static void printNumberedLines(Map map) {
printNumberedLines(mapToLines(map));
}
public static A printNumberedLines(A l) {
int i = 0;
if (l != null)
for (Object a : l) print((++i) + ". " + str(a));
return l;
}
public static void printNumberedLines(Object[] l) {
printNumberedLines(asList(l));
}
public static void printNumberedLines(Object o) {
printNumberedLines(lines(str(o)));
}
public static String lines(Iterable lines) {
return fromLines(lines);
}
public static String lines(Object[] lines) {
return fromLines(asList(lines));
}
public static List lines(String s) {
return toLines(s);
}
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 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 boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
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 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 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 boolean neq(Object a, Object b) {
return !eq(a, b);
}
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 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 boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || b != null && a.equals(b);
}
public static Set synchroHashSet() {
return Collections.synchronizedSet(new HashSet ());
}
public static void addIfNotNull(Collection l, A a) {
if (a != null && l != null)
l.add(a);
}
public static void addIfNotNull(MultiSet ms, A a) {
if (a != null && ms != null)
ms.add(a);
}
public static void closeAutoCloseables(Collection l) {
if (l != null)
for (AutoCloseable c : l) {
try {
c.close();
} catch (Throwable __e) {
_handleException(__e);
}
}
}
public static List getAndClearList(Collection l) {
if (l == null)
return emptyList();
synchronized (collectionMutex(l)) {
List out = cloneList(l);
l.clear();
return out;
}
}
public static DynModule dm_currentModuleMandatory() {
return dm_current_mandatory();
}
public static Map vm_busListenersByMessage_live_cache;
public static Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
public static Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
public static Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
public static AutoCloseable tempAdd(final Collection l, final A a) {
if (l == null || l.contains(a))
return null;
l.add(a);
return new AutoCloseable() {
public String toString() {
return "l.remove(a);";
}
public void close() throws Exception {
l.remove(a);
}
};
}
public static A third(List l) {
return _get(l, 2);
}
public static A third(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
for (int _repeat_152 = 0; _repeat_152 < 2; _repeat_152++) {
if (!it.hasNext())
return null;
it.next();
}
return it.hasNext() ? it.next() : null;
}
public static A third(Producer p) {
if (p == null)
return null;
for (int _repeat_153 = 0; _repeat_153 < 2; _repeat_153++) {
if (p.next() == null)
return null;
}
return p.next();
}
public static A third(A[] bla) {
return bla == null || bla.length <= 2 ? null : bla[2];
}
public static C third(T3 t) {
return t == null ? null : t.c;
}
public static VF1 runnableToVF1(final Runnable r) {
return r == null ? null : new VF1 () {
public void get(A a) {
try {
r.run();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "r.run()";
}
};
}
public static A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
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 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(A[] 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 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 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 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 String dm_require(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
public static TreeSet toCaseInsensitiveSet(Iterable c) {
if (isCISet(c))
return (TreeSet) c;
TreeSet set = caseInsensitiveSet();
addAll(set, c);
return set;
}
public static TreeSet toCaseInsensitiveSet(String... x) {
TreeSet set = caseInsensitiveSet();
addAll(set, x);
return set;
}
public static List toLinesFullTrim(String s) {
List l = new ArrayList();
for (String line : toLines(s)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
public static List toLinesFullTrim(File f) {
List l = new ArrayList();
for (String line : linesFromFile(f)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
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) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : 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 gazelle_postprocess(List l, Object... __) {
l = takeFirst_clone(10, l);
if (!boolPar("noEvals", __))
gazelle_processSafeEvalsInTree(l);
return l;
}
public static List gazelle_reasonWithPreprocessing(String input1, Object... __) {
F0 contextMaker = (F0) (assertNotNull("Need contextMaker", optPar("contextMaker", __)));
String userName = stringPar("userName", __);
boolean debug = boolPar("debug", __);
boolean debugPreprocessing = boolPar("debugPreprocessing", __);
Collector interpretables_out = (Collector) (optPar("interpretables_out", __));
Collection interpretables = gazelle_preprocess(input1, __);
if (debugPreprocessing) {
print("Got " + n2(interpretables, "interpretable") + ".");
printIndentLines(interpretables);
}
if (interpretables != null)
addAll(interpretables_out, interpretables);
Set acceptablePurposes = (Set) (optPar("acceptablePurposes", __));
if (acceptablePurposes == null)
acceptablePurposes = litset("");
List l2 = new ArrayList();
Set outputs = ciSet();
for (GInterpretable intp : interpretables) {
List results = dm_gazelle_reasonAboutChatInput_v2(userName, intp.text, paramsPlus(__, "acceptablePurposes", acceptablePurposes));
print(intp.text + " => " + n2(results, "result"));
for (GazelleTree tree : results) if (outputs.add(tree.line)) {
if (tree.mr != null)
tree.mr.interpretable = intp;
l2.add(tree);
}
}
gazelle_dropMatchedDefaultRules(l2, __);
return l2;
}
public static Object[] paramsWithout(Object[] a1, Object... keys) {
if (l(a1) == 1 && a1[0] instanceof Map)
return new Object[] { mapMinus((Map) a1[0], keys) };
Set set = lithashset(keys);
List l = new ArrayList();
for (int i = 0; i + 1 < l(a1); i += 2) if (!set.contains(a1[i])) {
l.add(a1[i]);
l.add(a1[i + 1]);
}
return toObjectArray(l);
}
public static String getType(Object o) {
return getClassName(o);
}
public static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
public static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
public static void sort(T[] a, Comparator super T> c) {
Arrays.sort(a, c);
}
public static void sort(T[] a) {
Arrays.sort(a);
}
public static void sort(List a, Comparator super T> c) {
Collections.sort(a, c);
}
public static void sort(List a) {
Collections.sort(a);
}
public static int ai_goodBadToInt(String s) {
if (eq(s, "good"))
return 1;
if (eq(s, "bad"))
return -1;
return 0;
}
public static int gazelle_historyLevelRequired(RuleEngine2.Rule rule) {
if (rule == null)
return 0;
int n = 0;
Matches m = new Matches();
for (GRuleLine l : unnull(rule.insWithType)) if (eq(l.type, "standard"))
n = max(n, 1);
else if (startsWith(l.type, "history-", m))
n = max(n, parseIntOpt(m.rest()));
return n;
}
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 javaTokWithAllBrackets(String s) {
return javaTokPlusBrackets2(s);
}
public static boolean eqGet(List l, int i, Object o) {
return eq(get(l, i), o);
}
public static boolean eqGet(Map map, A key, Object o) {
return eq(mapGet(map, key), o);
}
public static boolean containsNewLine(String s) {
return contains(s, '\n');
}
public static List splitAtTokenIndices(List tok, List indices) {
List l = new ArrayList();
for (int iI = -1; iI < l(indices); iI++) {
int i = or(get(indices, iI), 0) + 1;
int j = or(get(indices, iI + 1), l(tok));
l.add(trimJoin(tok.subList(i, j)));
}
return l;
}
public static Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
public static List mapToLines(Map map) {
List l = new ArrayList();
for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
return l;
}
public static String mapToLines(Map map, Object f) {
return lines(map(map, f));
}
public static String str(Object o) {
return o == null ? "null" : o.toString();
}
public static String str(char[] c) {
return new String(c);
}
public static String fromLines(Iterable lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines) buf.append(str(line)).append('\n');
return buf.toString();
}
public static String fromLines(String... lines) {
return fromLines(asList(lines));
}
public static IterableIterator toLines(File f) {
return linesFromFile(f);
}
public static List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
public static int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
public static Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
public static String joinWithSpace(Collection c) {
return join(" ", c);
}
public static String joinWithSpace(String... c) {
return join(" ", c);
}
public static boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
public static boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
public static void arraycopy(Object[] a, Object[] b) {
int n = min(a.length, b.length);
for (int i = 0; i < n; i++) b[i] = a[i];
}
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
System.arraycopy(src, srcPos, dest, destPos, n);
}
public static A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
public static A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(Iterable strings) {
return join("", strings);
}
public static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
public static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
public static List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
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 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 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(Object[] l) {
return emptyList(l(l));
}
public static ArrayList emptyList(Class c) {
return new ArrayList();
}
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 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 Set synchronizedSet() {
return synchroHashSet();
}
public static Set synchronizedSet(Set set) {
return Collections.synchronizedSet(set);
}
public static Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
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 A setAll(A o, Map fields) {
if (fields == null)
return o;
for (String field : keys(fields)) set(o, field, fields.get(field));
return o;
}
public static A setAll(A 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);
}
return o;
}
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 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 String dm_makeModule(String moduleLibID) {
return (String) dm_callOS("makeModule", moduleLibID);
}
public static boolean isCISet(Iterable l) {
return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator();
}
public static TreeSet caseInsensitiveSet() {
return new TreeSet(caseInsensitiveComparator());
}
public static TreeSet caseInsensitiveSet(Collection c) {
return toCaseInsensitiveSet(c);
}
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 CloseableIterableIterator linesFromFile(File f) {
try {
if (!f.exists())
return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
return linesFromReader(utf8bufferedReader(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean even(int i) {
return (i & 1) == 0;
}
public static boolean even(long i) {
return (i & 1) == 0;
}
public static List takeFirst_clone(List l, int n) {
return cloneSubList(l, 0, n);
}
public static List takeFirst_clone(int n, List l) {
return takeFirst_clone(l, n);
}
public static List takeFirst_clone(int n, Iterable i) {
List l = new ArrayList();
Iterator it = i.iterator();
for (int _repeat_292 = 0; _repeat_292 < n; _repeat_292++) {
if (it.hasNext())
l.add(it.next());
else
break;
}
return l;
}
public static void gazelle_processSafeEvalsInTree(List tree) {
Map evalCache = new HashMap();
if (tree != null)
for (GazelleTree t : tree) {
String l = dm_processEmbeddedSafeEvals(t.line, "evalCache", evalCache);
if (l != t.line) {
print("Processed eval: " + t.line + " => " + l);
t.line = l;
}
}
}
public static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
public static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
public static String stringPar(Object[] params, String name) {
return stringOptPar(params, name);
}
public static String stringPar(String name, Object[] params) {
return stringOptPar(params, name);
}
public static String stringPar(String name, Object[] params, String defaultValue) {
return optPar(name, params, defaultValue);
}
public static Collection gazelle_preprocess(String input1, Object... __) {
List interpretables = new ArrayList();
int max = optPar("max", __, 20);
Collector collector = limitedCollector(interpretables, max);
Map evalCache = new HashMap();
F1 eval = boolPar("noEvals", __) ? f_id() : new F1() {
public String get(String s) {
try {
return gazelle_processSafeEvals(s, evalCache);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "gazelle_processSafeEvals(s, evalCache)";
}
};
input1 = callF(eval, input1);
Set texts = litCISet(input1);
collector.add(new GInterpretable(input1));
RuleEngine2 engine = ((F0) optPar("contextMaker", __)).get().engine;
int nInterpreted = 0;
bigLoop: while (!collector.full() && nInterpreted < l(interpretables)) {
GInterpretable workingOn = get(interpretables, nInterpreted);
String input = workingOn.text;
String ruleBase = empty(workingOn.ruleID) ? "" : workingOn.ruleID + "+";
++nInterpreted;
for (RuleEngine2.SimplifyWithRule rule : engine.splitterRules()) {
try {
for (String out : gazelle_executeSplitterRule(engine, rule, input)) if (texts.add(out = callF(eval, out)))
if (collector.add(new GInterpretable(out, ruleBase + rule.globalID)))
break bigLoop;
} catch (Throwable __e) {
_handleException(__e);
}
}
for (GazelleTree t : dm_gazelle_reasonAboutChatInput_v2(null, input, paramsPlus(__, "skipSplitters", true, "acceptablePurposes", litset("preprocess"), "skipUserName", true, "skipUserID", true))) {
String s = callF(eval, t.line);
if (texts.add(s))
if (collector.add(new GInterpretable(s, ruleBase + t.ruleID(), t.mr)))
break bigLoop;
}
}
return interpretables;
}
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 > A printIndentLines(String indent, A lines) {
return printLinesWithIndent(indent, lines);
}
public static > A printIndentLines(A lines) {
return printLinesWithIndent(defaultIndent(), lines);
}
public static HashSet litset(A... items) {
return lithashset(items);
}
public static TreeSet ciSet() {
return caseInsensitiveSet();
}
public static List dm_gazelle_reasonAboutChatInput_v2(String userName, String content, Object... __) {
boolean debug = boolPar("debug", __);
boolean debugRules = boolPar("debugRules", __) || debug;
List preContext = (List) (optPar("preContext", __));
GazelleEvalContext ctx = (GazelleEvalContext) (optPar("ctx", __));
F0 contextMaker = (F0) (optPar("contextMaker", __));
if (debugRules)
print("Have ctx: " + (ctx != null) + ", contextMaker: " + (contextMaker != null));
if (ctx == null && contextMaker != null) {
ctx = contextMaker.get();
if (debugRules)
print("Called contextMaker, got " + n2(ctx.engine.rules, "rule"));
}
if (ctx == null)
ctx = dm_gazelle_stdEvalContext(dm_gazelle_allRulesWithComment(optPar("requiredComment", __, "discord")));
Set acceptablePurposes = (Set) (optPar("acceptablePurposes", __));
if (debug)
print(" == PROCESSING INPUT: " + content);
gazelle_dropRulesNotOnInput(ctx);
if (acceptablePurposes != null) {
if (debugRules) {
print("Purposes: " + acceptablePurposes);
print("Have purposes: " + collectUnique("purpose", ctx.engine.rules));
}
int nBefore = l(ctx.engine.rules);
ctx.engine.dropRulesWhere(r -> !acceptablePurposes.contains(unnull(r.purpose)));
if (debugRules)
print("Retaining " + n2(ctx.engine.rules, "rule") + " of " + nBefore);
}
if (debugRules)
print("Have rules: " + collect("globalID", ctx.engine.rules));
gazelle_addHelpers(ctx, __);
Object[] params = paramsPlus(paramsMinus(__, "ctx"), "firstConditionOnly", true, "dialogHistory", preContext);
GazelleTree tree1 = (GazelleTree) (optPar("tree", __));
if (tree1 == null)
tree1 = new GazelleTree(ctx, content);
List l = gazelle_getChildren_withContinuations(tree1, params);
if (nempty(userName) && !boolPar("skipUserName", __)) {
GazelleTree tree2 = new GazelleTree(ctx, optCurly(userName) + " says: " + content);
if (debug)
print("Tree2: " + tree2);
l.addAll(gazelle_getChildren_withContinuations(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(gazelle_getChildren_withContinuations(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);
Map inputMap = gazelle_inputMapFromLineAndHistory(content, listPlus(preContext, content));
if (debug)
print("reasonAbout inputMap=" + sfu(asTreeMap(inputMap)));
for (GazelleTree t : l) {
if (t.mr == null)
continue;
int iCond;
do {
iCond = t.mr.iCond;
dm_gazelle_matchStep_statement(t, passParams(__, "debug", "dm_gazelle_matchStatementsDebug"));
dm_gazelle_matchStep_additionalInput(t, inputMap, __);
dm_gazelle_matchStep_condition(t, __);
} while (t.mr.iCond > iCond);
}
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) + ")");
if (!boolPar("keepDefaults", __))
gazelle_dropMatchedDefaultRules(l, __);
return l;
}
public static Object[] paramsPlus(Object[] a1, Object... a2) {
if (a2 == null)
return a1;
if (a1 == null)
return a2;
if (l(a1) == 1 && a1[0] instanceof Map)
return new Object[] { mapPlus((Map) a1[0], 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 void gazelle_dropMatchedDefaultRules(List l, Object... __) {
List l2 = filter(l, t -> !eqic(t.lineType, "temporary fact"));
Set trumpedRules = new HashSet();
for (GazelleTree t : l2) addAll(trumpedRules, matchAll_first("trumps rule *", t.ruleComments()));
List trumped = filter(l2, new F1() {
public Boolean get(GazelleTree t) {
try {
return contains(t.ruleComments(), "default") || trumpedRules.contains(t.ruleID());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "contains(t.ruleComments(), \"default\")\r\n || trumpedRules.contains(t.ruleID())";
}
});
if (nempty(trumped) && l(trumped) < l(l2)) {
if (boolPar("debug", __) || boolPar("debugDefaults", __)) {
print("Removing default/trumped rules:");
printIndentLines(trumped);
print("Because there are also:");
printIndentLines(listMinusSet(l2, trumped));
}
l.removeAll(trumped);
}
}
public static Map mapMinus(Map map, Object... keys) {
if (empty(keys))
return map;
Map m2 = cloneMap(map);
for (Object key : keys) m2.remove(key);
return m2;
}
public static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
public static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
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 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 int parseIntOpt(String s) {
return isInteger(s) ? parseInt(s) : 0;
}
public static List javaTokPlusBrackets2(String s) {
return tok_combineRoundCurlySquareBrackets_keep(javaTok(s));
}
public static B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
public static B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
public static A or(A a, A b) {
return a != null ? a : b;
}
public static String trimJoin(List s) {
return trim(join(s));
}
public static Iterator emptyIterator() {
return Collections.emptyIterator();
}
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 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 int min(int a, int b) {
return Math.min(a, b);
}
public static long min(long a, long b) {
return Math.min(a, b);
}
public static float min(float a, float b) {
return Math.min(a, b);
}
public static float min(float a, float b, float c) {
return min(min(a, b), c);
}
public static double min(double a, double b) {
return Math.min(a, b);
}
public static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
public static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
public static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
public static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
public static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
public static A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
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 String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
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 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 String className(Object o) {
return getClassName(o);
}
public static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
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 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 void removeFromMultiPort(long vport) {
if (vport == 0)
return;
for (Object port : getMultiPorts()) call(port, "removePort", vport);
}
public static String callStaticAnswerMethod(List bots, String s) {
for (Object c : bots) try {
String answer = callStaticAnswerMethod(c, s);
if (!empty(answer))
return answer;
} catch (Throwable e) {
print("Error calling " + getProgramID(c));
e.printStackTrace();
}
return null;
}
public static String callStaticAnswerMethod(Object c, String s) {
String answer = (String) callOpt(c, "answer", s, litlist(s));
if (answer == null)
answer = (String) callOpt(c, "answer", s);
return emptyToNull(answer);
}
public static String callStaticAnswerMethod(String s) {
return callStaticAnswerMethod(mc(), s);
}
public static String callStaticAnswerMethod(String s, List history) {
return callStaticAnswerMethod(mc(), s, history);
}
public static String callStaticAnswerMethod(Object c, String s, List history) {
String answer = (String) callOpt(c, "answer", s, history);
if (answer == null)
answer = (String) callOpt(c, "answer", s);
return emptyToNull(answer);
}
public static List record_list = synchroList();
public static void record(Object o) {
record_list.add(o);
}
public static Object addToMultiPort_responder;
public static long addToMultiPort(final String botName) {
return addToMultiPort(botName, new Object() {
public String answer(String s, List history) {
String answer = (String) (callOpt(getMainClass(), "answer", s, history));
if (answer != null)
return answer;
answer = (String) callOpt(getMainClass(), "answer", s);
if (answer != null)
return answer;
if (match3("get injection id", s))
return getInjectionID();
return null;
}
});
}
public static long addToMultiPort(final String botName, final Object responder) {
addToMultiPort_responder = responder;
startMultiPort();
List ports = getMultiPorts();
if (ports == null)
return 0;
if (ports.isEmpty())
throw fail("No multiports!");
if (ports.size() > 1)
print("Multiple multi-ports. Using last one.");
Object port = last(ports);
Object responder2 = new Object() {
public String answer(String s, List history) {
if (match3("get injection id", s))
return getInjectionID();
if (match3("your name", s))
return botName;
return (String) call(responder, "answer", s, history);
}
};
record(responder2);
return (Long) call(port, "addResponder", botName, responder2);
}
public static AtomicInteger dialogServer_clients = new AtomicInteger();
public static boolean dialogServer_printConnects;
public static ThreadLocal startDialogServer_quiet = new ThreadLocal();
public static Set dialogServer_knownClients = synchroTreeSet();
public static int startDialogServerOnPortAbove(int port, DialogHandler handler) {
while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler)) ++port;
return port;
}
public static int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) {
while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler, true)) ++port;
return port;
}
public static void startDialogServer(int port, DialogHandler handler) {
if (!startDialogServerIfPortAvailable(port, handler))
throw fail("Can't start dialog server on port " + port);
}
public static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) {
return startDialogServerIfPortAvailable(port, handler, false);
}
public static ServerSocket startDialogServer_serverSocket;
public static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
return false;
}
final ServerSocket _serverSocket = serverSocket;
startDialogServer_serverSocket = serverSocket;
Thread thread = new Thread("Socket accept port " + port) {
public void run() {
try {
while (true) {
try {
final Socket s = _serverSocket.accept();
String client = s.getInetAddress().toString();
if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) {
print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet());
dialogServer_knownClients.add(client);
}
String threadName = "Handling client " + s.getInetAddress();
Thread t2 = new Thread(threadName) {
public void run() {
try {
final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
DialogIO io = new DialogIO() {
public boolean isLocalConnection() {
return s.getInetAddress().isLoopbackAddress();
}
public boolean isStillConnected() {
return !(eos || s.isClosed());
}
public void sendLine(String line) {
try {
w.write(line + "\n");
w.flush();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String readLineImpl() {
try {
return in.readLine();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void close() {
try {
s.close();
} catch (IOException e) {
}
}
public Socket getSocket() {
return s;
}
};
try {
handler.run(io);
} finally {
if (!io.noClose)
s.close();
}
} catch (IOException e) {
print("[internal] " + e);
} finally {
}
}
};
t2.setDaemon(true);
t2.start();
} catch (SocketTimeoutException e) {
}
}
} catch (IOException e) {
print("[internal] " + e);
}
}
};
if (daemon)
thread.setDaemon(true);
thread.start();
if (!isTrue(getAndClearThreadLocal(startDialogServer_quiet)))
print("Dialog server on port " + port + " started.");
return true;
}
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 volatile boolean readLine_noReadLine;
public static String readLine_lastInput;
public static String readLine_prefix = "[] ";
public static String readLine() {
if (readLine_noReadLine)
return null;
String s = readLineHidden();
if (s != null) {
readLine_lastInput = s;
print(readLine_prefix + s);
}
return s;
}
public static String getInnerMessage(Throwable e) {
if (e == null)
return null;
return getInnerException(e).getMessage();
}
public static boolean publicCommOn() {
return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication")));
}
public static int randomID_defaultLength = 12;
public static String randomID(int length) {
return makeRandomID(length);
}
public static String randomID() {
return randomID(randomID_defaultLength);
}
public static long now_virtualTime;
public static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
public static String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
public static String quote(String s) {
if (s == null)
return "null";
StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
quote_impl(s, out);
return out.toString();
}
public static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
public static int shorten_default = 100;
public static String shorten(String s) {
return shorten(s, shorten_default);
}
public static String shorten(String s, int max) {
return shorten(s, max, "...");
}
public static String shorten(String s, int max, String shortener) {
if (s == null)
return "";
if (max < 0)
return s;
return s.length() <= max ? s : substring(s, 0, min(s.length(), max - l(shortener))) + shortener;
}
public static String shorten(int max, String s) {
return shorten(s, max);
}
public static boolean match3(String pat, String s) {
return match3(pat, s, null);
}
public static boolean match3(String pat, String s, Matches matches) {
if (pat == null || s == null)
return false;
return match3(pat, parse3_cachedInput(s), matches);
}
public static boolean match3(String pat, List toks, Matches matches) {
List tokpat = parse3_cachedPattern(pat);
return match3(tokpat, toks, matches);
}
public static boolean match3(List tokpat, List toks, Matches matches) {
String[] m = match2(tokpat, toks);
if (m == null)
return false;
if (matches != null)
matches.m = m;
return true;
}
public static String unquote(String s) {
if (s == null)
return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i + 1, s.length() - i - 1);
}
}
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length() - 1 : s.length();
StringBuilder sb = new StringBuilder(l - 1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch(nextChar) {
case '\"':
ch = '\"';
break;
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\'':
ch = '\'';
break;
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s;
}
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 Throwable printStackTrace(Throwable e) {
print(getStackTrace(e));
return e;
}
public static void printStackTrace() {
printStackTrace(new Throwable());
}
public static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
public static void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
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, int n) {
return substring(s, n);
}
public static String dropFirst(String s) {
return substring(s, 1);
}
public static String indentx(String s) {
return indentx(indent_default, s);
}
public static String indentx(int n, String s) {
return dropSuffix(repeat(' ', n), indent(n, s));
}
public static String indentx(String indent, String s) {
return dropSuffix(indent, indent(indent, s));
}
public static String rtrim(String s) {
if (s == null)
return null;
int i = s.length();
while (i > 0 && " \t\r\n".indexOf(s.charAt(i - 1)) >= 0) --i;
return i < s.length() ? s.substring(0, i) : s;
}
public static String processID_cached;
public static String getPID() {
if (processID_cached == null) {
String name = ManagementFactory.getRuntimeMXBean().getName();
processID_cached = name.replaceAll("@.*", "");
}
return processID_cached;
}
public static String getInjectionID() {
return (String) call(getJavaX(), "getInjectionID", getMainClass());
}
public static Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
public static String getProgramTitle() {
return getProgramName();
}
public static String makeResponder_callAnswerMethod(Object bot, String s, List history) {
String answer = (String) callOpt(bot, "answer", s, history);
if (answer == null)
answer = (String) callOpt(bot, "answer", s);
return answer;
}
public static Responder makeResponder(final Object bot) {
if (bot instanceof Responder)
return (Responder) bot;
if (bot instanceof String) {
String f = (String) bot;
return new Responder() {
public String answer(String s, List history) {
String answer = (String) callOptMC((String) bot, s, history);
if (answer == null)
answer = (String) callOptMC((String) bot, s);
return answer;
}
};
}
return new Responder() {
public String answer(String s, List history) {
return makeResponder_callAnswerMethod(bot, s, history);
}
};
}
public static String defaultBotName() {
return getProgramTitle() + ".";
}
public static long parseLong(String s) {
if (s == null)
return 0;
return Long.parseLong(dropSuffix("L", s));
}
public static long parseLong(Object s) {
return Long.parseLong((String) s);
}
public static boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
public static Object vmBus_query(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
{
Object __433 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg);
if (__433 != null)
return __433;
}
return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg);
}
public static Object vmBus_query(String msg) {
return vmBus_query(msg, (Object) null);
}
public static String assertIdentifier(String s) {
return assertIsIdentifier(s);
}
public static String assertIdentifier(String msg, String s) {
return assertIsIdentifier(msg, s);
}
public static Object dm_os() {
{
Object __435 = vm_generalMap_get("stefansOS");
if (__435 != null)
return __435;
}
return creator();
}
public static Comparator caseInsensitiveComparator() {
return betterCIComparator();
}
public static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
public Object next() {
throw fail();
}
public boolean hasNext() {
return false;
}
};
public static CloseableIterableIterator emptyCloseableIterableIterator() {
return emptyCloseableIterableIterator_instance;
}
public static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
public static boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
public static CloseableIterableIterator linesFromReader(Reader r) {
final BufferedReader br = bufferedReader(r);
return iteratorFromFunction_f0_autoCloseable(new F0() {
public String get() {
try {
return readLineFromReaderWithClose(br);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret readLineFromReaderWithClose(br);";
}
}, _wrapIOCloseable(r));
}
public static BufferedReader utf8bufferedReader(InputStream in) {
try {
return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static BufferedReader utf8bufferedReader(File f) {
try {
return utf8bufferedReader(newFileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
public static GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
public static List cloneSubList(List l, int startIndex, int endIndex) {
return newSubList(l, startIndex, endIndex);
}
public static List cloneSubList(List l, int startIndex) {
return newSubList(l, startIndex);
}
public static String dm_processEmbeddedSafeEvals(String s, Object... __) {
Map evalCache = (Map) (optPar("evalCache", __));
if (!contains(s, "{="))
return s;
List tok = javaTok(s);
Map bracketMap = curlyBracketMap(tok);
for (int i = 1; i < l(tok) - 4; i += 2) {
{
if (!(eq(tok.get(i), "{") && eqGet(tok, i + 1, "") && eqGet(tok, i + 2, "=")))
continue;
}
int j = or(bracketMap.get(i), l(tok));
String code = joinSubList(tok, i + 4, j - 1);
if (!isSafeCodeFragment(code))
replaceTokens(tok, i + 2, i + 4, "UNSAFE: ");
else {
String result = mapGet(evalCache, code);
if (result == null) {
print("Evaluating: " + code);
try {
result = strOrEmpty(dm_javaEvalOrInterpret(code));
} catch (Throwable e) {
printStackTrace(e);
result = "";
}
mapPut(evalCache, code, result);
}
replaceTokens(tok, i, j + 1, result);
}
i = j - 2;
}
return trim(join(tok));
}
public static String stringOptPar(Object[] params, String name) {
return (String) optPar(params, name);
}
public static Collector limitedCollector(Collection l, int max) {
return limitedListCollector(l, max);
}
public static F1 f_id_value;
public static F1 f_id() {
if (f_id_value == null)
f_id_value = new F1 () {
public A get(A a) {
try {
return a;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret a;";
}
};
return f_id_value;
}
public static String gazelle_processSafeEvals(String text, Map evalCache) {
String l = dm_processEmbeddedSafeEvals(text, "evalCache", evalCache);
if (l != text) {
print("Processed eval: " + text + " => " + l);
text = l;
}
return text;
}
public static TreeSet litCISet(String... items) {
return litciset(items);
}
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)));
if (l(out) == 1 && eq(first(out), input))
return emptyList();
return out;
}
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 > A printLinesWithIndent(String indent, A lines) {
if (lines != null)
for (B s : lines) printIndent(indent, s);
return lines;
}
public static String defaultIndent() {
return indent(indent_default);
}
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 void gazelle_dropRulesNotOnInput(GazelleEvalContext ctx) {
ctx.engine.dropRulesWhere(r -> cicOneOf(r.comments, "in 1 = statement", "in = statement", "disable"));
}
public static HashSet collectUnique(Collection c, String field) {
HashSet set = new HashSet();
for (Object a : c) {
Object val = getOpt(a, field);
if (val != null)
set.add(val);
}
return set;
}
public static HashSet collectUnique(String field, Collection c) {
return collectUnique(c, field);
}
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 List gazelle_getChildren_withContinuations(GazelleTree tree, Object... __) {
List l = gazelle_getChildren(tree, __);
boolean debug = boolPar("debug", __) || boolPar("debugContinuations", __);
Matches m = new Matches();
boolean changes = false;
for (int i = 0; i < l(l); i++) {
GazelleTree t = l.get(i);
{
if (!(eq(t.lineType, "instruction") && match("continue with line * of rule * without variables", t.line, m)))
continue;
}
if (debug)
print("Processing continuation: " + sfu(m));
String ruleID = m.unq(1);
RuleEngine2.Rule rule = t.ctx.engine.getRule(ruleID);
if (rule == null) {
print("Follow-up rule not found: " + ruleID);
{
l.remove(i--);
continue;
}
}
changes = true;
t.mr.rule = rule;
t.mr.iCond = parseInt(m.unq(0)) - 1;
t.mr.map = ciMap();
if (!t.mr.moreConditions()) {
t.line = rule.out;
t.lineType = rule.outType();
}
gazelle_addPredictionToTreeNode(t);
}
if (changes)
gazelle_sortChildren(l);
return l;
}
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 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 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 boolean dm_gazelle_matchStep_statement(GazelleTree t, Object... __) {
if (t.rule() == null)
return false;
boolean debug = boolPar("debug", __) || boolPar("matchStatementsDebug", __);
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))
return false;
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))
return false;
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)));
if (debug)
print("fulfillment => " + 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));
{
if (gazelle_isRecentlyUsedMapping(t, newMap, __))
continue;
}
bestMap.put(newMap, l(newMap));
}
Map newMap = bestMap.get();
if (newMap == null) {
if (debug)
print("No matching statement found");
return false;
}
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);
return true;
}
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 void dm_gazelle_matchStep_additionalInput(GazelleTree t, Map inputsByType, Object... __) {
if (t.rule() == null)
return;
boolean debug = boolPar("debug", __);
TextAndType next = get(t.rule().insWithType, t.mr.iCond);
if (next == null || !startsWith(next.type, "history-"))
return;
if (ai_ruleEngine2_matchStep(t.mr, inputsByType, true, __)) {
if (debug)
print("Input match OK. new map: " + t.mr.map + ". Updating prediction.");
gazelle_addPredictionToTreeNode(t);
} else if (debug)
print("Input match failed");
}
public static void dm_gazelle_matchStep_condition(GazelleTree t, Object... __) {
if (t.rule() == null)
return;
boolean debug = boolPar("debug", __) || boolPar("debugConditions", __);
GRuleLine next = get(t.rule().insWithType, t.mr.iCond);
if (debug)
print("matchStep_condition: " + getString("type", next));
if (next == null || !eq(next.type, "condition"))
return;
boolean satisfied = false;
String cond = t.mr.applyMappingTo(next);
if (gazelle_isEmbeddedEval(cond)) {
if (debug)
print("Embedded eval: " + cond);
satisfied = eqic(dm_processEmbeddedSafeEvals(cond), "true");
} else {
GazelleEvalContext subCtx = (GazelleEvalContext) (callF(requiredPar("contextMaker", __)));
subCtx.engine.dropRulesWhere(r -> neq(r.purpose, "condition to eval"));
List l = dm_gazelle_reasonAboutChatInput_v2(null, cond, paramsPlus(paramsMinus(__, "acceptablePurposes"), "ctx", subCtx));
gazelle_processSafeEvalsInTree(l);
if (debug) {
print("Sub-Tree for condition " + cond + ":");
printIndentLines(l);
}
for (GazelleTree tree : l) if (eqic(tree.line, "true")) {
satisfied = true;
break;
} else if (eqic(tree.line, "false"))
break;
}
if (debug)
print("satisfied=" + satisfied);
if (!satisfied)
return;
t.mr.iCond++;
gazelle_addPredictionToTreeNode(t);
t.mr.remainingConditions = dropFirst(t.mr.remainingConditions);
t.mr.remainingConditionsWithType = dropFirst(t.mr.remainingConditionsWithType);
}
public static List gazelle_dropUnsatisfiedEntries(List l) {
return antiFilter(l, t -> t.mr != null && t.mr.moreConditions());
}
public static Map mapPlus(Map m, Object... data) {
m = cloneMap(m);
litmap_impl(m, data);
return m;
}
public static Object[] assertEvenLength(Object[] a) {
assertTrue(even(l(a)));
return a;
}
public static LinkedHashMap paramsToOrderedMap(Object... params) {
return asLinkedHashMap(paramsToMap(params));
}
public static Object[] mapToParams(Map map) {
return mapToObjectArray(map);
}
public static boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
public static boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
public static List matchAll_first(String pat, Iterable l) {
return map(matchAll(pat, l), new F1() {
public String get(Matches m) {
try {
return m.get(0);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "m.get(0)";
}
});
}
public static List listMinusSet(Iterable l, Collection stuff) {
if (empty(stuff))
return asList(l);
Set set = asSet(stuff);
List l2 = new ArrayList();
for (A a : l) if (!set.contains(a))
l2.add(a);
return l2;
}
public static List listMinusSet(Iterable l, Collection stuff, Collection