Warning : session_start(): open(/var/lib/php/sessions/sess_ufdjd07ntlr304a39tg7cnmm3q, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;
import javax.swing.border.*;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import javax.swing.undo.UndoManager;
import java.awt.datatransfer.StringSelection;
import java.text.*;
import java.nio.file.Files;
import java.nio.file.Path;
public class main {
public static class SFCat extends DynPrintLog {
public transient BakedBot bot;
public transient String imageID = "#1101382";
public String rulesList = "Computer Rules";
public void start() {
super.start();
ownResource(vmBus_onMessage("remoteMechListMirrorChanged", new VF1() {
public void get(String listName) {
try {
print("Got list change: " + listName);
if (eqic(listName, rulesList))
bot.setRules(mL_raw(rulesList));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "print(\"Got list change: \" + listName);\r\n if (eqic(listName, rulesList))\r...";
}
}));
actuallyLoadCat();
print("Number of rules: " + call(bot.factsBot(), "numRules"));
onSpeechRecognized(new VF1() {
public void get(String s) {
try {
dm_say(bot.answer(s));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_say(bot.answer(s));";
}
});
}
public void setIcon(String imageID) {
this.imageID = imageID;
revisualize();
}
public JComponent centerPart() {
return withMargin(10, jimage(imageID));
}
public void actuallyLoadCat() {
dm_useLocalMechListCopies();
if (bot == null) {
String rules = mL_raw(rulesList);
printIndent("RULES | ", rules);
bot = latestBotWithRulesAndCreator(rules, this);
}
}
}
public static void ownResource(AutoCloseable c) {
_registerAutoCloseable(c);
}
public static AutoCloseable vmBus_onMessage(final String msg, final VF1 onMessage) {
Map map = vm_busListenersByMessage_live();
synchronized (map) {
Set listeners = map.get(msg);
if (listeners == null)
map.put(msg, listeners = syncIdentityHashSet());
return tempAdd(listeners, new VF2() {
public void get(String _msg, Object arg) {
try {
callF(onMessage, arg);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, arg)";
}
});
}
}
public static AutoCloseable vmBus_onMessage(String msg, final VF2 onMessage) {
return vmBus_onMessage(msg, new VF1() {
public void get(Object[] o) {
try {
callF(onMessage, first(o), second(o));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, first(o), second(o));";
}
});
}
public static AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) {
return vmBus_onMessage(msg, runnableToVF1(onMessage));
}
public static volatile StringBuffer local_log = new StringBuffer();
public static volatile Appendable print_log = local_log;
public static volatile int print_log_max = 1024 * 1024;
public static volatile int local_log_max = 100 * 1024;
public static boolean print_silent;
public static Object print_byThread_lock = new Object();
public static volatile ThreadLocal print_byThread;
public static volatile Object print_allThreads;
public static void print() {
print("");
}
public static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
public static A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
public static void print_noNewLine(String s) {
Object f = print_byThread == null ? null : print_byThread.get();
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
print_raw(s);
}
public static void print_raw(String s) {
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
public static 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 String mL_raw(String name) {
return mechList_raw(name);
}
public static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
public static A call(Object o) {
return (A) callF(o);
}
public static A call(Object o, String method, String[] arg) {
return call(o, method, new Object[] { arg });
}
public static A call(Object o, String method, Object... args) {
return (A) call_cached(o, method, args);
}
public static int onSpeechRecognized_interval = 100;
public static TailFile onSpeechRecognized(final Object f) {
return watchQuotedLog_future(speechRecognitionLog(), onSpeechRecognized_interval, new VF1() {
public void get(String s) {
try {
pcallF(f, afterSquareBracketStuff(s));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcallF(f, afterSquareBracketStuff(s));";
}
});
}
public static boolean dm_say(Object text) {
text = trim(strOrNull(text));
if (empty(text))
return true;
vmBus_send("saying", text);
if (isFalse(dm_callModuleOpt(dm_voiceMatrixModule(), "isModuleEnabled", dm_current_mandatory_generic()))) {
print("[quiet] " + text);
return false;
}
print("Saying: " + text);
Object voiceOutput = dm_voiceOutputModule();
dm_callModule(voiceOutput, "say", text);
return voiceOutput != null;
}
public static int withMargin_defaultWidth = 6;
public static JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
public static JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
public static JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
public static JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static JLabel jimage(Image img) {
return jImageLabel(img);
}
public static JLabel jimage(String imageID) {
return jImageLabel(imageID);
}
public static void dm_useLocalMechListCopies() {
dm_useLocallyCopiedMechLists();
}
public static A printIndent(A o) {
print(indentx(str(o)));
return o;
}
public static void printIndent(String indent, Object o) {
print(indentx(indent, str(o)));
}
public static void printIndent(int indent, Object o) {
print(indentx(indent, str(o)));
}
public static BakedBot latestBotWithRulesAndCreator(String rules, Object creator) {
BakedBot bot = bakedBotWithRules(rules);
bot.useIterate(true);
bot.useDiskCache(true);
setCreatorTo(bot.bot, creator);
return bot;
}
public static Set _registerAutoCloseable_set = synchroHashSet();
public static void _registerAutoCloseable(AutoCloseable c) {
addIfNotNull(_registerAutoCloseable_set, c);
}
public static void cleanMeUp__registerAutoCloseable() {
closeAutoCloseables(getAndClearList(_registerAutoCloseable_set));
}
public static Cache> vm_busListenersByMessage_live_cache = new Cache("vm_busListenersByMessage_live_load");
public static Map vm_busListenersByMessage_live() {
return vm_busListenersByMessage_live_cache.get();
}
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 Map> callF_cache = newDangerousWeakHashMap();
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 callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null)
return null;
Class c = f.getClass();
ArrayList methods;
synchronized (callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1)
return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods()) if (m.getName().equals("get")) {
m.setAccessible(true);
l.add(m);
}
if (!l.isEmpty())
break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
public static Object first(Object list) {
return first((Iterable) list);
}
public static A first(List list) {
return empty(list) ? null : list.get(0);
}
public static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
public static A first(IterableIterator i) {
return first((Iterator ) i);
}
public static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
public static A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
public static Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
public static A first(Pair p) {
return p == null ? null : p.a;
}
public static A second(List l) {
return get(l, 1);
}
public static A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
public static B second(Pair p) {
return p == null ? null : p.b;
}
public static A third(List l) {
return _get(l, 2);
}
public static A third(A[] bla) {
return bla == null || bla.length <= 2 ? null : bla[2];
}
public static VF1 runnableToVF1(final Runnable r) {
return r == null ? null : new VF1 () {
public void get(A a) {
try {
r.run();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "r.run()";
}
};
}
public static 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 boolean isFalse(Object o) {
return eq(false, o);
}
public static String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0)
return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i + 1 < l && s.charAt(i + 1) == '\n')
++i;
}
}
return out.toString();
}
public static void print_append(Appendable _buf, String s, int max) {
try {
synchronized (_buf) {
_buf.append(s);
if (!(_buf instanceof StringBuilder))
return;
StringBuilder buf = (StringBuilder) (_buf);
max /= 2;
if (buf.length() > max)
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || b != null && a.equals(b);
}
public static String asString(Object o) {
return o == null ? null : o.toString();
}
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 __305 = mechList_raw_lock;
lock(__305);
try {
if (empty(name))
return "";
String src = mechList_raw_cache.get(name);
if (src != null)
return src;
AutoCloseable __306 = tempSetThreadLocal(loadPage_forcedTimeout_byThread, mechList_raw_timeout);
try {
src = mechList_raw_fresh(name);
if (src != null)
mechList_raw_cache.put(name, src);
return src;
} finally {
_close(__306);
}
} finally {
unlock(__305);
}
} 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 void _handleError(Error e) {
call(javax(), "_handleError", e);
}
public static Object call_cached(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me == null)
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
if ((me.getModifiers() & Modifier.STATIC) == 0)
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not static");
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me == null)
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
return invokeMethod(me, o, args);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static TailFile watchQuotedLog_future(File f, final VF1 onLine) {
return watchQuotedLog_future(f, tailFileDefaultInterval(), onLine);
}
public static TailFile watchQuotedLog_future(File f, int interval, final VF1 onLine) {
return tailFileFromCurrent(f, interval, vfAppendToLineBuffer(unquotingLineBuffer(onLine)));
}
public static File speechRecognitionLog() {
return new File(javaxDataDir(), "Speech Recognition/recognized.txt");
}
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 afterSquareBracketStuff(String s) {
return trimSubstring(s, indexOf(s, ']') + 1);
}
public static String trim(String s) {
return s == null ? null : s.trim();
}
public static String trim(StringBuilder buf) {
return buf.toString().trim();
}
public static String trim(StringBuffer buf) {
return buf.toString().trim();
}
public static String strOrNull(Object o) {
return o == null ? null : str(o);
}
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 void vmBus_send(String msg, Object... args) {
Object arg = empty(args) ? null : l(args) == 1 ? args[0] : 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 A dm_callModuleOpt(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __17 = dm_enter(mod);
try {
return (A) callOpt(mod, method, args);
} finally {
_close(__17);
}
}
public static Object dm_voiceMatrixModule() {
return dm_moduleWithClassNameEndingIn("VoiceMatrix");
}
public static InheritableThreadLocal dm_currentModule_generic = new InheritableThreadLocal();
public static Object dm_current_mandatory_generic() {
return assertNotNull("No module set", getWeakRef(dm_currentModule_generic.get()));
}
public static Object dm_voiceOutputModule() {
{
Object __25 = vmBus_query("voiceOutputModule");
if (__25 != null)
return __25;
}
return dm_requireModule("#1016614/VoiceOutput");
}
public static A dm_callModule(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __21 = dm_enter(mod);
try {
return call(mod, method, args);
} finally {
_close(__21);
}
}
public static Object swing(Object f) {
return swingAndWait(f);
}
public static A swing(F0 f) {
return (A) swingAndWait(f);
}
public static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
public static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
public static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
public static Object get(Object o, String field) {
try {
if (o == null)
return null;
if (o instanceof Class)
return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
f.setAccessible(true);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
public static Object get_raw(Object o, String field) {
try {
Field f = get_findField(o.getClass(), field);
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
public static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
public static JLabel jImageLabel(Image img) {
return swingNu(JLabel.class, imageIcon(img));
}
public static JLabel jImageLabel(Icon icon) {
return swingNu(JLabel.class, icon);
}
public static JLabel jImageLabel(String imageID) {
return jImageLabel(imageIcon(imageID));
}
public static JLabel jImageLabel(String text, String imageID) {
final JLabel l = swingNu(JLabel.class, text, imageIcon(imageID), JLabel.CENTER);
{
swing(new Runnable() {
public void run() {
try {
l.setVerticalTextPosition(SwingConstants.BOTTOM);
l.setHorizontalTextPosition(SwingConstants.CENTER);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "l.setVerticalTextPosition(SwingConstants.BOTTOM);\r\n l.setHorizontalTextPos...";
}
});
}
return l;
}
public static void dm_useLocallyCopiedMechLists() {
dm_requireModule("#1016073/MechLists");
useLocalMechListCopies(true);
setOptMC("serverMechList_raw_fresh_verbose", true);
setOptMC("mechList_goToCreator_dont", true);
}
public static String indentx(String s) {
return indentx(indent_default, s);
}
public static String indentx(int n, String s) {
return dropSuffix(repeat(' ', n), indent(n, s));
}
public static String indentx(String indent, String s) {
return dropSuffix(indent, indent(indent, s));
}
public static String str(Object o) {
return o == null ? "null" : o.toString();
}
public static String str(char[] c) {
return new String(c);
}
public static BakedBot bakedBotWithRules(String rules) {
BakedBot bot = new BakedBot();
bot.lists.setText("NL Logic Examples", rules);
return bot;
}
public static void setCreatorTo(Object o, Object creator) {
setOpt(o, "creator_class", newWeakReference(creator));
}
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 Set synchroHashSet() {
return Collections.synchronizedSet(new HashSet ());
}
public static void addIfNotNull(Collection l, A a) {
if (a != null && l != null)
l.add(a);
}
public static void closeAutoCloseables(Collection l) {
if (l != null)
for (AutoCloseable c : l) {
try {
c.close();
} catch (Throwable __e) {
_handleException(__e);
}
}
}
public static List getAndClearList(Collection l) {
if (l == null)
return emptyList();
synchronized (collectionMutex(l)) {
List out = cloneList(l);
l.clear();
return out;
}
}
public static Map vm_generalHashMap(Object name) {
synchronized (get(javax(), "generalMap")) {
Map m = (Map) (vm_generalMap_get(name));
if (m == null)
vm_generalMap_put(name, m = syncHashMap());
return m;
}
}
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 Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
public static Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
public static HashMap> callMC_cache = new HashMap();
public static String callMC_key;
public static Method callMC_value;
public static Object callMC(String method, String[] arg) {
return callMC(method, new Object[] { arg });
}
public static Object callMC(String method, Object... args) {
try {
Method me;
if (callMC_cache == null)
callMC_cache = new HashMap();
synchronized (callMC_cache) {
me = method == callMC_key ? callMC_value : null;
}
if (me != null)
try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
List m;
synchronized (callMC_cache) {
m = callMC_cache.get(method);
}
if (m == null) {
if (callMC_cache.isEmpty()) {
callMC_makeCache();
m = callMC_cache.get(method);
}
if (m == null)
throw fail("Method named " + method + " not found in main");
}
int n = m.size();
if (n == 1) {
me = m.get(0);
synchronized (callMC_cache) {
callMC_key = method;
callMC_value = me;
}
try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
}
for (int i = 0; i < n; i++) {
me = m.get(i);
if (call_checkArgs(me, args, false))
return invokeMethod(me, null, args);
}
throw fail("No method called " + method + " with matching arguments found in main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void callMC_makeCache() {
synchronized (callMC_cache) {
callMC_cache.clear();
Class _c = (Class) mc(), c = _c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
m.setAccessible(true);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
public static int l(Object[] a) {
return a == null ? 0 : a.length;
}
public static int l(boolean[] a) {
return a == null ? 0 : a.length;
}
public static int l(byte[] a) {
return a == null ? 0 : a.length;
}
public static int l(short[] a) {
return a == null ? 0 : a.length;
}
public static int l(long[] a) {
return a == null ? 0 : a.length;
}
public static int l(int[] a) {
return a == null ? 0 : a.length;
}
public static int l(float[] a) {
return a == null ? 0 : a.length;
}
public static int l(double[] a) {
return a == null ? 0 : a.length;
}
public static int l(char[] a) {
return a == null ? 0 : a.length;
}
public static int l(Collection c) {
return c == null ? 0 : c.size();
}
public static int l(Map m) {
return m == null ? 0 : m.size();
}
public static int l(CharSequence s) {
return s == null ? 0 : s.length();
}
public static long l(File f) {
return f == null ? 0 : f.length();
}
public static int l(Object o) {
return o == null ? 0 : o instanceof String ? l((String) o) : o instanceof Map ? l((Map) o) : o instanceof Collection ? l((Collection) o) : o instanceof Object[] ? l((Object[]) o) : o instanceof boolean[] ? l((boolean[]) o) : o instanceof byte[] ? l((byte[]) o) : o instanceof char[] ? l((char[]) o) : o instanceof short[] ? l((short[]) o) : o instanceof int[] ? l((int[]) o) : o instanceof float[] ? l((float[]) o) : o instanceof double[] ? l((double[]) o) : o instanceof long[] ? l((long[]) o) : (Integer) call(o, "size");
}
public static RuntimeException fail() {
throw new RuntimeException("fail");
}
public static RuntimeException fail(Throwable e) {
throw asRuntimeException(e);
}
public static RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
public static RuntimeException fail(String msg) {
throw new RuntimeException(msg == null ? "" : msg);
}
public static RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
public static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
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 call_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 A _get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
public static Object _get(Object o, String field) {
return get(o, field);
}
public static A _get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
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 int indexOf(List l, A a, int startIndex) {
if (l == null)
return -1;
for (int i = startIndex; i < l(l); i++) if (eq(l.get(i), a))
return i;
return -1;
}
public static int indexOf(List l, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
public static int indexOf(List l, A a) {
if (l == null)
return -1;
return l.indexOf(a);
}
public static int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
public static int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
public static int indexOf(String a, char b) {
return a == null ? -1 : a.indexOf(b);
}
public static int indexOf(String a, int i, char b) {
return indexOf(a, b, i);
}
public static int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
public static int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
public static int indexOf(A[] x, A a) {
if (x == null)
return -1;
for (int i = 0; i < l(x); i++) if (eq(x[i], a))
return i;
return -1;
}
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 AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null)
return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
public static String mechList_raw_fresh(String name) {
return mechList_opt_raw_fresh(name);
}
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 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 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 Cache vm_busListeners_live_cache = new Cache("vm_busListeners_live_load");
public static Set vm_busListeners_live() {
return vm_busListeners_live_cache.get();
}
public static Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
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 Class javax() {
return getJavaX();
}
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 int tailFileDefaultInterval_value = 100;
public static int tailFileDefaultInterval() {
return tailFileDefaultInterval_value;
}
public static TailFile tailFileFromCurrent(File file, int interval, Object onData) {
TailFile tf = new TailFile(file, interval, onData);
tf.l = l(file);
tf.start();
return tf;
}
public static VF1 vfAppendToLineBuffer(final LineBuffer buf) {
return new VF1() {
public void get(String s) {
try {
buf.append(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "buf.append(s)";
}
};
}
public static LineBuffer unquotingLineBuffer(final Object onLine) {
return new LineBuffer(new VF1() {
public void get(String line) {
try {
if (isQuoted(line))
pcallF(onLine, unquote(line));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (isQuoted(line))\r\n pcallF(onLine, unquote(line));";
}
});
}
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 Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
public static String trimSubstring(String s, int x) {
return trim(substring(s, x));
}
public static String trimSubstring(String s, int x, int y) {
return trim(substring(s, x, y));
}
public static String getType(Object o) {
return getClassName(o);
}
public static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
public static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
public static void 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 Object dm_getModule(Object moduleOrID) {
if (eq(moduleOrID, ""))
return null;
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
public static AutoCloseable dm_enter(Object mod) {
return (AutoCloseable) callOpt(dm_getModule(mod), "enter");
}
public static Object callOpt(Object o) {
return callF(o);
}
public static A callOpt(Object o, String method, Object... args) {
return (A) callOpt_cached(o, method, args);
}
public static Object dm_moduleWithClassNameEndingIn(final String suffix) {
for (Object m : dm_listModules()) if (endsWith(className(m), suffix))
return m;
return null;
}
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 A getWeakRef(WeakReference ref) {
return ref == null ? null : ref.get();
}
public static Object vmBus_query(String msg, Object... args) {
Object arg = empty(args) ? null : l(args) == 1 ? args[0] : args;
{
Object __50 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg);
if (__50 != null)
return __50;
}
return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg);
}
public static Object vmBus_query(String msg) {
return vmBus_query(msg, (Object) null);
}
public static String dm_requireModule(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
public static 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 Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
public static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
public static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
public static int imageIcon_cacheSize = 10;
public static boolean imageIcon_verbose;
public static Map imageIcon_cache;
public static Lock imageIcon_lock = lock();
public static ThreadLocal imageIcon_fixGIF = new ThreadLocal();
public static ImageIcon imageIcon(String imageID) {
try {
if (imageID == null)
return null;
Lock __119 = imageIcon_lock;
lock(__119);
try {
if (imageIcon_cache == null)
imageIcon_cache = new MRUCache(imageIcon_cacheSize);
imageID = fsI(imageID);
ImageIcon ii = imageIcon_cache.get(imageID);
if (ii == null) {
if (imageIcon_verbose)
print("Loading image icon: " + imageID);
File f = loadBinarySnippet(imageID);
Boolean b = imageIcon_fixGIF.get();
if (!isFalse(b))
ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
else
ii = new ImageIcon(f.toURI().toURL());
} else
imageIcon_cache.remove(imageID);
imageIcon_cache.put(imageID, ii);
return ii;
} finally {
unlock(__119);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ImageIcon imageIcon(Image img) {
return new ImageIcon(img);
}
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 String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
public static String repeat(char c, int n) {
n = Math.max(n, 0);
char[] chars = new char[n];
for (int i = 0; i < n; i++) chars[i] = c;
return new String(chars);
}
public static List repeat(A a, int n) {
n = Math.max(n, 0);
List l = new ArrayList(n);
for (int i = 0; i < n; i++) l.add(a);
return l;
}
public static List repeat(int n, A a) {
return repeat(a, n);
}
public static int indent_default = 2;
public static String indent(int indent) {
return repeat(' ', indent);
}
public static String indent(int indent, String s) {
return indent(repeat(' ', indent), s);
}
public static String indent(String indent, String s) {
return indent + s.replace("\n", "\n" + indent);
}
public static String indent(String s) {
return indent(indent_default, s);
}
public static List indent(String indent, List lines) {
List l = new ArrayList();
for (String s : lines) l.add(indent + s);
return l;
}
public static Field setOpt_findField(Class c, String field) {
HashMap map;
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map.get(field);
}
public static void setOpt(Object o, String field, Object value) {
try {
if (o == null)
return;
Class c = o.getClass();
HashMap map;
if (getOpt_cache == null)
map = getOpt_makeCache(c);
else
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
setOpt_raw(o, field, value);
return;
}
Field f = map.get(field);
if (f != null)
smartSet(f, o, value);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void setOpt(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Field setOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
f.setAccessible(true);
return f;
}
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
public static WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
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();
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 volatile PersistableThrowable _handleException_lastException;
public static List _handleException_onException = synchroList(ll("printStackTrace2"));
public static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3);
}
}
public static ArrayList emptyList() {
return new ArrayList();
}
public static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
public static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
public static ArrayList emptyList(Class c) {
return new ArrayList();
}
public static Object collectionMutex(Object o) {
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
public static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
public static ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
public static A vm_generalMap_get(Object key) {
return (A) vm_generalMap().get(key);
}
public static Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
public static Map syncHashMap() {
return synchroHashMap();
}
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 Map synchroMap() {
return synchroHashMap();
}
public static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
public static Class mc() {
return main.class;
}
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 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 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 Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
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 boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null)
return false;
if (o instanceof ThreadLocal)
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
public static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
public static Thread currentThread() {
return Thread.currentThread();
}
public static TreeMap caseInsensitiveMap() {
return new TreeMap(caseInsensitiveComparator());
}
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 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 A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
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);
} else if (readMode instanceof VirtualMechLists)
return ((VirtualMechLists) readMode).mL_raw(name);
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 Set vm_generalIdentityHashSet(Object name) {
synchronized (get(javax(), "generalMap")) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = syncIdentityHashSet());
return set;
}
}
public static Class __javax;
public static Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(Iterable strings) {
return join("", strings);
}
public static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
public static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
public static List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
public static boolean isQuoted(String s) {
if (isNormalQuoted(s))
return true;
return isMultilineQuoted(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 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 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 Object callFunction(Object f, Object... args) {
return callF(f, args);
}
public static String substring(String s, int x) {
return substring(s, x, l(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 boolean isStringOrIntOrLong(Object o) {
return o instanceof String || o instanceof Integer || o instanceof Long;
}
public static A dm_callOS(String functionName, Object... args) {
return (A) call(dm_os(), functionName, args);
}
public static Object dm_resolveModule(Object moduleOrStem) {
return dm_callOS("resolveModule", moduleOrStem);
}
public static List dm_listModules() {
return callCreator("listModules");
}
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 String className(Object o) {
return getClassName(o);
}
public static void assertTrue(Object o) {
if (!(eq(o, true)))
throw fail(str(o));
}
public static boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
public static boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
public static Object pcallFAll_returnFirstNotNull(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
Object __56 = pcallF(f, args);
if (__56 != null)
return __56;
}
return null;
}
public static Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) {
while (it.hasNext()) {
Object __57 = pcallF(it.next(), args);
if (__57 != null)
return __57;
}
return null;
}
public static String dm_makeModule(String moduleLibID) {
return (String) callCreator("makeModule", moduleLibID);
}
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 A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () {
public A get() {
try {
return nuObject(c, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret nuObject(c, args);";
}
});
}
public static String fsI(String id) {
return formatSnippetID(id);
}
public static String fsI(long id) {
return formatSnippetID(id);
}
public static File loadBinarySnippet(String snippetID) {
try {
long id = parseSnippetID(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile(snippetID);
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean loadBufferedImageFixingGIFs_debug;
public static ThreadLocal> loadBufferedImageFixingGIFs_output = new ThreadLocal();
public static Image loadBufferedImageFixingGIFs(File file) {
try {
if (!file.exists())
return null;
if (!isGIF(file))
return ImageIO.read(file);
if (loadBufferedImageFixingGIFs_debug)
print("loadBufferedImageFixingGIFs" + ": checking gif");
ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
reader.setInput(ImageIO.createImageInputStream(file));
int numImages = reader.getNumImages(true);
IIOMetadata imageMetaData = reader.getImageMetadata(0);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
boolean foundBug = false;
for (int i = 0; i < numImages && !foundBug; i++) {
IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
if (Integer.parseInt(delay) == 0) {
foundBug = true;
}
break;
}
}
}
if (loadBufferedImageFixingGIFs_debug)
print("loadBufferedImageFixingGIFs" + ": " + f2s(file) + " foundBug=" + foundBug);
Image image;
if (!foundBug) {
image = Toolkit.getDefaultToolkit().createImage(f2s(file));
} else {
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
{
ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
try {
ImageWriter writer = ImageIO.getImageWriter(reader);
writer.setOutput(ios);
writer.prepareWriteSequence(null);
for (int i = 0; i < numImages; i++) {
BufferedImage frameIn = reader.read(i);
IIOMetadataNode root = (IIOMetadataNode) reader.getImageMetadata(i).getAsTree(metaFormatName);
int nNodes = root.getLength();
for (int j = 0; j < nNodes; j++) {
org.w3c.dom.Node node = root.item(j);
if (node.getNodeName().equalsIgnoreCase("GraphicControlExtension")) {
String delay = ((IIOMetadataNode) node).getAttribute("delayTime");
if (Integer.parseInt(delay) == 0) {
((IIOMetadataNode) node).setAttribute("delayTime", "10");
}
break;
}
}
IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frameIn), null);
metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
IIOImage frameOut = new IIOImage(frameIn, null, metadata);
writer.writeToSequence(frameOut, writer.getDefaultWriteParam());
}
writer.endWriteSequence();
} finally {
_close(ios);
}
}
byte[] data = baoStream.toByteArray();
setVar(loadBufferedImageFixingGIFs_output.get(), data);
if (loadBufferedImageFixingGIFs_debug)
print("Data size: " + l(data));
image = Toolkit.getDefaultToolkit().createImage(data);
}
return image;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static MechMode mechMode_value = new MechMode();
public static MechMode mechMode() {
return mechMode_value;
}
public static void setOpt_raw(Object o, String field, Object value) {
try {
if (o == null)
return;
if (o instanceof Class)
setOpt_raw((Class) o, field, value);
else {
Field f = setOpt_raw_findField(o.getClass(), field);
if (f != null) {
f.setAccessible(true);
smartSet(f, o, value);
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void setOpt_raw(Class c, String field, Object value) {
try {
if (c == null)
return;
Field f = setOpt_raw_findStaticField(c, field);
if (f != null) {
f.setAccessible(true);
smartSet(f, null, value);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Field setOpt_raw_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
public static Field setOpt_raw_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
public static void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
if (type == int.class && value instanceof Long)
value = ((Long) value).intValue();
if (type == LinkedHashMap.class && value instanceof Map) {
f.set(o, asLinkedHashMap((Map) value));
return;
}
try {
if (f.getType() == Concept.Ref.class) {
f.set(o, ((Concept) o).new Ref((Concept) value));
return;
}
if (o instanceof Concept.Ref) {
f.set(o, ((Concept.Ref) o).get());
return;
}
} catch (Throwable _e) {
}
throw e;
}
}
public static 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 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 A getOpt(Object o, String field) {
return (A) getOpt_cached(o, field);
}
public static Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null)
return null;
f.setAccessible(true);
return f.get(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A getOpt(Class c, String field) {
try {
if (c == null)
return null;
Field f = getOpt_findStaticField(c, field);
if (f == null)
return null;
f.setAccessible(true);
return (A) f.get(null);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
public static boolean isSubtypeOf(Class a, Class b) {
return b.isAssignableFrom(a);
}
public static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
public static List synchroList(List l) {
return Collections.synchronizedList(l);
}
public static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
public static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
public static Throwable innerException(Throwable e) {
return getInnerException(e);
}
public static int max(int a, int b) {
return Math.max(a, b);
}
public static int max(int a, int b, int c) {
return max(max(a, b), c);
}
public static long max(int a, long b) {
return Math.max((long) a, b);
}
public static long max(long a, long b) {
return Math.max(a, b);
}
public static double max(int a, double b) {
return Math.max((double) a, b);
}
public static float max(float a, float b) {
return Math.max(a, b);
}
public static double max(double a, double b) {
return Math.max(a, b);
}
public static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
public static double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
public static float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
public static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
public static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
public static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
public static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
public static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
public static ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
public static ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
public static ArrayList asList(Iterable s) {
if (s instanceof ArrayList)
return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s) l.add(a);
return l;
}
public static ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null)
while ((a = p.next()) != null) l.add(a);
return l;
}
public static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
public static Map vm_generalMap_map;
public static Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
public static B mapPutOrRemove(Map map, A key, B value) {
if (map != null && key != null)
if (value != null)
return map.put(key, value);
else
return map.remove(key);
return null;
}
public static Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
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 List _registerWeakMap_preList;
public static A _registerWeakMap(A map) {
if (javax() == null) {
if (_registerWeakMap_preList == null)
_registerWeakMap_preList = synchroList();
_registerWeakMap_preList.add(map);
return map;
}
try {
call(javax(), "_registerWeakMap", map);
} catch (Throwable e) {
printException(e);
print("Upgrade JavaX!!");
}
return map;
}
public static void _onLoad_registerWeakMap() {
assertNotNull(javax());
if (_registerWeakMap_preList == null)
return;
for (Object o : _registerWeakMap_preList) _registerWeakMap(o);
_registerWeakMap_preList = null;
}
public static int isAndroid_flag;
public static boolean isAndroid() {
if (isAndroid_flag == 0)
isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1;
return isAndroid_flag > 0;
}
public static Boolean isHeadless_cache;
public static boolean isHeadless() {
if (isHeadless_cache != null)
return isHeadless_cache;
if (isAndroid())
return isHeadless_cache = true;
if (GraphicsEnvironment.isHeadless())
return isHeadless_cache = true;
try {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) {
return isHeadless_cache = true;
}
}
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 Comparator caseInsensitiveComparator() {
return betterCIComparator();
}
public static String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
public static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
public static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
public static String 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 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 String unnull(String s) {
return s == null ? "" : s;
}
public static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
public static List unnull(List l) {
return l == null ? emptyList() : l;
}
public static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
public static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
public static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
public static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
public static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
public static 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 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 __374 = downloadLock();
lock(__374);
try {
if (serverMechList_raw_fresh_verbose)
print("serverMechList_raw_fresh " + name);
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);
if (serverMechList_raw_fresh_verbose)
print("Mech list " + name + ": " + (appended ? "appended" : same ? "same" : "downloaded"));
saveTextFile(remoteMechListMirrorMetaFile(name), struct(getMultipleKeys(map, "Name", "Status")));
if (same)
return text;
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);
}
vmBus_send("remoteMechListMirrorChanged", name);
return text;
} finally {
unlock(__374);
}
}
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 boolean isNormalQuoted(String s) {
int l = l(s);
if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"'))
return false;
int j = 1;
while (j < l) if (s.charAt(j) == '"')
return j == l - 1;
else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
return false;
}
public static boolean isMultilineQuoted(String s) {
if (!startsWith(s, "["))
return false;
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
return i < s.length() && s.charAt(i) == '[';
}
public static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
public static boolean startsWith(String a, char c) {
return nempty(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, l(b)) };
return true;
}
public static boolean startsWith(List a, List b) {
if (a == null || l(b) > l(a))
return false;
for (int i = 0; i < l(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
public static File userDir() {
return new File(userHome());
}
public static File userDir(String path) {
return new File(userHome(), path);
}
public static Object dm_os() {
return creator();
}
public static A callCreator(String functionName, Object... args) {
return (A) call(creator(), functionName, args);
}
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 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 List> _threadInfo_makers = synchroList();
public static Object _threadInfo() {
if (empty(_threadInfo_makers))
return null;
HashMap map = new HashMap();
pcallFAll(_threadInfo_makers, map);
return map;
}
public static Runnable asRunnable(Object o) {
return toRunnable(o);
}
public static void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
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 String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
public static String formatSnippetID(long id) {
return "#" + id;
}
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 File DiskSnippetCache_file(long snippetID) {
return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException {
File file = DiskSnippetCache_file(snippetID);
return file.exists() ? file : null;
}
public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException {
saveBinaryFile(DiskSnippetCache_file(snippetID), data);
}
public static byte[] loadDataSnippetImpl(String snippetID) throws IOException {
byte[] data;
try {
URL url = new URL(dataSnippetLink(snippetID));
print("Loading library: " + hideCredentials(url));
try {
data = loadBinaryPage(url.openConnection());
} catch (RuntimeException e) {
data = null;
}
if (data == null || data.length == 0) {
url = new URL("http://data.tinybrain.de/blobs/" + parseSnippetID(snippetID));
print("Loading library: " + hideCredentials(url));
data = loadBinaryPage(url.openConnection());
}
print("Bytes loaded: " + data.length);
} catch (FileNotFoundException e) {
throw new IOException("Binary snippet #" + snippetID + " not found or not public");
}
return data;
}
public static long fileSize(String path) {
return getFileSize(path);
}
public static long fileSize(File f) {
return getFileSize(f);
}
public static File loadDataSnippetToFile(String snippetID) {
try {
snippetID = fsI(snippetID);
File f = DiskSnippetCache_file(parseSnippetID(snippetID));
List urlsTried = new ArrayList();
List errors = new ArrayList();
try {
URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID)));
print("Loading library: " + hideCredentials(url));
try {
loadBinaryPageToFile(openConnection(url), f);
if (fileSize(f) == 0)
throw fail();
} catch (Throwable e) {
errors.add(e);
url = addAndReturn(urlsTried, new URL("http://data.tinybrain.de/blobs/" + psI(snippetID)));
print("Trying other server: " + hideCredentials(url));
loadBinaryPageToFile(openConnection(url), f);
print("Got bytes: " + fileSize(f));
}
if (fileSize(f) == 0)
throw fail();
System.err.println("Bytes loaded: " + fileSize(f));
} catch (Throwable e) {
printStackTrace(e);
errors.add(e);
throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors));
}
return f;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static byte[] isGIF_magic = bytesFromHex("47494638");
public static boolean isGIF(byte[] data) {
return byteArrayStartsWith(data, isGIF_magic);
}
public static boolean isGIF(File f) {
return isGIF(loadBeginningOfBinaryFile(f, l(isGIF_magic)));
}
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 setVar(IVar v, A value) {
if (v != null)
v.set(value);
}
public static LinkedHashMap asLinkedHashMap(Map map) {
if (map instanceof LinkedHashMap)
return (LinkedHashMap) map;
LinkedHashMap m = new LinkedHashMap();
if (map != null)
synchronized (collectionMutex(map)) {
m.putAll(map);
}
return m;
}
public static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
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 void printException(Throwable e) {
printStackTrace(e);
}
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 volatile PersistableThrowable lastException_lastException;
public static PersistableThrowable lastException() {
return lastException_lastException;
}
public static void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
public static String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
public static String hideCredentials(String url) {
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
public static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
public static 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_4 = 0; _repeat_4 < n; _repeat_4++) {
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 boolean fileExists(String path) {
return path != null && new File(path).exists();
}
public static boolean fileExists(File f) {
return f != null && f.exists();
}
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 Map emptyMap() {
return new HashMap();
}
public static ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal();
public static void checkFileNotTooBigToRead(File f) {
callF(checkFileNotTooBigToRead_tl.get(), f);
}
public static File remoteMechListMirrorsDir() {
return javaxDataDir("Remote Mech Lists");
}
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 urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
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 String struct(Object o) {
return structure(o);
}
public static String struct(Object o, structure_Data data) {
return structure(o, data);
}
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 A or(A a, A b) {
return a != null ? a : b;
}
public static File localMechListFile(String listName) {
return newFile(localMechListsDir(), uniqueFileNameUsingMD5_80_v2(listName) + ".text");
}
public static boolean neq(Object a, Object b) {
return !eq(a, b);
}
public static WeakReference creator_class;
public static Object creator() {
return creator_class == null ? null : creator_class.get();
}
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;
startIndex = Math.max(0, startIndex);
endIndex = Math.min(l(l), endIndex);
if (startIndex >= endIndex)
return ll();
return l.subList(startIndex, endIndex);
}
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 List> _threadInheritInfo_retrievers = synchroList();
public static void _threadInheritInfo(Object info) {
if (info == null)
return;
pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
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 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 File getGlobalCache() {
File file = new File(javaxCachesDir(), "Binary Snippets");
file.mkdirs();
return file;
}
public static byte[] saveBinaryFile(String fileName, byte[] contents) {
try {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
FileOutputStream fileOutputStream = newFileOutputStream(tempFileName);
fileOutputStream.write(contents);
fileOutputStream.close();
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
vmBus_send("wroteFile", file);
return contents;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static byte[] saveBinaryFile(File fileName, byte[] contents) {
return saveBinaryFile(fileName.getPath(), contents);
}
public static String dataSnippetLink(String snippetID) {
long id = parseSnippetID(snippetID);
if (id >= 1100000 && id < 1200000)
return imageServerURL() + id;
if (id >= 1400000 && id < 1500000)
return "http://butter.botcompany.de:8080/files/" + id + "?_pass=" + muricaPassword();
if (id >= 1200000 && id < 1300000) {
String pw = muricaPassword();
if (empty(pw))
throw fail("Please set 'murica password by running #1008829");
return "http://butter.botcompany.de:8080/1008823/raw/" + id + "?_pass=" + pw;
} else
return "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id + "&contentType=application/binary";
}
public static ThreadLocal>> loadBinaryPage_responseHeaders = new ThreadLocal();
public static ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal();
public static byte[] loadBinaryPage(String url) {
try {
print("Loading " + url);
return loadBinaryPage(loadPage_openConnection(new URL(url)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static byte[] loadBinaryPage(URLConnection con) {
try {
Map extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders);
setHeaders(con);
for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
return loadBinaryPage_noHeaders(con);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static byte[] loadBinaryPage_noHeaders(URLConnection con) {
try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
InputStream inputStream = con.getInputStream();
loadBinaryPage_responseHeaders.set(con.getHeaderFields());
long len = 0;
try {
len = con.getContentLength();
} catch (Throwable e) {
printStackTrace(e);
}
int n = 0;
while (true) {
int ch = inputStream.read();
if (ch < 0)
break;
buf.write(ch);
if (++n % 100000 == 0)
println(" " + n + (len != 0 ? "/" + len : "") + " bytes loaded.");
}
inputStream.close();
return buf.toByteArray();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A addAndReturn(Collection c, A a) {
if (c != null)
c.add(a);
return a;
}
public static void loadBinaryPageToFile(String url, File file) {
try {
print("Loading " + url);
loadBinaryPageToFile(openConnection(new URL(url)), file);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void loadBinaryPageToFile(URLConnection con, File file) {
try {
setHeaders(con);
loadBinaryPageToFile_noHeaders(con, file);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void loadBinaryPageToFile_noHeaders(URLConnection con, File file) {
try {
File ftemp = new File(f2s(file) + "_temp");
FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp));
try {
InputStream inputStream = con.getInputStream();
long len = 0;
try {
len = con.getContentLength();
} catch (Throwable e) {
printStackTrace(e);
}
String pat = " {*}" + (len != 0 ? "/" + len : "") + " bytes loaded.";
copyStreamWithPrints(inputStream, buf, pat);
inputStream.close();
buf.close();
file.delete();
renameFile_assertTrue(ftemp, file);
} finally {
if (buf != null)
buf.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static URLConnection openConnection(URL url) {
try {
ping();
callOpt(javax(), "recordOpenURLConnection", str(url));
return url.openConnection();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static long psI(String snippetID) {
return parseSnippetID(snippetID);
}
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 byte[] bytesFromHex(String s) {
return hexToBytes(s);
}
public static boolean byteArrayStartsWith(byte[] a, byte[] b) {
if (a == null || b == null)
return false;
if (a.length < b.length)
return false;
for (int i = 0; i < b.length; i++) if (a[i] != b[i])
return false;
return true;
}
public static byte[] loadBeginningOfBinaryFile(File file, int maxBytes) {
return loadBinaryFilePart(file, 0, maxBytes);
}
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 Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
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;
startIndex = max(0, startIndex);
endIndex = min(l(l), endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == l(l))
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 fromUtf8(byte[] bytes) {
try {
return 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 boolean structure_showTiming, structure_checkTokenCount;
public static String structure(Object o) {
return structure(o, new structure_Data());
}
public static String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
public static void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack)) popLast(d.stack).run();
}
public static void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
public static boolean structure_allowShortening = false;
public static class structure_Data {
public PrintWriter out;
public int stringSizeLimit;
public int shareStringsLongerThan = 20;
public boolean noStringSharing;
public IdentityHashMap seen = new IdentityHashMap();
public HashMap strings = new HashMap();
public HashSet concepts = new HashSet();
public HashMap> fieldsByClass = new HashMap();
public HashMap persistenceInfo = new HashMap();
public int n;
public List stack = new ArrayList();
public structure_Data append(String token) {
out.print(token);
++n;
return this;
}
public structure_Data append(int i) {
out.print(i);
++n;
return this;
}
public structure_Data append(String token, int tokCount) {
out.print(token);
n += tokCount;
return this;
}
public structure_Data app(String token) {
out.print(token);
return this;
}
public structure_Data app(int i) {
out.print(i);
return this;
}
}
public static void structure_1(final Object o, final structure_Data d) {
try {
if (o == null) {
d.append("null");
return;
}
Class c = o.getClass();
boolean concept = false;
concept = o instanceof Concept;
List lFields = d.fieldsByClass.get(c);
if (lFields == null) {
if (o instanceof Number) {
PrintWriter out = d.out;
if (o instanceof Integer) {
int i = ((Integer) o).intValue();
out.print(i);
d.n += i < 0 ? 2 : 1;
return;
}
if (o instanceof Long) {
long l = ((Long) o).longValue();
out.print(l);
out.print("L");
d.n += l < 0 ? 2 : 1;
return;
}
if (o instanceof Short) {
short s = ((Short) o).shortValue();
d.append("sh ", 2);
out.print(s);
d.n += s < 0 ? 2 : 1;
return;
}
if (o instanceof Float) {
d.append("fl ", 2);
quoteToPrintWriter(str(o), out);
return;
}
if (o instanceof Double) {
d.append("d(", 3);
quoteToPrintWriter(str(o), out);
d.append(")");
return;
}
if (o instanceof BigInteger) {
out.print("bigint(");
out.print(o);
out.print(")");
d.n += ((BigInteger) o).signum() < 0 ? 5 : 4;
return;
}
}
if (o instanceof Boolean) {
d.append(((Boolean) o).booleanValue() ? "t" : "f");
return;
}
if (o instanceof Character) {
d.append(quoteCharacter((Character) o));
return;
}
if (o instanceof File) {
d.append("File ").append(quote(((File) o).getPath()));
return;
}
Integer ref = d.seen.get(o);
if (o instanceof String && ref == null)
ref = d.strings.get((String) o);
if (ref != null) {
d.append("t").app(ref);
return;
}
if (!(o instanceof String))
d.seen.put(o, d.n);
else {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (!d.noStringSharing) {
if (d.shareStringsLongerThan == Integer.MAX_VALUE)
d.seen.put(o, d.n);
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, d.n);
}
quoteToPrintWriter(s, d.out);
d.n++;
return;
}
if (o instanceof HashSet) {
d.append(o instanceof LinkedHashSet ? "lhs" : "hashset");
structure_1(new ArrayList((Set) o), d);
return;
}
if (o instanceof TreeSet) {
d.append("treeset");
structure_1(new ArrayList((Set) o), d);
return;
}
String name = c.getName();
if (o instanceof Collection && !startsWith(name, "main$")) {
if (name.equals("java.util.Collections$SynchronizedList") || name.equals("java.util.Collections$SynchronizedRandomAccessList"))
d.append("sync");
d.append("[");
final int l = d.n;
final Iterator it = ((Collection) o).iterator();
d.stack.add(new Runnable() {
public void run() {
try {
if (!it.hasNext())
d.append("]");
else {
d.stack.add(this);
if (d.n != l)
d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.sta...";
}
});
return;
}
if (o instanceof Map && !startsWith(name, "main$")) {
if (o instanceof LinkedHashMap)
d.append("lhm");
else if (o instanceof HashMap)
d.append("hm");
else if (name.equals("java.util.Collections$SynchronizedMap"))
d.append("sync");
else if (name.equals("java.util.Collections$SynchronizedSortedMap")) {
d.append("sync tm", 2);
}
d.append("{");
final int l = d.n;
final Iterator it = ((Map) o).entrySet().iterator();
d.stack.add(new Runnable() {
public boolean v;
public Map.Entry e;
public void run() {
if (v) {
d.append("=");
v = false;
d.stack.add(this);
structure_1(e.getValue(), d);
} else {
if (!it.hasNext())
d.append("}");
else {
e = (Map.Entry) it.next();
v = true;
d.stack.add(this);
if (d.n != l)
d.append(", ");
structure_1(e.getKey(), d);
}
}
}
});
return;
}
if (c.isArray()) {
if (o instanceof byte[]) {
d.append("ba ").append(quote(bytesToHex((byte[]) o)));
return;
}
final int n = Array.getLength(o);
if (o instanceof boolean[]) {
String hex = boolArrayToHex((boolean[]) o);
int i = l(hex);
while (i > 0 && hex.charAt(i - 1) == '0' && hex.charAt(i - 2) == '0') i -= 2;
d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i)));
return;
}
String atype = "array", sep = ", ";
if (o instanceof int[]) {
atype = "intarray";
sep = " ";
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
public int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0)
d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")");
return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")");
return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
if (d.n != l)
d.append(", ");
d.append(i);
}
d.append("}");
return;
}
if (name.startsWith("java.") || name.startsWith("javax.")) {
d.append("j ").append(quote(str(o)));
return;
}
String dynName = shortDynamicClassName(o);
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
Class cc = c;
while (cc != Object.class) {
for (Field field : getDeclaredFields_cached(cc)) {
String fieldName = field.getName();
if (fieldName.equals("_persistenceInfo"))
d.persistenceInfo.put(c, field);
if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
continue;
fields.add(field);
}
cc = cc.getSuperclass();
}
lFields = asList(fields);
for (int i = 0; i < l(lFields); i++) {
Field f = lFields.get(i);
if (f.getName().equals("this$1")) {
lFields.remove(i);
lFields.add(0, f);
break;
}
}
d.fieldsByClass.put(c, lFields);
} else {
Integer ref = d.seen.get(o);
if (ref != null) {
d.append("t").app(ref);
return;
}
d.seen.put(o, d.n);
}
Field persistenceInfoField = (Field) (d.persistenceInfo.get(c));
Map persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o);
LinkedHashMap fv = new LinkedHashMap();
for (Field f : lFields) {
Object value;
try {
value = f.get(o);
} catch (Exception e) {
value = "?";
}
if (value != null && (persistenceInfo == null || !Boolean.FALSE.equals(persistenceInfo.get(f.getName()))))
fv.put(f.getName(), value);
}
String name = c.getName();
String shortName = dropPrefix("main$", name);
if (concept && eq(fv.get("className"), shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
fv.putAll((Map) fv.get("fieldValues"));
fv.remove("fieldValues");
shortName = shortDynamicClassName(o);
fv.remove("className");
}
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
d.append(shortName);
final int l = d.n;
final Iterator it = fv.entrySet().iterator();
d.stack.add(new Runnable() {
public void run() {
try {
if (!it.hasNext()) {
if (d.n != l)
d.append(")");
} else {
Map.Entry e = (Map.Entry) it.next();
d.append(d.n == l ? "(" : ", ");
d.append((String) e.getKey()).append("=");
d.stack.add(this);
structure_1(e.getValue(), d);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!it.hasNext()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 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 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 File javaxCachesDir_dir;
public static File javaxCachesDir() {
return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches");
}
public static File javaxCachesDir(String sub) {
return newFile(javaxCachesDir(), sub);
}
public static String imageServerURL() {
return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/");
}
public static volatile boolean muricaPassword_pretendNotAuthed;
public static String muricaPassword() {
if (muricaPassword_pretendNotAuthed)
return null;
return trim(loadTextFile(muricaPasswordFile()));
}
public static int loadPage_defaultTimeout = 60000;
public static ThreadLocal loadPage_charset = new ThreadLocal();
public static boolean loadPage_allowGzip = true, loadPage_debug;
public static boolean loadPage_anonymous;
public static int loadPage_verboseness = 100000;
public static int loadPage_retries = 1;
public static ThreadLocal loadPage_silent = new ThreadLocal();
public static volatile int loadPage_forcedTimeout;
public static ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal();
public static ThreadLocal>> loadPage_responseHeaders = new ThreadLocal();
public static ThreadLocal> loadPage_extraHeaders = new ThreadLocal();
public static String loadPageSilently(String url) {
try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadPageSilently(URL url) {
try {
if (url.getProtocol().equals("https"))
disableCertificateValidation();
if (!networkAllowanceTest(str(url)))
throw fail("Not allowed: " + url);
IOException e = null;
for (int tries = 0; tries < loadPage_retries; tries++) try {
URLConnection con = loadPage_openConnection(url);
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
if (loadPageThroughProxy_enabled) {
print("Trying proxy because of: " + e);
try {
return loadPageThroughProxy(str(url));
} catch (Throwable e2) {
print(" " + exceptionToStringShort(e2));
}
} else if (loadPage_debug)
print(exceptionToStringShort(e));
if (tries < loadPage_retries - 1)
sleepSeconds(1);
}
throw e;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadPage_preprocess(String url) {
if (url.startsWith("tb/"))
url = tb_mainServer() + "/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
public static String loadPage(String url) {
try {
url = loadPage_preprocess(url);
if (!isTrue(loadPage_silent.get()))
printWithTime("Loading: " + hideCredentials(url));
return loadPageSilently(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadPage(URL url) {
return loadPage(url.toExternalForm());
}
public static String loadPage(URLConnection con, URL url) throws IOException {
return loadPage(con, url, true);
}
public static String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
if (addHeaders)
try {
if (!loadPage_anonymous)
setHeaders(con);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
con.setRequestProperty("X-No-Cookies", "1");
for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
} catch (Throwable e) {
}
vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
loadPage_responseHeaders.set(con.getHeaderFields());
InputStream in = null;
try {
in = con.getInputStream();
if (loadPage_debug)
print("Put stream in map: " + currentThread());
String contentType = con.getContentType();
if (contentType == null) {
throw new IOException("Page could not be read: " + hideCredentials(url));
}
String charset = loadPage_charset == null ? null : loadPage_charset.get();
if (charset == null)
charset = loadPage_guessCharset(contentType);
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = newGZIPInputStream(in);
}
Reader r;
try {
r = new InputStreamReader(in, unquote(charset));
} catch (UnsupportedEncodingException e) {
print(toHex(utf8(charset)));
throw e;
}
StringBuilder buf = new StringBuilder();
int n = 0;
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
if ((n % loadPage_verboseness) == 0)
print(" " + n + " chars read");
}
return buf.toString();
} finally {
if (loadPage_debug)
print("loadPage done");
vm_generalSubMap("URLConnection per thread").remove(currentThread());
if (in != null)
in.close();
}
}
public static String loadPage_guessCharset(String contentType) {
Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType);
String match = m.matches() ? m.group(1) : null;
if (loadPage_debug)
print("loadPage: contentType=" + contentType + ", match: " + match);
return or(match, "UTF-8");
}
public static URLConnection loadPage_openConnection(URL url) {
URLConnection con = openConnection(url);
int timeout = toInt(loadPage_forcedTimeout_byThread.get());
if (timeout == 0)
timeout = loadPage_forcedTimeout;
if (timeout != 0)
setURLConnectionTimeouts(con, loadPage_forcedTimeout);
else
setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
return con;
}
public static A getAndClearThreadLocal(ThreadLocal tl) {
A a = tl.get();
tl.set(null);
return a;
}
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 Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
public static Set keys(Object map) {
return keys((Map) map);
}
public static A println(A a) {
return print(a);
}
public static File mkdirsFor(File file) {
return mkdirsForFile(file);
}
public static void copyStreamWithPrints(InputStream in, OutputStream out, String pat) {
try {
byte[] buf = new byte[65536];
int total = 0;
while (true) {
int n = in.read(buf);
if (n <= 0)
return;
out.write(buf, 0, n);
if ((total + n) / 100000 > total / 100000)
print(pat.replace("{*}", str(roundDownTo(total, 100000))));
total += n;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void renameFile_assertTrue(File a, File b) {
try {
if (!a.exists())
throw fail("Source file not found: " + f2s(a));
if (b.exists())
throw fail("Target file exists: " + f2s(b));
mkdirsForFile(b);
if (!a.renameTo(b))
throw fail("Can't rename " + f2s(a) + " to " + f2s(b));
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 byte[] loadBinaryFilePart(File file, long start, long end) {
try {
RandomAccessFile raf = new RandomAccessFile(file, "r");
int n = toInt(min(raf.length(), end - start));
byte[] buffer = new byte[n];
try {
raf.seek(start);
raf.readFully(buffer, 0, n);
return buffer;
} finally {
raf.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 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();
loadPage_charset.set("UTF-8");
String contents = loadPage(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 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 double parseDouble(String s) {
return Double.parseDouble(s);
}
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 String n2(long l) {
return formatWithThousands(l);
}
public static String n2(Collection l) {
return n2(l(l));
}
public static String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
public static String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
public static String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
public static String n2(Collection l, String singular) {
return n2(l(l), singular);
}
public static String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
public static String n2(Map m, String singular) {
return n2(l(m), singular);
}
public static String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
public static String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
public static List collect(Collection c, String field) {
return collectField(c, field);
}
public static List collect(String field, Collection c) {
return collectField(c, field);
}
public static List collect(Class c, String field) {
return collect(list(c), field);
}
public static void sleepInCleanUp(long ms) {
try {
if (ms < 0)
return;
Thread.sleep(ms);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void _registerIO(Object object, String path, boolean opened) {
}
public static A assertEquals(Object x, A y) {
return assertEquals(null, x, y);
}
public static A assertEquals(String msg, Object x, A y) {
if (assertVerbose())
return assertEqualsVerbose(msg, x, y);
if (!(x == null ? y == null : x.equals(y)))
throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
return y;
}
public static List javaTokC(String s) {
if (s == null)
return null;
int l = s.length();
ArrayList tok = new ArrayList();
int i = 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;
}
i = j;
if (i >= l)
break;
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 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));
i = j;
}
return tok;
}
public static A popLast(List l) {
return liftLast(l);
}
public static void quoteToPrintWriter(String s, PrintWriter out) {
if (s == null) {
out.print("null");
return;
}
out.print('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"') {
out.print('\\');
out.print(c);
} else if (c == '\r')
out.print("\\r");
else if (c == '\n')
out.print("\\n");
else if (c == '\0')
out.print("\\0");
else
out.print(c);
}
out.print('"');
}
public static String quoteCharacter(char c) {
if (c == '\'')
return "'\\''";
if (c == '\\')
return "'\\\\'";
if (c == '\r')
return "'\\r'";
if (c == '\n')
return "'\\n'";
if (c == '\t')
return "'\\t'";
return "'" + c + "'";
}
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 String boolArrayToHex(boolean[] a) {
return bytesToHex(boolArrayToBytes(a));
}
public static Iterator emptyIterator() {
return Collections.emptyIterator();
}
public static String shortDynamicClassName(Object o) {
if (o instanceof DynamicObject && ((DynamicObject) o).className != null)
return ((DynamicObject) o).className;
return shortClassName(o);
}
public static int stdcompare(Number a, Number b) {
return cmp(a, b);
}
public static int stdcompare(String a, String b) {
return cmp(a, b);
}
public static int stdcompare(long a, long b) {
return a < b ? -1 : a > b ? 1 : 0;
}
public static int stdcompare(Object a, Object b) {
return cmp(a, b);
}
public static Map getDeclaredFields_cache = newDangerousWeakHashMap();
public static Field[] getDeclaredFields_cached(Class c) {
Field[] fields;
synchronized (getDeclaredFields_cache) {
fields = getDeclaredFields_cache.get(c);
if (fields == null) {
getDeclaredFields_cache.put(c, fields = c.getDeclaredFields());
for (Field f : fields) f.setAccessible(true);
}
}
return fields;
}
public static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
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 String or2(String a, String b) {
return nempty(a) ? a : b;
}
public static String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
public static File muricaPasswordFile() {
return new File(javaxSecretDir(), "murica/muricaPasswordFile");
}
public static volatile boolean disableCertificateValidation_attempted;
public static void disableCertificateValidation() {
try {
if (disableCertificateValidation_attempted)
return;
disableCertificateValidation_attempted = true;
try {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean networkAllowanceTest(String url) {
return isAllowed("networkAllowanceTest", url);
}
public static final boolean loadPageThroughProxy_enabled = false;
public static String loadPageThroughProxy(String url) {
return null;
}
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 sleepSeconds(double s) {
if (s > 0)
sleep(round(s * 1000));
}
public static String tb_mainServer_default = "http://tinybrain.de:8080";
public static Object tb_mainServer_override;
public static String tb_mainServer() {
if (tb_mainServer_override != null)
return (String) callF(tb_mainServer_override);
return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default));
}
public static File tb_mainServer_file() {
return getProgramFile("#1001638", "mainserver.txt");
}
public static boolean tb_mainServer_isDefault() {
return eq(tb_mainServer(), tb_mainServer_default);
}
public static A printWithTime(A a) {
print(hmsWithColons() + ": " + a);
return a;
}
public static Map vm_generalSubMap(Object name) {
synchronized (get(javax(), "generalMap")) {
Map map = (Map) (vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = synchroMap());
return map;
}
}
public static GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
public static GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
public static String toHex(byte[] bytes) {
return bytesToHex(bytes);
}
public static String toHex(byte[] bytes, int ofs, int len) {
return bytesToHex(bytes, ofs, len);
}
public static byte[] utf8(String s) {
return toUtf8(s);
}
public static Matcher regexpMatcher(String pat, String s) {
return compileRegexp(pat).matcher(unnull(s));
}
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 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 URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) {
if (con.getConnectTimeout() == 0) {
con.setConnectTimeout(toInt(timeout));
if (con.getConnectTimeout() != timeout)
print("Warning: URL connect timeout not set by JDK.");
}
if (con.getReadTimeout() == 0) {
con.setReadTimeout(toInt(timeout));
if (con.getReadTimeout() != timeout)
print("Warning: URL read timeout not set by JDK.");
}
return con;
}
public static String getComputerID_quick() {
return computerID();
}
public static int roundDownTo(int x, int n) {
return x / n * n;
}
public static long roundDownTo(long x, long n) {
return x / n * n;
}
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 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 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) {
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 A optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
public static int lUtf8(String s) {
return l(utf8(s));
}
public static String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
public static double fraction(double d) {
return d % 1;
}
public static String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
public static String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
public static String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
public static String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
public static List collectField(Collection c, String field) {
List l = new ArrayList();
if (c != null)
for (Object a : c) l.add(getOpt(a, field));
return l;
}
public static List collectField(String field, Collection c) {
return collectField(c, field);
}
public static List list(Class type) {
return db_mainConcepts().list(type);
}
public static List list(Concepts concepts, Class type) {
return concepts.list(type);
}
public static List list(String type) {
return db_mainConcepts().list(type);
}
public static List list(Concepts concepts, String type) {
return concepts.list(type);
}
public static ThreadLocal assertVerbose_value = new ThreadLocal();
public static void assertVerbose(boolean b) {
assertVerbose_value.set(b);
}
public static boolean assertVerbose() {
return isTrue(assertVerbose_value.get());
}
public static A assertEqualsVerbose(Object x, A y) {
assertEqualsVerbose((String) null, x, y);
return y;
}
public static A assertEqualsVerbose(String msg, Object x, A y) {
if (!eq(x, y)) {
throw fail((msg != null ? msg + ": " : "") + (y) + " != " + (x));
} else
print("OK: " + (x));
return y;
}
public static String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
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 byte[] boolArrayToBytes(boolean[] a) {
byte[] b = new byte[(l(a) + 7) / 8];
for (int i = 0; i < l(a); i++) if (a[i])
b[i / 8] |= 1 << (i & 7);
return b;
}
public static String shortClassName(Object o) {
if (o == null)
return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
public static int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
public static int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
public static int cmp(Object a, Object b) {
if (a == null)
return b == null ? 0 : -1;
if (b == null)
return 1;
return ((Comparable) a).compareTo(b);
}
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 volatile Object isAllowed_function;
public static volatile boolean isAllowed_all = true;
public static boolean isAllowed(String askingMethod, Object... args) {
Object f = vm_generalMap_get("isAllowed_function");
if (f != null && !isTrue(callF(f, askingMethod, args)))
return false;
return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args));
}
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 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 long round(double d) {
return Math.round(d);
}
public static File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
public static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
public static String hmsWithColons() {
return hmsWithColons(now());
}
public static String hmsWithColons(long time) {
return new SimpleDateFormat("HH:mm:ss").format(time);
}
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 Map compileRegexp_cache = syncMRUCache(10);
public static java.util.regex.Pattern compileRegexp(String pat) {
java.util.regex.Pattern p = compileRegexp_cache.get(pat);
if (p == null)
compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat));
return p;
}
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 _computerID;
public static Lock computerID_lock = lock();
public static String computerID() {
if (_computerID == null) {
Lock __569 = computerID_lock;
lock(__569);
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(__569);
}
}
return _computerID;
}
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 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 A optPar(Object[] params, String name) {
return optParam(params, name);
}
public static A optPar(Object[] params, String name, 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 formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
public static volatile Concepts mainConcepts;
public static Concepts db_mainConcepts() {
if (mainConcepts == null) {
mainConcepts = new Concepts(getDBProgramID());
mainConcepts.classFinder = _defaultClassFinder();
}
return mainConcepts;
}
public static String shortenClassName(String name) {
if (name == null)
return null;
int i = lastIndexOf(name, "$");
if (i < 0)
i = lastIndexOf(name, ".");
return i < 0 ? name : substring(name, i + 1);
}
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 File getProgramDir() {
return programDir();
}
public static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
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 A _registerIOWrap(A wrapper, Object wrapped) {
return wrapper;
}
public static Map syncMRUCache(int size) {
return synchroMap(new MRUCache(size));
}
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 char stringToChar(String s) {
if (l(s) != 1)
throw fail("bad stringToChar: " + s);
return firstChar(s);
}
public static String getDBProgramID_id;
public static String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
public static Object _defaultClassFinder_value;
public static Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
public static int lastIndexOf(String a, String b) {
return a == null || b == null ? -1 : a.lastIndexOf(b);
}
public static int lastIndexOf(String a, char b) {
return a == null ? -1 : a.lastIndexOf(b);
}
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 File programDir_mine;
public static File programDir() {
return programDir(getProgramID());
}
public static File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetID(snippetID));
if (me) {
String c = caseID();
if (nempty(c))
dir = newFile(dir, c);
}
return dir;
}
public static File programDir(String snippetID, String subPath) {
return new File(programDir(snippetID), subPath);
}
public static String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
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 Random defaultRandomGenerator() {
return ThreadLocalRandom.current();
}
public static char firstChar(String s) {
return s.charAt(0);
}
public static String programIDWithCase() {
return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID();
}
public static boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b))
return false;
return parseSnippetID(a) == parseSnippetID(b);
}
public static String programID() {
return getProgramID();
}
public static String programID(Object o) {
return getProgramID(o);
}
public static volatile String caseID_caseID;
public static String caseID() {
return caseID_caseID;
}
public static void caseID(String id) {
caseID_caseID = id;
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
public static String quoteUnlessIdentifierOrInteger(String s) {
return quoteIfNotIdentifierOrInteger(s);
}
public static String quoteIfNotIdentifierOrInteger(String s) {
if (s == null)
return null;
return isJavaIdentifier(s) || isInteger(s) ? s : quote(s);
}
public static boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
public static 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()) {
m.setAccessible(true);
multiMapPut(cache, m.getName(), m);
}
_c = _c.getSuperclass();
}
}
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 abstract static class VF1 {
public abstract void get(A a);
}
public static class BakedBot {
public VirtualMechLists lists = new SimpleMechLists();
public Class bot;
public int goodTests, badTests;
public static String defaultSnippetID = "#1017706";
public String snippetID = defaultSnippetID;
public BakedBot(VirtualMechLists lists) {
this.lists = lists;
_init();
}
public BakedBot() {
_init();
}
public void _init() {
bot = hotwireDependentSharingClasses(snippetID, VirtualMechLists.class);
setOpt(bot, "mechLibID", null);
setOpt(bot, "makeAndroid3_disable", true);
setLists(lists);
runMain(bot);
}
public String answer(String s) {
return unnull(callAnswerMethod(bot, s));
}
public String answer_verbose(String s) {
return print("< ", answer(print("> ", s)));
}
public String check(String input, String expectedOutput) {
return assertEqualsVerbose_match(unnull(expectedOutput), answer(print("> ", input)));
}
public boolean pcheck(String input, String expectedOutput) {
try {
check(input, expectedOutput);
++goodTests;
return true;
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
++badTests;
return false;
}
public boolean pcheckOrPrintLog(String input, String expectedOutput) {
if (pcheck(input, expectedOutput))
return true;
{
printLines((List) getOpt(getBot("TelegramFactsBot"), "checkingLog"));
return false;
}
}
public void setList(String name, String text) {
lists.setText(name, text);
}
public String getList(String name) {
return lists.mL_raw(name);
}
public void setAuthorized(boolean b) {
setOpt(bot, "authorized", b);
}
public String answerAuthed(String s) {
final boolean authedOld = isTrue(getOpt(bot, "authorized"));
setAuthorized(true);
tempAfterwards(new Runnable() {
public void run() {
try {
setAuthorized(authedOld);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "setAuthorized(authedOld);";
}
});
return answer(s);
}
public void setLists(VirtualMechLists lists) {
this.lists = lists;
setAll(callOpt(bot, "mechMode"), "readMode", lists, "writeMode", lists);
}
public Object getBot(String shortClassName) {
return firstWithShortClassName((List) get(bot, "bots"), shortClassName);
}
public void cleanMeUp() {
cleanUp(bot);
bot = null;
}
public Object factsBot() {
return getBot("TelegramFactsBot");
}
public void addFact(String fact) {
if (!contains(lines(lists.mL_raw("Random facts")), fact))
lists.append("Random facts", fact);
}
public void printTestStats() {
print("\nGood tests: " + goodTests + ", bad tests: " + badTests + "\n");
}
public void imagineMode() {
set(factsBot(), "imagineMode", true);
}
public Collection imaginedFacts() {
return (Collection) get(factsBot(), "imaginedFacts");
}
public void useIterate(boolean useIterate) {
set(factsBot(), "useIterate", useIterate);
}
public void useDiskCache(boolean useDiskCache) {
setOpt(bot, "transpileRaw_useDiskCache", useDiskCache);
}
public void debug(boolean debug) {
set(factsBot(), "debug", debug);
}
public void setRules(String rules) {
if (lists instanceof SimpleMechLists)
((SimpleMechLists) lists).setText("NL Logic Examples", rules);
}
}
public abstract static class DynPrintLog extends DynModule {
public transient JTextArea ta;
public transient Lock updatePrintLog_lock = lock();
public transient StringBuffer actualPrintLog;
public JComponent visualize() {
return awtEvery(jSection("Log", ta = moveCaretToEnd(typeWriterTextArea(getPrintLog()))), 500, new Runnable() {
public void run() {
try {
updatePrintLog();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "updatePrintLog();";
}
});
}
public void updatePrintLog() {
Lock __81 = updatePrintLog_lock;
lock(__81);
try {
if (ta != null)
setText(ta, getPrintLog());
} finally {
unlock(__81);
}
}
public JTextArea myPrintLogComponent() {
return ta;
}
public void enableWordWrap() {
enableWordWrapForTextArea(ta);
}
public String getPrintLog() {
if (actualPrintLog == null)
actualPrintLog = liveLocalPrintLog_realMC(this);
return str(actualPrintLog);
}
}
public static class LineBuffer {
public VF1 onLine;
public StringBuilder currentLine = new StringBuilder();
public LineBuffer() {
}
public LineBuffer(VF1 onLine) {
this.onLine = onLine;
}
public void append(String s) {
append(s, onLine);
}
public void append(String s, VF1 onLine) {
currentLine.append(s);
if (contains(s, '\n')) {
int i = 0, j;
s = str(currentLine);
while ((j = indexOf(s, i, '\n')) >= 0) {
String line = dropTrailingBackslashR(substring(s, i, j));
callF(onLine, line);
i = j + 1;
}
currentLine = new StringBuilder(substring(s, i));
}
}
public int size() {
return l(currentLine);
}
}
public abstract static class VF2 {
public abstract void get(A a, B b);
}
public static class Var implements IVar {
public A v;
public Var() {
}
public Var(A v) {
this.v = v;
}
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() {
return v;
}
public synchronized boolean has() {
return v != null;
}
public synchronized void clear() {
v = null;
}
public String toString() {
return str(get());
}
}
public abstract static class F0 {
public abstract A get();
}
public static class MRUCache extends LinkedHashMap {
public int maxSize = 10;
public MRUCache() {
}
public MRUCache(int maxSize) {
this.maxSize = maxSize;
}
public boolean removeEldestEntry(Map.Entry eldest) {
return size() > maxSize;
}
}
public 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 static class TailFile implements AutoCloseable {
public File file;
public int interval;
public Object onData;
public long l;
public Flag stopped = new Flag();
public java.util.Timer timer;
public ReliableSingleThread thread;
public volatile boolean hasIdled, debug;
public TailFile() {
}
public TailFile(final File file, int interval, Object onData) {
this.onData = onData;
this.interval = interval;
this.file = file;
thread = new ReliableSingleThread(new Runnable() {
public void run() {
try {
update();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "update()";
}
});
}
public void update() {
long l2 = l(file);
if (l2 < l)
l = 0;
if (l2 == l)
hasIdled = true;
else
try {
if (debug)
print("New data in " + f2s(file) + ": " + n2(l2 - l, "byte"));
for (String s : loadTextFilePart_iterator(file, l, l2)) pcallF(onData, s);
l = l2;
} catch (Throwable __e) {
_handleException(__e);
}
}
public void start() {
timer = doEvery(interval, new Runnable() {
public void run() {
try {
if (!stopped.isUp())
thread.trigger();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!stopped.isUp()) thread.trigger()";
}
});
}
public void stop() {
timer.cancel();
timer = null;
if (stopped.raise())
thread.triggerAndWait();
}
public void close() {
stop();
}
public boolean started() {
return timer != null;
}
public void debugOn() {
if (debug)
return;
debug = true;
print("Watching file: " + f2s(file));
}
}
public static ThreadLocal DynamicObject_loading = new ThreadLocal();
public static class DynamicObject {
public String className;
public LinkedHashMap fieldValues = new LinkedHashMap();
public DynamicObject() {
}
public DynamicObject(String className) {
this.className = className;
}
}
public static class PersistableThrowable {
public String className;
public String msg;
public String stacktrace;
public PersistableThrowable() {
}
public PersistableThrowable(Throwable e) {
if (e == null)
className = "Crazy Null Error";
else {
className = getClassName(e).replace('/', '.');
msg = e.getMessage();
stacktrace = getStackTrace_noRecord(e);
}
}
public String toString() {
return nempty(msg) ? className + ": " + msg : className;
}
}
public static interface IVar {
public void set(A a);
public A get();
public boolean has();
public void clear();
}
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 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 __370 = lock;
lock(__370);
try {
if (loaded == 0) {
value = make();
changeCount++;
loaded = sysNow();
}
return value;
} finally {
unlock(__370);
}
}
public void clear() {
Lock __371 = lock;
lock(__371);
try {
if (debug && loaded != 0)
print("Clearing cache");
value = null;
changeCount++;
loaded = 0;
} finally {
unlock(__371);
}
}
public void clear(double seconds) {
Lock __372 = lock;
lock(__372);
try {
if (seconds != 0 && loaded != 0 && sysNow() >= loaded + seconds * 1000)
clear();
} finally {
unlock(__372);
}
}
public void set(A a) {
Lock __373 = lock;
lock(__373);
try {
value = a;
++changeCount;
loaded = sysNow();
} finally {
unlock(__373);
}
}
public A make() {
return (A) callF(maker);
}
}
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 class ReliableSingleThread implements Runnable {
public Object runnable;
public boolean trigger;
public Thread thread;
public String name = "Single Thread";
public F0 enter;
public ReliableSingleThread(Object runnable) {
this.runnable = runnable;
}
public void trigger() {
go();
}
public synchronized void go() {
trigger = true;
if (!running()) {
AutoCloseable __381 = callF(enter);
try {
thread = startThread(name, new Runnable() {
public void run() {
try {
_run();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_run();";
}
});
} finally {
_close(__381);
}
}
}
public void run() {
go();
}
public void get() {
go();
}
public synchronized boolean running() {
return thread != null;
}
public void triggerAndWait() {
trigger();
while (running()) sleep(1);
}
public void _run() {
while (licensed()) {
synchronized (this) {
if (!trigger) {
thread = null;
break;
}
trigger = false;
}
pcallF(runnable);
}
}
public synchronized void cancel() {
cancelAndInterruptThread(thread);
thread = null;
}
}
public static class SimpleMechLists extends VirtualMechLists {
public Map lists = syncCIMap();
public boolean verbose;
public String mL_raw(String listName) {
if (verbose)
print("List requested: " + listName);
return lists.get(listName);
}
public void append(String listName, String text) {
if (verbose)
print("Appending to " + listName);
lists.put(listName, appendNewLineIfNempty(lists.get(listName)) + text);
}
public void setText(String listName, String text) {
if (verbose)
print("Replacing: " + listName);
lists.put(listName, text);
}
}
public abstract static class DynModule {
public String name, toolTip;
public PersistableThrowable _error;
public Map> mechLists;
public Map _persistenceInfo;
public transient Object _host;
public transient Map timers = newWeakHashMap();
public transient Set _resources = synchroHashSet();
public transient Lock lock;
public transient boolean persistOnChangedField = true;
public transient int changeCount;
public transient Object changeCountSync = new Object();
public transient List onChange;
public transient boolean verboseTimers;
public transient ReliableSingleThread rstUpdate;
public transient Set componentFieldsToKeep;
public transient Map transientGeneralMap = synchroHashMap();
public transient Q q;
public DynModule() {
dm_initErrorHandling();
setMainDesktopPane((JDesktopPane) getCreatorOpt("desktop"));
}
public boolean isVisible() {
return isTrue(getOpt(_host, "visible"));
}
public String moduleName() {
return name;
}
public void setModuleName(String name) {
String oldName = this.name;
if (!eq(name, oldName)) {
this.name = name;
possiblyInternalFrameTitle(vis(), name);
vmBus_send("moduleNameChange", this, oldName, name);
}
}
public void setModuleToolTip(String toolTip) {
this.toolTip = toolTip;
}
public JComponent vis() {
return (JComponent) getOpt(_host, "vis");
}
public A ownResource(A a) {
if (a != null)
_resources.add(a);
return a;
}
public A ownTimer(A timer) {
if (timer instanceof AutoCloseable)
ownResource((AutoCloseable) timer);
ownTimer(timer, "cancelTimerOrInterruptThread");
return timer;
}
public void ownTimer(Object timer, Object closerHelper) {
timers.put(timer, closerHelper);
}
public void singleTimer(java.util.Timer timer) {
stopAllTimers();
ownTimer(timer);
}
public void stopAllTimers() {
for (AutoCloseable resource : getAndClearList(_resources)) {
if (verboseTimers)
print("Releasing resource: " + resource);
try {
resource.close();
} catch (Throwable __e) {
_handleException(__e);
}
}
{
final Map __361 = getAndClearMap(timers);
for (Object timer : keys(__361)) {
Object closerHelper = __361.get(timer);
if (verboseTimers)
print("Stopping timer: " + closerHelper + " / " + timer);
pcallFInRealOrMyMC(this, closerHelper, timer);
}
}
}
public void cleanMeUp_dynModule() {
stopAllTimers();
}
public void persistMe() {
synchronized (changeCountSync) {
++changeCount;
}
pcallFAll(onChange);
callOpt(_host, "_change");
updateMe();
}
public void _change() {
persistMe();
}
public void change() {
persistMe();
}
public void updateMe() {
rstUpdate().trigger();
}
public void changeAndUpdate() {
_change();
updateMe();
}
public boolean setField(String name, Object value) {
AutoCloseable __364 = enter();
try {
{
try {
if (eq(get(this, name), value))
return false;
} catch (Throwable __e) {
_handleException(__e);
}
set(this, name, value);
}
if (persistOnChangedField && !isFalse(mapGet(_persistenceInfo, name)))
_change();
return true;
} finally {
_close(__364);
}
}
public A setFieldAndReturn(String name, A value) {
setField(name, value);
return value;
}
public boolean setFields(Object... params) {
boolean change = false;
for (int i = 0; i < l(params); i += 2) if (setField((String) params[i], params[i + 1]))
change = true;
return change;
}
public void start() {
}
public void revisualize() {
call(creator(), "revisualizeModule", _host);
}
public AutoCloseable enter() {
AutoCloseable c = tempSetThreadLocal(dm_currentModule_value, new WeakReference(this));
final Object realMC = getMainClass(this);
if (realMC != mc()) {
c = combineAutoCloseables(tempInterceptPrint(new F1() {
public Boolean get(String s) {
try {
{
call(realMC, "print", s);
return false;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret false with call(realMC, 'print, s);";
}
}), c);
c = combineAutoCloseables(tempSetTL(realMC_tl(), realMC), c);
}
return c;
}
public AutoCloseable enterAndLock() {
return combineAutoCloseables(enter(), tempLock(lock));
}
public boolean setError(Throwable e) {
setField("_error", persistableThrowable(e));
return true;
}
public void clearError() {
setField("_error", null);
}
public void onChange(Runnable r) {
Lock __362 = lock;
lock(__362);
try {
if (onChange == null)
onChange = synchroList();
addIfNotThere(onChange, r);
} finally {
unlock(__362);
}
}
public void onChangeAndNow(Runnable r) {
onChange(r);
callF(r);
}
public void update() {
}
public void unvisualize() {
zeroAllFieldsOfTypeExcept(this, Component.class, componentFieldsToKeep);
}
public List menuItems() {
return null;
}
public void enhanceFrame(Container f) {
internalFramePopupMenuFromActions_threaded(f, menuItems());
String switchableFields = callOpt(this, "switchableFields");
for (String field : splitAtSpace(switchableFields)) {
Class type = fieldType(this, field);
if (eq(boolean.class, type))
dm_boolFieldMenuItem(f, field);
else if (eq(int.class, type))
dm_intFieldMenuItem(f, field);
else if (eq(double.class, type))
dm_doubleFieldMenuItem(f, field);
}
}
public ReliableSingleThread rstUpdate() {
if (rstUpdate == null)
rstUpdate = dm_rst(this, new Runnable() {
public void run() {
try {
AutoCloseable __365 = enter();
try {
update();
} finally {
_close(__365);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __365 = enter(); try { update(); } finally { _close(__365); }";
}
});
return rstUpdate;
}
public Q q() {
AutoCloseable __366 = enter();
try {
if (q == null) {
Lock __363 = lock;
lock(__363);
try {
if (q == null)
q = dm_startQ();
} finally {
unlock(__363);
}
}
return q;
} finally {
_close(__366);
}
}
public A withUpdate(A a) {
rstUpdate().trigger();
return a;
}
public DynModule module() {
return this;
}
}
public static void _registerTimer(java.util.Timer timer) {
_registerTimer_original(timer);
dm_currentModule().ownTimer(timer);
}
public static class Flag {
public boolean up;
public synchronized boolean raise() {
if (!up) {
up = true;
notifyAll();
return true;
} else
return false;
}
public synchronized void waitUntilUp() {
while (!up) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void waitUntilUp(long timeout) {
if (!up) {
try {
wait(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized boolean isUp() {
return up;
}
public String toString() {
return isUp() ? "up" : "down";
}
public void waitForThisOr(Flag otherFlag) {
try {
while (!isUp() && !otherFlag.isUp()) Thread.sleep(50);
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
public abstract static class VirtualMechLists {
public abstract String mL_raw(String listName);
public void append(String listName, String text) {
}
public void setText(String listName, String text) {
}
}
public static class Q implements AutoCloseable {
public String name = "Unnamed Queue";
public List q = synchroLinkedList();
public ReliableSingleThread rst = new ReliableSingleThread(new Runnable() {
public void run() {
try {
_run();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_run()";
}
});
public volatile boolean retired;
public Q() {
}
public Q(String name) {
this.name = name;
}
public void add(Runnable r) {
q.add(r);
_trigger();
}
public void _trigger() {
rst.name = name;
rst.go();
}
public void add(Object r) {
add(toRunnable(r));
}
public void _run() {
Runnable r;
while (licensed() && !retired && (r = syncPopFirst(q)) != null) {
try {
r.run();
} catch (Throwable __e) {
_handleException(__e);
}
}
}
public void close() {
retired = true;
}
public void done() {
}
public boolean isEmpty() {
return q.isEmpty();
}
public int size() {
return q.size();
}
}
public abstract static class F1 {
public abstract B get(A a);
}
public static int concepts_internStringsLongerThan = 10;
public static ThreadLocal concepts_unlisted = new ThreadLocal();
public static interface Derefable {
public Concept get();
}
public static interface IConceptIndex {
public void update(Concept c);
public void remove(Concept c);
}
public static interface IFieldIndex {
public List getAll(Val val);
}
public static class Concepts {
public Map concepts = synchroTreeMap();
public HashMap perClassData = new HashMap();
public String programID;
public long idCounter;
public volatile long changes, changesWritten;
public volatile java.util.Timer autoSaver;
public volatile boolean savingConcepts, dontSave, noXFullGrab;
public boolean vmBusSend = true;
public boolean initialSave = true;
public int autoSaveInterval = -1000;
public boolean useGZIP = true, quietSave;
public ReentrantLock lock = new ReentrantLock(true);
public ReentrantLock saverLock = new ReentrantLock(true);
public long lastSaveTook, lastSaveWas;
public float maxAutoSavePercentage = 10;
public List conceptIndices;
public Map, Map> fieldIndices;
public List saveActions = synchroList();
public Object classFinder;
public Concepts() {
}
public Concepts(String programID) {
this.programID = programID;
}
public synchronized long internalID() {
do {
++idCounter;
} while (hasConcept(idCounter));
return idCounter;
}
public void initProgramID() {
if (programID == null)
programID = getDBProgramID();
}
public Concepts load() {
return load(false);
}
public Concepts safeLoad() {
return load(true);
}
public Concepts load(boolean allDynamic) {
initProgramID();
try {
if (tryToGrab(allDynamic))
return this;
} catch (Throwable e) {
if (!exceptionMessageContains(e, "no xfullgrab"))
printShortException(e);
print("xfullgrab failed - loading DB of " + programID + " from disk");
}
return loadFromDisk(allDynamic);
}
public Concepts loadFromDisk() {
return loadFromDisk(false);
}
public Concepts loadFromDisk(boolean allDynamic) {
if (nempty(concepts))
clearConcepts();
long time = now();
Map _concepts = concepts;
readLocally2_allDynamic.set(allDynamic);
AutoCloseable __124 = tempSetTL(readLocally2_classFinder, classFinder);
try {
readLocally2(this, programID, "concepts");
Map __concepts = concepts;
concepts = _concepts;
concepts.putAll(__concepts);
int l = readLocally_stringLength;
int tokrefs = unstructure_tokrefs;
assignConceptsToUs();
done("Loaded " + n(l(concepts), "concepts"), time);
if (fileSize(getProgramFile(programID, "idCounter.structure")) != 0)
readLocally2(this, programID, "idCounter");
else
calcIdCounter();
if (initialSave)
allChanged();
return this;
} finally {
_close(__124);
}
}
public Concepts loadConcepts() {
return load();
}
public boolean tryToGrab(boolean allDynamic) {
if (sameSnippetID(programID, getDBProgramID()))
return false;
RemoteDB db = connectToDBOpt(programID);
try {
if (db != null) {
loadGrab(db.fullgrab(), allDynamic);
return true;
}
} finally {
if (db != null)
db.close();
}
return false;
}
public Concepts load(String grab) {
return loadGrab(grab, false);
}
public Concepts safeLoad(String grab) {
return loadGrab(grab, true);
}
public Concepts loadGrab(String grab, boolean allDynamic) {
clearConcepts();
DynamicObject_loading.set(true);
try {
Map map = (Map) unstructure(grab, allDynamic, classFinder);
concepts.putAll(map);
assignConceptsToUs();
for (long l : map.keySet()) idCounter = max(idCounter, l);
} finally {
DynamicObject_loading.set(null);
}
allChanged();
return this;
}
public void assignConceptsToUs() {
for (Concept c : values(concepts)) {
c._concepts = this;
callOpt_noArgs(c, "_doneLoading2");
}
}
public String progID() {
return programID == null ? getDBProgramID() : programID;
}
public Concept getConcept(String id) {
return empty(id) ? null : getConcept(parseLong(id));
}
public Concept getConcept(long id) {
return (Concept) concepts.get((long) id);
}
public Concept getConcept(RC ref) {
return ref == null ? null : getConcept(ref.longID());
}
public boolean hasConcept(long id) {
return concepts.containsKey((long) id);
}
public void deleteConcept(long id) {
Concept c = getConcept(id);
if (c == null)
print("Concept " + id + " not found");
else
c.delete();
}
public void calcIdCounter() {
long id_ = 0;
for (long id : keys(concepts)) id_ = max(id_, id);
idCounter = id_ + 1;
saveLocally2(this, programID, "idCounter");
}
public void saveConceptsIfDirty() {
saveConcepts();
}
public void save() {
saveConcepts();
}
public void saveConcepts() {
if (dontSave)
return;
initProgramID();
saverLock.lock();
savingConcepts = true;
long start = now(), time;
try {
String s = null;
long _changes = changes;
if (_changes == changesWritten)
return;
File f = getProgramFile(programID, useGZIP ? "concepts.structure.gz" : "concepts.structure");
lock.lock();
long fullTime = now();
try {
saveLocally2(this, programID, "idCounter");
if (useGZIP) {
saveGZStructureToFile(f, cloneMap(concepts));
getProgramFile(programID, "concepts.structure").delete();
} else
s = structure(cloneMap(concepts));
} finally {
lock.unlock();
}
while (nempty(saveActions)) pcallF(popFirst(saveActions));
changesWritten = _changes;
if (!useGZIP) {
time = now() - start;
if (!quietSave)
print("Saving " + toM(l(s)) + "M chars (" + time + " ms)");
start = now();
saveTextFile(f, javaTokWordWrap(s));
getProgramFile(programID, "concepts.structure.gz").delete();
}
copyFile(f, getProgramFile(programID, "backups/concepts.structure" + (useGZIP ? ".gz" : "") + ".backup" + ymd() + "-" + formatInt(hours(), 2)));
time = now() - start;
if (!quietSave)
print(programID + ": Saved " + toK(f.length()) + " K, " + n(concepts, "concepts") + " (" + time + " ms)");
lastSaveWas = fullTime;
lastSaveTook = now() - fullTime;
} finally {
savingConcepts = false;
saverLock.unlock();
}
}
public void _autoSaveConcepts() {
if (autoSaveInterval < 0 && maxAutoSavePercentage != 0) {
long pivotTime = Math.round(lastSaveWas + lastSaveTook * 100.0 / maxAutoSavePercentage);
if (now() < pivotTime) {
return;
}
}
try {
saveConcepts();
} catch (Throwable e) {
print("Concept save failed, will try again: " + e);
}
}
public void clearConcepts() {
concepts.clear();
allChanged();
}
public synchronized void allChanged() {
++changes;
if (vmBusSend)
vmBus_send("conceptsChanged", this);
}
public synchronized void autoSaveConcepts() {
if (autoSaver == null) {
if (isTransient())
throw fail("Can't persist transient database");
autoSaver = doEvery_daemon(abs(autoSaveInterval), new Runnable() {
public void run() {
try {
_autoSaveConcepts();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_autoSaveConcepts()";
}
});
}
}
public void cleanMeUp() {
boolean shouldSave = autoSaver != null;
if (autoSaver != null) {
autoSaver.cancel();
autoSaver = null;
}
while (savingConcepts) sleepInCleanUp(10);
if (shouldSave)
saveConceptsIfDirty();
}
public Map getIDsAndNames() {
Map map = new HashMap();
Map cloned = cloneMap(concepts);
for (long id : keys(cloned)) map.put(id, cloned.get(id).className);
return map;
}
public void deleteConcepts(List l) {
for (Object o : l) if (o instanceof Long)
concepts.remove((Long) o);
else if (o instanceof Concept)
((Concept) o).delete();
else
warn("Can't delete " + getClassName(o));
}
public A conceptOfType(Class type) {
return firstOfType(allConcepts(), type);
}
public List conceptsOfType(Class type) {
return filterByType(allConcepts(), type);
}
public List listConcepts(Class type) {
return conceptsOfType(type);
}
public List list(Class type) {
return conceptsOfType(type);
}
public List list(String type) {
return conceptsOfType(type);
}
public List conceptsOfType(String type) {
return filterByDynamicType(allConcepts(), "main$" + type);
}
public boolean hasConceptOfType(Class extends Concept> type) {
return hasType(allConcepts(), type);
}
public void persistConcepts() {
loadConcepts();
autoSaveConcepts();
}
public void conceptPersistence() {
persistConcepts();
}
public Concepts persist() {
persistConcepts();
return this;
}
public void persist(int interval) {
autoSaveInterval = interval;
persist();
}
public A ensureHas(Class c, Runnable r) {
A a = conceptOfType(c);
if (a == null) {
r.run();
a = conceptOfType(c);
if (a == null)
throw fail("Concept not made by " + r + ": " + shortClassName(c));
}
return a;
}
public void ensureHas(Class extends Concept> c1, Class extends Concept> c2, Object func) {
for (Concept a : conceptsOfType(c1)) {
Concept b = findBackRef(a, c2);
if (b == null) {
callF(func, a);
b = findBackRef(a, c2);
if (b == null)
throw fail("Concept not made by " + func + ": " + shortClassName(c2));
}
}
}
public void forEvery(Class extends Concept> type, Object func) {
for (Concept c : conceptsOfType(type)) callF(func, c);
}
public int deleteAll(Class extends Concept> type) {
List l = (List) conceptsOfType(type);
for (Concept c : l) c.delete();
return l(l);
}
public Collection allConcepts() {
synchronized (concepts) {
return new ArrayList(values(concepts));
}
}
public int countConcepts(Class c, Object... params) {
int n = 0;
for (A x : list(c)) if (checkConceptFields(x, params))
++n;
return n;
}
public int countConcepts(String c, Object... params) {
int n = 0;
for (Concept x : list(c)) if (checkConceptFields(x, params))
++n;
return n;
}
public int countConcepts() {
return l(concepts);
}
public synchronized void addConceptIndex(IConceptIndex index) {
if (conceptIndices == null)
conceptIndices = new ArrayList();
conceptIndices.add(index);
}
public synchronized void removeConceptIndex(IConceptIndex index) {
if (conceptIndices == null)
return;
conceptIndices.remove(index);
if (empty(conceptIndices))
conceptIndices = null;
}
public synchronized void addFieldIndex(Class extends Concept> c, String field, IFieldIndex index) {
if (fieldIndices == null)
fieldIndices = new HashMap();
Map map = fieldIndices.get(c);
if (map == null)
fieldIndices.put(c, map = new HashMap());
map.put(field, index);
}
public synchronized IFieldIndex getFieldIndex(Class extends Concept> c, String field) {
if (fieldIndices == null)
return null;
Map map = fieldIndices.get(c);
return map == null ? null : map.get(field);
}
public RC xnew(String name, Object... values) {
return new RC(cnew(name, values));
}
public void xset(long id, String field, Object value) {
xset(new RC(id), field, value);
}
public void xset(RC c, String field, Object value) {
if (value instanceof RC)
value = getConcept((RC) value);
cset(getConcept(c), field, value);
}
public Object xget(long id, String field) {
return xget(new RC(id), field);
}
public Object xget(RC c, String field) {
return xgetPost(cget(getConcept(c), field));
}
public Object xgetPost(Object o) {
o = deref(o);
if (o instanceof Concept)
return new RC((Concept) o);
return o;
}
public void xdelete(long id) {
xdelete(new RC(id));
}
public void xdelete(RC c) {
getConcept(c).delete();
}
public void xdelete(List l) {
for (RC c : l) xdelete(c);
}
public List xlist() {
return map("toPassRef", allConcepts());
}
public List xlist(String className) {
return map("toPassRef", conceptsOfType(className));
}
public boolean isTransient() {
return eq(programID, "-");
}
public String xfullgrab() {
if (noXFullGrab)
throw fail("no xfullgrab (DB too large)");
Lock __123 = lock();
lock(__123);
try {
if (changes == changesWritten && !isTransient())
return loadConceptsStructure(programID);
return structure(cloneMap(concepts));
} finally {
unlock(__123);
}
}
public void xshutdown() {
cleanKillVM();
}
public long xchangeCount() {
return changes;
}
public int xcount() {
return countConcepts();
}
public void register(Concept c) {
if (c._concepts == this)
return;
if (c._concepts != null)
throw fail("Can't re-register");
c._concepts = this;
c.id = internalID();
c.created = now();
concepts.put((long) c.id, c);
c.change();
}
public void conceptChanged(Concept c) {
allChanged();
if (conceptIndices != null)
for (IConceptIndex index : conceptIndices) index.update(c);
}
}
public static class Concept extends DynamicObject {
public transient Concepts _concepts;
public long id;
public long created;
public Concept(String className) {
super(className);
_created();
}
public Concept() {
if (!_loading()) {
_created();
}
}
public Concept(boolean unlisted) {
if (!unlisted)
_created();
}
public List[ refs;
public List][ backRefs;
public static boolean loading() {
return _loading();
}
public static boolean _loading() {
return isTrue(DynamicObject_loading.get());
}
public void _created() {
if (!isTrue(concepts_unlisted.get()))
db_mainConcepts().register(this);
}
public class Ref] {
public A value;
public Ref() {
if (!isTrue(DynamicObject_loading.get()))
refs = addDyn(refs, this);
}
public Ref(A value) {
this.value = value;
refs = addDyn(refs, this);
index();
}
public Concept concept() {
return Concept.this;
}
public A get() {
return value;
}
public boolean has() {
return value != null;
}
public void set(A a) {
if (a == value)
return;
unindex();
value = a;
index();
}
public void set(Ref ref) {
set(ref.get());
}
public void clear() {
set((A) null);
}
public void index() {
if (value != null)
value.backRefs = addDyn(value.backRefs, this);
change();
}
public void unindex() {
if (value != null)
value.backRefs = removeDyn(value.backRefs, this);
}
public void change() {
Concept.this.change();
}
}
public class RefL extends AbstractList {
public List[> l = new ArrayList();
public A set(int i, A o) {
A prev = l.get(i).get();
l.get(i).set(o);
return prev;
}
public void add(int i, A o) {
l.add(i, new Ref(o));
}
public A get(int i) {
return l.get(i).get();
}
public A remove(int i) {
return l.remove(i).get();
}
public int size() {
return l.size();
}
public boolean contains(Object o) {
if (o instanceof Concept)
for (Ref] r : l) if (eq(r.get(), o))
return true;
return super.contains(o);
}
}
public void delete() {
for (Ref r : unnull(refs)) r.unindex();
refs = null;
for (Ref r : cloneList(backRefs)) r.set((Concept) null);
backRefs = null;
if (_concepts != null) {
_concepts.concepts.remove((long) id);
_concepts.allChanged();
if (_concepts.conceptIndices != null)
for (IConceptIndex index : _concepts.conceptIndices) index.remove(this);
_concepts = null;
}
id = 0;
}
public BaseXRef export() {
return new BaseXRef(_concepts.progID(), id);
}
public void change() {
if (_concepts != null)
_concepts.conceptChanged(this);
}
public void _change() {
change();
}
public String _programID() {
return _concepts == null ? getDBProgramID() : _concepts.progID();
}
}
public static class RC {
public transient Object owner;
public String id;
public RC() {
}
public RC(long id) {
this.id = str(id);
}
public RC(Object owner, long id) {
this.id = str(id);
this.owner = owner;
}
public RC(Concept c) {
this(c.id);
}
public long longID() {
return parseLong(id);
}
public String toString() {
return id;
}
public transient RemoteDB db;
public String getString(String field) {
return db.xS(this, field);
}
public Object get(String field) {
return db.xget(this, field);
}
public void set(String field, Object value) {
db.xset(this, field, value);
}
}
public static class BaseXRef {
public String programID;
public long id;
public BaseXRef() {
}
public BaseXRef(String programID, long id) {
this.id = id;
this.programID = programID;
}
public boolean equals(Object o) {
if (!(o instanceof BaseXRef))
return false;
BaseXRef r = (BaseXRef) (o);
return eq(programID, r.programID) && eq(id, r.id);
}
public int hashCode() {
return programID.hashCode() + (int) id;
}
}
public static class XRef extends Concept {
public BaseXRef ref;
public XRef() {
}
public XRef(BaseXRef ref) {
this.ref = ref;
_doneLoading2();
}
public void _doneLoading2() {
getIndex().put(ref, this);
}
public HashMap getIndex() {
return getXRefIndex(_concepts);
}
}
public static synchronized HashMap getXRefIndex(Concepts concepts) {
HashMap cache = (HashMap) concepts.perClassData.get(XRef.class);
if (cache == null)
concepts.perClassData.put(XRef.class, cache = new HashMap());
return cache;
}
public static XRef lookupOrCreateXRef(BaseXRef ref) {
XRef xref = getXRefIndex(db_mainConcepts()).get(ref);
if (xref == null)
xref = new XRef(ref);
return xref;
}
public static void cleanMeUp_concepts() {
if (mainConcepts != null)
mainConcepts.cleanMeUp();
mainConcepts = null;
}
public static void loadAndAutoSaveConcepts() {
mainConcepts.persist();
}
public static void loadAndAutoSaveConcepts(int interval) {
mainConcepts.persist(interval);
}
public static RC toPassRef(Concept c) {
return new RC(c);
}
public static B pairB(Pair p) {
return p == null ? null : p.b;
}
public static List myInnerClasses_list = litlist("VF1", null, "Derefable", "VF2", "JSection", "Var", "DefunctClassLoader", "TokCondition", "IFieldIndex", "talkToThisVM_IO", "Str", "UTF8Processor", "ReliableSingleThread", "SingleComponentPanel", "DynModule", "FixedRateTimer", "Concept", "BakedBot", "Rect", "Pt", "ProgramScan", "F0", "F1", "IterableIterator", "betterCIComparator_C", "F2", "RemoteDB", "Flag", "VirtualMechLists", "unstructure_Receiver", "ScannedBot", "SFCat", "Concepts", "RC", "XRef", "ExpiringMap2", "BaseXRef", "CloseableIterableIterator", "getOpt_Map", "Producer", "structure_Data", "SimpleMechLists", "IVar", "MechMode", "Cache", "_MethodCache", "talkTo_IO", "LineBuffer", "Matches", "LiveValue", "Q", "TailFile", "CriticalAction", "DialogHandler", "Pair", "CompilerBot", "DynPrintLog", "JavaXClassLoader", "DialogIO", "BetterLabel", "MRUCache", "componentPopupMenu_Adapter", "JavaXClassLoaderWithParent2", "DynamicObject", "IConceptIndex", "PersistableThrowable", "talkToSubBot_IO", "Android3", "SmartTimerTask", "Responder");
public static List myInnerClasses() {
return myInnerClasses_list;
}
public static InheritableThreadLocal> dm_currentModule_value = new InheritableThreadLocal();
public static DynModule dm_currentModule() {
return getWeakRef(dm_currentModule_value.get());
}
public static void _onLoad_dm_currentModule() {
setOptMC("dm_currentModule_generic", dm_currentModule_value);
}
public static void cleanMeUp_dm_currentModule() {
dm_currentModule_value = new InheritableThreadLocal();
}
public static void cancelTimerOrInterruptThread(Object timer) {
if (timer instanceof Thread && !(timer instanceof AutoCloseable))
interruptThread((Thread) timer);
else
cancelTimer(timer);
}
public static Method findMethod(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Method m = findMethod_static((Class) o, method, args, false);
if (m == null)
return null;
m.setAccessible(true);
return m;
} else {
Method m = findMethod_instance(o, method, args, false);
if (m == null)
return null;
m.setAccessible(true);
return m;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Method findMethod_static(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");
;
if (!m.getName().equals(method)) {
if (debug)
System.out.println("Method name mismatch: " + method);
continue;
}
if ((m.getModifiers() & Modifier.STATIC) == 0 || !findMethod_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
public static Method findMethod_instance(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");
;
if (m.getName().equals(method) && findMethod_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
return null;
}
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 Class> hotwireDependentSharingClasses(String progID, Class... classesToShare) {
Class c = hotwireSharingClasses(progID, classesToShare);
makeDependent(c);
return c;
}
public static void runMain(Object c, String... args) {
callMain(c, args);
}
public static void runMain() {
callMain();
}
public static int callAnswerMethod_version;
public static String callAnswerMethod(String s) {
if (callAnswerMethod_version == 0)
if (hasMethod(mc(), "answer", "", new ArrayList()))
callAnswerMethod_version = 1;
else if (hasMethod(mc(), "answer", ""))
callAnswerMethod_version = 2;
else
callAnswerMethod_version = -1;
if (callAnswerMethod_version == 1)
return (String) callMC("answer", s, emptyList());
else if (callAnswerMethod_version == 2)
return (String) callMC("answer", s);
return null;
}
public static String callAnswerMethod(Object responder, String s) {
return callAnswerMethod(responder, s, litlist(s));
}
public static String callAnswerMethod(Object responder, String s, List history) {
String answer = (String) callOpt(responder, "answer", s, history);
if (answer == null)
answer = (String) callOpt(responder, "answer", s);
return emptyToNull(answer);
}
public static String assertEqualsVerbose_match(String x, String y) {
assertEqualsVerbose_match((String) null, x, y);
return y;
}
public static String assertEqualsVerbose_match(String msg, String x, String y) {
if (!match(x, y)) {
throw fail((msg != null ? msg + ": " : "") + quote(y) + " != " + quote(x));
} else
print("OK: " + quote(x));
return y;
}
public static void printLines(Collection c) {
for (Object o : unnull(c)) print(o);
}
public static Object getBot(String botID) {
return callOpt(getMainBot(), "getBot", botID);
}
public static AutoCloseable tempAfterwards(final Object r) {
return new AutoCloseable() {
public void close() {
callF(r);
}
};
}
public static void setAll(Object o, Map fields) {
if (fields == null)
return;
for (String field : keys(fields)) set(o, field, fields.get(field));
}
public static void setAll(Object o, Object... values) {
failIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
set(o, field, value);
}
}
public static A firstWithShortClassName(Iterable l, String name) {
if (l != null)
for (A a : l) if (shortClassNameIs(a, name))
return a;
return null;
}
public static A firstWithShortClassName(A[] l, String name) {
if (l != null)
for (A a : l) if (shortClassNameIs(a, name))
return a;
return null;
}
public static boolean cleanUp_interruptThreads;
public static void cleanUp(Object c) {
if (c == null)
return;
if (c instanceof Collection) {
cleanUp((Collection) c);
return;
}
if (c instanceof Map) {
for (Object o : keys((Map) c)) cleanUp(o);
for (Object o : values((Map) c)) cleanUp(o);
((Map) c).clear();
return;
}
try {
preCleanUp(c);
setOpt(c, "ping_pauseAll", false);
innerCleanUp(c);
pcallOpt(c, "finalize");
List androids = (List) getOpt(c, "record_list");
for (Object android : unnull(androids)) pcallOpt(android, "dispose");
List classes = (List) (getOpt(c, "hotwire_classes"));
if (classes != null)
for (WeakReference cc : classes) {
try {
cleanUp(cc.get());
} catch (Throwable __e) {
_handleException(__e);
}
}
if (cleanUp_interruptThreads) {
List threads = registeredThreads(c);
if (nempty(threads)) {
print("cleanUp: Interrupting " + n2(threads, "thread") + ": " + joinWithComma(allToString(threads)));
interruptThreads(threads);
}
}
} catch (Throwable __e) {
_handleException(__e);
}
setOpt(c, "cleaningUp_flag", false);
if (c instanceof Class && ((Class) c).getName().equals("main"))
retireClassLoader(((Class) c).getClassLoader());
}
public static void cleanUp(Collection l) {
if (l == null)
return;
for (Object c : l) cleanUp(c);
l.clear();
}
public static String lines(Collection lines) {
return fromLines(lines);
}
public static List lines(String s) {
return toLines(s);
}
public static void set(Object o, String field, Object value) {
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
f.setAccessible(true);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void set(Class c, String field, Object value) {
try {
Field f = set_findStaticField(c, field);
f.setAccessible(true);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
public static Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
public static A awtEvery(A component, long delay, Object r) {
swingEvery(component, delay, r);
return component;
}
public static A awtEvery(A component, long delay, long firstDelay, Object r) {
swingEvery(component, delay, firstDelay, r);
return component;
}
public static void awtEvery(RootPaneContainer frame, long delay, Object r) {
swingEvery(frame, delay, r);
}
public static A awtEvery(A component, double delaySeconds, Object r) {
return awtEvery(component, toMS(delaySeconds), r);
}
public static JPanel jSection(Component c) {
return jSection("", c);
}
public static JPanel jSection(final String title, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
border = BorderFactory.createTitledBorder(border, title);
JSection panel = new JSection(c);
panel.setBorder(border);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);\r\n bo...";
}
});
}
public static JPanel jSection(String title) {
return jSection(title, jpanel());
}
public static A moveCaretToEnd(A ta) {
setCaretPosition(ta, textAreaTextLength(ta));
return ta;
}
public static JTextArea typeWriterTextArea() {
return newTypeWriterTextArea();
}
public static JTextArea typeWriterTextArea(String text) {
return newTypeWriterTextArea(text);
}
public static String getPrintLog() {
return str(print_log);
}
public static boolean setText_opt = true;
public static A setText(A c, Object text) {
setText((Object) c, text);
return c;
}
public static A setText(final A c, Object text) {
final String s = strUnnull(text);
{
swing(new Runnable() {
public void run() {
try {
c.getEditor().setItem(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.getEditor().setItem(s);";
}
});
}
return c;
}
public static void setText(JLabel c, Object text) {
setText((Object) c, text);
}
public static JButton setText(JButton c, Object text) {
setText((Object) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text)));
return c;
}
public static A setText(final A c, Object text) {
if (c == null)
return null;
final String s = strUnnull(text);
{
swing(new Runnable() {
public void run() {
try {
if (!setText_opt || neq(callOpt(c, "getText"), s))
call(c, "setText", s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n call(c, \"setText\", s);";
}
});
}
return c;
}
public static void enableWordWrapForTextArea(final JTextArea ta) {
if (ta != null) {
swing(new Runnable() {
public void run() {
try {
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ta.setLineWrap(true);\r\n ta.setWrapStyleWord(true);";
}
});
}
}
public static StringBuffer liveLocalPrintLog_realMC(Object o) {
Object realMC = getMainClass(o);
if (realMC != mc())
return (StringBuffer) getOpt(realMC, "local_log");
return liveLocalPrintLog();
}
public static String dropTrailingBackslashR(String s) {
int i = l(s);
while (i > 0 && s.charAt(i - 1) == '\r') --i;
return substring(s, 0, i);
}
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 Set keySet(Map map) {
return map == null ? new HashSet() : map.keySet();
}
public static Set keySet(Object map) {
return keys((Map) map);
}
public static int loadTextFilePart_iterator_chunkSize = 65536;
public static Iterable loadTextFilePart_iterator(File file, long start, long end) {
try {
if (end - start <= loadTextFilePart_iterator_chunkSize)
return ll(loadTextFilePart(file, start, end));
final FileInputStream in = newFileInputStream(file);
in.skip(start);
final byte[] buf = new byte[loadTextFilePart_iterator_chunkSize];
final UTF8Processor p = new UTF8Processor();
return iteratorFF(new F0() {
public Object get() {
try {
String s = readChunkThroughUTF8Processor(p, in, buf);
if (nempty(s))
return s;
in.close();
return endMarker();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S s = readChunkThroughUTF8Processor(p, in, buf);\r\n //print(\"Chunk read: \" ...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static FixedRateTimer doEvery(long delay, final Object r) {
return doEvery(delay, delay, r);
}
public static FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
return timer;
}
public static FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
}
public static FixedRateTimer doEvery(double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), r);
}
public static int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
public static boolean hasLock(Lock lock) {
return ((ReentrantLock) lock).isHeldByCurrentThread();
}
public static long sysNow() {
ping();
return System.nanoTime() / 1000000;
}
public static int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
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 Class _run(String progID, String... args) {
Class main = hotwire(progID);
callMain(main, args);
return main;
}
public static void cancelAndInterruptThread(Thread t) {
if (t == null)
return;
cancelThread(t);
t.interrupt();
}
public static Map syncCIMap() {
return (Map) synchroMap(caseInsensitiveMap());
}
public static Flag dm_initErrorHandling_flag = new Flag();
public static void dm_initErrorHandling() {
raiseFlagAndDo(dm_initErrorHandling_flag, new Runnable() {
public void run() {
try {
_handleException_addHandler("dm_initErrorHandling_handler");
assertNull(_onRegisterThread);
_onRegisterThread = new VF1() {
public void get(Thread t) {
try {
DynModule m = dm_currentModule();
if (m == null)
printStackTrace("New thread made outside of a module");
else
m.ownTimer(t);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "DynModule m = dm_currentModule();\r\n if (m == null) printStackTrace(\"New ...";
}
};
_threadInfo_makers.add(new VF1() {
public void get(Map map) {
try {
mapPut(map, "dm_currentModule_value", dm_currentModule());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "mapPut(map, 'dm_currentModule_value, dm_currentModule())";
}
});
_threadInheritInfo_retrievers.add(new VF1() {
public void get(Map map) {
try {
Object mod = map.get("dm_currentModule_value");
if (mod instanceof DynModule)
dm_currentModule_value.set(new WeakReference((DynModule) mod));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "O mod = map.get('dm_currentModule_value);\r\n if (mod instanceof DynModule...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_handleException_addHandler(f dm_initErrorHandling_handler);\r\n \r\n asser...";
}
});
}
public static void dm_initErrorHandling_handler(Throwable e) {
DynModule m = dm_currentModule();
if (m == null)
print("Weird: Error outside of module");
else
m.setField("_error", persistableThrowable(e));
}
public static void setMainDesktopPane(JDesktopPane desktop) {
mainDesktopPane_value = desktop;
}
public static A getCreatorOpt(String field) {
return (A) getOpt(creator(), field);
}
public static A possiblyInternalFrameTitle(A c, String title) {
JInternalFrame f = getInternalFrame(c);
if (f != null)
internalFrameTitle(f, title);
else
frameTitle(getFrame(c), title);
return c;
}
public static Map getAndClearMap(Map map) {
if (map == null)
return emptyMap();
synchronized (collectionMutex(map)) {
Map out = cloneMap(map);
map.clear();
return out;
}
}
public static Object pcallFInRealOrMyMC(final Object realm, final Object f, final Object... args) {
try {
return callFInRealOrMyMC(realm, f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
public static A pcallFInRealOrMyMC(Object realm, F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
public static B pcallFInRealOrMyMC(Object realm, F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
public static B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
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(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 AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
public static AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
public static ThreadLocal realMC_tl_tl = new ThreadLocal();
public static ThreadLocal realMC_tl() {
return realMC_tl_tl;
}
public static AutoCloseable tempLock(final Lock lock) {
if (lock == null)
return null;
lock(lock);
return new AutoCloseable() {
public String toString() {
return "unlock(lock);";
}
public void close() throws Exception {
unlock(lock);
}
};
}
public static boolean addIfNotThere(Collection c, A a) {
return setAdd(c, a);
}
public static void onChange(JSpinner spinner, Object r) {
spinner.addChangeListener(changeListener(r));
}
public static A onChange(A b, Object r) {
b.addItemListener(itemListener(r));
return b;
}
public static void onChange(JTextComponent tc, Object r) {
onUpdate(tc, r);
}
public static void onChange(final JSlider slider, final Object r) {
{
swing(new Runnable() {
public void run() {
try {
slider.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "slider.addChangeListener(changeListener(r));";
}
});
}
}
public static void onChange(JComboBox cb, final Object r) {
if (isEditableComboBox(cb))
onChange(textFieldFromComboBox(cb), r);
else
onSelectedItem(cb, new VF1