Warning : session_start(): open(/var/lib/php/sessions/sess_863198meih8ersm11uto874nv6, 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.IF1;
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 loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import java.text.NumberFormat;
import java.text.*;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.swing.undo.UndoManager;
import java.text.SimpleDateFormat;
import java.awt.datatransfer.StringSelection;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.nio.file.Files;
import java.nio.file.Path;
class main {
public static class WhatDidYouDoTodayBot extends DynAttractorBot {
public AttractorBot makeBot() {
return new AI_WhatDidYouDoTodayBot();
}
}
public static boolean _moduleClass_WhatDidYouDoTodayBot;
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 B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
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 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 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 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 = defaultDefaultClassFinder();
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 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 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 void _handleError(Error e) {
call(javax(), "_handleError", e);
}
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 Object defaultDefaultClassFinder() {
return new F1() {
public Class get(String name) {
try {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (startsWith(name, "loadableUtils.utils$"))
return findClass_fullName("main" + substring(name, 19));
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 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 void removeFromMultiPort(long vport) {
if (vport == 0)
return;
for (Object port : getMultiPorts()) call(port, "removePort", vport);
}
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 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 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 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 Object callOptMC(String method, Object... args) {
return callOpt(mc(), method, args);
}
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) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, min(a.length, b.length));
}
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
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 String str(Object o) {
return o == null ? "null" : o.toString();
}
public static String str(char[] c) {
return new String(c);
}
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 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 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(File f) {
return getFileSize(f) == 0;
}
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 List getMultiPorts() {
return (List) callOpt(getJavaX(), "getMultiPorts");
}
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 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 ArrayList litlist(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
public static String emptyToNull(String s) {
return eq(s, "") ? null : s;
}
public static Map emptyToNull(Map map) {
return empty(map) ? null : map;
}
public static void startMultiPort() {
List mp = getMultiPorts();
if (mp != null && mp.isEmpty()) {
nohupJavax("#1001639");
throw fail("Upgrading JavaX, please restart this program afterwards.");
}
}
public static A last(List l) {
return empty(l) ? null : l.get(l.size() - 1);
}
public static char last(String s) {
return empty(s) ? '#' : s.charAt(l(s) - 1);
}
public static int last(int[] a) {
return l(a) != 0 ? a[l(a) - 1] : 0;
}
public static A last(A[] a) {
return l(a) != 0 ? a[l(a) - 1] : null;
}
public static A last(Iterator it) {
A a = null;
while (it.hasNext()) {
ping();
a = it.next();
}
return a;
}
public static Set synchroTreeSet() {
return Collections.synchronizedSet(new TreeSet ());
}
public static boolean forbiddenPort(int port) {
return port == 5037;
}
public static A getAndClearThreadLocal(ThreadLocal tl) {
A a = tl.get();
tl.set(null);
return a;
}
public static String defaultThreadName_name;
public static String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
public static Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
public static Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
public static Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
public static Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
public static Runnable toRunnable(final Object o) {
if (o instanceof Runnable)
return (Runnable) o;
return new Runnable() {
public void run() {
try {
callF(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(o)";
}
};
}
public static Map _registerThread_threads;
public static Object _onRegisterThread;
public static Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
public static void _registerThread() {
_registerThread(Thread.currentThread());
}
public static String readLineHidden() {
try {
if (get(javax(), "readLine_reader") == null)
set(javax(), "readLine_reader", new BufferedReader(new InputStreamReader(System.in, "UTF-8")));
try {
return ((BufferedReader) get(javax(), "readLine_reader")).readLine();
} finally {
consoleClearInput();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(File f, String defaultContents) {
try {
checkFileNotTooBigToRead(f);
if (f == null || !f.exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(f);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(String fileName, String defaultContents) {
return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
}
public static String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
} finally {
reader.close();
}
return str(builder);
}
public static String _userHome;
public static String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
public static File userHome(String path) {
return new File(userDir(), path);
}
public static String makeRandomID(int length) {
return makeRandomID(length, defaultRandomGenerator());
}
public static String makeRandomID(int length, Random random) {
char[] id = new char[length];
for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
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 Map> parse3_cachedInput_cache = synchronizedMRUCache(1000);
public static List parse3_cachedInput(String s) {
List tok = parse3_cachedInput_cache.get(s);
if (tok == null)
parse3_cachedInput_cache.put(s, tok = parse3(s));
return tok;
}
public static Map> parse3_cachedPattern_cache = synchronizedMRUCache(1000);
public static synchronized List parse3_cachedPattern(String s) {
List tok = parse3_cachedPattern_cache.get(s);
if (tok == null)
parse3_cachedPattern_cache.put(s, tok = parse3(s));
return tok;
}
public static String[] match2(List pat, List tok) {
int i = pat.indexOf("...");
if (i < 0)
return match2_match(pat, tok);
pat = new ArrayList(pat);
pat.set(i, "*");
while (pat.size() < tok.size()) {
pat.add(i, "*");
pat.add(i + 1, "");
}
return match2_match(pat, tok);
}
public static String[] match2_match(List pat, List tok) {
List result = new ArrayList();
if (pat.size() != tok.size()) {
return null;
}
for (int i = 1; i < pat.size(); i += 2) {
String p = pat.get(i), t = tok.get(i);
if (eq(p, "*"))
result.add(t);
else if (!equalsIgnoreCase(unquote(p), unquote(t)))
return null;
}
return result.toArray(new String[result.size()]);
}
public static boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
public static boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
public static boolean endsWith(String a, String b, Matches m) {
if (!endsWith(a, b))
return false;
m.m = new String[] { dropLast(l(b), a) };
return true;
}
public static Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
public static String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
public static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
public static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
public static String[] drop(int n, String[] a) {
n = Math.min(n, a.length);
String[] b = new String[a.length - n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
public static Object[] drop(int n, Object[] a) {
n = Math.min(n, a.length);
Object[] b = new Object[a.length - n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
public static ArrayList toList(A[] a) {
return asList(a);
}
public static ArrayList toList(int[] a) {
return asList(a);
}
public static ArrayList toList(Set s) {
return asList(s);
}
public static ArrayList toList(Iterable s) {
return asList(s);
}
public static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
public static String repeat(char c, int n) {
n = Math.max(n, 0);
char[] chars = new char[n];
for (int i = 0; i < n; i++) chars[i] = c;
return new String(chars);
}
public static List repeat(A a, int n) {
n = Math.max(n, 0);
List l = new ArrayList(n);
for (int i = 0; i < n; i++) l.add(a);
return l;
}
public static List repeat(int n, A a) {
return repeat(a, n);
}
public static int indent_default = 2;
public static String indent(int indent) {
return repeat(' ', indent);
}
public static String indent(int indent, String s) {
return indent(repeat(' ', indent), s);
}
public static String indent(String indent, String s) {
return indent + s.replace("\n", "\n" + indent);
}
public static String indent(String s) {
return indent(indent_default, s);
}
public static List indent(String indent, List lines) {
List l = new ArrayList();
if (lines != null)
for (String s : lines) l.add(indent + s);
return l;
}
public static Map vm_generalMap_map;
public static Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
public static String getProgramName_cache;
public static String getProgramName() {
Lock __233 = downloadLock();
lock(__233);
try {
if (getProgramName_cache == null)
getProgramName_cache = getSnippetTitleOpt(programID());
return getProgramName_cache;
} finally {
unlock(__233);
}
}
public static void _onLoad_getProgramName() {
startThread(new Runnable() {
public void run() {
try {
getProgramName();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "getProgramName();";
}
});
}
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 A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
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 String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
public static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
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 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 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 void nohupJavax(final String javaxargs) {
startThread(new Runnable() {
public void run() {
try {
call(hotwireOnce("#1008562"), "nohupJavax", javaxargs);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs);";
}
});
}
public static void nohupJavax(final String javaxargs, final String vmArgs) {
startThread(new Runnable() {
public void run() {
try {
call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs, vmArgs);";
}
});
}
public static Runnable _topLevelErrorHandling(final Runnable runnable) {
final Object info = _threadInfo();
return new Runnable() {
public void run() {
try {
try {
_threadInheritInfo(info);
runnable.run();
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }";
}
};
}
public static WeakReference weakRef(A a) {
return newWeakReference(a);
}
public static 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 consoleClearInput() {
consoleSetInput("");
}
public static ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal();
public static void checkFileNotTooBigToRead(File f) {
callF(checkFileNotTooBigToRead_tl.get(), f);
}
public static File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
public static File newFile(String name) {
return name == null ? null : new File(name);
}
public static String actualUserHome_value;
public static String actualUserHome() {
if (actualUserHome_value == null) {
if (isAndroid())
actualUserHome_value = "/storage/emulated/0/";
else
actualUserHome_value = System.getProperty("user.home");
}
return actualUserHome_value;
}
public static File actualUserHome(String sub) {
return newFile(new File(actualUserHome()), sub);
}
public static File userDir() {
return new File(userHome());
}
public static File userDir(String path) {
return new File(userHome(), path);
}
public static Random defaultRandomGenerator() {
return ThreadLocalRandom.current();
}
public static Map synchronizedMRUCache(int maxSize) {
return synchroMap(new MRUCache(maxSize));
}
public static List parse3(String s) {
return dropPunctuation(javaTokPlusPeriod(s));
}
public static boolean equalsIgnoreCase(String a, String b) {
return eqic(a, b);
}
public static boolean equalsIgnoreCase(char a, char b) {
return eqic(a, b);
}
public static char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s) - 1);
}
public static String[] dropLast(String[] a, int n) {
n = Math.min(n, a.length);
String[] b = new String[a.length - n];
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
public static List dropLast(List l) {
return subList(l, 0, l(l) - 1);
}
public static List dropLast(int n, List l) {
return subList(l, 0, l(l) - n);
}
public static List dropLast(Iterable l) {
return dropLast(asList(l));
}
public static String dropLast(String s) {
return substring(s, 0, l(s) - 1);
}
public static String dropLast(String s, int n) {
return substring(s, 0, l(s) - n);
}
public static String dropLast(int n, String s) {
return dropLast(s, n);
}
public static volatile PersistableThrowable lastException_lastException;
public static PersistableThrowable lastException() {
return lastException_lastException;
}
public static void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
public static String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
public static String hideCredentials(String url) {
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
public static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
public static Lock downloadLock_lock = fairLock();
public static Lock downloadLock() {
return downloadLock_lock;
}
public static void lock(Lock lock) {
try {
ping();
if (lock == null)
return;
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
print("Locking interrupted! I probably deadlocked, oops.");
printStackTrace(e);
rethrow(e);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
public static void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
public static ReentrantLock lock() {
return fairLock();
}
public static String getSnippetTitleOpt(String s) {
return isSnippetID(s) ? getSnippetTitle(s) : s;
}
public static void unlock(Lock lock, String msg) {
if (lock == null)
return;
print("Unlocking: " + msg);
lock.unlock();
}
public static void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
}
public static Throwable unwrapTrivialExceptionWraps(Throwable e) {
if (e == null)
return e;
while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause();
return e;
}
public static String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix))
return s;
return replacement + substring(s, l(prefix));
}
public static Throwable innerException2(Throwable e) {
if (e == null)
return null;
while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
return e;
}
public static 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 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 Class hotwireOnce(String programID) {
return hotwireCached(programID, false);
}
public static WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
public static void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
if (type == int.class && value instanceof Long)
value = ((Long) value).intValue();
if (type == LinkedHashMap.class && value instanceof Map) {
f.set(o, asLinkedHashMap((Map) value));
return;
}
try {
if (f.getType() == Concept.Ref.class) {
f.set(o, ((Concept) o).new Ref((Concept) value));
return;
}
if (o instanceof Concept.Ref) {
f.set(o, ((Concept.Ref) o).get());
return;
}
} catch (Throwable _e) {
}
throw e;
}
}
public static void consoleSetInput(final String text) {
if (headless())
return;
setTextAndSelectAll(consoleInputField(), text);
focusConsole();
}
public static Map synchroMap() {
return synchroHashMap();
}
public static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
public static List dropPunctuation_keep = ll("*", "<", ">");
public static List dropPunctuation(List tok) {
tok = new ArrayList(tok);
for (int i = 1; i < tok.size(); i += 2) {
String t = tok.get(i);
if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) {
tok.set(i - 1, tok.get(i - 1) + tok.get(i + 1));
tok.remove(i);
tok.remove(i);
i -= 2;
}
}
return tok;
}
public static String dropPunctuation(String s) {
return join(dropPunctuation(nlTok(s)));
}
public static List javaTokPlusPeriod(String s) {
List tok = new ArrayList();
int l = s.length();
int i = 0;
while (i < l) {
int j = i;
char c;
String cc;
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j + 2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l)
break;
c = s.charAt(i);
cc = s.substring(i, Math.min(i + 2, l));
if (c == (char) 0x201C || c == (char) 0x201D)
c = '"';
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
char _c = s.charAt(j);
if (_c == (char) 0x201C || _c == (char) 0x201D)
_c = '"';
if (_c == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
if (j - 1 >= i + 1) {
tok.add(opener + s.substring(i + 1, j - 1) + opener);
i = j;
continue;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
else if (Character.isDigit(c))
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else if (cc.equals("[[")) {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (cc.equals("[=") && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else if (s.substring(j, Math.min(j + 3, l)).equals("..."))
j += 3;
else if (c == '$' || c == '#')
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
return tok;
}
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 subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
public static List subList(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return l.subList(startIndex, endIndex);
}
public static ReentrantLock fairLock() {
return new ReentrantLock(true);
}
public static void lockOrFail(Lock lock, long timeout) {
try {
ping();
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String getSnippetTitle(String id) {
try {
if (id == null)
return null;
if (!isSnippetID(id))
return "?";
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.getSnippetTitle(id);
if (isLocalSnippetID(id))
return localSnippetTitle(id);
long parsedID = parseSnippetID(id);
String url;
if (isImageServerSnippet(parsedID))
url = imageServerURL() + "title/" + parsedID + muricaCredentialsQuery();
else if (isGeneralFileServerSnippet(parsedID))
url = "http://butter.botcompany.de:8080/files/name/" + parsedID;
else
url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies();
String title = trim(loadPageSilently(url));
if (title != null)
try {
saveTextFileIfChanged(snippetTitle_cacheFile(id), title);
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
return or(title, "?");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String getSnippetTitle(long id) {
return getSnippetTitle(fsI(id));
}
public static TreeMap hotwireCached_cache = new TreeMap();
public static Lock hotwireCached_lock = lock();
public static Class hotwireCached(String programID) {
return hotwireCached(programID, true);
}
public static Class hotwireCached(String programID, boolean runMain) {
return hotwireCached(programID, runMain, false);
}
public static Class hotwireCached(String programID, boolean runMain, boolean dependent) {
Lock __311 = hotwireCached_lock;
lock(__311);
try {
programID = formatSnippetID(programID);
Class c = hotwireCached_cache.get(programID);
if (c == null) {
c = hotwire(programID);
if (dependent)
makeDependent(c);
if (runMain)
callMain(c);
hotwireCached_cache.put(programID, c);
}
return c;
} finally {
unlock(__311);
}
}
public static LinkedHashMap asLinkedHashMap(Map map) {
if (map instanceof LinkedHashMap)
return (LinkedHashMap) map;
LinkedHashMap m = new LinkedHashMap();
if (map != null)
synchronized (collectionMutex(map)) {
m.putAll(map);
}
return m;
}
public static boolean headless() {
return isHeadless();
}
public static JTextField setTextAndSelectAll(final JTextField tf, final String text) {
{
swing(new Runnable() {
public void run() {
try {
tf.setText(text);
tf.selectAll();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tf.setText(text);\r\n tf.selectAll();";
}
});
}
return tf;
}
public static JTextField consoleInputField() {
Object console = get(getJavaX(), "console");
return (JTextField) getOpt(console, "tfInput");
}
public static void focusConsole(String s) {
setConsoleInput(s);
focusConsole();
}
public static void focusConsole() {
JComponent tf = consoleInputFieldOrComboBox();
if (tf != null) {
tf.requestFocus();
}
}
public static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
public static List nlTok(String s) {
return javaTokPlusPeriod(s);
}
public static String asString(Object o) {
return o == null ? null : o.toString();
}
public static IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
public static boolean isLocalSnippetID(String snippetID) {
return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID));
}
public static boolean isLocalSnippetID(long snippetID) {
return snippetID >= 1000 && snippetID <= 9999;
}
public static String localSnippetTitle(String snippetID) {
if (!isLocalSnippetID(snippetID))
return null;
File f = localSnippetFile(snippetID);
if (!f.exists())
return null;
return or2(getFileInfoField(dropExtension(f), "Title"), "Unnamed");
}
public static boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
public static String imageServerURL() {
return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/");
}
public static String muricaCredentialsQuery() {
return htmlQuery(muricaCredentials());
}
public static boolean isGeneralFileServerSnippet(long id) {
return id >= 1400000 && id < 1500000;
}
public static String tb_mainServer_default = "http://tinybrain.de:8080";
public static Object tb_mainServer_override;
public static String tb_mainServer() {
if (tb_mainServer_override != null)
return (String) callF(tb_mainServer_override);
return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default));
}
public static File tb_mainServer_file() {
return getProgramFile("#1001638", "mainserver.txt");
}
public static boolean tb_mainServer_isDefault() {
return eq(tb_mainServer(), tb_mainServer_default);
}
public static String standardCredentials_noCookies() {
return standardCredentials() + "&noCookies=1";
}
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 boolean saveTextFileIfChanged(File f, String contents) {
return saveTextFileIfDifferent(f, contents);
}
public static File snippetTitle_cacheFile(String snippetID) {
return javaxCachesDir("Snippet Titles/" + psI(snippetID));
}
public static String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
public static A or(A a, A b) {
return a != null ? a : b;
}
public static String fsI(String id) {
return formatSnippetID(id);
}
public static String fsI(long id) {
return formatSnippetID(id);
}
public static Class> hotwire(String src) {
assertFalse(_inCore());
Class j = getJavaX();
if (isAndroid()) {
synchronized (j) {
List libraries = new ArrayList();
File srcDir = (File) call(j, "transpileMain", src, libraries);
if (srcDir == null)
throw fail("transpileMain returned null (src=" + quote(src) + ")");
Object androidContext = get(j, "androidContext");
return (Class) call(j, "loadx2android", srcDir, src);
}
} else {
Class c = (Class) (call(j, "hotwire", src));
hotwire_copyOver(c);
return c;
}
}
public static Object makeDependent_postProcess;
public static void makeDependent(Object c) {
if (c == null)
return;
assertTrue("Not a class", c instanceof Class);
dependentClasses();
hotwire_classes.add(new WeakReference(c));
Object local_log = getOpt(mc(), "local_log");
if (local_log != null)
setOpt(c, "local_log", local_log);
Object print_byThread = getOpt(mc(), "print_byThread");
if (print_byThread != null)
setOpt(c, "print_byThread", print_byThread);
callF(makeDependent_postProcess, c);
}
public static A callMain(A c, String... args) {
callOpt(c, "main", new Object[] { args });
return c;
}
public static void callMain() {
callMain(mc());
}
public static Object swing(Object f) {
return swingAndWait(f);
}
public static A swing(F0 f) {
return (A) swingAndWait(f);
}
public static void setConsoleInput(String text) {
consoleSetInput(text);
}
public static JComponent consoleInputFieldOrComboBox() {
Object console = get(getJavaX(), "console");
JComboBox cb = (JComboBox) (getOpt(console, "cbInput"));
if (cb != null)
return cb;
return (JTextField) getOpt(console, "tfInput");
}
public static A proxy(Class intrface, final Object target) {
if (target == null)
return null;
if (isInstance(intrface, target))
return (A) target;
return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) {
return call(target, method.getName(), unnull(args));
}
});
}
public static A proxy(Object target, Class intrface) {
return proxy(intrface, target);
}
public static long psI(String snippetID) {
return parseSnippetID(snippetID);
}
public static File localSnippetFile(long snippetID) {
return localSnippetsDir(snippetID + ".text");
}
public static File localSnippetFile(String snippetID) {
return localSnippetFile(parseSnippetID(snippetID));
}
public static String or2(String a, String b) {
return nempty(a) ? a : b;
}
public static String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
public static String getFileInfoField(File f, String field) {
return getOneLineFileInfoField(f, field);
}
public static File dropExtension(File f) {
return f == null ? null : fileInSameDir(f, dropExtension(f.getName()));
}
public static String dropExtension(String s) {
return takeFirst(s, smartLastIndexOf(s, '.'));
}
public static File javaxDataDir_dir;
public static File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
public static File javaxDataDir(String... subs) {
return newFile(javaxDataDir(), subs);
}
public static String htmlQuery(Map params) {
return params.isEmpty() ? "" : "?" + makePostData(params);
}
public static String htmlQuery(Object... data) {
return htmlQuery(litmap(data));
}
public static Object[] muricaCredentials() {
String pass = muricaPassword();
return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0];
}
public static File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
public static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
public static String standardCredentials() {
String user = standardCredentialsUser();
String pass = standardCredentialsPass();
if (nempty(user) && nempty(pass))
return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
return "";
}
public static boolean saveTextFileIfDifferent(File f, String contents) {
if (eq(loadTextFile(f), contents))
return false;
{
saveTextFile(f, contents);
return true;
}
}
public static File javaxCachesDir_dir;
public static File javaxCachesDir() {
return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
}
public static File javaxCachesDir(String sub) {
return newFile(javaxCachesDir(), sub);
}
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 Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
public static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
public static String baseClassName(String className) {
return substring(className, className.lastIndexOf('.') + 1);
}
public static String baseClassName(Object o) {
return baseClassName(getClassName(o));
}
public static String prependIfNempty(String prefix, String s) {
return empty(s) ? s : prefix + s;
}
public static void assertFalse(Object o) {
if (!(eq(o, false)))
throw fail(str(o));
}
public static boolean assertFalse(boolean b) {
if (b)
throw fail("oops");
return b;
}
public static boolean assertFalse(String msg, boolean b) {
if (b)
throw fail(msg);
return b;
}
public static boolean _inCore() {
return false;
}
public static List hotwire_copyOver_after = synchroList();
public static void hotwire_copyOver(Class c) {
for (String field : ll("print_log", "print_silent", "androidContext", "_userHome")) setOptIfNotNull(c, field, getOpt(mc(), field));
setOptIfNotNull(c, "mainBot", getMainBot());
setOpt(c, "creator_class", new WeakReference(mc()));
pcallFAll(hotwire_copyOver_after, c);
}
public static List dependentClasses() {
return cleanUpAndGetWeakReferencesList(hotwire_classes);
}
public static void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
public static boolean isInstance(Class type, Object arg) {
return type.isInstance(arg);
}
public static File localSnippetsDir() {
return javaxDataDir("Personal Programs");
}
public static File localSnippetsDir(String sub) {
return newFile(localSnippetsDir(), sub);
}
public static String getOneLineFileInfoField(File f, String field) {
File infoFile = associatedInfosFile(f);
List lines = lines(loadTextFile(infoFile));
return firstStartingWithIC_drop(lines, field + ": ");
}
public static File fileInSameDir(File f, String newName) {
return newFile(parentFile(f), newName);
}
public static List takeFirst(List l, int n) {
return l(l) <= n ? l : newSubListOrSame(l, 0, n);
}
public static List takeFirst(int n, List l) {
return takeFirst(l, n);
}
public static String takeFirst(int n, String s) {
return substring(s, 0, n);
}
public static String takeFirst(String s, int n) {
return substring(s, 0, n);
}
public static List takeFirst(int n, Iterable i) {
List l = new ArrayList();
Iterator it = i.iterator();
for (int _repeat_341 = 0; _repeat_341 < n; _repeat_341++) {
if (it.hasNext())
l.add(it.next());
else
break;
}
return l;
}
public static int smartLastIndexOf(String s, char c) {
if (s == null)
return 0;
int i = s.lastIndexOf(c);
return i >= 0 ? i : l(s);
}
public static String makePostData(Map map) {
List l = new ArrayList();
for (Map.Entry e : map.entrySet()) {
String key = (String) (e.getKey());
Object val = e.getValue();
if (val != null) {
String value = str(val);
l.add(urlencode(key) + "=" + urlencode((value)));
}
}
return join("&", l);
}
public static String makePostData(Object... params) {
return makePostData(litorderedmap(params));
}
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 volatile boolean muricaPassword_pretendNotAuthed;
public static String muricaPassword() {
if (muricaPassword_pretendNotAuthed)
return null;
return trim(loadTextFile(muricaPasswordFile()));
}
public static File getProgramDir() {
return programDir();
}
public static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
public static String standardCredentialsUser() {
return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-username"), userDir(".tinybrain/username"))));
}
public static String standardCredentialsPass() {
return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-userpass"), userDir(".tinybrain/userpass"))));
}
public static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static File saveTextFile(String fileName, String contents) throws IOException {
CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
try {
File file = new File(fileName);
mkdirsForFile(file);
String tempFileName = fileName + "_temp";
File tempFile = new File(tempFileName);
if (contents != null) {
if (tempFile.exists())
try {
String saveName = tempFileName + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) {
printStackTrace(e);
}
FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
vmBus_send("wroteFile", file);
return file;
} finally {
action.done();
}
}
public static File saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
return fileName;
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 Map emptyMap() {
return new HashMap();
}
public static List> hotwire_classes = synchroList();
public static Class> hotwireDependent(String src) {
Class c = hotwire(src);
makeDependent(c);
return c;
}
public static void setOptIfNotNull(Object o, String field, Object value) {
if (value != null)
setOpt(o, field, value);
}
public static Object mainBot;
public static Object getMainBot() {
return mainBot;
}
public static void pcallFAll(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) pcallF(f, args);
}
public static void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
public static List cleanUpAndGetWeakReferencesList(List> l) {
if (l == null)
return null;
synchronized (l) {
List out = new ArrayList();
for (int i = 0; i < l(l); i++) {
A a = l.get(i).get();
if (a == null)
l.remove(i--);
else
out.add(a);
}
return out;
}
}
public static Runnable addThreadInfoToRunnable(final Object r) {
final Object info = _threadInfo();
return info == null ? asRunnable(r) : new Runnable() {
public void run() {
try {
_inheritThreadInfo(info);
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_inheritThreadInfo(info); callF(r);";
}
};
}
public static File associatedInfosFile(File f) {
return replaceExtension(f, ".infos");
}
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 String firstStartingWithIC_drop(Collection l, final String prefix) {
for (String s : unnull(l)) if (swic(s, prefix))
return substring(s, l(prefix));
return null;
}
public static String firstStartingWithIC_drop(String prefix, Collection l) {
return firstStartingWithIC_drop(l, prefix);
}
public static File parentFile(File f) {
return dirOfFile(f);
}
public static List newSubListOrSame(List l, int startIndex) {
return newSubListOrSame(l, startIndex, l(l));
}
public static List newSubListOrSame(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = max(0, startIndex);
endIndex = min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return cloneList(l.subList(startIndex, endIndex));
}
public static LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
public static File muricaPasswordFile() {
return new File(javaxSecretDir(), "murica/muricaPasswordFile");
}
public static File programDir_mine;
public static File programDir() {
return programDir(getProgramID());
}
public static File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
if (me) {
String c = caseID();
if (nempty(c))
dir = newFile(dir, c);
}
return dir;
}
public static File programDir(String snippetID, String subPath) {
return new File(programDir(snippetID), subPath);
}
public static File oneOfTheFiles(String... paths) {
if (paths != null)
for (String path : paths) if (fileExists(path))
return newFile(path);
return null;
}
public static File oneOfTheFiles(File... files) {
if (files != null)
for (File f : files) if (fileExists(f))
return f;
return null;
}
public static File javaxSecretDir_dir;
public static File javaxSecretDir() {
return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
}
public static File javaxSecretDir(String sub) {
return newFile(javaxSecretDir(), sub);
}
public static List beginCriticalAction_inFlight = synchroList();
public static class CriticalAction {
public String description;
public CriticalAction() {
}
public CriticalAction(String description) {
this.description = description;
}
public void done() {
beginCriticalAction_inFlight.remove(this);
}
}
public static CriticalAction beginCriticalAction(String description) {
ping();
CriticalAction c = new CriticalAction(description);
beginCriticalAction_inFlight.add(c);
return c;
}
public static void cleanMeUp_beginCriticalAction() {
int n = 0;
while (nempty(beginCriticalAction_inFlight)) {
int m = l(beginCriticalAction_inFlight);
if (m != n) {
n = m;
try {
print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
} catch (Throwable __e) {
_handleException(__e);
}
}
sleepInCleanUp(10);
}
}
public static File mkdirsForFile(File file) {
File dir = file.getParentFile();
if (dir != null) {
dir.mkdirs();
if (!dir.isDirectory())
if (dir.isFile())
throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!");
else
throw fail("Unknown IO exception during mkdirs of " + f2s(file));
}
return file;
}
public static String mkdirsForFile(String path) {
mkdirsForFile(new File(path));
return path;
}
public static void copyFile(File src, File dest) {
try {
FileInputStream inputStream = new FileInputStream(src.getPath());
FileOutputStream outputStream = newFileOutputStream(dest.getPath());
try {
copyStream(inputStream, outputStream);
inputStream.close();
} finally {
outputStream.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static FileOutputStream newFileOutputStream(File path) throws IOException {
return newFileOutputStream(path.getPath());
}
public static FileOutputStream newFileOutputStream(String path) throws IOException {
return newFileOutputStream(path, false);
}
public static FileOutputStream newFileOutputStream(File path, boolean append) throws IOException {
return newFileOutputStream(path.getPath(), append);
}
public static FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
mkdirsForFile(path);
FileOutputStream f = new FileOutputStream(path, append);
_registerIO(f, path, true);
return f;
}
public static void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll(vm_busListeners_live(), msg, arg);
pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}
public static void vmBus_send(String msg) {
vmBus_send(msg, (Object) 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 Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
public static A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
public static B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
public static Runnable asRunnable(Object o) {
return toRunnable(o);
}
public static void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
public static File replaceExtension(File f, String extOld, String extNew) {
return newFile(replaceExtension(f2s(f), extOld, extNew));
}
public static File replaceExtension(File f, String extNew) {
return replaceExtension(f, fileExtension(f), extNew);
}
public static String replaceExtension(String s, String extOld, String extNew) {
s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s);
return s + addPrefixOptIfNempty(".", extNew);
}
public static String replaceExtension(String name, String extNew) {
return replaceExtension(name, fileExtension(name), extNew);
}
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 boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
public static boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
public static File dirOfFile(File f) {
return f == null ? null : f.getParentFile();
}
public static boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b))
return false;
return parseSnippetID(a) == parseSnippetID(b);
}
public static volatile String caseID_caseID;
public static String caseID() {
return caseID_caseID;
}
public static void caseID(String id) {
caseID_caseID = id;
}
public static boolean fileExists(String path) {
return path != null && new File(path).exists();
}
public static boolean fileExists(File f) {
return f != null && f.exists();
}
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 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 sleepInCleanUp(long ms) {
try {
if (ms < 0)
return;
Thread.sleep(ms);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
public static String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
public static void copyStream(InputStream in, OutputStream out) {
try {
byte[] buf = new byte[65536];
while (true) {
int n = in.read(buf);
if (n <= 0)
return;
out.write(buf, 0, n);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void _registerIO(Object object, String path, boolean opened) {
}
public static Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
public static Set vm_busListeners_live_cache;
public static Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
public static Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
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 Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
public static String fileExtension(File f) {
if (f == null)
return null;
return fileExtension(f.getName());
}
public static String fileExtension(String s) {
return substring(s, smartLastIndexOf(s, '.'));
}
public static String dropSuffixIC(String suffix, String s) {
return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
public static String addPrefixOptIfNempty(String prefix, String s) {
return addPrefixIfNotEmpty2(prefix, s);
}
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 startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
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 List collectField(Collection c, String field) {
List l = new ArrayList();
if (c != null)
for (Object a : c) l.add(getOpt(a, field));
return l;
}
public static List collectField(String field, Collection c) {
return collectField(c, field);
}
public static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
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 String addPrefixIfNotEmpty2(String prefix, String s) {
return empty(s) ? "" : addPrefix(prefix, s);
}
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 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 boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
public static String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
public static boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
}
public static boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b))
return false;
m.m = new String[] { substring(a, 0, l(a) - l(b)) };
return true;
}
public static String addPrefix(String prefix, String s) {
return s.startsWith(prefix) ? s : prefix + s;
}
public static BufferedReader bufferedReader(Reader r) {
return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
}
public static CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) {
class IFF2 extends CloseableIterableIterator {
public A a;
public boolean done;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
return _a;
}
public void getNext() {
if (done || a != null)
return;
a = f.get();
done = a == null;
}
public void close() throws Exception {
if (closeable != null)
closeable.close();
}
}
;
return new IFF2();
}
public static String readLineFromReaderWithClose(BufferedReader r) {
try {
String s = r.readLine();
if (s == null)
r.close();
return s;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
return c == null ? null : new AutoCloseable() {
public String toString() {
return "c.close();\r\n _registerIO(c, null, false);";
}
public void close() throws Exception {
c.close();
_registerIO(c, null, false);
}
};
}
public static A _registerIOWrap(A wrapper, Object wrapped) {
return wrapper;
}
public static FileInputStream newFileInputStream(File path) throws IOException {
return newFileInputStream(path.getPath());
}
public static FileInputStream newFileInputStream(String path) throws IOException {
FileInputStream f = new FileInputStream(path);
_registerIO(f, path, true);
return f;
}
public static int gzInputStream_defaultBufferSize = 65536;
public static GZIPInputStream gzInputStream(File f) {
try {
return gzInputStream(new FileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static GZIPInputStream gzInputStream(File f, int bufferSize) {
try {
return gzInputStream(new FileInputStream(f), bufferSize);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static GZIPInputStream gzInputStream(InputStream in) {
return gzInputStream(in, gzInputStream_defaultBufferSize);
}
public static GZIPInputStream gzInputStream(InputStream in, int bufferSize) {
try {
return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static final class _MethodCache {
public final Class c;
public final HashMap> cache = new HashMap();
public _MethodCache(Class c) {
this.c = c;
_init();
}
public void _init() {
Class _c = c;
while (_c != null) {
for (Method m : _c.getDeclaredMethods()) if (!reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
_c = _c.getSuperclass();
}
for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
}
public Method findMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public Method findStaticMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (isStaticMethod(me) && call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
public static class MRUCache extends LinkedHashMap {
public int maxSize = 10;
public MRUCache() {
}
public MRUCache(int maxSize) {
this.maxSize = maxSize;
}
public boolean removeEldestEntry(Map.Entry eldest) {
return size() > maxSize;
}
}
public abstract static class CloseableIterableIterator extends IterableIterator implements AutoCloseable {
public void close() throws Exception {
}
}
public abstract static class DialogIO {
public String line;
public boolean eos, loud, noClose;
public Lock lock = lock();
public abstract String readLineImpl();
public abstract boolean isStillConnected();
public abstract void sendLine(String line);
public abstract boolean isLocalConnection();
public abstract Socket getSocket();
public abstract void close();
public int getPort() {
Socket s = getSocket();
return s == null ? 0 : s.getPort();
}
public boolean helloRead;
public int shortenOutputTo = 500;
public String readLineNoBlock() {
String l = line;
line = null;
return l;
}
public boolean waitForLine() {
try {
ping();
if (line != null)
return true;
line = readLineImpl();
if (line == null)
eos = true;
return line != null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String readLine() {
waitForLine();
helloRead = true;
return readLineNoBlock();
}
public String ask(String s, Object... args) {
if (loud)
return askLoudly(s, args);
if (!helloRead)
readLine();
if (args.length != 0)
s = format3(s, args);
sendLine(s);
return readLine();
}
public String askLoudly(String s, Object... args) {
if (!helloRead)
readLine();
if (args.length != 0)
s = format3(s, args);
print("> " + shorten(s, shortenOutputTo));
sendLine(s);
String answer = readLine();
print("< " + shorten(answer, shortenOutputTo));
return answer;
}
public void pushback(String l) {
if (line != null)
throw fail();
line = l;
helloRead = false;
}
}
public abstract static class DialogHandler {
public abstract void run(DialogIO io);
}
public static class Var implements IVar {
public A v;
public Var() {
}
public Var(A v) {
this.v = v;
}
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() {
return v;
}
public synchronized boolean has() {
return v != null;
}
public synchronized void clear() {
v = null;
}
public String toString() {
return str(get());
}
}
public abstract static class DynAttractorBot extends DynPrintLog {
public String input, dialogText;
public boolean voiceMode;
public transient AttractorBot bot;
public transient List onBotSaid = synchroList();
public transient boolean activateOnOutput = true;
public void submitInput(String input) {
setField("input", input);
submitInput();
}
public void submitInput() {
Lock __8 = lock;
lock(__8);
try {
setField("input", trim(input));
addToDialog("User: " + input);
String s = input;
if (match("new dialogue", s) || match("new dialog", s))
startDialog();
else if (bot != null)
bot.addInput(input);
} finally {
unlock(__8);
}
}
public JComponent visualize() {
return jtabs("Dialog", northCenterAndSouthWithMargins(rightAlignedButtons(dm_fieldCheckBox("voiceMode"), "New dialog", runnableThread(new Runnable() {
public void run() {
try {
startDialog();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startDialog();";
}
}), "Clear window", runnableThread(new Runnable() {
public void run() {
try {
clearDialogText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "clearDialogText();";
}
})), wordWrapTextArea(dm_textArea_scrollDown_readOnly("dialogText")), dm_textFieldAndSubmit_q("input", "submitInput", "focusOnShow", true)), "Log", super.visualize());
}
public void runBot(AttractorBot bot) {
this.bot = bot;
runBot();
}
public void addToDialog(String s) {
setField("dialogText", appendWithNewLine(dialogText, print(s)));
}
public void runBot() {
bot.say = new VF1() {
public void get(String s) {
try {
addToDialog("Bot: " + s);
pcallFAll(onBotSaid, s);
vmBus_send("aBotSaid", me(), s);
if (voiceMode) {
if (activateOnOutput)
dm_activateOSAndModule();
dm_say(s);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addToDialog(\"Bot: \" + s);\r\n pcallFAll(onBotSaid, s);\r\n vmBus_send a...";
}
};
startThread("Bot", new Runnable() {
public void run() {
try {
bot.run_public();
print("\n[end]");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "bot.run_public();\r\n print(\"\\n[end]\");";
}
});
}
public void clearDialogText() {
setField("dialogText", "");
}
public abstract AttractorBot makeBot();
public void startDialog() {
clearDialogText();
runBot(makeBot());
}
public void start() {
super.start();
logModuleOutput();
dm_onTopInput_q(new VF1() {
public void get(String s) {
try {
if (!voiceMode)
return;
submitInput(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!voiceMode) ret;\r\n //dm_activateOSAndModule();\r\n submitInput(s);";
}
});
startDialog();
}
}
public static interface IResourceLoader {
public String loadSnippet(String snippetID);
public String getTranspiled(String snippetID);
public int getSnippetType(String snippetID);
public String getSnippetTitle(String snippetID);
public File loadLibrary(String snippetID);
public File pathToJavaXJar();
public File getSnippetJar(String snippetID, String transpiledSrc);
}
public abstract static class AttractorBot extends AbstractSayAndInputBot implements Runnable {
public List inputQueue = synchroLinkedList();
public Set activeThreads = synchroSet();
public List preprocessors = synchroList();
public F1 isYes = new F1() {
public Boolean get(String x) {
try {
return isYes_1(x);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "isYes_1(x)";
}
};
public LinkedHashSet facts = new LinkedHashSet();
public LinkedHashSet assumptions = new LinkedHashSet();
public List standardAttractors = synchroList();
public List activeAttractors = synchroList();
public List lowPrioAttractors = synchroList();
public String line;
public AttractorBot() {
input = new F0() {
public String get() {
try {
return getInput();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret getInput();";
}
};
standardPreprocessors();
}
public void remember(String fact) {
if (facts.add(fact))
print("[Bot learned:] " + fact);
}
public void assume(String fact) {
if (assumptions.add(fact))
print("[Bot assumes:] " + fact);
}
public String getInput() {
while (empty(inputQueue)) sleep(10);
return trim(popFirst(inputQueue));
}
public boolean yes() {
return callF(isYes, input());
}
public void run_public() {
AutoCloseable __11 = tempAddToCollection(activeThreads, currentThread());
try {
run();
} finally {
_close(__11);
}
}
public void addInput(String s) {
inputQueue.add(s);
line = s;
if (empty(activeThreads))
attractorBattle();
}
public void attractorBattle() {
if (empty(inputQueue))
return;
String input = getInput();
print("Input: " + input);
List attractors = getAndClearList(activeAttractors);
addAll(attractors, standardAttractors);
addAll(attractors, getAndClearList(lowPrioAttractors));
if (empty(attractors)) {
print("No attractors, ignoring input");
return;
}
List matchingAttractors = new ArrayList();
for (Attractor a : attractors) {
try {
if (a.matches(input)) {
a.input = input;
matchingAttractors.add(a);
}
} catch (Throwable __e) {
_handleException(__e);
}
}
if (empty(matchingAttractors)) {
print("No matching attractors, ignoring input");
return;
}
print("Got " + n2(matchingAttractors, "matching attractor") + ": " + matchingAttractors);
Attractor winner = first(matchingAttractors);
if (l(matchingAttractors) > 1)
print("Choosing first attractor");
winner.run();
}
public void addAttractor(Attractor a) {
addAttractors(a);
}
public void tempAttractor(Attractor a) {
addAttractors(a);
}
public void addAttractors(Attractor... attractors) {
addAll(activeAttractors, attractors);
}
public void addLowPrioAttractor(Attractor a) {
add(lowPrioAttractors, a);
}
public void lowPrioAttractor(Attractor a) {
addLowPrioAttractor(a);
}
public void addStandardAttractor(Attractor a) {
add(standardAttractors, a);
}
public void standardAttractors(Attractor... attractors) {
addAll(standardAttractors, attractors);
}
public void addPreprocessors(Object... l) {
addAll(preprocessors, l);
}
public void standardPreprocessors() {
addPreprocessors("ai_dropLeadingAndTrailingAppellations_sortedByLength");
}
}
public static class AI_WhatDidYouDoTodayBot extends AttractorBot {
public Long now;
public String name;
public void run() {
say("What did you do today?");
}
public class SetNameAttractor extends Attractor {
public String name;
public boolean matches(String s) {
Matches m = new Matches();
if (matchStartX("My name is ...", s, m)) {
name = m.unq(0);
return true;
}
if (match("I have no name", s)) {
name = null;
return true;
}
return false;
}
public void run() {
if (nempty(name) && eqic(AI_WhatDidYouDoTodayBot.this.name, name)) {
say("I know, " + name);
return;
}
AI_WhatDidYouDoTodayBot.this.name = name;
say("Hello " + or2(name, "stranger"));
}
}
public class Attractor1 extends Attractor {
public boolean matches(String s) {
Matches m = new Matches();
if (matchStartX("I ...", s, m))
return true;
return false;
}
public void run() {
say(nempty(name) ? switcheroo_youToI(switcheroo_iToName(name, input)) : switcheroo(input));
}
}
public AI_WhatDidYouDoTodayBot() {
standardAttractors(new SetNameAttractor(), new Attractor1());
}
}
public abstract static class IterableIterator implements Iterator , Iterable {
public Iterator iterator() {
return this;
}
public void remove() {
unsupportedOperation();
}
}
public static class AbstractSayAndInputBot {
public VF1 say;
public List onOutput;
public F0 input;
public void say(String s) {
callF(say, s);
pcallFAll(onOutput, s);
}
public void say(Iterable l) {
for (String s : unnull(l)) say(s);
}
public String input() {
return callF(input);
}
}
public static interface IVar {
public void set(A a);
public A get();
public boolean has();
public void clear();
}
public static class Attractor implements IAttractor, Runnable {
public F1 tester;
public Runnable action;
public String input;
public Attractor() {
}
public Attractor(F1 tester, Runnable action) {
this.action = action;
this.tester = tester;
}
public Attractor(Runnable action) {
this.action = action;
}
public boolean matches(String s) {
return isTrue(callF(tester, s));
}
public void run() {
callF(action);
}
public String toString() {
return standard_toString(this);
}
}
public static class DefaultAttractor extends Attractor {
public DefaultAttractor() {
this(null);
}
public DefaultAttractor(Runnable action) {
this.action = action;
tester = f1_true();
}
}
public static class MatchAttractor extends Attractor {
public String pattern;
public MatchAttractor(String pattern) {
this.pattern = pattern;
}
public MatchAttractor(String pattern, Runnable action) {
this.action = action;
this.pattern = pattern;
}
public boolean matches(String s) {
return matchX2(pattern, s);
}
}
public static class YesAttractor extends Attractor {
public YesAttractor() {
tester = new F1() {
public Boolean get(String x) {
try {
return isYes_1(x);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "isYes_1(x)";
}
};
}
public YesAttractor(Runnable action) {
this();
this.action = action;
}
}
public static interface IAttractor {
public boolean matches(String s);
}
public static List ai_dropLeadingAndTrailingAppellations_sortedByLength(String s) {
return stringsSortedByLength(ai_dropLeadingAndTrailingAppellations_iterator(s));
}
public static boolean reflection_isForbiddenMethod(Method m) {
return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}
public static void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
public static Field makeAccessible(Field f) {
f.setAccessible(true);
return f;
}
public static Method makeAccessible(Method m) {
m.setAccessible(true);
return m;
}
public static Set allInterfacesImplementedBy(Class c) {
if (c == null)
return null;
HashSet set = new HashSet();
allInterfacesImplementedBy_find(c, set);
return set;
}
public static void allInterfacesImplementedBy_find(Class c, Set set) {
if (c.isInterface() && !set.add(c))
return;
do {
for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set);
} while ((c = c.getSuperclass()) != null);
}
public static Method findMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args);
}
public static boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
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 boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
public static Method findStaticMethod(Class c, String method, Object... args) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (!m.getName().equals(method))
continue;
if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
public static boolean findStaticMethod_checkArgs(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length)
return false;
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i])))
return false;
return true;
}
public static JTabbedPane jtabs(Object... x) {
return fillJTabs(swingNu(JTabbedPane.class), x);
}
public static JPanel northCenterAndSouthWithMargins(Component n, Component c, Component s) {
return applyDefaultMargin(northCenterAndSouth(withBottomMargin(n), c, withTopMargin(s)));
}
public static JPanel rightAlignedButtons(Object... params) {
return jRightAlignedButtons(params);
}
public static JCheckBox dm_fieldCheckBox(String field) {
return dm_fieldCheckBox(humanizeFormLabel(field), field);
}
public static JCheckBox dm_fieldCheckBox(String text, String field) {
if (isIdentifier(text) && !isIdentifier(field)) {
String temp = field;
field = text;
text = temp;
}
return jLiveValueCheckBox(text, dm_fieldLiveValue(field));
}
public static Runnable runnableThread(final Runnable r) {
return new Runnable() {
public void run() {
try {
startThread(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startThread(r)";
}
};
}
public static JTextArea wordWrapTextArea() {
return wrappedTextArea();
}
public static JTextArea wordWrapTextArea(JTextArea ta) {
enableWordWrapForTextArea(ta);
return ta;
}
public static JTextArea dm_textArea_scrollDown_readOnly(String field) {
return jLiveValueTextArea_scrollDown(dm_fieldLiveValue(field));
}
public static JComponent dm_textFieldAndSubmit_q(String field, final String submitMethodName, Object... __) {
final DynModule m = dm_current_mandatory();
return dm_textFieldAndSubmit(field, r_dm_q(new Runnable() {
public void run() {
try {
call(m, submitMethodName);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "call(m, submitMethodName)";
}
}), __);
}
public static String appendWithNewLine(String a, String b) {
if (empty(b))
return a;
if (empty(a))
return b;
return addSuffix(a, "\n") + b;
}
public static void dm_activateOSAndModule(Object module) {
dm_activateOS();
dm_showModule(module);
}
public static void dm_activateOSAndModule() {
dm_activateOSAndModule(dm_current());
}
public static boolean dm_say(Object text) {
text = trim(strOrNull(text));
if (empty(text))
return true;
vmBus_send("saying", text);
if (isFalse(dm_callModuleOpt(dm_voiceMatrixModule(), "isModuleEnabled", dm_current_mandatory_generic()))) {
print("[quiet] " + text);
return false;
}
print("Saying: " + text);
Object voiceOutput = dm_voiceOutputModule();
dm_callModule(voiceOutput, "say", text);
return voiceOutput != null;
}
public static boolean logModuleOutput_installed;
public static void logModuleOutput() {
if (logModuleOutput_installed)
return;
logModuleOutput_installed = true;
final File logFile = getProgramFile("output.txt");
final LineBuffer buf = new LineBuffer(new VF1() {
public void get(String line) {
try {
appendToTextFile(logFile, "[" + localDateWithMilliseconds() + "] " + line + "\n");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "appendToTextFile(logFile, \"[\" + localDateWithMilliseconds() + \"] \" + line + \"...";
}
});
print_forAllThreads(new VF1() {
public void get(String s) {
try {
buf.append(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "buf.append(s);";
}
});
}
public static void dm_onTopInput_q(final VF1 r) {
final DynModule m = dm_current_mandatory();
dm_onTopInput(new VF1() {
public void get(final String s) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(r, s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r, s);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(r, s);";
}
});
}
public static File loadLibrary(String snippetID) {
return loadBinarySnippet(snippetID);
}
public static List synchroLinkedList() {
return Collections.synchronizedList(new LinkedList ());
}
public static Set synchroSet() {
return synchroHashSet();
}
public static Set synchroSet(Set set) {
return Collections.synchronizedSet(set);
}
public static boolean isYes_1(String s) {
return match_vbar("accept|except|save|definitely|and if it is|is if it is right|is this|right|enter|submit|send|you got it|close enough|that it is|bingo|confirm|confirming|confirmed|i said yes|it is|surely|is this the man|guess my man|just|sieve|yesterday's", s) || matchStart_vbar("yes|yeah|yep|yup|yo|yay|absolutely|correct|you can say that|chore|shore|shorts|sure|is yes|okay|ok|that's correct|you are right|you're right|you're correct|you just said it", s) || matchEnd_vbar("that's right|got it|could say that|could say so|that's it|couldn't be anything else", s);
}
public static volatile boolean sleep_noSleep;
public static void sleep(long ms) {
ping();
if (ms < 0)
return;
if (isAWTThread() && ms > 100)
throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void sleep() {
try {
if (sleep_noSleep)
throw fail("nosleep");
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A popFirst(List l) {
if (empty(l))
return null;
A a = first(l);
l.remove(0);
return a;
}
public static A popFirst(Collection l) {
if (empty(l))
return null;
A a = first(l);
l.remove(a);
return a;
}
public static AutoCloseable tempAddToCollection(Collection l, A a) {
return tempAdd(l, a);
}
public static Class run(String progID, String... args) {
Class main = hotwire(progID);
callMain(main, args);
return main;
}
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 List getAndClearList(Collection l) {
if (l == null)
return emptyList();
synchronized (collectionMutex(l)) {
List out = cloneList(l);
l.clear();
return out;
}
}
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 Map addAll(Map a, Map extends A, ? extends B> b) {
if (a != null)
a.putAll(b);
return a;
}
public static void add(BitSet bs, int i) {
bs.set(i);
}
public static boolean add(Collection c, A a) {
return c != null && c.add(a);
}
public static void add(Container c, Component x) {
addToContainer(c, x);
}
public static void say(String s) {
print(s);
}
public static boolean matchStartX(String pat, String s, Matches matches) {
return matchStart(dropSuffix("...", pat), s, matches);
}
public static String switcheroo_youToI(String s) {
return translateUsingWordTree(s, mapToWordTree(mechMap("Switcheroo you -> I")));
}
public static String switcheroo_iToName(String name, String s) {
Map map = mechMap("Switcheroo I -> $name");
map = mapValues(map, x -> replaceIC(x, "$name", name));
return translateUsingWordTree(s, mapToWordTree(map));
}
public static List switcheroo_themap = ll("mine", "yours", "my", "your", "you are", "i am", "are you", "am i", "you're", "i'm", "you've", "i've", "me", "you", "i", "you");
public static String switcheroo(String s) {
List tok = nlTok5(s);
for (int i = 1; i < l(tok); i += 2) {
for (int j = 0; j < l(switcheroo_themap); j += 2) {
String x = switcheroo_themap.get(j), y = switcheroo_themap.get(j + 1);
List tokx = nlTok5(x), toky = nlTok5(y);
switcheroo_matchReplace(tok, i, tokx, toky);
switcheroo_matchReplace(tok, i, toky, tokx);
}
}
return join(map("switcheroo_dropAsterisk", tok));
}
public static String switcheroo_dropAsterisk(String t) {
return startsWith(t, "*") && l(t) > 1 ? substring(t, 1) : t;
}
public static void switcheroo_matchReplace(List tok, int i, List tokx, List toky) {
if (switcheroo_tokRegionMatch(tok, i, tokx)) {
for (int j = 0; j * 2 + 1 < l(tokx); j++) tok.set(i + j * 2, "*" + toky.get(1 + j * 2));
}
}
public static boolean switcheroo_tokRegionMatch(List tok, int i, List tokx) {
for (int j = 0; j * 2 + 1 < l(tokx); j++) if (!eqic(get(tok, i + j * 2), get(tokx, 1 + j * 2)))
return false;
return true;
}
public static Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
public static UnsupportedOperationException unsupportedOperation() {
throw new UnsupportedOperationException();
}
public static String standard_toString(Object o) {
if (o == null)
return "null";
String name = shortClassName(o);
Set fields = fieldNames(o);
if (empty(fields))
return name;
return name + "(" + joinWithComma(mapNonNulls(fields, field -> {
Object value = get(o, field);
if (value == null)
return null;
return field + "=" + str(value);
})) + ")";
}
public static F1 f1_true() {
return f1_const(true);
}
public static boolean matchX2(String pat, String s) {
return matchX_vbar(pat, s);
}
public static boolean matchX2(String pat, String s, Matches matches) {
return matchX_vbar(pat, s, matches);
}
public static List stringsSortedByLength(Iterable l) {
return sortedByCalculatedField(l, new F1() {
public Integer get(String s) {
try {
return l(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "l(s)";
}
});
}
public static IterableIterator ai_dropLeadingAndTrailingAppellations_iterator(String s) {
final Set phrases = mechSetCI("Appellations");
return repeatedInputModificationsIterator(s, new F1>>() {
public List> get(String s) {
try {
return ai_dropLeadingAndTrailingPhrasesIterators(s, phrases);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ai_dropLeadingAndTrailingPhrasesIterators(s, phrases)";
}
});
}
public static Method findMethod_cached(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
_MethodCache cache = callOpt_getCache(((Class) o));
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
return m;
return null;
} else {
_MethodCache cache = callOpt_getCache(o.getClass());
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (findMethod_checkArgs(m, args, false))
return m;
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static JTabbedPane fillJTabs(final JTabbedPane tabs, final Object... _x) {
if (tabs != null) {
swing(new Runnable() {
public void run() {
try {
clearTabs(tabs);
Object[] x = flattenArray2(_x);
int idx = 0;
if (get(x, 0) instanceof Integer) {
idx = asInt(get(x, 0));
x = dropFirst(x);
if (empty(x)) {
x = arrayrep(null, idx);
idx = 0;
}
}
int n = 0;
for (int i = 0; i < l(x); i++) {
++n;
if (x[i] instanceof Component)
tabs.addTab("Tab " + n, wrap((Component) x[i]));
else {
String name = str(or(x[i], "Tab " + n));
Component c;
if (get(x, i + 1) instanceof Component)
c = (Component) get(x, ++i);
else
c = new JPanel();
tabs.addTab(name, wrap(c));
}
}
if (idx != 0)
tabs.setSelectedIndex(min(tabs.getTabCount() - 1, idx));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "clearTabs(tabs);\r\n Object[] x = flattenArray2(_x);\r\n ifdef fillJTabs_de...";
}
});
}
return tabs;
}
public static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
public static A applyDefaultMargin(final A c) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMarg...";
}
});
}
return c;
}
public static JPanel northCenterAndSouth(Component n, Component c, Component s) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.NORTH, wrap(n));
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
}
public static int withBottomMargin_defaultWidth = 6;
public static JPanel withBottomMargin(Component c) {
return withBottomMargin(withBottomMargin_defaultWidth, c);
}
public static JPanel withBottomMargin(final int w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(0, 0, w, 0));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static int withTopMargin_defaultWidth = 6;
public static JPanel withTopMargin(Component c) {
return withTopMargin(withTopMargin_defaultWidth, c);
}
public static JPanel withTopMargin(final int w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(w, 0, 0, 0));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static JPanel jRightAlignedButtons(Object... params) {
List l = new ArrayList();
for (int i = 0; i < l(params); i += 2) if (params[i] != null)
if (params[i] instanceof JComponent)
l.add((JComponent) params[i--]);
else
l.add(jbutton((String) params[i], params[i + 1]));
return jRightAlignedLine(l);
}
public static Map humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5");
public static String humanizeFormLabel(String s) {
if (containsSpace(s))
return s;
return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID"));
}
public static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
public static JCheckBox jLiveValueCheckBox(String text, final SimpleLiveValue lv) {
final JCheckBox cb = jCheckBox(text);
bindCheckBoxToLiveValue(cb, lv);
return cb;
}
public static SimpleLiveValue dm_fieldLiveValue(String fieldName) {
return dm_fieldLiveValue(dm_current_mandatory(), fieldName);
}
public static SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) {
Lock __130 = module.lock;
lock(__130);
try {
Class type = getFieldType(module, fieldName);
final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName));
module.onChange(new Runnable() {
public void run() {
try {
Object o = get(module, fieldName);
value.set(o);
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting \" + fi...";
}
});
value.onChange(new Runnable() {
public void run() {
try {
module.setField(fieldName, value.get());
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting 2 \" + ...";
}
});
return value;
} finally {
unlock(__130);
}
}
public static JTextArea wrappedTextArea(final JTextArea ta) {
enableWordWrapForTextArea(ta);
return ta;
}
public static JTextArea wrappedTextArea() {
return wrappedTextArea(jtextarea());
}
public static JTextArea wrappedTextArea(String text) {
JTextArea ta = wrappedTextArea();
setText(ta, text);
return ta;
}
public static void enableWordWrapForTextArea(final JTextArea ta) {
if (ta != null) {
swing(new Runnable() {
public void run() {
try {
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ta.setLineWrap(true);\r\n ta.setWrapStyleWord(true);";
}
});
}
}
public static JTextArea jLiveValueTextArea_scrollDown(final SimpleLiveValue lv) {
final JTextArea ta = typeWriterTextArea();
bindTextComponentToLiveValue_scrollDown(ta, lv);
return ta;
}
public static JComponent dm_textFieldAndSubmit(String field, final String submitMethodName, Object... __) {
final DynModule m = dm_current_mandatory();
return dm_textFieldAndSubmit(field, runnableThread(new Runnable() {
public void run() {
try {
call(m, submitMethodName);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "call(m, submitMethodName)";
}
}), __);
}
public static JComponent dm_textFieldAndSubmit(String field, Runnable action, Object... __) {
JTextField tf = boolPar("centered", __) ? dm_centeredTextField(field) : dm_textField(field);
if (boolPar("focusOnShow", __))
focusAndSelectAllOnShow(tf);
return centerAndEastWithMargin(onEnter(tf, action), jbutton(optPar("buttonText", __, "Submit"), action));
}
public static Runnable r_dm_q(final Runnable r) {
return new Runnable() {
public void run() {
try {
dm_q(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_q(r)";
}
};
}
public static String addSuffix(String s, String suffix) {
return s == null || s.endsWith(suffix) ? s : s + suffix;
}
public static void dm_activateOS() {
activateFrame(dm_desktopPane());
}
public static void dm_showModule(Object module) {
Object stem = dm_getStem(module);
if (stem != null)
dm_callOS("showModule", stem);
}
public static void dm_showModule() {
dm_showModule(dm_current_mandatory());
}
public static DynModule dm_current() {
return dm_currentModule();
}
public static String strOrNull(Object o) {
return o == null ? null : str(o);
}
public static A dm_callModuleOpt(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __54 = dm_enter(mod);
try {
return (A) callOpt_withVarargs(mod, method, args);
} finally {
_close(__54);
}
}
public static Object dm_voiceMatrixModule() {
return dm_moduleWithClassNameEndingIn("VoiceMatrix");
}
public static Object dm_voiceOutputModule() {
{
Object __62 = vmBus_query("voiceOutputModule");
if (__62 != null)
return __62;
}
return dm_requireModule("#1016614/VoiceOutput");
}
public static Object dm_callModule(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __65 = dm_enter(mod);
try {
return call(mod, method, args);
} finally {
_close(__65);
}
}
public static void appendToTextFile(File file, String contents) {
try {
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
if (contents != null) {
FileOutputStream fileOutputStream = new FileOutputStream(file, true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void appendToTextFile(String file, String contents) {
appendToTextFile(programFile(file), contents);
}
public static String localDateWithMilliseconds(long time) {
SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss''SSSS");
return format.format(time);
}
public static String localDateWithMilliseconds() {
return localDateWithMilliseconds(now());
}
public static void print_forAllThreads(Object f) {
assertNull("todo", print_allThreads);
print_allThreads = f;
}
public static void dm_onTopInput(final VF1 r) {
final DynModule m = dm_current_mandatory();
dm_ownResource(vmBus_onMessage("topInput", new VF1() {
public void get(final String s) {
try {
m.enter();
callF(r, s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "m.enter();\r\n callF(r, s)";
}
}));
}
public static void dm_onTopInput(final Runnable r) {
final DynModule m = dm_current_mandatory();
dm_ownResource(vmBus_onMessage("topInput", new VF1() {
public void get(final String s) {
try {
m.enter();
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "m.enter();\r\n callF(r)";
}
}));
}
public static File loadBinarySnippet(String snippetID) {
try {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
long id = parseSnippetID(snippetID);
if (isImageServerSnippet(id))
return loadImageAsFile(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile(snippetID);
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Set synchroHashSet() {
return Collections.synchronizedSet(new HashSet ());
}
public static boolean match_vbar(String pat, String s) {
return match_vbar(pat, s, null);
}
public static boolean match_vbar(String pat, String s, Matches matches) {
for (String pat2 : tok_splitAtVerticalBar(pat)) if (match3(pat2, s, matches))
return true;
return false;
}
public static boolean matchStart_vbar(String pat, String s) {
return matchStart_vbar(pat, s, null);
}
public static boolean matchStart_vbar(String pat, String s, Matches matches) {
for (String pat2 : splitAtTokens(pat, ll("|"))) if (matchStart(pat2, s, matches))
return true;
return false;
}
public static boolean matchEnd_vbar(String pat, String s) {
return matchEnd_vbar(pat, s, null);
}
public static boolean matchEnd_vbar(String pat, String s, Matches matches) {
for (String pat2 : splitAtTokens(pat, ll("|"))) if (matchEnd(pat2, s, matches))
return true;
return false;
}
public static Object sleepQuietly_monitor = new Object();
public static void sleepQuietly() {
try {
assertFalse(isAWTThread());
synchronized (sleepQuietly_monitor) {
sleepQuietly_monitor.wait();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 void addToContainer(final Container a, final Component b) {
if (a != null && b != null) {
swing(new Runnable() {
public void run() {
try {
a.add(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.add(b);";
}
});
}
}
public static boolean matchStart(String pat, String s) {
return matchStart(pat, s, null);
}
public static boolean matchStart(String pat, String s, Matches matches) {
if (s == null)
return false;
return matchStart(pat, parse3_cachedInput(s), matches);
}
public static boolean matchStart(String pat, List toks, Matches matches) {
if (toks == null)
return false;
List tokpat = parse3_cachedPattern(pat);
if (toks.size() < tokpat.size())
return false;
String[] m = match2(tokpat, toks.subList(0, tokpat.size()));
if (m == null)
return false;
if (matches != null) {
matches.m = new String[m.length + 1];
arraycopy(m, matches.m);
matches.m[m.length] = join(toks.subList(tokpat.size(), toks.size()));
}
return true;
}
public static boolean translateUsingWordTree_debug;
public static boolean translateUsingWordTree_printReplacements;
public static String translateUsingWordTree(String input, Map tree) {
return join(translateUsingWordTree(javaTok(input), tree));
}
public static List translateUsingWordTree(List tok, Map tree) {
for (int i = 1; i < l(tok); ) i = translateUsingWordTree_scanFrom(tok, i, tree);
return tok;
}
public static int translateUsingWordTree_scanFrom(List tok, int i, Map tree) {
int j = i;
String best = null;
int bestIndex = 0;
while (true) {
if (j > i) {
String def = (String) (tree.get(""));
if (def != null) {
best = def;
bestIndex = j;
}
}
if (j >= l(tok))
break;
Object t = tree.get(tok.get(j));
if (translateUsingWordTree_debug)
print(i + "-" + j + " / " + joinSubList(tok, i, j + 1) + " => " + sfu(t));
if (t == null)
break;
if (t instanceof String) {
int k = j + 2;
if (translateUsingWordTree_printReplacements)
print("translateUsingWordTree: replacing " + sfu(subList(tok, i, k - 1) + " with " + quote(t)));
replaceTokens(tok, i, k - 1, (String) t);
return k;
}
tree = (Map) t;
j += 2;
}
if (best != null) {
int k = bestIndex;
replaceTokens(tok, i, k - 1, best);
return k;
}
return i + 2;
}
public static Map mapToWordTree(Map map) {
Map tree = ciMap();
{
final Map __22 = unnull(map);
for (String key : keys(__22)) {
String value = __22.get(key);
wordTreeAdd(tree, javaTokC(key), value);
}
}
return simplifyWordTree(tree);
}
public static Map mechMap(String listName) {
return mechMapCI(listName);
}
public static Map mapValues(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map)) m.put(key, callF(func, map.get(key)));
return m;
}
public static Map mapValues(Map map, IF1 f) {
return mapValues(f, map);
}
public static Map mapValues(Map map, Object func) {
return mapValues(func, map);
}
public static List replaceIC(List l, String a, String b) {
List l2 = new ArrayList();
for (int i = 0; i < l(l); i++) {
String s = l.get(i);
l2.add(eqic(s, a) ? b : s);
}
return l2;
}
public static String replaceIC(String s, String a, String b) {
return s.replaceAll("(?i)" + patternQuote(a), quoteReplacement(b));
}
public static List nlTok5(String s) {
List tok = new ArrayList();
int l = l(s);
int i = 0;
while (i < l) {
int j = i;
char c;
String cc;
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j + 2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l)
break;
c = s.charAt(i);
cc = s.substring(i, Math.min(i + 2, l));
if (c == '“' || c == '”')
c = '"';
if (c == '"') {
char opener = c;
++j;
while (j < l) {
char _c = s.charAt(j);
if (_c == '“' || _c == '”')
_c = '"';
if (_c == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
if (j - 1 >= i + 1) {
tok.add(opener + s.substring(i + 1, j - 1) + opener);
i = j;
continue;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
else if (Character.isDigit(c))
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else if (cc.equals("[[")) {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (cc.equals("[=") && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else if (s.substring(j, Math.min(j + 3, l)).equals("..."))
j += 3;
else if (c == '$' || c == '#')
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
return tok;
}
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 Iterator emptyIterator() {
return Collections.emptyIterator();
}
public static String shortClassName(Object o) {
if (o == null)
return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
public static Set fieldNames(Object o) {
return allFields(o);
}
public static List mapNonNulls(Iterable l, Object f) {
return mapNonNulls(f, l);
}
public static List mapNonNulls(Object f, Iterable l) {
List x = new ArrayList();
if (l != null)
for (Object o : l) addIfNotNull(x, callF(f, o));
return x;
}
public static List mapNonNulls(Object f, Object[] l) {
List x = new ArrayList();
if (l != null)
for (Object o : l) addIfNotNull(x, callF(f, o));
return x;
}
public static List mapNonNulls(Iterable l, F1 f) {
return mapNonNulls(f, l);
}
public static List mapNonNulls(F1 f, Iterable l) {
List x = new ArrayList();
if (l != null)
for (Object o : l) addIfNotNull(x, callF(f, o));
return x;
}
public static List mapNonNulls(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) addIfNotNull(x, f.get(o));
return x;
}
public static F1 f1_const(final B b) {
return new F1 () {
public B get(A a) {
return b;
}
};
}
public static boolean matchX_vbar(String pat, String s) {
return matchX_vbar(pat, s, null);
}
public static boolean matchX_vbar(String pat, String s, Matches matches) {
for (String pat2 : tok_splitAtVerticalBar(pat)) if (matchX(pat2, s, matches))
return true;
return false;
}
public static int withMargin_defaultWidth = 6;
public static JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
public static JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
public static JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
public static JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static List sortedByCalculatedField(Iterable c, Object f) {
return sortByCalculatedField(c, f);
}
public static List sortedByCalculatedField(Object f, Iterable c) {
return sortedByCalculatedField(c, f);
}
public static TreeSet mechSetCI(String name) {
return mechCISet(name);
}
public static > IterableIterator repeatedInputModificationsIterator(String input, final F1> makeIterators) {
final HashSet seen = lithashset(input);
final LinkedList> pool = new LinkedList();
addAll(pool, callF(makeIterators, input));
return iteratorFromFunction(new F0() {
public String get() {
try {
while (!empty(pool)) {
ping();
Iterator it = first(pool);
if (!it.hasNext()) {
removeFirst(pool);
continue;
}
String entry = it.next();
if (!seen.add(entry))
continue;
addAll(pool, callF(makeIterators, entry));
return entry;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "while ping (!empty(pool)) {\r\n Iterator it = first(pool);\r\n if (!...";
}
});
}
public static List> ai_dropLeadingAndTrailingPhrasesIterators(String s, Set phrases) {
return ll(ai_dropLeadingPhrases(s, phrases), ai_dropTrailingPhrases(s, phrases));
}
public static void clearTabs(final JTabbedPane tabs) {
if (tabs != null) {
swing(new Runnable() {
public void run() {
try {
tabs.removeAll();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tabs.removeAll();";
}
});
}
}
public static Object[] flattenArray2(Object... a) {
List l = new ArrayList();
if (a != null)
for (Object x : a) if (x instanceof Object[])
l.addAll(asList((Object[]) x));
else if (x instanceof Collection)
l.addAll((Collection) x);
else
l.add(x);
return asObjectArray(l);
}
public static int asInt(Object o) {
return toInt(o);
}
public static Object[] arrayrep(Object a, int n) {
return asArray(repeat(a, n));
}
public static JComponent wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
public static JComponent wrap_2(Object swingable) {
if (swingable == null)
return null;
JComponent c;
if (swingable instanceof Component)
c = componentToJComponent(((Component) swingable));
else
c = componentToJComponent((Component) callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
public static A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () {
public A get() {
try {
return nuObject(c, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret nuObject(c, args);";
}
});
}
public static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
public static JButton jbutton(String text) {
return newButton(text, null);
}
public static JButton jbutton(Action action) {
return swingNu(JButton.class, action);
}
public static JPanel jRightAlignedLine(Component... components) {
return jrightAlignedLine(components);
}
public static JPanel jRightAlignedLine(List extends Component> components) {
return jrightAlignedLine(components);
}
public static boolean containsSpace(String s) {
return containsSpaces(s);
}
public static String firstToUpper(String s) {
if (empty(s))
return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public static List replaceElementsUsingMap(Iterable l, final Map map) {
return map(l, new F1 () {
public A get(A a) {
try {
return getOrKeep(map, a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "getOrKeep(map, a)";
}
});
}
public static List splitCamelCase(String s) {
return ai_splitCamelCase(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 JCheckBox jCheckBox() {
return swingNu(JCheckBox.class);
}
public static JCheckBox jCheckBox(boolean checked) {
return swingNu(JCheckBox.class, "", checked);
}
public static JCheckBox jCheckBox(String text, boolean checked) {
return swingNu(JCheckBox.class, text, checked);
}
public static JCheckBox jCheckBox(String text) {
return swingNu(JCheckBox.class, text);
}
public static JCheckBox jCheckBox(String text, boolean checked, final Object onChange) {
JCheckBox cb = jCheckBox(checked, onChange);
cb.setText(text);
return cb;
}
public static JCheckBox jCheckBox(boolean checked, final Object onChange) {
final JCheckBox cb = jCheckBox(checked);
cb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(onChange, cb.isSelected());
}
});
return cb;
}
public static A bindCheckBoxToLiveValue(final A cb, final SimpleLiveValue lv) {
bindLiveValueListenerToComponent(cb, lv, new Runnable() {
public void run() {
try {
setChecked(cb, isTrue(lv.get()));
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: se...";
}
});
onChange(cb, new Runnable() {
public void run() {
try {
lv.set(isChecked(cb));
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: se...";
}
});
return cb;
}
public static Class getFieldType(Object o, String field) {
return fieldType(o, field);
}
public static JTextArea jtextarea() {
return jTextArea();
}
public static JTextArea jtextarea(String text) {
return jTextArea(text);
}
public static boolean setText_opt = true;
public static A setText(A c, Object text) {
setText((JComponent) c, text);
return c;
}
public static A setText(final A c, Object text) {
final String s = strUnnull(text);
{
swing(new Runnable() {
public void run() {
try {
c.getEditor().setItem(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.getEditor().setItem(s);";
}
});
}
return c;
}
public static void setText(JLabel c, Object text) {
setText((JComponent) c, text);
}
public static JButton setText(JButton c, Object text) {
setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text)));
return c;
}
public static A setText(final A c, Object text) {
if (c == null)
return null;
final String s = strUnnull(text);
{
swing(new Runnable() {
public void run() {
try {
if (!setText_opt || neq(callOpt(c, "getText"), s))
call(c, "setText", s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n call(c, \"setText\", s);";
}
});
}
return c;
}
public static JTextArea typeWriterTextArea() {
return newTypeWriterTextArea();
}
public static JTextArea typeWriterTextArea(String text) {
return newTypeWriterTextArea(text);
}
public static A bindTextComponentToLiveValue_scrollDown(final A tc, final LiveValue lv) {
return bindLiveValueListenerToComponent(tc, lv, new Runnable() {
public void run() {
try {
setTextAndMoveCaretToEnd(tc, strOrNull(lv.get()));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "setTextAndMoveCaretToEnd(tc, strOrNull(lv.get()))";
}
});
}
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, Map __) {
return boolOptParam(name, __);
}
public static boolean boolPar(String name, Object[] params, boolean defaultValue) {
return optParam(params, name, defaultValue);
}
public static JTextField dm_centeredTextField(String field) {
return centerTextField(dm_textField(field));
}
public static JTextField dm_textField(String field) {
return dm_fieldTextField(field);
}
public static A focusOnShow(final A a) {
onFirstComponentShow(a, new Runnable() {
public void run() {
try {
focus(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "focus(a)";
}
});
return a;
}
public static A focusAndSelectAllOnShow(final A a) {
onFirstComponentShow(a, new Runnable() {
public void run() {
try {
focusAndSelectAll(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "focusAndSelectAll(a)";
}
});
return a;
}
public static JPanel centerAndEastWithMargin(Component c, Component e) {
return centerAndEastWithMarginInbetween(c, e);
}
public static JTextField onEnter(final JTextField tf, final Object action) {
if (action == null || tf == null)
return tf;
tf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
tf.selectAll();
callF(action);
} catch (Throwable __e) {
messageBox(__e);
}
}
});
return tf;
}
public static JButton onEnter(JButton btn, final Object action) {
if (action == null || btn == null)
return btn;
btn.addActionListener(actionListener(action));
return btn;
}
public static JList onEnter(JList list, Object action) {
list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action)));
return list;
}
public static JComboBox onEnter(final JComboBox cb, final Object action) {
{
swing(new Runnable() {
public void run() {
try {
if (cb.isEditable()) {
JTextField text = (JTextField) cb.getEditor().getEditorComponent();
onEnter(text, action);
} else {
cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
cb.getActionMap().put("enter", abstractAction("", new Runnable() {
public void run() {
try {
cb.hidePopup();
callF(action);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cb.hidePopup(); callF(action);";
}
}));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (cb.isEditable()) {\r\n JTextField text = (JTextField) cb.getEditor().g...";
}
});
}
return cb;
}
public static JTable onEnter(final JTable table, final Object action) {
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
table.getActionMap().put("Enter", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
callF(action, table.getSelectedRow());
}
});
return table;
}
public static JTextField onEnter(Object action, JTextField tf) {
return onEnter(tf, action);
}
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 Object optPar(String name, Map params) {
return optParam(name, params);
}
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 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 boolean activateFrame(final Component c) {
return swing(new F0() {
public Boolean get() {
try {
Frame f = getAWTFrame(c);
if (f == null)
return false;
if (!f.isVisible())
f.setVisible(true);
if (f.getState() == Frame.ICONIFIED)
f.setState(Frame.NORMAL);
if (isWindows()) {
boolean fullscreen = f.getExtendedState() == Frame.MAXIMIZED_BOTH;
f.setExtendedState(JFrame.ICONIFIED);
f.setExtendedState(fullscreen ? JFrame.MAXIMIZED_BOTH : JFrame.NORMAL);
}
f.toFront();
return true;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Frame f = getAWTFrame(c);\r\n if (f == null) false;\r\n if (!f.isVisible())...";
}
});
}
public static JDesktopPane dm_desktopPane() {
return dm_getOSOpt("desktop");
}
public static Object dm_getStem(Object moduleOrID) {
if (isStringOrIntOrLong(moduleOrID))
return dm_getStemByID(moduleOrID);
return or(getOpt(dm_getModule(moduleOrID), "_host"), moduleOrID);
}
public static Object dm_callOS(String functionName, Object... args) {
return call(dm_os(), functionName, args);
}
public static Object dm_getModule(Object moduleOrID) {
if (moduleOrID == null || eq(moduleOrID, ""))
return null;
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
return dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
public static AutoCloseable dm_enter(Object mod) {
return (AutoCloseable) callOpt(dm_getModule(mod), "enter");
}
public static Object callOpt_withVarargs(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me == null) {
return null;
}
if ((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(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);
}
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Object dm_moduleWithClassNameEndingIn(final String suffix) {
for (Object m : dm_listModules()) if (endsWith(className(m), suffix))
return m;
return null;
}
public static Object vmBus_query(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
{
Object __138 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg);
if (__138 != null)
return __138;
}
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 dm_requireModule(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
public static File programFile(String name) {
return prepareProgramFile(name);
}
public static File programFile(String progID, String name) {
return prepareProgramFile(progID, name);
}
public static SimpleDateFormat simpleDateFormat_local(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(localTimeZone());
return sdf;
}
public static A assertNull(A a) {
assertTrue(a == null);
return a;
}
public static A assertNull(String msg, A a) {
assertTrue(msg, a == null);
return a;
}
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