import java.util.*; import java.util.zip.*; import java.util.List; import java.util.regex.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.table.*; import java.io.*; import java.net.*; import java.lang.reflect.*; import java.lang.ref.*; import java.lang.management.*; import java.security.*; import java.security.spec.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import java.math.*; import x30_pkg.x30_util; import static x30_pkg.x30_util.VF1; import static x30_pkg.x30_util.l; import static x30_pkg.x30_util.fail; import static x30_pkg.x30_util.indexOf; import static x30_pkg.x30_util.getOpt; import static x30_pkg.x30_util.setOpt; import static x30_pkg.x30_util.callOpt; import static x30_pkg.x30_util.newWeakHashMap; import static x30_pkg.x30_util.newDangerousWeakHashMap; import static x30_pkg.x30_util.get; import static x30_pkg.x30_util.get_raw; import static x30_pkg.x30_util.assertTrue; import static x30_pkg.x30_util.isHeadless; import static x30_pkg.x30_util.isAndroid; import static x30_pkg.x30_util.isTrue; import static x30_pkg.x30_util.asList; import x30_pkg.x30_util.DynamicObject; import loadableUtils.utils; import static loadableUtils.utils._threadInfo; import static loadableUtils.utils._threadInheritInfo; import static loadableUtils.utils._threadInfo_addMakerAndRetriever; import static loadableUtils.utils.dm_currentModule; import static loadableUtils.utils.dm_current_mandatory; import static loadableUtils.utils.match; import static loadableUtils.utils.getOpt_raw; import static loadableUtils.utils.setOpt_raw; import static loadableUtils.utils.getField; import static loadableUtils.utils.fieldType; import static loadableUtils.utils.format3; import static loadableUtils.utils.vm_generalIdentityHashSet; import static loadableUtils.utils.vm_generalHashMap; import static loadableUtils.utils.vm_generalWeakSubMap; import static loadableUtils.utils.bindToComponent; import static loadableUtils.utils.struct; import static loadableUtils.utils.structure; import static loadableUtils.utils.loadPage; import static loadableUtils.utils.loadPage_utf8; import static loadableUtils.utils.loadPageSilentlyWithTimeout; import static loadableUtils.utils.loadPageSilently; import static loadableUtils.utils.loadSnippet; import static loadableUtils.utils.loadSnippetQuietly; import static loadableUtils.utils.sendToLocalBot; import static loadableUtils.utils.componentPopupMenu; import static loadableUtils.utils.componentPopupMenu_top; import static loadableUtils.utils.componentPopupMenu_getEvent; import static loadableUtils.utils.componentPopupMenu_initForComponent; import static loadableUtils.utils.listPopupMenu; import static loadableUtils.utils.tablePopupMenu; import static loadableUtils.utils.sexyTableWithoutDrag; import static loadableUtils.utils.dm_current_generic; import static loadableUtils.utils.dm_current_mandatory_generic; import static loadableUtils.utils.cset; import static loadableUtils.utils.DynamicObject_loading; import static loadableUtils.utils.concepts_unlisted; import static loadableUtils.utils.makePopupMenuConditional; import static loadableUtils.utils.makeConceptsTable_idWidth; import static loadableUtils.utils.showConceptsTable_afterUpdate; import static loadableUtils.utils.dynamicObjectIsLoading; import loadableUtils.utils.F0; import loadableUtils.utils.F1; import loadableUtils.utils.Matches; import loadableUtils.utils.BetterLabel; import loadableUtils.utils.SingleComponentPanel; import loadableUtils.utils.Snippet; import loadableUtils.utils.Q; import loadableUtils.utils.ImageSurface; import loadableUtils.utils.structure_Data; import loadableUtils.utils.RGBImage; import loadableUtils.utils.RGB; import loadableUtils.utils.BWImage; import loadableUtils.utils.MakesBufferedImage; import loadableUtils.utils.Concept; import loadableUtils.utils.Concepts; import loadableUtils.utils.IConceptIndex; import loadableUtils.utils.IFieldIndex; import loadableUtils.utils.Derefable; import loadableUtils.utils.ImageSurfaceSelector; import loadableUtils.utils.SimpleCRUD; import loadableUtils.utils.PersistableThrowable; import loadableUtils.utils.DynModule; import loadableUtils.utils.DynPrintLog; import loadableUtils.utils.DynObjectTable; import loadableUtils.utils.DynImageSurface; import loadableUtils.utils.DynCalculatedList; import java.text.NumberFormat; class main { public static class SingleWordMechListsIndex extends DynPrintLog { public transient volatile MultiMap index; public transient volatile boolean couldNotLoad; public void start() { super.start(); startThread(new Runnable() { public void run() { try { try { dm_useLocalMechListCopies(); List lists = mechListsWithSingleWords(); index = indexMechLists(lists); print("Indexed " + n2(lists, "list") + ". " + n2(l(index), "entry", "entries")); dm_registerAs("aMechListIndex"); } catch (Throwable _e) { couldNotLoad = true; throw rethrow(_e); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n dm_useLocalMechListCopies();\r\n List lists = mec..."; } }); } public Map> getIndex() { do { if (couldNotLoad) return null; if (index != null) return index.data; sleep(100); } while (licensed()); return null; } public List mechListsForEntry(String s) { return mapGet(getIndex(), s); } } public static boolean _moduleClass_SingleWordMechListsIndex; public static Object callF(Object f, Object... args) { try { if (f instanceof String) return callMC((String) f, args); return x30_util.callF(f, args); } catch (Exception __e) { throw rethrow(__e); } } public static A callF(F0 f) { return f == null ? null : f.get(); } public static B callF(F1 f, A a) { return f == null ? null : f.get(a); } public static C callF(F2 f, A a, B b) { return f == null ? null : f.get(a, b); } public static void callF(VF1 f, A a) { if (f != null) f.get(a); } public static Object callMC(String method, Object... args) { return call(mc(), method, args); } public static Object call(Object o) { return callF(o); } public static Object call(Object o, String method, Object... args) { return call_withVarargs(o, method, args); } public static void _onLoad_initUtils() { utils.__javax = javax(); } public static void _onLoad_defaultClassFinder() { setDefaultClassFinder(new F1() { public Class get(String name) { try { Class c = findClass_fullName(name); if (c != null) return c; if (startsWith(name, "main$")) return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + substring(name, 4)); return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Class c = findClass_fullName(name);\r\n if (c != null) ret c;\r\n if (start..."; } }); } public static String programID() { return getProgramID(); } public static String programID(Object o) { return getProgramID(o); } public static volatile StringBuffer local_log = new StringBuffer(); public static volatile Appendable print_log = local_log; public static volatile int print_log_max = 1024 * 1024; public static volatile int local_log_max = 100 * 1024; public static boolean print_silent; public static Object print_byThread_lock = new Object(); public static volatile ThreadLocal print_byThread; public static volatile Object print_allThreads; public static volatile Object print_preprocess; public static void print() { print(""); } public static A print(String s, A o) { print((endsWithLetterOrDigit(s) ? s + ": " : s) + o); return o; } public static A print(A o) { ping_okInCleanUp(); if (print_silent) return o; String s = String.valueOf(o) + "\n"; print_noNewLine(s); return o; } public static void print_noNewLine(String s) { Object f = getThreadLocal(print_byThread_dontCreate()); if (f == null) f = print_allThreads; if (f != null) if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s))) return; print_raw(s); } public static void print_raw(String s) { if (print_preprocess != null) s = (String) callF(print_preprocess, s); s = fixNewLines(s); Appendable loc = local_log; Appendable buf = print_log; int loc_max = print_log_max; if (buf != loc && buf != null) { print_append(buf, s, print_log_max); loc_max = local_log_max; } if (loc != null) print_append(loc, s, loc_max); System.out.print(s); } public static 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 void dm_useLocalMechListCopies() { dm_useLocallyCopiedMechLists(); } public static List mechListsWithSingleWords() { List out = new ArrayList(); for (Pair nameAndText : localMechListCopies_iterator()) { IterableIterator it = tlft_iterator(nameAndText.b); if (it.hasNext() && !any("containsSpaces", it)) out.add(nameAndText.a); } return out; } public static MultiMap indexMechLists(List listNames) { MultiMap mm = ciMultiMap(); for (String name : unnull(listNames)) for (String line : mL(name)) mm.put(line, name); return mm; } public static MultiMap indexMechLists(String... listNames) { return indexMechLists(asList(listNames)); } 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 AutoCloseable dm_registerAs(String... msgs) { F0 f = new F0() { public String get() { try { return dm_moduleID(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret dm_moduleID();"; } }; return combineAutoCloseables(map(msgs, msg -> dm_vmBus_answerToMessage(msg, f))); } 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 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 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 B mapGet(Map map, A a) { return map == null || a == null ? null : map.get(a); } public static B mapGet(A a, Map map) { return map == null || a == null ? null : map.get(a); } public static Class mc() { return main.class; } public static Object call_withVarargs(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findStaticMethod(method, args); if (me != null) return invokeMethod(me, null, args); List methods = cache.cache.get(method); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } { if (!(isStaticMethod(m))) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, null, newArgs); } throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found"); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(method, args); if (me != null) return invokeMethod(me, o, args); List methods = cache.cache.get(method); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, o, newArgs); } throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found"); } } catch (Exception __e) { throw rethrow(__e); } } public static Class javax() { return getJavaX(); } public static void setDefaultClassFinder(Object cf) { _defaultClassFinder_value = cf; } public static HashMap findClass_fullName_cache = new HashMap(); public static Class findClass_fullName(String name) { synchronized (findClass_fullName_cache) { if (findClass_fullName_cache.containsKey(name)) return findClass_fullName_cache.get(name); Class c; try { c = Class.forName(name); } catch (ClassNotFoundException e) { c = null; } findClass_fullName_cache.put(name, c); return c; } } public static boolean startsWith(String a, String b) { return a != null && a.startsWith(b); } public static boolean startsWith(String a, char c) { return nemptyString(a) && a.charAt(0) == c; } public static boolean startsWith(String a, String b, Matches m) { if (!startsWith(a, b)) return false; m.m = new String[] { substring(a, strL(b)) }; return true; } public static boolean startsWith(List a, List b) { if (a == null || listL(b) > listL(a)) return false; for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i))) return false; return true; } public static String substring(String s, int x) { return substring(s, x, strL(s)); } public static String substring(String s, int x, int y) { if (s == null) return null; if (x < 0) x = 0; if (x >= s.length()) return ""; if (y < x) y = x; if (y > s.length()) y = s.length(); return s.substring(x, y); } public static Object _defaultClassFinder_value; public static Object _defaultClassFinder() { return _defaultClassFinder_value; } public static String programID; public static String getProgramID() { return nempty(programID) ? formatSnippetIDOpt(programID) : "?"; } public static String getProgramID(Class c) { String id = (String) getOpt(c, "programID"); if (nempty(id)) return formatSnippetID(id); return "?"; } public static String getProgramID(Object o) { return getProgramID(getMainClass(o)); } public static boolean endsWithLetterOrDigit(String s) { return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1)); } public static void ping_okInCleanUp() { if (ping_pauseAll || ping_anyActions) ping_impl(true); } public static Object getThreadLocal(Object o, String name) { ThreadLocal t = (ThreadLocal) (getOpt(o, name)); return t != null ? t.get() : null; } public static A getThreadLocal(ThreadLocal tl) { return tl == null ? null : tl.get(); } public static ThreadLocal print_byThread_dontCreate() { return print_byThread; } public static boolean isFalse(Object o) { return eq(false, o); } public static String fixNewLines(String s) { int i = indexOf(s, '\r'); if (i < 0) return s; int l = s.length(); StringBuilder out = new StringBuilder(l); out.append(s, 0, i); for (; i < l; i++) { char c = s.charAt(i); if (c != '\r') out.append(c); else { out.append('\n'); if (i + 1 < l && s.charAt(i + 1) == '\n') ++i; } } return out.toString(); } public static void print_append(Appendable _buf, String s, int max) { try { synchronized (_buf) { _buf.append(s); if (!(_buf instanceof StringBuilder)) return; StringBuilder buf = (StringBuilder) _buf; max /= 2; if (buf.length() > max) try { int newLength = max / 2; int ofs = buf.length() - newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } } } catch (Exception __e) { throw rethrow(__e); } } public static String defaultThreadName_name; public static String defaultThreadName() { if (defaultThreadName_name == null) defaultThreadName_name = "A thread by " + programID(); return defaultThreadName_name; } public static Runnable wrapAsActivity(Object r) { return toRunnable(r); } public static Thread newThread(Object runnable) { return new Thread(_topLevelErrorHandling(toRunnable(runnable))); } public static Thread newThread(Object runnable, String name) { if (name == null) name = defaultThreadName(); return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name); } public static Thread newThread(String name, Object runnable) { return newThread(runnable, name); } public static Runnable toRunnable(final Object o) { if (o instanceof Runnable) return (Runnable) o; return new Runnable() { public void run() { try { callF(o); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; } }; } public static Map _registerThread_threads; public static Object _onRegisterThread; public static Thread _registerThread(Thread t) { if (_registerThread_threads == null) _registerThread_threads = newWeakHashMap(); _registerThread_threads.put(t, true); vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc())); callF(_onRegisterThread, t); return t; } public static void _registerThread() { _registerThread(Thread.currentThread()); } public static void dm_useLocallyCopiedMechLists() { dm_requireModule("#1016073/MechLists"); useLocalMechListCopies(true); setOptMC("serverMechList_raw_fresh_verbose", true); setOptMC("mechList_goToCreator_dont", true); } public static IterableIterator> localMechListCopies_iterator() { return mapI(namesOfLocalMechListCopies(), new F1>() { public Pair get(String name) { try { return pair(name, loadTextFile(remoteMechListMirrorFile(name))); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pair(name, loadTextFile(remoteMechListMirrorFile(name)))"; } }); } public static IterableIterator tlft_iterator(String s) { IterableIterator it = lines_iterator(s); return iff_endOnNull(new F0() { public String get() { try { while (it.hasNext()) { String line = it.next(); if (nempty(line = trim(line))) return line; } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "while (it.hasNext()) {\r\n S line = it.next();\r\n if (nempty(line = tr..."; } }); } public static boolean any(Object pred, Iterable l) { if (l != null) for (A a : l) if (isTrue(callF(pred, a))) return true; return false; } public static boolean containsSpaces(String s) { return indexOf(s, ' ') >= 0; } public static MultiMap ciMultiMap() { return caseInsensitiveMultiMap(); } public static String unnull(String s) { return s == null ? "" : s; } public static Collection unnull(Collection l) { return l == null ? emptyList() : l; } public static List unnull(List l) { return l == null ? emptyList() : l; } public static Map unnull(Map l) { return l == null ? emptyMap() : l; } public static Iterable unnull(Iterable i) { return i == null ? emptyList() : i; } public static A[] unnull(A[] a) { return a == null ? (A[]) new Object[0] : a; } public static BitSet unnull(BitSet b) { return b == null ? new BitSet() : b; } public static Pair unnull(Pair p) { return p != null ? p : new Pair(null, null); } public static List mL(String name) { return mechList_opt(name); } public static String formatWithThousands(long l) { return formatWithThousandsSeparator(l); } public static double fraction(double d) { return d % 1; } public static String n_fancy2(long l, String singular, String plural) { return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural); } public static String n_fancy2(Collection l, String singular, String plural) { return n_fancy2(l(l), singular, plural); } public static String n_fancy2(Map m, String singular, String plural) { return n_fancy2(l(m), singular, plural); } public static String n_fancy2(Object[] a, String singular, String plural) { return n_fancy2(l(a), singular, plural); } public static String dm_moduleID(Object module) { return strOrNull(getOpt(dm_getStem(module), "id")); } public static String dm_moduleID() { return dm_moduleID(dm_current_mandatory()); } public static AutoCloseable combineAutoCloseables(final AutoCloseable a, final AutoCloseable b) { return a == null ? b : b == null ? a : new AutoCloseable() { public String toString() { return "a.close(); b.close();"; } public void close() throws Exception { a.close(); b.close(); } }; } public static AutoCloseable combineAutoCloseables(AutoCloseable a, AutoCloseable b, AutoCloseable c, AutoCloseable... more) { return combineAutoCloseables(concatLists(ll(a, b, c), asList(more))); } public static AutoCloseable combineAutoCloseables(Iterable l) { return foldl(new F2() { public AutoCloseable get(AutoCloseable a, AutoCloseable b) { try { return combineAutoCloseables(a, b); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "combineAutoCloseables(a,b)"; } }, null, l); } 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 AutoCloseable dm_vmBus_answerToMessage(String msg, final F0 f) { final DynModule m = dm_current_mandatory(); return dm_ownResource(vmBus_addListener_basic(msg, new F2() { public Object get(String _msg, Object arg) { try { AutoCloseable __30 = m.enter(); try { return callF(f); } finally { _close(__30); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n ret callF(f);"; } })); } public static AutoCloseable dm_vmBus_answerToMessage(String msg, final F1 f) { final DynModule m = dm_current_mandatory(); return dm_ownResource(vmBus_addListener_basic(msg, new F2() { public Object get(String _msg, Object arg) { try { AutoCloseable __31 = m.enter(); try { return callF(f, arg); } finally { _close(__31); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp m.enter();\r\n ret callF(f, arg);"; } })); } public static void _handleError(Error e) { call(javax(), "_handleError", 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 isAWTThread() { if (isAndroid()) return false; if (isHeadless()) return false; return isAWTThread_awt(); } public static boolean isAWTThread_awt() { return SwingUtilities.isEventDispatchThread(); } 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 final Map callOpt_cache = newDangerousWeakHashMap(); public static Object callOpt_cached(Object o, String methodName, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me == null || (me.getModifiers() & Modifier.STATIC) == 0) return null; return invokeMethod(me, null, args); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me == null) return null; return invokeMethod(me, o, args); } } catch (Exception __e) { throw rethrow(__e); } } public static _MethodCache callOpt_getCache(Class c) { synchronized (callOpt_cache) { _MethodCache cache = callOpt_cache.get(c); if (cache == null) callOpt_cache.put(c, cache = new _MethodCache(c)); return cache; } } public static Object invokeMethod(Method m, Object o, Object... args) { try { try { return m.invoke(o, args); } catch (InvocationTargetException e) { throw rethrow(getExceptionCause(e)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args))); } } catch (Exception __e) { throw rethrow(__e); } } public static boolean isStaticMethod(Method m) { return methodIsStatic(m); } public static Object[] massageArgsForVarArgsCall(Method m, Object[] args) { Class[] types = m.getParameterTypes(); int n = types.length - 1, nArgs = args.length; if (nArgs < n) return null; for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i])) return null; Class varArgType = types[n].getComponentType(); for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType)) return null; Object[] newArgs = new Object[n + 1]; arraycopy(args, 0, newArgs, 0, n); Object[] varArgs = arrayOfType(varArgType, nArgs - n); arraycopy(args, n, varArgs, 0, nArgs - n); newArgs[n] = varArgs; return newArgs; } public static String joinWithComma(Collection c) { return join(", ", c); } public static String joinWithComma(String... c) { return join(", ", c); } public static String joinWithComma(Pair p) { return p == null ? "" : joinWithComma(str(p.a), str(p.b)); } public static List classNames(Collection l) { return getClassNames(l); } public static List classNames(Object[] l) { return getClassNames(Arrays.asList(l)); } public static Class __javax; public static Class getJavaX() { try { return __javax; } catch (Exception __e) { throw rethrow(__e); } } public static boolean nemptyString(String s) { return s != null && s.length() > 0; } public static int strL(String s) { return s == null ? 0 : s.length(); } public static int listL(Collection l) { return l == null ? 0 : l.size(); } public static boolean neq(Object a, Object b) { return !eq(a, b); } public static boolean nempty(Collection c) { return !empty(c); } public static boolean nempty(CharSequence s) { return !empty(s); } public static boolean nempty(Object[] o) { return !empty(o); } public static boolean nempty(byte[] o) { return !empty(o); } public static boolean nempty(int[] o) { return !empty(o); } public static boolean nempty(Map m) { return !empty(m); } public static boolean nempty(Iterator i) { return i != null && i.hasNext(); } public static boolean nempty(Object o) { return !empty(o); } public static String formatSnippetIDOpt(String s) { return isSnippetID(s) ? formatSnippetID(s) : s; } public static String formatSnippetID(String id) { return "#" + parseSnippetID(id); } public static String formatSnippetID(long id) { return "#" + id; } public static Class getMainClass() { return mc(); } public static Class getMainClass(Object o) { try { if (o == null) return null; if (o instanceof Class && eq(((Class) o).getName(), "x30")) return (Class) o; return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main"); } catch (Exception __e) { throw rethrow(__e); } } public static boolean eq(Object a, Object b) { return a == null ? b == null : a == b || b != null && a.equals(b); } 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 String dm_requireModule(String moduleLibID) { return dm_makeModule(moduleLibID); } public static boolean useLocalMechListCopies_flag; public static boolean useLocalMechListCopies() { return useLocalMechListCopies_flag; } public static void useLocalMechListCopies(boolean flag) { useLocalMechListCopies_flag = flag; if (flag) mechMode().readMode = "localCopies"; } public static void setOptMC(String field, Object value) { setOpt(mc(), field, value); } public static class mapI_It extends IterableIterator { public Object f; public Iterator i; public mapI_It() { } public mapI_It(Object f, Iterator i) { this.i = i; this.f = f; } public boolean hasNext() { return i.hasNext(); } public Object next() { return callF(f, i.next()); } public String toString() { return formatFunctionCall("mapI", f, i); } } public static IterableIterator mapI(final Object f, final Iterator i) { return new mapI_It(f, i); } public static IterableIterator mapI(IterableIterator i, Object f) { return mapI((Iterator) i, f); } public static IterableIterator mapI(Object f, IterableIterator i) { return mapI((Iterator) i, f); } public static IterableIterator mapI(Iterator i, Object f) { return mapI(f, i); } public static IterableIterator mapI(Iterable i, IF1 f) { return mapI(i, (Object) f); } public static IterableIterator mapI(Iterable i, Object f) { return mapI(f, i.iterator()); } public static IterableIterator mapI(Object f, Iterable i) { return mapI(i, f); } public static List namesOfLocalMechListCopies() { return map(new F1() { public String get(File f) { try { return getString(safeUnstructMap(loadTextFile(f)), "Name"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getString(safeUnstructMap(loadTextFile(f)), 'Name)"; } }, listFilesWithExtension(remoteMechListMirrorsDir(), ".meta")); } public static Pair pair(A a, B b) { return new Pair(a, b); } public static Pair pair(A a) { return new Pair(a, a); } 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 File remoteMechListMirrorFile(String listName) { return newFile(remoteMechListMirrorsDir(), uniqueFileNameUsingMD5_80_v2(upper(listName))); } public static IterableIterator lines_iterator(final String s) { if (s == null) return emptyIterableIterator(); return iteratorFromFunction(new F0() { public int start = 0; public String get() { int i = toLines_nextLineBreak(s, start); if (i < 0) { String toReturn = s.length() > start ? s.substring(start) : null; start = s.length(); return toReturn; } String toReturn = 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 toReturn; } }); } public static IterableIterator iff_endOnNull(final Object f) { return iteratorFromFunction(f); } public static IterableIterator iff_endOnNull(F0 f) { return iteratorFromFunction(f); } 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 MultiMap caseInsensitiveMultiMap() { MultiMap mm = new MultiMap(); mm.data = caseInsensitiveMap(); return mm; } 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 mechList_opt(String name) { return mechList_opt_tlft(name); } public static String formatWithThousandsSeparator(long l) { return NumberFormat.getInstance(new Locale("en_US")).format(l); } public static String strOrNull(Object o) { return o == null ? null : str(o); } public static Object dm_getStem(Object moduleOrID) { if (isStringOrIntOrLong(moduleOrID)) return dm_getStemByID(moduleOrID); return or(getOpt(dm_getModule(moduleOrID), "_host"), moduleOrID); } public static List concatLists(Collection... lists) { List l = new ArrayList(); if (lists != null) for (Collection list : lists) if (list != null) l.addAll(list); return l; } public static List concatLists(Collection> lists) { List l = new ArrayList(); if (lists != null) for (Collection list : lists) if (list != null) l.addAll(list); return l; } public static List ll(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; } public static A foldl(F2 f, A seed, Iterable l) { A a = seed; if (l != null) for (B b : l) a = callF(f, a, b); return a; } public static AutoCloseable dm_ownResource(AutoCloseable resource) { dm_currentModuleMandatory().ownResource(resource); return resource; } public static AutoCloseable vmBus_addListener_basic(String msg, Object listener) { Map map = vm_busListenersByMessage_live(); synchronized (map) { Set listeners = map.get(msg); if (listeners == null) map.put(msg, listeners = syncIdentityHashSet()); return tempAdd(listeners, listener); } } 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 void failIfUnlicensed() { assertTrue("license off", licensed()); } public static Thread currentThread() { return Thread.currentThread(); } 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 Throwable getExceptionCause(Throwable e) { Throwable c = e.getCause(); return c != null ? c : e; } public static String joinWithSpace(Collection c) { return join(" ", c); } public static String joinWithSpace(String... c) { return join(" ", c); } public static boolean methodIsStatic(Method m) { return (m.getModifiers() & Modifier.STATIC) != 0; } public static boolean argumentCompatibleWithType(Object arg, Class type) { return arg == null ? !type.isPrimitive() : isInstanceX(type, arg); } public static void arraycopy(Object[] a, Object[] b) { int n = min(a.length, b.length); for (int i = 0; i < n; i++) b[i] = a[i]; } public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) { System.arraycopy(src, srcPos, dest, destPos, n); } public static A[] arrayOfType(Class type, int n) { return makeArray(type, n); } public static A[] arrayOfType(int n, Class type) { return arrayOfType(type, n); } public static String join(String glue, Iterable strings) { if (strings == null) return ""; if (strings instanceof Collection) { if (((Collection) strings).size() == 1) return str(first(((Collection) strings))); } StringBuilder buf = new StringBuilder(); Iterator i = strings.iterator(); if (i.hasNext()) { buf.append(i.next()); while (i.hasNext()) buf.append(glue).append(i.next()); } return buf.toString(); } public static String join(String glue, String... strings) { return join(glue, Arrays.asList(strings)); } public static String join(Iterable strings) { return join("", strings); } public static String join(Iterable strings, String glue) { return join(glue, strings); } public static String join(String[] strings) { return join("", strings); } public static String join(String glue, Pair p) { return p == null ? "" : str(p.a) + glue + str(p.b); } public static 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 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 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 WeakReference newWeakReference(A a) { return a == null ? null : new WeakReference(a); } public static String dm_makeModule(String moduleLibID) { return (String) dm_callOS("makeModule", moduleLibID); } public static MechMode mechMode_value = new MechMode(); public static MechMode mechMode() { return mechMode_value; } public static String formatFunctionCall(String fname, Object... args) { return fname + "(" + joinWithComma(allToString(args)) + ")"; } public static String getString(Map map, Object key) { return map == null ? null : (String) map.get(key); } public static String getString(List l, int idx) { return (String) get(l, idx); } public static String getString(Object o, Object key) { if (o instanceof Map) return getString((Map) o, key); if (key instanceof String) return (String) getOpt(o, (String) key); throw fail("Not a string key: " + getClassName(key)); } public static String getString(String key, Object o) { return getString(o, (Object) key); } public static Map safeUnstructMap(String s) { return safeUnstructureMap(s); } public static List listFilesWithExtension(File dir, String ext) { return listFilesWithSuffix(dir, addPrefixOptIfNempty(".", ext)); } public static List listFilesWithExtension(String ext, File dir) { return listFilesWithExtension(dir, ext); } public static File remoteMechListMirrorsDir() { return javaxDataDir("Remote Mech Lists"); } 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 uniqueFileNameUsingMD5_80_v2(String fullName) { return uniqueFileNameUsingMD5_80_v2(fullName, md5(fullName)); } public static String uniqueFileNameUsingMD5_80_v2(String fullName, String md5) { return takeFirst(80 - 33, fileNameEncode(fullName)) + " - " + md5; } public static String upper(String s) { return s == null ? null : s.toUpperCase(); } public static char upper(char c) { return Character.toUpperCase(c); } public static IterableIterator emptyIterableIterator_instance = new IterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; public static IterableIterator emptyIterableIterator() { return emptyIterableIterator_instance; } public static IterableIterator iteratorFromFunction(final Object f) { class IFF extends IterableIterator { 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 = (A) callF(f); done = a == null; } } ; return new IFF(); } public static IterableIterator iteratorFromFunction(final F0 f) { return iteratorFromFunction_f0(f); } 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 TreeMap caseInsensitiveMap() { return new TreeMap(caseInsensitiveComparator()); } 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 List mechList_opt_tlft(String name) { return mechList_opt_tlft_cached(name); } public static boolean isStringOrIntOrLong(Object o) { return o instanceof String || o instanceof Integer || o instanceof Long; } public static Object dm_getStemByID(Object id) { return dm_callOS("getModuleByID", str(id)); } public static A or(A a, A b) { return a != null ? a : b; } 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 DynModule dm_currentModuleMandatory() { return dm_current_mandatory(); } public static Map vm_busListenersByMessage_live_cache; public static Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache; } public static Map vm_busListenersByMessage_live_load() { return vm_generalHashMap("busListenersByMessage"); } public static Set syncIdentityHashSet() { return (Set) synchronizedSet(identityHashSet()); } public static AutoCloseable tempAdd(final Collection l, final A a) { if (l == null || l.contains(a)) return null; l.add(a); return new AutoCloseable() { public String toString() { return "l.remove(a);"; } public void close() throws Exception { l.remove(a); } }; } public static boolean isInstanceX(Class type, Object arg) { if (type == boolean.class) return arg instanceof Boolean; if (type == int.class) return arg instanceof Integer; if (type == long.class) return arg instanceof Long; if (type == float.class) return arg instanceof Float; if (type == short.class) return arg instanceof Short; if (type == char.class) return arg instanceof Character; if (type == byte.class) return arg instanceof Byte; if (type == double.class) return arg instanceof Double; return type.isInstance(arg); } public static int min(int a, int b) { return Math.min(a, b); } public static long min(long a, long b) { return Math.min(a, b); } public static float min(float a, float b) { return Math.min(a, b); } public static float min(float a, float b, float c) { return min(min(a, b), c); } public static double min(double a, double b) { return Math.min(a, b); } public static double min(double[] c) { double x = Double.MAX_VALUE; for (double d : c) x = Math.min(x, d); return x; } public static float min(float[] c) { float x = Float.MAX_VALUE; for (float d : c) x = Math.min(x, d); return x; } public static byte min(byte[] c) { byte x = 127; for (byte d : c) if (d < x) x = d; return x; } public static short min(short[] c) { short x = 0x7FFF; for (short d : c) if (d < x) x = d; return x; } public static int min(int[] c) { int x = Integer.MAX_VALUE; for (int d : c) if (d < x) x = d; return x; } public static A[] makeArray(Class type, int n) { return (A[]) Array.newInstance(type, n); } public static 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 Throwable printStackTrace2(Throwable e) { print(getStackTrace2(e)); return e; } public static void printStackTrace2() { printStackTrace2(new Throwable()); } public static void printStackTrace2(String msg) { printStackTrace2(new Throwable(msg)); } public static String 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 List synchroList() { return Collections.synchronizedList(new ArrayList()); } public static List synchroList(List l) { return Collections.synchronizedList(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 Object dm_callOS(String functionName, Object... args) { return call(dm_os(), functionName, args); } public static List allToString(Collection c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } public static List allToString(Object[] c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } public static Map safeUnstructureMap(String s) { return (Map) safeUnstructure(s); } public static List listFilesWithSuffix(File dir, String suffix) { List l = new ArrayList(); for (File f : listFiles(dir)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix))) l.add(f); return l; } public static String addPrefixOptIfNempty(String prefix, String s) { return addPrefixIfNotEmpty2(prefix, 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 md5(String text) { try { if (text == null) return "-"; return bytesToHex(md5_impl(toUtf8(text))); } catch (Exception __e) { throw rethrow(__e); } } public static String md5(byte[] data) { if (data == null) return "-"; return bytesToHex(md5_impl(data)); } public static MessageDigest md5_md; public static byte[] md5_impl(byte[] data) { try { return MessageDigest.getInstance("MD5").digest(data); } catch (Exception __e) { throw rethrow(__e); } } public static String md5(File file) { return md5OfFile(file); } 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_943 = 0; _repeat_943 < n; _repeat_943++) { if (it.hasNext()) l.add(it.next()); else break; } return l; } public static String fileNameEncode_safeChars = " ()[]#,!"; public static String fileNameEncode(String s) { StringBuilder buf = new StringBuilder(); int n = l(s); for (int i = 0; i < n; i++) { char c = s.charAt(i); if (contains(fileNameEncode_safeChars, c)) buf.append(c); else buf.append(urlencode(str(c))); } return str(buf); } public static IterableIterator iteratorFromFunction_f0(final F0 f) { class IFF2 extends IterableIterator { 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; } } ; return new IFF2(); } 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 Comparator caseInsensitiveComparator() { return betterCIComparator(); } public static Map>> mechList_opt_tlft_cached_cache = ciMap(); public static Lock mechList_opt_tlft_cached_lock = lock(); public static List mechList_opt_tlft_cached(String name) { MechListDependentCache> listCache; { Lock __88 = mechList_opt_tlft_cached_lock; lock(__88); try { listCache = mechList_opt_tlft_cached_cache.get(name); if (listCache == null) mechList_opt_tlft_cached_cache.put(name, listCache = new MechListDependentCache(name, new F1>() { public List get(String x) { try { return tlft(x); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tlft(x)"; } })); } finally { unlock(__88); } } return listCache.get(); } public static boolean isString(Object o) { return o instanceof String; } public static boolean isIdentifier(String s) { return isJavaIdentifier(s); } public static Object dm_getService(String serviceName) { return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName))); } public static Object dm_resolveModule(Object moduleOrStem) { return dm_callOS("resolveModule", moduleOrStem); } public static Set synchronizedSet() { return synchroHashSet(); } public static Set synchronizedSet(Set set) { return Collections.synchronizedSet(set); } public static Set identityHashSet() { return Collections.newSetFromMap(new IdentityHashMap()); } public static String getStackTrace2(Throwable e) { return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n"); } 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 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 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 Object dm_os() { { Object __386 = vm_generalMap_get("stefansOS"); if (__386 != null) return __386; } return creator(); } public static Object safeUnstructure(String s) { return unstructure(s, true); } public static File[] listFiles(File dir) { File[] files = dir.listFiles(); return files == null ? new File[0] : files; } public static File[] listFiles(String dir) { return listFiles(new File(dir)); } 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 addPrefixIfNotEmpty2(String prefix, String s) { return empty(s) ? "" : addPrefix(prefix, s); } public static String _userHome; public static String userHome() { if (_userHome == null) { if (isAndroid()) _userHome = "/storage/sdcard0/"; else _userHome = System.getProperty("user.home"); } return _userHome; } public static File userHome(String path) { return new File(userDir(), path); } public static String bytesToHex(byte[] bytes) { return bytesToHex(bytes, 0, bytes.length); } public static String bytesToHex(byte[] bytes, int ofs, int len) { StringBuilder stringBuilder = new StringBuilder(len * 2); for (int i = 0; i < len; i++) { String s = "0" + Integer.toHexString(bytes[ofs + i]); stringBuilder.append(s.substring(s.length() - 2, s.length())); } return stringBuilder.toString(); } public static byte[] toUtf8(String s) { try { return s.getBytes("UTF-8"); } catch (Exception __e) { throw rethrow(__e); } } public static boolean md5OfFile_verbose; public static String md5OfFile(String path) { return md5OfFile(newFile(path)); } public static String md5OfFile(File f) { try { if (!f.exists()) return "-"; if (md5OfFile_verbose) print("Getting MD5 of " + f); MessageDigest md5 = MessageDigest.getInstance("MD5"); FileInputStream in = new FileInputStream(f); try { byte[] buf = new byte[65536]; int l; while (true) { l = in.read(buf); if (l <= 0) break; md5.update(buf, 0, l); } return bytesToHex(md5.digest()); } finally { _close(in); } } catch (Exception __e) { throw rethrow(__e); } } 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 boolean contains(Collection c, Object o) { return c != null && c.contains(o); } public static boolean contains(Object[] x, Object o) { if (x != null) for (Object a : x) if (eq(a, o)) return true; return false; } public static boolean contains(String s, char c) { return s != null && s.indexOf(c) >= 0; } public static boolean contains(String s, String b) { return s != null && s.indexOf(b) >= 0; } public static boolean contains(BitSet bs, int i) { return bs != null && bs.get(i); } public static String urlencode(String x) { try { return URLEncoder.encode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; public static CloseableIterableIterator emptyCloseableIterableIterator() { return emptyCloseableIterableIterator_instance; } public static boolean ewic(String a, String b) { return endsWithIgnoreCase(a, b); } public static boolean ewic(String a, String b, Matches m) { return endsWithIgnoreCase(a, b, m); } public static CloseableIterableIterator linesFromReader(Reader r) { final BufferedReader br = bufferedReader(r); return iteratorFromFunction_f0_autoCloseable(new F0() { public String get() { try { return readLineFromReaderWithClose(br); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret readLineFromReaderWithClose(br);"; } }, _wrapIOCloseable(r)); } public static BufferedReader utf8bufferedReader(InputStream in) { try { return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in)); } catch (Exception __e) { throw rethrow(__e); } } public static BufferedReader utf8bufferedReader(File f) { try { return utf8bufferedReader(newFileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } public static GZIPInputStream newGZIPInputStream(File f) { return gzInputStream(f); } public static GZIPInputStream newGZIPInputStream(InputStream in) { return gzInputStream(in); } public static betterCIComparator_C betterCIComparator_instance; public static betterCIComparator_C betterCIComparator() { if (betterCIComparator_instance == null) betterCIComparator_instance = new betterCIComparator_C(); return betterCIComparator_instance; } public static class betterCIComparator_C implements Comparator { public int compare(String s1, String s2) { if (s1 == null) return s2 == null ? 0 : -1; if (s2 == null) return 1; int n1 = s1.length(); int n2 = s2.length(); int min = Math.min(n1, n2); for (int i = 0; i < min; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 != c2) { c1 = Character.toUpperCase(c1); c2 = Character.toUpperCase(c2); if (c1 != c2) { c1 = Character.toLowerCase(c1); c2 = Character.toLowerCase(c2); if (c1 != c2) { return c1 - c2; } } } } return n1 - n2; } } public static TreeMap ciMap() { return caseInsensitiveMap(); } 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 List tlft(String s) { return toLinesFullTrim(s); } public static List tlft(File f) { return toLinesFullTrim(f); } 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 boolean isJavaIdentifier(String s) { if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0))) return false; for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i))) return false; return true; } public static Object vmBus_query(String msg, Object... args) { Object arg = vmBus_wrapArgs(args); { Object __382 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg); if (__382 != null) return __382; } return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg); } public static Object vmBus_query(String msg) { return vmBus_query(msg, (Object) null); } public static String assertIdentifier(String s) { return assertIsIdentifier(s); } public static String assertIdentifier(String msg, String s) { return assertIsIdentifier(msg, s); } public static Set synchroHashSet() { return Collections.synchronizedSet(new HashSet()); } public static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); } public static String hideCredentials(String url) { return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2="); } public static String hideCredentials(Object o) { return hideCredentials(str(o)); } public static String getStackTrace(Throwable throwable) { lastException(throwable); return getStackTrace_noRecord(throwable); } public static String getStackTrace_noRecord(Throwable throwable) { StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); return hideCredentials(writer.toString()); } public static String getStackTrace() { return getStackTrace_noRecord(new Throwable()); } public static Throwable unwrapTrivialExceptionWraps(Throwable e) { if (e == null) return e; while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause(); return e; } public static String replacePrefix(String prefix, String replacement, String s) { if (!startsWith(s, prefix)) return s; return replacement + substring(s, l(prefix)); } public static Throwable innerException2(Throwable e) { if (e == null) return null; while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause(); return e; } public static String dropSuffix(String suffix, String s) { return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s; } public static Throwable getException(Runnable r) { try { callF(r); return null; } catch (Throwable e) { return e; } } public static String className(Object o) { return getClassName(o); } public static boolean eqOneOf(Object o, Object... l) { for (Object x : l) if (eq(o, x)) return true; return false; } public static Object vm_generalMap_get(Object key) { return vm_generalMap().get(key); } public static WeakReference creator_class; public static Object creator() { return creator_class == null ? null : creator_class.get(); } public static Object unstructure(String text) { return unstructure(text, false); } public static Object unstructure(String text, final boolean allDynamic) { return unstructure(text, allDynamic, null); } public static int structure_internStringsLongerThan = 50; public static int unstructure_unquoteBufSize = 100; public static int unstructure_tokrefs; public abstract static class unstructure_Receiver { public abstract void set(Object o); } public static Object unstructure(String text, boolean allDynamic, Object classFinder) { if (text == null) return null; return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder); } public static Object unstructure_reader(BufferedReader reader) { return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null); } public static Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object _classFinder) { final boolean debug = unstructure_debug; final class X { public int i = -1; public final Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder(); public HashMap refs = new HashMap(); public HashMap tokrefs = new HashMap(); public HashSet concepts = new HashSet(); public HashMap classesMap = new HashMap(); public List stack = new ArrayList(); public String curT; public char[] unquoteBuf = new char[unstructure_unquoteBufSize]; public String unquote(String s) { return unquoteUsingCharArray(s, unquoteBuf); } public String t() { return curT; } public String tpp() { String t = curT; consume(); return t; } public void parse(final unstructure_Receiver out) { String t = t(); int refID = 0; if (structure_isMarker(t, 0, l(t))) { refID = parseInt(t.substring(1)); consume(); } final int _refID = refID; final int tokIndex = i; parse_inner(refID, tokIndex, new unstructure_Receiver() { public void set(Object o) { if (_refID != 0) refs.put(_refID, o); if (o != null) tokrefs.put(tokIndex, o); out.set(o); } }); } public void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) { String t = t(); Class c = classesMap.get(t); if (c == null) { if (t.startsWith("\"")) { String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan); out.set(s); return; } if (t.startsWith("'")) { out.set(unquoteCharacter(tpp())); return; } if (t.equals("bigint")) { out.set(parseBigInt()); return; } if (t.equals("d")) { out.set(parseDouble()); return; } if (t.equals("fl")) { out.set(parseFloat()); return; } if (t.equals("sh")) { consume(); t = tpp(); if (t.equals("-")) { t = tpp(); out.set((short) (-parseInt(t))); return; } out.set((short) parseInt(t)); return; } if (t.equals("-")) { consume(); t = tpp(); out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return; } if (isInteger(t) || isLongConstant(t)) { consume(); if (isLongConstant(t)) { out.set(parseLong(t)); return; } long l = parseLong(t); boolean isInt = l == (int) l; out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return; } if (t.equals("false") || t.equals("f")) { consume(); out.set(false); return; } if (t.equals("true") || t.equals("t")) { consume(); out.set(true); return; } if (t.equals("-")) { consume(); t = tpp(); out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return; } if (isInteger(t) || isLongConstant(t)) { consume(); if (isLongConstant(t)) { out.set(parseLong(t)); return; } long l = parseLong(t); boolean isInt = l == (int) l; out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return; } if (t.equals("File")) { consume(); File f = new File(unquote(tpp())); out.set(f); return; } if (t.startsWith("r") && isInteger(t.substring(1))) { consume(); int ref = Integer.parseInt(t.substring(1)); Object o = refs.get(ref); if (o == null) print("Warning: unsatisfied back reference " + ref); out.set(o); return; } if (t.startsWith("t") && isInteger(t.substring(1))) { consume(); int ref = Integer.parseInt(t.substring(1)); Object o = tokrefs.get(ref); if (o == null) print("Warning: unsatisfied token reference " + ref); out.set(o); return; } if (t.equals("hashset")) { parseHashSet(out); return; } if (t.equals("lhs")) { parseLinkedHashSet(out); return; } if (t.equals("treeset")) { parseTreeSet(out); return; } if (t.equals("ciset")) { parseCISet(out); return; } if (eqOneOf(t, "hashmap", "hm")) { consume(); parseMap(new HashMap(), out); return; } if (t.equals("lhm")) { consume(); parseMap(new LinkedHashMap(), out); return; } if (t.equals("tm")) { consume(); parseMap(new TreeMap(), out); return; } if (t.equals("cimap")) { consume(); parseMap(ciMap(), out); return; } if (t.equals("sync")) { consume(); if (t().equals("tm")) { consume(); { parseMap(synchronizedTreeMap(), out); return; } } if (t().equals("[")) { parseList(synchroList(), out); return; } { parseMap(synchronizedMap(), out); return; } } if (t.equals("{")) { parseMap(out); return; } if (t.equals("[")) { this.parseList(new ArrayList(), out); return; } if (t.equals("bitset")) { parseBitSet(out); return; } if (t.equals("array") || t.equals("intarray")) { parseArray(out); return; } if (t.equals("ba")) { consume(); String hex = unquote(tpp()); out.set(hexToBytes(hex)); return; } if (t.equals("boolarray")) { consume(); int n = parseInt(tpp()); String hex = unquote(tpp()); out.set(boolArrayFromBytes(hexToBytes(hex), n)); return; } if (t.equals("class")) { out.set(parseClass()); return; } if (t.equals("l")) { parseLisp(out); return; } if (t.equals("null")) { consume(); out.set(null); return; } if (eq(t, "c")) { consume("c"); t = t(); assertTrue(isJavaIdentifier(t)); concepts.add(t); } } if (eq(t, "j")) { consume("j"); out.set(parseJava()); return; } if (c == null && !isJavaIdentifier(t)) throw new RuntimeException("Unknown token " + (i + 1) + ": " + t); consume(); String className, fullClassName; if (eq(t(), ".")) { consume(); className = fullClassName = t + "." + assertIdentifier(tpp()); } else { className = t; fullClassName = "main$" + t; } if (c == null) { if (allDynamic) c = null; else c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName); if (c != null) classesMap.put(className, c); } boolean hasBracket = eq(t(), "("); if (hasBracket) consume(); boolean hasOuter = hasBracket && eq(t(), "this$1"); DynamicObject dO = null; Object o = null; final String thingName = t; if (c != null) { o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c); if (o instanceof DynamicObject) dO = (DynamicObject) o; } else { if (concepts.contains(t) && (c = findClass("Concept")) != null) o = dO = (DynamicObject) nuEmptyObject(c); else dO = new DynamicObject(); dO.className = className; } if (refID != 0) refs.put(refID, o != null ? o : dO); tokrefs.put(tokIndex, o != null ? o : dO); final LinkedHashMap fields = new LinkedHashMap(); final Object _o = o; final DynamicObject _dO = dO; if (hasBracket) { stack.add(new Runnable() { public void run() { try { if (eq(t(), ")")) { consume(")"); objRead(_o, _dO, fields); out.set(_o != null ? _o : _dO); } else { final String key = unquote(tpp()); if (!eq(tpp(), "=")) throw fail("= expected, got " + t() + " after " + quote(key) + " in object " + thingName); stack.add(this); parse(new unstructure_Receiver() { public void set(Object value) { fields.put(key, value); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \")\")) {\r\n consume(\")\");\r\n objRead(_o, _dO, ..."; } }); } else { objRead(o, dO, fields); out.set(o != null ? o : dO); } } public void objRead(Object o, DynamicObject dO, Map fields) { if (o != null) if (dO != null) { setOptAllDyn(dO, fields); } else { setOptAll_pcall(o, fields); } else for (String field : keys(fields)) dO.fieldValues.put(intern(field), fields.get(field)); if (o != null) pcallOpt_noArgs(o, "_doneLoading"); } public void parseSet(final Set set, final unstructure_Receiver out) { this.parseList(new ArrayList(), new unstructure_Receiver() { public void set(Object o) { set.addAll((List) o); out.set(set); } }); } public void parseLisp(final unstructure_Receiver out) { throw fail("class Lisp not included"); } public void parseBitSet(final unstructure_Receiver out) { consume("bitset"); consume("{"); final BitSet bs = new BitSet(); stack.add(new Runnable() { public void run() { try { if (eq(t(), "}")) { consume("}"); out.set(bs); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { bs.set((Integer) o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n ..."; } }); } public void parseList(final List list, final unstructure_Receiver out) { consume("["); stack.add(new Runnable() { public void run() { try { if (eq(t(), "]")) { consume("]"); out.set(list); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { list.add(o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"]\")) {\r\n consume(\"]\");\r\n out.set(list);\r\n ..."; } }); } public void parseArray(final unstructure_Receiver out) { final String type = tpp(); consume("{"); final List list = new ArrayList(); stack.add(new Runnable() { public void run() { try { if (eq(t(), "}")) { consume("}"); out.set(type.equals("intarray") ? toIntArray(list) : list.toArray()); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { list.add(o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(type.equals(\"..."; } }); } public Object parseClass() { consume("class"); consume("("); String name = unquote(tpp()); consume(")"); Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : findClass_fullName(name); if (c != null) return c; DynamicObject dO = new DynamicObject(); dO.className = "java.lang.Class"; name = dropPrefix("main$", name); dO.fieldValues.put("name", name); return dO; } public Object parseBigInt() { consume("bigint"); consume("("); String val = tpp(); if (eq(val, "-")) val = "-" + tpp(); consume(")"); return new BigInteger(val); } public Object parseDouble() { consume("d"); consume("("); String val = unquote(tpp()); consume(")"); return Double.parseDouble(val); } public Object parseFloat() { consume("fl"); String val; if (eq(t(), "(")) { consume("("); val = unquote(tpp()); consume(")"); } else { val = unquote(tpp()); } return Float.parseFloat(val); } public void parseHashSet(unstructure_Receiver out) { consume("hashset"); parseSet(new HashSet(), out); } public void parseLinkedHashSet(unstructure_Receiver out) { consume("lhs"); parseSet(new LinkedHashSet(), out); } public void parseTreeSet(unstructure_Receiver out) { consume("treeset"); parseSet(new TreeSet(), out); } public void parseCISet(unstructure_Receiver out) { consume("ciset"); parseSet(ciSet(), out); } public void parseMap(unstructure_Receiver out) { parseMap(new TreeMap(), out); } public Object parseJava() { String j = unquote(tpp()); Matches m = new Matches(); if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m)) return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2))); else { warn("Unknown Java object: " + j); return null; } } public void parseMap(final Map map, final unstructure_Receiver out) { consume("{"); stack.add(new Runnable() { public boolean v; public Object key; public void run() { if (v) { v = false; stack.add(this); if (!eq(tpp(), "=")) throw fail("= expected, got " + t() + " in map of size " + l(map)); parse(new unstructure_Receiver() { public void set(Object value) { map.put(key, value); if (eq(t(), ",")) consume(); } }); } else { if (eq(t(), "}")) { consume("}"); out.set(map); } else { v = true; stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { key = o; } }); } } } }); } public void consume() { curT = tok.next(); ++i; } public void consume(String s) { if (!eq(t(), s)) { throw fail(quote(s) + " expected, got " + quote(t())); } consume(); } public void parse_x(unstructure_Receiver out) { consume(); parse(out); while (nempty(stack)) popLast(stack).run(); } } Boolean b = DynamicObject_loading.get(); DynamicObject_loading.set(true); try { final Var v = new Var(); X x = new X(); x.parse_x(new unstructure_Receiver() { public void set(Object o) { v.set(o); } }); unstructure_tokrefs = x.tokrefs.size(); return v.get(); } finally { DynamicObject_loading.set(b); } } public static boolean unstructure_debug; 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 addPrefix(String prefix, String s) { return s.startsWith(prefix) ? s : prefix + s; } public static File userDir() { return new File(userHome()); } public static File userDir(String path) { return new File(userHome(), path); } 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 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 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 ReentrantLock fairLock() { return new ReentrantLock(true); } public static List toLinesFullTrim(String s) { List l = new ArrayList(); for (String line : toLines(s)) if (nempty(line = trim(line))) l.add(line); return l; } public static List toLinesFullTrim(File f) { List l = new ArrayList(); for (String line : linesFromFile(f)) if (nempty(line = trim(line))) l.add(line); return l; } public static Object vmBus_wrapArgs(Object... args) { return empty(args) ? null : l(args) == 1 ? args[0] : args; } public static Object pcallFAll_returnFirstNotNull(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) { Object __538 = pcallF(f, args); if (__538 != null) return __538; } return null; } public static Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) { while (it.hasNext()) { Object __539 = pcallF(it.next(), args); if (__539 != null) return __539; } return null; } 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 String assertIsIdentifier(String s) { if (!isIdentifier(s)) throw fail("Not an identifier: " + quote(s)); return s; } public static String assertIsIdentifier(String msg, String s) { if (!isIdentifier(s)) throw fail(msg + " - Not an identifier: " + quote(s)); return s; } 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 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 Producer javaTokC_noMLS_iterator(final String s) { return javaTokC_noMLS_iterator(s, 0); } public static Producer javaTokC_noMLS_iterator(final String s, final int startIndex) { return new Producer() { public final int l = s.length(); public int i = startIndex; public String next() { if (i >= l) return null; int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } i = j; if (i >= l) return null; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else ++j; String t = quickSubstring(s, i, j); i = j; return t; } }; } public static Producer javaTokC_noMLS_onReader(final BufferedReader r) { final class X implements Producer { public StringBuilder buf = new StringBuilder(); public char c, d, e = 'x'; public X() { nc(); nc(); nc(); } public void nc() { try { c = d; d = e; if (e == '\0') return; int i = r.read(); e = i < 0 ? '\0' : i == '\0' ? '_' : (char) i; } catch (Exception __e) { throw rethrow(__e); } } public void ncSave() { if (c != '\0') { buf.append(c); nc(); } } public String next() { while (c != '\0') { if (c == ' ' || c == '\t' || c == '\r' || c == '\n') nc(); else if (c == '/' && d == '*') { do nc(); while (c != '\0' && !(c == '*' && d == '/')); nc(); nc(); } else if (c == '/' && d == '/') { do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0); } else break; } if (c == '\0') return null; if (c == '\'' || c == '"') { char opener = c; ncSave(); while (c != '\0') { if (c == opener || c == '\n') { ncSave(); break; } else if (c == '\\') { ncSave(); ncSave(); } else ncSave(); } } else if (Character.isJavaIdentifierStart(c)) do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\''); else if (Character.isDigit(c)) { do ncSave(); while (Character.isDigit(c)); if (c == 'L') ncSave(); } else ncSave(); String t = buf.toString(); buf.setLength(0); return t; } } return new X(); } public static String unquoteUsingCharArray(String s, char[] buf) { 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(); if (l > buf.length) return unquote(s); int n = 0; 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++; } } buf[n++] = (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); char[] x = Character.toChars(code); int lx = x.length; for (int j = 0; j < lx; j++) buf[n++] = x[j]; i += 5; continue; default: ch = nextChar; } i++; } buf[n++] = ch; } return new String(buf, 0, n); } } return s; } public static boolean structure_isMarker(String s, int i, int j) { if (i >= j) return false; if (s.charAt(i) != 'm') return false; ++i; while (i < j) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } public static int parseInt(String s) { return empty(s) ? 0 : Integer.parseInt(s); } public static int parseInt(char c) { return Integer.parseInt(str(c)); } public static String internIfLongerThan(String s, int l) { return s == null ? null : l(s) >= l ? intern(s) : s; } 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 char unquoteCharacter(String s) { assertTrue(s.startsWith("'") && s.length() > 1); return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length() - 1 : s.length()) + "\"").charAt(0); } public static double parseDouble(String s) { return Double.parseDouble(s); } public static float parseFloat(String s) { return Float.parseFloat(s); } public static boolean isLongConstant(String s) { if (!s.endsWith("L")) return false; s = s.substring(0, l(s) - 1); return isInteger(s); } public static boolean isInteger(String s) { int n = l(s); if (n == 0) return false; int i = 0; if (s.charAt(0) == '-') if (++i >= n) return false; while (i < n) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } public static SortedMap synchronizedTreeMap() { return synchroTreeMap(); } public static List parseList(String s) { return (List) safeUnstructure(s); } public static Map synchronizedMap() { return synchroMap(); } public static Map synchronizedMap(Map map) { return synchroMap(map); } public static byte[] hexToBytes(String s) { if (odd(l(s))) throw fail("Hex string has odd length: " + quote(shorten(10, s))); int n = l(s) / 2; byte[] bytes = new byte[n]; for (int i = 0; i < n; i++) { int a = parseHexChar(s.charAt(i * 2)); int b = parseHexChar(s.charAt(i * 2 + 1)); if (a < 0 || b < 0) throw fail("Bad hex byte: " + quote(substring(s, i * 2, i * 2 + 2)) + " at " + i * 2 + "/" + l(s)); bytes[i] = (byte) ((a << 4) | b); } return bytes; } public static boolean[] boolArrayFromBytes(byte[] a, int n) { boolean[] b = new boolean[n]; int m = min(n, l(a) * 8); for (int i = 0; i < m; i++) b[i] = (a[i / 8] & 1 << (i & 7)) != 0; return b; } public static A nuStubInnerObject(Class c) { return nuStubInnerObject(c, null); } public static A nuStubInnerObject(Class c, Object classFinder) { try { Class outerType = getOuterClass(c, classFinder); Constructor m = c.getDeclaredConstructor(outerType); m.setAccessible(true); return (A) m.newInstance(new Object[] { null }); } catch (Exception __e) { throw rethrow(__e); } } public static Map nuEmptyObject_cache = newDangerousWeakHashMap(); public static A nuEmptyObject(Class c) { try { Constructor ctr; synchronized (nuEmptyObject_cache) { ctr = nuEmptyObject_cache.get(c); if (ctr == null) { nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c)); ctr.setAccessible(true); } } try { return (A) ctr.newInstance(); } catch (InstantiationException e) { if (empty(e.getMessage())) if ((c.getModifiers() & Modifier.ABSTRACT) != 0) throw fail("Can't instantiate abstract class " + className(c), e); else throw fail("Can't instantiate " + className(c), e); else throw rethrow(e); } } catch (Exception __e) { throw rethrow(__e); } } public static Constructor nuEmptyObject_findConstructor(Class c) { for (Constructor m : c.getDeclaredConstructors()) if (m.getParameterTypes().length == 0) return m; throw fail("No default constructor declared in " + c.getName()); } public static HashMap findClass_cache = new HashMap(); public static Class findClass(String name) { synchronized (findClass_cache) { if (findClass_cache.containsKey(name)) return findClass_cache.get(name); if (!isJavaIdentifier(name)) return null; Class c; try { c = Class.forName("main$" + name); } catch (ClassNotFoundException e) { c = null; } findClass_cache.put(name, c); return c; } } 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 void setOptAllDyn(DynamicObject o, Map fields) { if (fields == null) return; HashMap fieldMap = instanceFieldsMap(o); for (Map.Entry e : fields.entrySet()) { String field = e.getKey(); Object val = e.getValue(); boolean has = fieldMap.containsKey(field); if (has) setOpt(o, field, val); else { o.fieldValues.put(intern(field), val); } } } public static void setOptAll_pcall(Object o, Map fields) { if (fields == null) return; for (String field : keys(fields)) try { setOpt(o, field, fields.get(field)); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } public static void setOptAll_pcall(Object o, Object... values) { warnIfOddCount(values); for (int i = 0; i + 1 < l(values); i += 2) { String field = (String) values[i]; Object value = values[i + 1]; try { setOpt(o, field, value); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } } public static Set keys(Map map) { return map == null ? new HashSet() : map.keySet(); } public static Set keys(Object map) { return keys((Map) map); } public static Set keys(MultiMap mm) { return mm.keySet(); } public static String intern(String s) { return fastIntern(s); } public static void pcallOpt_noArgs(Object o, String method) { try { callOpt_noArgs(o, method); } catch (Throwable __e) { _handleException(__e); } } 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 int[] toIntArray(List l) { int[] a = new int[l(l)]; for (int i = 0; i < a.length; i++) a[i] = l.get(i); return a; } public static String dropPrefix(String prefix, String s) { return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s; } public static TreeSet ciSet() { return caseInsensitiveSet(); } public static boolean jmatch(String pat, String s) { return jmatch(pat, s, null); } public static boolean jmatch(String pat, String s, Matches matches) { if (s == null) return false; return jmatch(pat, javaTok(s), matches); } public static boolean jmatch(String pat, List toks) { return jmatch(pat, toks, null); } public static boolean jmatch(String pat, List toks, Matches matches) { List tokpat = javaTok(pat); String[] m = match2(tokpat, toks); if (m == null) return false; else { if (matches != null) matches.m = m; return true; } } public static Object nuObject(String className, Object... args) { try { return nuObject(classForName(className), args); } catch (Exception __e) { throw rethrow(__e); } } public static A nuObject(Class c, Object... args) { try { if (args.length == 0) return nuObjectWithoutArguments(c); Constructor m = nuObject_findConstructor(c, args); m.setAccessible(true); return (A) m.newInstance(args); } catch (Exception __e) { throw rethrow(__e); } } public static Constructor nuObject_findConstructor(Class c, Object... args) { for (Constructor m : c.getDeclaredConstructors()) { if (!nuObject_checkArgs(m.getParameterTypes(), args, false)) continue; return m; } throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : "")); } public static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) { if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } public static boolean warn_on = true; public static void warn(String s) { if (warn_on) print("Warning: " + s); } public static void warn(String s, List warnings) { warn(s); if (warnings != null) warnings.add(s); } public static A popLast(List l) { return liftLast(l); } public static void _registerIO(Object object, String path, boolean opened) { } 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 String quickSubstring(String s, int i, int j) { if (i == j) return ""; return s.substring(i, j); } 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 NavigableMap synchroTreeMap() { return Collections.synchronizedNavigableMap(new TreeMap()); } public static Map synchroMap() { return synchroHashMap(); } public static Map synchroMap(Map map) { return Collections.synchronizedMap(map); } public static boolean odd(int i) { return (i & 1) != 0; } public static boolean odd(long i) { return (i & 1) != 0; } public static boolean odd(BigInteger i) { return odd(toInt(i)); } public static 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 int parseHexChar(char c) { if (c >= '0' && c <= '9') return charDiff(c, '0'); if (c >= 'a' && c <= 'f') return charDiff(c, 'a') + 10; if (c >= 'A' && c <= 'F') return charDiff(c, 'A') + 10; return -1; } public static Class getOuterClass(Class c) { return getOuterClass(c, null); } public static Class getOuterClass(Class c, Object classFinder) { try { String s = c.getName(); int i = s.lastIndexOf('$'); String name = substring(s, 0, i); if (classFinder != null) return (Class) callF(classFinder, name); return Class.forName(name); } catch (Exception __e) { throw rethrow(__e); } } public static HashMap instanceFieldsMap(Object o) { Class c = o.getClass(); HashMap map; synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } return map; } 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 void warnIfOddCount(Object... list) { if (odd(l(list))) printStackTrace("Odd list size: " + list); } public static Method fastIntern_method; public static String fastIntern(String s) { try { if (s == null) return null; if (fastIntern_method == null) { fastIntern_method = findMethodNamed(javax(), "internPerProgram"); if (fastIntern_method == null) upgradeJavaXAndRestart(); } return (String) fastIntern_method.invoke(null, s); } catch (Exception __e) { throw rethrow(__e); } } public static Map> callOpt_noArgs_cache = newDangerousWeakHashMap(); public static Object callOpt_noArgs(Object o, String method) { try { if (o == null) return null; if (o instanceof Class) return callOpt(o, method); Class c = o.getClass(); HashMap map; synchronized (callOpt_noArgs_cache) { map = callOpt_noArgs_cache.get(c); if (map == null) map = callOpt_noArgs_makeCache(c); } Method m = map.get(method); return m != null ? m.invoke(o) : null; } catch (Exception __e) { throw rethrow(__e); } } public static HashMap callOpt_noArgs_makeCache(Class c) { HashMap map = new HashMap(); Class _c = c; do { for (Method m : c.getDeclaredMethods()) if (m.getParameterTypes().length == 0 && !reflection_isForbiddenMethod(m)) { m.setAccessible(true); String name = m.getName(); if (!map.containsKey(name)) map.put(name, m); } _c = _c.getSuperclass(); } while (_c != null); callOpt_noArgs_cache.put(c, map); return map; } public static TreeSet caseInsensitiveSet() { return new TreeSet(caseInsensitiveComparator()); } public static TreeSet caseInsensitiveSet(Collection c) { return toCaseInsensitiveSet(c); } public static int javaTok_n, javaTok_elements; public static boolean javaTok_opt; public static List javaTok(String s) { ++javaTok_n; ArrayList tok = new ArrayList(); int l = s == null ? 0 : s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(javaTok_substringN(s, i, j)); ++n; i = j; if (i >= l) break; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) { j += 2; while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j; } else if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { int c2 = s.charAt(j); if (c2 == opener || c2 == '\n' && opener == '\'') { ++j; break; } else if (c2 == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else if (c == '[' && d == '[') { do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]")); j = Math.min(j + 2, l); } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') { do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]")); j = Math.min(j + 3, l); } else ++j; tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } public static List javaTok(List tok) { return javaTokWithExisting(join(tok), tok); } public static 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 Map classForName_cache = synchroHashMap(); public static Class classForName(String name) { try { Class c = classForName_cache.get(name); if (c == null) classForName_cache.put(name, c = Class.forName(name)); return c; } catch (Exception __e) { throw rethrow(__e); } } public static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap(); public static Object nuObjectWithoutArguments(String className) { try { return nuObjectWithoutArguments(classForName(className)); } catch (Exception __e) { throw rethrow(__e); } } public static A nuObjectWithoutArguments(Class c) { try { if (nuObjectWithoutArguments_cache == null) return (A) nuObjectWithoutArguments_findConstructor(c).newInstance(); Constructor m = nuObjectWithoutArguments_cache.get(c); if (m == null) nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c)); return (A) m.newInstance(); } catch (Exception __e) { throw rethrow(__e); } } public static Constructor nuObjectWithoutArguments_findConstructor(Class c) { for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) { m.setAccessible(true); return m; } throw fail("No default constructor found in " + c.getName()); } public static List getClasses(Object[] array) { List l = new ArrayList(); for (Object o : array) l.add(_getClass(o)); return l; } public static A liftLast(List l) { if (l.isEmpty()) return null; int i = l(l) - 1; A a = l.get(i); l.remove(i); return a; } public static Object pcallFunction(Object f, Object... args) { try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); } return null; } public static class getOpt_Map extends WeakHashMap { public getOpt_Map() { if (getOpt_special == null) getOpt_special = new HashMap(); clear(); } public void clear() { super.clear(); put(Class.class, getOpt_special); put(String.class, getOpt_special); } } public static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map())); public static HashMap getOpt_special; public static Object getOpt_cached(Object o, String field) { try { if (o == null) return null; Class c = o.getClass(); HashMap map; synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } if (map == getOpt_special) { if (o instanceof Class) return getOpt((Class) o, field); if (o instanceof Map) return ((Map) o).get(field); } Field f = map.get(field); if (f != null) return f.get(o); if (o instanceof DynamicObject) return ((DynamicObject) o).fieldValues.get(field); return null; } catch (Exception __e) { throw rethrow(__e); } } public static HashMap getOpt_makeCache(Class c) { HashMap map; if (isSubtypeOf(c, Map.class)) map = getOpt_special; else { map = new HashMap(); if (!reflection_classesNotToScan().contains(c.getName())) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) { f.setAccessible(true); String name = f.getName(); if (!map.containsKey(name)) map.put(name, f); } _c = _c.getSuperclass(); } while (_c != null); } } if (getOpt_cache != null) getOpt_cache.put(c, map); return map; } 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 Map synchroHashMap() { return Collections.synchronizedMap(new HashMap()); } public static int toInt(Object o) { if (o == null) return 0; if (o instanceof Number) return ((Number) o).intValue(); if (o instanceof String) return parseInt((String) o); throw fail("woot not int: " + getClassName(o)); } public static int toInt(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } public static int charDiff(char a, char b) { return (int) a - (int) b; } public static int charDiff(String a, char b) { return charDiff(stringToChar(a), b); } 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 Method findMethodNamed(Object obj, String method) { if (obj == null) return null; if (obj instanceof Class) return findMethodNamed((Class) obj, method); return findMethodNamed(obj.getClass(), method); } public static Method findMethodNamed(Class c, String method) { while (c != null) { for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) { m.setAccessible(true); return m; } c = c.getSuperclass(); } return null; } public static void upgradeJavaXAndRestart() { run("#1001639"); restart(); sleep(); } public static boolean reflection_isForbiddenMethod(Method m) { return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives"); } public static TreeSet toCaseInsensitiveSet(Iterable c) { if (isCISet(c)) return (TreeSet) c; TreeSet set = caseInsensitiveSet(); addAll(set, c); return set; } public static TreeSet toCaseInsensitiveSet(String... x) { TreeSet set = caseInsensitiveSet(); addAll(set, x); return set; } public static String javaTok_substringN(String s, int i, int j) { if (i == j) return ""; if (j == i + 1 && s.charAt(i) == ' ') return " "; return s.substring(i, j); } public static String javaTok_substringC(String s, int i, int j) { return s.substring(i, j); } public static List javaTokWithExisting(String s, List existing) { ++javaTok_n; int nExisting = javaTok_opt && existing != null ? existing.size() : 0; ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList(); int l = s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(javaTok_substringN(s, i, j)); ++n; i = j; if (i >= l) break; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) { j += 2; while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j; } else if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else if (c == '[' && d == '[') { do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]")); j = Math.min(j + 2, l); } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') { do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]")); j = Math.min(j + 3, l); } else ++j; if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } public static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) { return t.length() == j - i && s.regionMatches(i, t, 0, j - i); } 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 Class _getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } public static Class _getClass(Object o) { return o == null ? null : o instanceof Class ? (Class) o : o.getClass(); } public static Class _getClass(Object realm, String name) { try { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; } } public static Object callFunction(Object f, Object... args) { return callF(f, args); } public static void clear(Collection c) { if (c != null) c.clear(); } public static void put(Map map, A a, B b) { if (map != null) map.put(a, b); } public static void put(List l, int i, A a) { if (l != null && i >= 0 && i < l(l)) l.set(i, a); } public static List _registerDangerousWeakMap_preList; public static A _registerDangerousWeakMap(A map) { return _registerDangerousWeakMap(map, null); } public static A _registerDangerousWeakMap(A map, Object init) { callF(init, map); if (init instanceof String) { final String f = (String) init; init = new VF1() { public void get(Map map) { try { callMC(f, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callMC(f, map)"; } }; } if (javax() == null) { if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList(); _registerDangerousWeakMap_preList.add(pair(map, init)); return map; } call(javax(), "_registerDangerousWeakMap", map, init); return map; } public static void _onLoad_registerDangerousWeakMap() { assertNotNull(javax()); if (_registerDangerousWeakMap_preList == null) return; for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b); _registerDangerousWeakMap_preList = null; } public static boolean isSubtypeOf(Class a, Class b) { return b.isAssignableFrom(a); } public static Set reflection_classesNotToScan_value = litset("jdk.internal.loader.URLClassPath"); public static Set reflection_classesNotToScan() { return reflection_classesNotToScan_value; } public static char stringToChar(String s) { if (l(s) != 1) throw fail("bad stringToChar: " + s); return firstChar(s); } public static Class run(String progID, String... args) { Class main = hotwire(progID); callMain(main, args); return main; } public static void restart() { Object j = getJavaX(); call(j, "cleanRestart", get(j, "fullArgs")); } public static boolean isCISet(Iterable l) { return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator(); } 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 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 Class getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } public static Class getClass(Object o) { return o instanceof Class ? (Class) o : o.getClass(); } public static Class getClass(Object realm, String name) { try { try { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; } } catch (Exception __e) { throw rethrow(__e); } } public static String classNameToVM(String name) { return name.replace(".", "$"); } public static A assertNotNull(A a) { assertTrue(a != null); return a; } public static A assertNotNull(String msg, A a) { assertTrue(msg, a != null); return a; } public static HashSet litset(A... items) { return lithashset(items); } public static char firstChar(String s) { return s.charAt(0); } 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 A callMain(A c, String... args) { callOpt(c, "main", new Object[] { args }); return c; } public static void callMain() { callMain(mc()); } public static String asString(Object o) { return o == null ? null : o.toString(); } public static HashSet lithashset(A... items) { HashSet set = new HashSet(); for (A a : items) set.add(a); return set; } 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 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 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 MultiMap { public Map> data = new HashMap>(); public MultiMap() { } public MultiMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); } public MultiMap(MultiMap map) { putAll(map); } public MultiMap(Map> data) { this.data = data; } public void put(A key, B value) { synchronized (data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); list.add(value); } } public void addAll(A key, Collection values) { synchronized (data) { putAll(key, values); } } public void addAllIfNotThere(A key, Collection values) { synchronized (data) { for (B value : values) setPut(key, value); } } public void setPut(A key, B value) { synchronized (data) { if (!containsPair(key, value)) put(key, value); } } public boolean containsPair(A key, B value) { synchronized (data) { return get(key).contains(value); } } public void putAll(A key, Collection values) { synchronized (data) { for (B value : values) put(key, value); } } public void removeAll(A key, Collection values) { synchronized (data) { for (B value : values) remove(key, value); } } public List get(A key) { synchronized (data) { List list = data.get(key); return list == null ? Collections.emptyList() : list; } } public List getActual(A key) { synchronized (data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); return list; } } public void clean(A key) { synchronized (data) { List list = data.get(key); if (list != null && list.isEmpty()) data.remove(key); } } public Set keySet() { synchronized (data) { return data.keySet(); } } public Set keys() { synchronized (data) { return data.keySet(); } } public void remove(A key) { synchronized (data) { data.remove(key); } } public void remove(A key, B value) { synchronized (data) { List list = data.get(key); if (list != null) { list.remove(value); if (list.isEmpty()) data.remove(key); } } } public void clear() { synchronized (data) { data.clear(); } } public boolean containsKey(A key) { synchronized (data) { return data.containsKey(key); } } public B getFirst(A key) { synchronized (data) { List list = get(key); return list.isEmpty() ? null : list.get(0); } } public void addAll(MultiMap map) { putAll(map); } public void putAll(MultiMap map) { synchronized (data) { for (A key : map.keySet()) putAll(key, map.get(key)); } } public int keysSize() { synchronized (data) { return l(data); } } public int size() { synchronized (data) { int n = 0; for (List l : data.values()) n += l(l); return n; } } public List reverseGet(B b) { synchronized (data) { List l = new ArrayList(); for (A key : data.keySet()) if (data.get(key).contains(b)) l.add(key); return l; } } public Map> asMap() { synchronized (data) { return cloneMap(data); } } public boolean isEmpty() { synchronized (data) { return data.isEmpty(); } } public List _makeEmptyList() { return new ArrayList(); } public Collection> allLists() { synchronized (data) { return new ArrayList(data.values()); } } public List allValues() { return concatLists(values(data)); } public Object mutex() { return data; } public String toString() { return "mm" + str(data); } } public abstract static class CloseableIterableIterator extends IterableIterator implements AutoCloseable { public void close() throws Exception { } } public static interface Producer { public A next(); } public static interface IF1 { public B get(A a); } 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 static class MechListDependentCache extends Cache { public String listName, lastListContents; public MechListDependentCache() { } public MechListDependentCache(String listName, Object maker) { this.maker = maker; this.listName = listName; } public A make() { return (A) callF(maker, lastListContents); } public A get() { if (hasLock(lock)) return value; { String listContents = mL_raw(listName); Lock __100 = lock; lock(__100); try { if (!eqOrSame(listContents, lastListContents)) clear(); lastListContents = listContents; } finally { unlock(__100); } } return super.get(); } } public abstract static class IterableIterator implements Iterator, Iterable { public Iterator iterator() { return this; } public void remove() { unsupportedOperation(); } } public abstract static class F2 { public abstract C get(A a, B b); } public static class MechMode { public Object readMode; public Object writeMode; public MechMode() { } public MechMode(Object readMode, Object writeMode) { this.writeMode = writeMode; this.readMode = readMode; } public String toString() { return "MechMode(" + readMode + ", " + writeMode + ")"; } public boolean equals(Object o) { if (!(o instanceof MechMode)) return false; MechMode x = (MechMode) o; return eq(readMode, x.readMode) && eq(writeMode, x.writeMode); } public int hashCode() { int h = -866263200; h = h * 2 + _hashCode(readMode); h = h * 2 + _hashCode(writeMode); return h; } } public static class Pair implements Comparable> { public A a; public B b; public Pair() { } public Pair(A a, B b) { this.b = b; this.a = a; } public int hashCode() { return hashCodeFor(a) + 2 * hashCodeFor(b); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Pair)) return false; Pair t = (Pair) o; return eq(a, t.a) && eq(b, t.b); } public String toString() { return "<" + a + ", " + b + ">"; } public int compareTo(Pair p) { if (p == null) return 1; int i = ((Comparable) a).compareTo(p.a); if (i != 0) return i; return ((Comparable) b).compareTo(p.b); } } public static interface IVar { public void set(A a); public A get(); public boolean has(); public void clear(); } public static class Cache { public Object maker; public A value; public long loaded; public static boolean debug; public long changeCount; public Lock lock = lock(); public Cache() { } public Cache(Object maker) { this.maker = maker; } public A get() { if (hasLock(lock)) return value; Lock __104 = lock; lock(__104); try { if (loaded == 0) { value = make(); changeCount++; loaded = sysNow(); } return value; } finally { unlock(__104); } } public void clear() { Lock __105 = lock; lock(__105); try { if (debug && loaded != 0) print("Clearing cache"); value = null; changeCount++; loaded = 0; } finally { unlock(__105); } } public void clear(double seconds) { Lock __106 = lock; lock(__106); try { if (seconds != 0 && loaded != 0 && sysNow() >= loaded + seconds * 1000) clear(); } finally { unlock(__106); } } public void set(A a) { Lock __107 = lock; lock(__107); try { value = a; ++changeCount; loaded = sysNow(); } finally { unlock(__107); } } public A make() { return (A) callF(maker); } } 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 void multiMapPut(MultiMap mm, A key, B value) { if (mm != null && key != null && value != null) mm.put(key, value); } 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 Map putAll(Map a, Map b) { if (a != null) a.putAll(b); return a; } public static void remove(List l, int i) { if (l != null && i >= 0 && i < l(l)) l.remove(i); } public static void remove(Collection l, A a) { if (l != null) l.remove(a); } public static Set keySet(Map map) { return map == null ? new HashSet() : map.keySet(); } public static Set keySet(Object map) { return keys((Map) map); } public static Set keySet(MultiMap mm) { return mm.keySet(); } public static A reverseGet(List l, int idx) { if (l == null || idx < 0) return null; int n = l(l); return idx < n ? l.get(n - 1 - idx) : null; } public static Map cloneMap(Map map) { if (map == null) return new HashMap(); synchronized (map) { return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map); } } public static Collection values(Map map) { return map == null ? emptyList() : map.values(); } public static Collection values(MultiMap mm) { return mm == null ? emptyList() : concatLists(values(mm.data)); } public static boolean hasLock(Lock lock) { return ((ReentrantLock) lock).isHeldByCurrentThread(); } public static String mL_raw(String name) { return mechList_raw(name); } public static boolean eqOrSame(Object a, Object b) { return a == null ? b == null : a == b || b != null && a.equals(b); } public static Iterator iterator(Iterable c) { return c == null ? emptyIterator() : c.iterator(); } public static UnsupportedOperationException unsupportedOperation() { throw new UnsupportedOperationException(); } public static int _hashCode(Object a) { return a == null ? 0 : a.hashCode(); } public static int hashCodeFor(Object a) { return a == null ? 0 : a.hashCode(); } public static long sysNow() { ping(); return System.nanoTime() / 1000000; } 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 ExpiringMap2 mechList_raw_cache = new ExpiringMap2(10000).setMap(ciMap()); public static Lock mechList_raw_lock = lock(); public static int mechList_raw_timeout = 60000; public static String mechList_raw(String name) { try { Lock __128 = mechList_raw_lock; lock(__128); try { if (empty(name)) return ""; String src = mechList_raw_cache.get(name); if (src != null) return src; src = mechList_raw_fresh(name); if (src != null) mechList_raw_cache.put(name, src); return src; } finally { unlock(__128); } } catch (Exception __e) { throw rethrow(__e); } } public static VF2 mechList_raw_listener = new VF2() { public void get(String msg, Object arg) { try { if (eq(msg, "mechChange") && arg instanceof String) { mechList_raw_cache.remove((String) arg); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(msg, 'mechChange) && arg instanceof S) {\r\n //print(\"Got change noti..."; } }; public static void _onLoad_mechList_raw() { add(vm_busListeners_live(), mechList_raw_listener); } public static void cleanMeUp_mechList_raw() { remove(vm_busListeners_live(), mechList_raw_listener); } public static Iterator emptyIterator() { return Collections.emptyIterator(); } public static String mechList_raw_fresh(String name) { return mechList_opt_raw_fresh(name); } 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 String mechList_opt_raw_fresh(String name) { Object readMode = mechMode().readMode; if (readMode instanceof File) { String md5Name = uniqueFileNameUsingMD5_80_v2(upper(name)); return loadTextFileFromZipFile((File) readMode, md5Name); } boolean useLocal = false, useRemote = true; if (eq(readMode, "mergeLocalAndRemote")) useLocal = true; else if (eq(readMode, "local")) { useLocal = true; useRemote = false; } String s = ""; if (useRemote) { if (eq(mechMode().readMode, "localCopies")) s = unnull(loadTextFile(remoteMechListMirrorFile(name))); else s = serverMechList_raw_fresh(name, true); } if (useLocal) s = appendNewLineIfNempty(s) + localMechList_opt_raw_fresh(name); return s; } 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 String loadTextFileFromZipFile(File inZip, String fileName) { try { if (!fileExists(inZip)) return null; try { ZipFile zip = new ZipFile(inZip); try { return loadTextFileFromZipFile(zip, fileName); } finally { _close(zip); } } catch (Throwable e) { throw fail(f2s(inZip), e); } } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFileFromZipFile(ZipFile zip, String fileName) { try { ZipEntry entry = zip.getEntry(fileName); if (entry == null) return null; InputStream fin = zip.getInputStream(entry); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copyStream(fin, baos); return fromUTF8(baos.toByteArray()); } finally { _close(fin); } } catch (Exception __e) { throw rethrow(__e); } } public static boolean serverMechList_raw_fresh_verbose; public static String serverMechList_raw_fresh(String name) { return serverMechList_raw_fresh(name, false); } public static String serverMechList_raw_fresh(String name, boolean opt) { Lock __146 = downloadLock(); lock(__146); try { String text = null; try { text = loadTextFile(remoteMechListMirrorFile(name)); } catch (Throwable __e) { _handleException(__e); } Object[] params = muricaCredentialsPlus("md5", md5OrNull(text), "l", l(text), "opt", opt ? 1 : 0, "withStatus", 1); String url = "http://butter.botcompany.de:8080/mech/raw/list-text/" + urlencode(name); String page = postPageSilently(url, params); Map map = jsonDecodeMap(page); boolean same = eq(map.get("Same"), true); boolean appended = eq(map.get("Appended"), true); saveTextFile(remoteMechListMirrorMetaFile(name), struct(getMultipleKeys(map, "Name", "Status"))); if (!same) { if (appended) text += (String) map.get("Text"); else text = (String) map.get("Text"); saveTextFile(remoteMechListMirrorFile(name), text); File nameFile = remoteMechListMirrorNameFile(name); if (!fileExists(nameFile)) { String actualName = or((String) map.get("Name"), name); saveTextFile(nameFile, actualName); } } if (serverMechList_raw_fresh_verbose) print("Mech list " + name + ": " + (appended ? "appended" : same ? "same" : "downloaded") + ": " + n2(countLines(text), "line")); if (!same) vmBus_send("remoteMechListMirrorChanged", name); return text; } finally { unlock(__146); } } public static String appendNewLineIfNempty(String s) { return empty(s) ? "" : s + "\n"; } public static String localMechList_opt_raw_fresh(String name) { return unnull(loadTextFile(localMechListFile(name))); } public static Object swing(Object f) { return swingAndWait(f); } public static A swing(F0 f) { return (A) swingAndWait(f); } 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 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 String fromUTF8(byte[] bytes) { return fromUtf8(bytes); } public static Lock downloadLock_lock = fairLock(); public static Lock downloadLock() { return downloadLock_lock; } public static Object[] muricaCredentialsPlus(Object... params) { return concatArrays(muricaCredentials(), params); } public static String md5OrNull(String s) { return s == null ? null : md5(s); } public static String postPageSilently(String url, Object... params) { return doPostSilently(litmap(params), url); } public static Map jsonDecodeMap(String s) { Object o = jsonDecode(s); if (o instanceof List && empty((List) o)) return new HashMap(); if (o instanceof Map) return (Map) o; else throw fail("Not a JSON map: " + s); } 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 File remoteMechListMirrorMetaFile(String listName) { return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".meta"); } public static Map getMultipleKeys(Map map, A... keys) { Map map2 = similarEmptyMap(map); if (map != null) for (A key : keys) map2.put(key, map.get(key)); return map2; } public static File remoteMechListMirrorNameFile(String listName) { return javaxDataDir("Remote Mech Lists/" + uniqueFileNameUsingMD5_80_v2(upper(listName)) + ".name"); } public static int countLines(String s) { return l(toLines(s)); } 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 File localMechListFile(String listName) { return newFile(localMechListsDir(), uniqueFileNameUsingMD5_80_v2(listName) + ".text"); } 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 String fromUtf8(byte[] bytes) { try { return bytes == null ? null : new String(bytes, "UTF-8"); } catch (Exception __e) { throw rethrow(__e); } } public static Object[] concatArrays(Object[]... arrays) { int l = 0; for (Object[] a : arrays) l += l(a); Object[] x = new Object[l]; int i = 0; for (Object[] a : arrays) if (a != null) { System.arraycopy(a, 0, x, i, l(a)); i += l(a); } return x; } public static Object[] muricaCredentials() { String pass = muricaPassword(); return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0]; } public static String doPostSilently(Map urlParameters, String url) { return doPostSilently(makePostData(urlParameters), url); } public static String doPostSilently(String urlParameters, String url) { doPost_silently.set(true); return doPost(urlParameters, url); } 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 boolean jsonDecode_useOrderedMaps = true; public static Object jsonDecode(final String text) { final List tok = jsonTok(text); if (l(tok) == 1) return null; class Y { public int i = 1; public Object parse() { String t = tok.get(i); if (t.startsWith("\"")) { String s = unquote(tok.get(i)); i += 2; return s; } if (t.equals("{")) return parseMap(); if (t.equals("[")) return this.parseList(); if (t.equals("null")) { i += 2; return null; } if (t.equals("false")) { i += 2; return false; } if (t.equals("true")) { i += 2; return true; } boolean minus = false; if (t.equals("-")) { minus = true; i += 2; t = get(tok, i); } if (isInteger(t)) { i += 2; if (eq(get(tok, i), ".")) { String x = t + "." + get(tok, i + 2); i += 4; double d = parseDouble(x); if (minus) d = -d; return d; } else { long l = parseLong(t); if (minus) l = -l; return l != (int) l ? new Long(l) : new Integer((int) l); } } throw new RuntimeException("Unknown token " + (i + 1) + ": " + t + ": " + text); } public Object parseList() { consume("["); List list = new ArrayList(); while (!tok.get(i).equals("]")) { list.add(parse()); if (tok.get(i).equals(",")) i += 2; } consume("]"); return list; } public Object parseMap() { consume("{"); Map map = jsonDecode_useOrderedMaps ? new LinkedHashMap() : new TreeMap(); while (!tok.get(i).equals("}")) { String key = unquote(tok.get(i)); i += 2; consume(":"); Object value = parse(); map.put(key, value); if (tok.get(i).equals(",")) i += 2; } consume("}"); return map; } public void consume(String s) { if (!tok.get(i).equals(s)) { String prevToken = i - 2 >= 0 ? tok.get(i - 2) : ""; String nextTokens = join(tok.subList(i, Math.min(i + 4, tok.size()))); throw fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")"); } i += 2; } } return new Y().parse(); } 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 long now_virtualTime; public static long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } 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 Map similarEmptyMap(Map m) { if (m instanceof TreeMap) return new TreeMap(((TreeMap) m).comparator()); if (m instanceof LinkedHashMap) return new LinkedHashMap(); return new HashMap(); } public static File localMechListsDir() { return javaxDataDir("Mech Lists"); } 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 volatile boolean muricaPassword_pretendNotAuthed; public static String muricaPassword() { if (muricaPassword_pretendNotAuthed) return null; return trim(loadTextFile(muricaPasswordFile())); } 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 ThreadLocal doPost_silently = new ThreadLocal(); public static ThreadLocal doPost_timeout = new ThreadLocal(); public static String doPost(Map urlParameters, String url) { return doPost(makePostData(urlParameters), url); } public static String doPost(String urlParameters, String url) { try { URL _url = new URL(url); ping(); return doPost(urlParameters, _url.openConnection(), _url); } catch (Exception __e) { throw rethrow(__e); } } public static String doPost(String urlParameters, URLConnection conn, URL url) { try { boolean silently = isTrue(optParam(doPost_silently)); Long timeout = optParam(doPost_timeout); setHeaders(conn); int l = lUtf8(urlParameters); if (!silently) print("Sending POST request: " + hideCredentials(url) + " (" + l + " bytes)"); if (timeout != null) setURLConnectionTimeouts(conn, timeout); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", str(l)); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); writer.write(urlParameters); writer.flush(); String contents = loadPage_utf8(conn, url, false); writer.close(); return contents; } catch (Exception __e) { throw rethrow(__e); } } public static List jsonTok(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); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isLetter(c)) do ++j; while (j < l && Character.isLetter(s.charAt(j))); else if (Character.isDigit(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 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 Runnable asRunnable(Object o) { return toRunnable(o); } public static void _inheritThreadInfo(Object info) { _threadInheritInfo(info); } public static File muricaPasswordFile() { return new File(javaxSecretDir(), "murica/muricaPasswordFile"); } public static LinkedHashMap litorderedmap(Object... x) { LinkedHashMap map = new LinkedHashMap(); litmap_impl(map, x); return map; } public static A optParam(ThreadLocal tl, A defaultValue) { return optPar(tl, defaultValue); } public static A optParam(ThreadLocal tl) { return optPar(tl); } public static A optParam(Object[] opt, String name, A defaultValue) { int n = l(opt); if (n == 1 && opt[0] instanceof Map) { Map map = (Map) (opt[0]); return map.containsKey(name) ? (A) map.get(name) : defaultValue; } if (!even(l(opt))) throw fail("Odd parameter length"); for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name)) return (A) opt[i + 1]; return defaultValue; } public static Object optParam(Object[] opt, String name) { return optParam(opt, name, null); } public static void setHeaders(URLConnection con) throws IOException { String computerID = getComputerID_quick(); if (computerID != null) try { con.setRequestProperty("X-ComputerID", computerID); con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version")); } catch (Throwable e) { } } public static int lUtf8(String s) { return l(utf8(s)); } public static URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) { con.setConnectTimeout(toInt(timeout)); con.setReadTimeout(toInt(timeout)); if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout) print("Warning: Timeouts not set by JDK."); return con; } 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 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 A optPar(ThreadLocal tl, A defaultValue) { A a = tl.get(); if (a != null) { tl.set(null); return a; } return defaultValue; } public static A optPar(ThreadLocal tl) { return optPar(tl, null); } public static Object optPar(Object[] params, String name) { return optParam(params, name); } public static Object optPar(String name, Object[] params) { return optParam(params, name); } public static A optPar(Object[] params, String name, A defaultValue) { return optParam(params, name, defaultValue); } public static A optPar(String name, Object[] params, A defaultValue) { return optParam(params, name, defaultValue); } public static boolean even(int i) { return (i & 1) == 0; } public static boolean even(long i) { return (i & 1) == 0; } public static String getComputerID_quick() { return computerID(); } public static byte[] utf8(String s) { return toUtf8(s); } public static String _computerID; public static Lock computerID_lock = lock(); public static String computerID() { if (_computerID == null) { Lock __1173 = computerID_lock; lock(__1173); try { if (_computerID != null) return _computerID; File file = computerIDFile(); _computerID = loadTextFile(file.getPath()); if (_computerID == null) { _computerID = loadTextFile(userDir(".tinybrain/computer-id")); if (_computerID == null) _computerID = makeRandomID(12, new SecureRandom()); saveTextFile(file, _computerID); } } finally { unlock(__1173); } } return _computerID; } public static File computerIDFile() { return javaxDataDir("Basic Info/computer-id.txt"); } 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 Random defaultRandomGenerator() { return ThreadLocalRandom.current(); } public static class ExpiringMap2 extends AbstractMap { public Map> byKey = new HashMap(); public PriorityBlockingQueue> queue = new PriorityBlockingQueue(); public long standardExpiryTime; public boolean renewOnOverwrite = true, renewOnGet; public Object onChange; public ExpiringMap2() { } public ExpiringMap2(long standardExpiryTime) { this.standardExpiryTime = standardExpiryTime; } public ExpiringMap2(long standardExpiryTime, Object onChange) { this.onChange = onChange; this.standardExpiryTime = standardExpiryTime; } public synchronized boolean clean() { boolean changes = false; Pair p; while ((p = queue.peek()) != null && sysTime() >= p.a) { p = queue.poll(); Pair v = byKey.get(p.b); if (v != null) { byKey.remove(p.b); changes = true; change(); } } return changes; } public void change() { callF(onChange); } public synchronized B put(A a, B b) { clean(); long timeout = sysTime() + standardExpiryTime; Pair p = byKey.get(a); if (p != null && renewOnOverwrite) queue.remove(new Pair(p.a, a)); byKey.put(a, pair(timeout, b)); change(); if (p == null || renewOnOverwrite) queue.add(new Pair(timeout, a)); return pairB(p); } public synchronized B remove(Object a) { clean(); Pair p = byKey.get(a); if (p == null) return null; queue.remove(new Pair(p.a, a)); byKey.remove(a); change(); return p.b; } public synchronized B get(Object a) { clean(); Pair p = byKey.get(a); if (renewOnGet && p != null) { queue.remove(new Pair(p.a, a)); long timeout = sysTime() + standardExpiryTime; byKey.put((A) a, pair(timeout, p.b)); queue.add(new Pair(timeout, a)); } return pairB(p); } public synchronized Set> entrySet() { clean(); return synchronizedSet(mapValues("pairB", byKey).entrySet()); } public synchronized Set keySet() { clean(); return synchronizedSet(byKey.keySet()); } public synchronized int size() { clean(); return byKey.size(); } public void setStandardExpiryTime(long ms) { standardExpiryTime = ms; } public synchronized ExpiringMap2 setMap(Map innerMap) { byKey = innerMap; return this; } } public abstract static class VF2 { public abstract void get(A a, B b); } public static B pairB(Pair p) { return p == null ? null : p.b; } public static long sysTime() { return sysNow(); } public static void change() { callOpt(getOptMC("mainConcepts"), "allChanged"); } 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, Object func) { return mapValues(func, map); } public static Object getOptMC(String field) { return getOpt(mc(), field); } }