loadFont_cached_cache = new HashMap();
static synchronized Font loadFont_cached(String snippetID) { try {
snippetID = formatSnippetID(snippetID);
Font f = loadFont_cached_cache.get(snippetID);
if (f == null)
loadFont_cached_cache.put(snippetID, f = loadFont(snippetID, 12f));
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static synchronized Font loadFont_cached(String snippetID, float size) { try {
return loadFont_cached(snippetID).deriveFont(size);
} catch (Exception __e) { throw rethrow(__e); } }
static int iround(double d) {
return (int) Math.round(d);
}
static int iround(Number n) {
return iround(toDouble(n));
}
static float getSwingFontScale() {
return or((Float) vm_generalMap_get("swingFontScale_value"), 1f);
}
static A jenableUndoRedo(final A textcomp) {
{ swing(new Runnable() { public void run() { try {
final UndoManager undo = new UndoManager();
vm_generalWeakSet("Undo Managers").add(undo);
textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() { public void run() { try {
if (undo.canUndo()) undo.undo()
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canUndo()) undo.undo()"; }}));
textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() { public void run() { try {
if (undo.canRedo()) undo.redo()
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canRedo()) undo.redo()"; }}));
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new UndoManager undo;\r\n vm_generalWeakSet(\"Undo Managers\").add(undo)..."; }}); }
return textcomp;
}
static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static boolean swic(String a, String b, Matches m) {
if (!swic(a, b)) return false;
m.m = new String[] {substring(a, l(b))};
return true;
}
static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
static boolean containsNewLines(String s) {
return containsNewLine(s);
}
static String jlabel_textAsHTML_center(String text) {
return ""
+ replace(htmlencode2(text), "\n", "
")
+ "
";
}
static Object callOpt_withVarargs(Object o, String method, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me == null) {
// TODO: varargs
return null;
}
if ((me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
return null;
}
} catch (Exception __e) { throw rethrow(__e); } }
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null) for (A x : a) l.add(x);
return l;
}
static Throwable printStackTrace2(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace2(e));
return e;
}
static void printStackTrace2() {
printStackTrace2(new Throwable());
}
static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static Throwable innerException(Throwable e) {
return getInnerException(e);
}
static JTextField onEnter(final JTextField tf, final Object action) {
if (action == null || tf == null) return tf;
tf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
tf.selectAll();
callF(action);
} catch (Throwable __e) { messageBox(__e); }}});
return tf;
}
static JButton onEnter(JButton btn, final Object action) {
if (action == null || btn == null) return btn;
btn.addActionListener(actionListener(action));
return btn;
}
static JList onEnter(JList list, Object action) {
list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action)));
return list;
}
static JComboBox onEnter(final JComboBox cb, final Object action) {
{ swing(new Runnable() { public void run() { try {
if (cb.isEditable()) {
JTextField text = (JTextField) cb.getEditor().getEditorComponent();
onEnter(text, action);
} else {
cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
cb.getActionMap().put("enter", abstractAction("", new Runnable() { public void run() { try { cb.hidePopup(); callF(action);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.hidePopup(); callF(action);"; }}));
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (cb.isEditable()) {\r\n JTextField text = (JTextField) cb.getEditor().g..."; }}); }
return cb;
}
static JTable onEnter(final JTable table, final Object action) {
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
table.getActionMap().put("Enter", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
callF(action, table.getSelectedRow());
}
});
return table;
}
/*static JTextArea onEnter(final JTextArea ta, fO action) {
addKeyListener(ta, enterKeyListener(action));
ret ta;
}*/
static JTextField onEnter(Object action, JTextField tf) {
return onEnter(tf, action);
}
static ActionListener actionListener(final Object runnable) {
return actionListener(runnable, null);
}
static ActionListener actionListener(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener) return (ActionListener) runnable;
final Object info = _threadInfo();
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
_threadInheritInfo(info);
AutoCloseable __1 = holdInstance(instanceToHold); try {
callF(runnable);
} finally { _close(__1); }} catch (Throwable __e) { messageBox(__e); }}};
}
static String getSelectedItem(JList l) {
return (String) l.getSelectedValue();
}
static String getSelectedItem(JComboBox cb) {
return strOrNull(cb.getSelectedItem());
}
static A vm_generalMap_getOrCreate(Object key, F0 create) {
return vm_generalMap_getOrCreate(key, f0ToIF0(create));
}
static A vm_generalMap_getOrCreate(Object key, IF0 create) {
Map generalMap = vm_generalMap();
if (generalMap == null) return null; // must be x30 init
synchronized(generalMap) { // should switch to locks here
A a = (A) (vm_generalMap_get(key));
if (a == null)
vm_generalMap_put(key, a = create == null ? null : create.get());
return a;
}
}
static A printException(A e) {
printStackTrace(e);
return e;
}
static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static Throwable _storeException_value;
static void _storeException(Throwable e) {
_storeException_value = e;
}
static Set syncIdentityHashSet() {
return (Set) synchronizedSet(identityHashSet());
}
static Map syncHashMap() {
return synchroHashMap();
}
static Map vm_generalMap_map;
static Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
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;
}
static boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x)) return true; return false;
}
static boolean startsWithOneOf(String s, Matches m, String... l) {
for (String x : l) if (startsWith(s, x, m)) return true; return false;
}
static boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static String hostNameFromURL(String url) { try {
return new URL(url).getHost();
} catch (Exception __e) { throw rethrow(__e); } }
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) {
makeAccessible(f);
smartSet(f, o, value);
}
}
} catch (Exception __e) { throw rethrow(__e); } }
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) {
makeAccessible(f);
smartSet(f, null, value);
}
} catch (Exception __e) { throw rethrow(__e); } }
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;
}
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;
}
static void smartSet(Field f, Object o, Object value) throws Exception {
try {
f.set(o, value);
} catch (Exception e) {
Class type = f.getType();
// take care of common case (long to int)
if (type == int.class && value instanceof Long)
{ f.set(o, ((Long) value).intValue()); return; }
if (type == boolean.class && value instanceof String)
{ f.set(o, isTrueOrYes(((String) value))); return; }
if (type == LinkedHashMap.class && value instanceof Map)
{ f.set(o, asLinkedHashMap((Map) value)); return; }
throw e;
}
}
static A setDyn(A o, String key, Object value) {
setDynObjectValue(o, key, value);
return o;
}
static ClassLoader classLoaderForObject(Object o) {
if (o instanceof ClassLoader) return ((ClassLoader) o);
if (o == null) return null;
return _getClass(o).getClassLoader();
}
// Note: This is actually broken. Inner classes must stay with a $ separator
static String classNameToVM(String name) {
return name.replace(".", "$");
}
static void clear(Collection c) {
if (c != null) c.clear();
}
static void clear(Map map) {
if (map != null) map.clear();
}
static void put(Map map, A a, B b) {
if (map != null) map.put(a, b);
}
static void put(List l, int i, A a) {
if (l != null && i >= 0 && i < l(l)) l.set(i, a);
}
static B syncMapGet2(Map map, A a) {
if (map == null) return null;
synchronized(collectionMutex(map)) {
return map.get(a);
}
}
static B syncMapGet2(A a, Map map) {
return syncMapGet2(map, a);
}
static boolean isSubtypeOf(Class a, Class b) {
return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static Set reflection_classesNotToScan_value = litset(
"jdk.internal.loader.URLClassPath"
);
static Set reflection_classesNotToScan() {
return reflection_classesNotToScan_value;
}
static A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null) return null;
A old = tl.get();
tl.set(value);
return old;
}
static String className(Object o) {
return getClassName(o);
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static Font loadFont(String snippetID) { try {
return loadFont(snippetID, 12f);
} catch (Exception __e) { throw rethrow(__e); } }
static Font loadFont(InputStream in) { try {
return Font.createFont(Font.TRUETYPE_FONT, in);
} catch (Exception __e) { throw rethrow(__e); } }
static Font loadFont(String snippetID, float fontSize) {
return loadFont(loadLibrary(snippetID), fontSize);
}
static Font loadFont(File f, float fontSize) { try {
return Font.createFont(Font.TRUETYPE_FONT, f).deriveFont(fontSize);
} catch (Exception __e) { throw rethrow(__e); } }
static Font loadFont(InputStream in, float fontSize) { try {
return Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(fontSize);
} catch (Exception __e) { throw rethrow(__e); } }
static double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o instanceof String)
return parseDouble(((String) o));
if (o == null) return 0.0;
throw fail(o);
}
static Set vm_generalWeakSet(Object name) {
synchronized(get(javax(), "generalMap")) {
Set set = (Set) (vm_generalMap_get(name));
if (set == null)
vm_generalMap_put(name, set = newWeakHashSet());
return set;
}
}
static AbstractAction abstractAction(String name, final Object runnable) {
return new AbstractAction(name) {
public void actionPerformed(ActionEvent evt) {
pcallF(runnable);
}
};
}
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);"; }});
}
static boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static String substring(String s, int x) {
return substring(s, x, strL(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
int n = s.length();
if (y < x) y = x;
if (y > n) y = n;
if (x >= y) return "";
return s.substring(x, y);
}
// convenience method for quickly dropping a prefix
static String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
static boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la-lb, b, 0, lb);
}
static boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b)) return false;
if (m != null)
m.m = new String[] { substring(a, 0, l(a)-l(b)) };
return true;
}
static boolean containsNewLine(String s) {
return contains(s, '\n'); // screw \r, nobody needs it
}
static List replace(List l, A a, A b) {
for (int i = 0; i < l(l); i++)
if (eq(l.get(i), a))
l.set(i, b);
return l;
}
static List replace(A a, A b, List l) {
return replace(l, a, b);
}
// replace all occurrences of a in s with b
static String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
static String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
static String htmlencode2(String s) {
return htmlencode_noQuotes(s);
}
static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ",
hideCredentials(str(innerException2(e)))) + "\n");
}
static Throwable getInnerException(Throwable e) {
if (e == null) return null;
while (e.getCause() != null)
e = e.getCause();
return e;
}
static Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
static void messageBox(final String msg) {
if (headless()) print(msg);
else { swing(new Runnable() { public void run() { try {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES..."; }}); }
}
static void messageBox(Throwable e) {
//showConsole();
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
static KeyListener enterKeyListener(final Object action) {
return new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER)
pcallF(action);
}
};
}
static Runnable rCallOnSelectedListItem(final JList list, final Object action) {
return new Runnable() { public void run() { try { pcallF(action, getSelectedItem(list)) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, getSelectedItem(list))"; }};
}
static ThreadLocal> holdInstance_l = new ThreadLocal();
static AutoCloseable holdInstance(Object o) {
if (o == null) return null;
listThreadLocalAdd(holdInstance_l, o);
return new AutoCloseable() {
public void close() {
listThreadLocalPopLast(holdInstance_l);
}
};
}
static String strOrNull(Object o) {
return o == null ? null : str(o);
}
static IF0 f0ToIF0(F0 f) {
return f == null ? null : () -> f.get();
}
static Set synchronizedSet() {
return synchroHashSet();
}
static Set synchronizedSet(Set set) {
return Collections.synchronizedSet(set);
}
static Set identityHashSet() {
return Collections.newSetFromMap(new IdentityHashMap());
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b)) return false;
m.m = new String[] {substring(a, strL(b))};
return true;
}
static boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a)) return false;
for (int i = 0; i < listL(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
static String theAGIBlueDomain() {
return "agi.blue";
}
static boolean isTrueOrYes(Object o) {
return isTrueOpt(o) || o instanceof String && (eqicOneOf(((String) o), "1", "t", "true") || isYes(((String) o)));
}
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;
}
static void setDynObjectValue(DynamicObject o, String field, Object value) {
dynamicObject_setRawFieldValue(o, field, value);
}
static HashSet litset(A... items) {
return lithashset(items);
}
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;
}
static File loadLibrary(String snippetID) {
return loadBinarySnippet(snippetID);
}
static double parseDouble(String s) {
return Double.parseDouble(s);
}
static Set newWeakHashSet() {
return synchroWeakHashSet();
}
static Object nuObject(String className, Object... args) { try {
return nuObject(classForName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }
// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
ret nuObject(_getClass(realm, className), args);
}*/
static A nuObject(Class c, Object... args) { try {
if (args.length == 0) return nuObjectWithoutArguments(c); // cached!
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) { throw rethrow(__e); } }
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!" : ""));
}
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;
}
static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static int strL(String s) {
return s == null ? 0 : s.length();
}
static int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static String htmlencode_noQuotes(String s) {
if (s == null) return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '<') out.append("<");
else if (c == '>') out.append(">");
else if (c > 127 || c == '&') {
int cp = s.codePointAt(i);
out.append("");
out.append(intToHex_flexLength(cp));
out.append(';');
i += Character.charCount(cp)-1;
} else
out.append(c);
}
return out.toString();
}
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;
}
static String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix)) return s;
return replacement + substring(s, l(prefix));
}
static Throwable innerException2(Throwable e) {
if (e == null) return null;
while (empty(e.getMessage()) && e.getCause() != null)
e = e.getCause();
return e;
}
static Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
static boolean headless() {
return isHeadless();
}
static void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null) tl.set(l = new ArrayList());
l.add(a);
}
static A listThreadLocalPopLast(ThreadLocal> tl) {
List l = tl.get();
if (l == null) return null;
A a = popLast(l);
if (empty(l)) tl.set(null);
return a;
}
// TODO: OurSyncCollections
static Set synchroHashSet() {
return Collections.synchronizedSet(new HashSet());
}
static boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static int listL(Collection l) {
return l == null ? 0 : l.size();
}
static boolean eqic(String a, String b) {
if ((a == null) != (b == null)) return false;
if (a == null) return true;
return a.equalsIgnoreCase(b);
}
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);
}
static boolean isTrueOpt(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
return false;
}
static boolean eqicOneOf(String s, String... l) {
for (String x : l) if (eqic(s, x)) return true; return false;
}
static List isYes_yesses = litlist("y", "yes", "yeah", "y", "yup", "yo", "corect", "sure", "ok", "afirmative"); // << collapsed words, so "corect" means "correct"
static boolean isYes(String s) {
return isYes_yesses.contains(collapseWord(toLowerCase(get(parse3(s), 1))));
}
static void dynamicObject_setRawFieldValue(DynamicObject o, Object key, Object value) {
if (o == null) return;
// double sync, but should be OK here because of locking order o > o.fieldValues
synchronized(o) {
o.fieldValues = syncMapPut2_createLinkedHashMap((LinkedHashMap) o.fieldValues, key, value);
}
}
static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
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);
}
static File loadBinarySnippet(String snippetID) {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
return loadBinarySnippet_noResourceLoader(snippetID);
}
static File loadBinarySnippet_noResourceLoader(String snippetID) { try {
long id = parseSnippetID(snippetID);
if (isImageServerSnippet(id)) return loadImageAsFile(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (fileSize(f) == 0)
f = loadDataSnippetToFile_noResourceLoader(snippetID);
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static Set synchroWeakHashSet() {
return Collections.newSetFromMap((Map) newWeakHashMap());
}
static Map classForName_cache = synchroHashMap();
static Class classForName(String name) { try {
if (classForName_cache == null) return Class.forName(name); // in class init
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); } }
static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static Object nuObjectWithoutArguments(String className) { try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) { throw rethrow(__e); } }
static A nuObjectWithoutArguments(Class c) { try {
if (nuObjectWithoutArguments_cache == null)
// in class init
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); } }
static Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors())
if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
static String intToHex_flexLength(int i) {
return Integer.toHexString(i);
}
static A popLast(List l) {
return liftLast(l);
}
static List popLast(int n, List l) {
return liftLast(n, l);
}
static String asString(Object o) {
return o == null ? null : o.toString();
}
static ArrayList litlist(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
static String collapseWord(String s) {
if (s == null) return "";
StringBuilder buf = new StringBuilder();
for (int i = 0; i < l(s); i++)
if (i == 0 || !charactersEqualIC(s.charAt(i), s.charAt(i-1)))
buf.append(s.charAt(i));
return buf.toString();
}
static List toLowerCase(List strings) {
List x = new ArrayList();
for (String s : strings)
x.add(s.toLowerCase());
return x;
}
static String[] toLowerCase(String[] strings) {
String[] x = new String[l(strings)];
for (int i = 0; i < l(strings); i++)
x[i] = strings[i].toLowerCase();
return x;
}
static String toLowerCase(String s) {
return s == null ? "" : s.toLowerCase();
}
static List parse3(String s) {
return dropPunctuation(javaTokPlusPeriod(s));
}
static LinkedHashMap syncMapPut2_createLinkedHashMap(LinkedHashMap map, A key, B value) {
if (key != null)
if (value != null) {
if (map == null) map = new LinkedHashMap();
synchronized(collectionMutex(map)) { map.put(key, value); }
} else if (map != null) synchronized(collectionMutex(map)) { map.remove(key); }
return map;
}
static long parseLong(String s) {
if (empty(s)) return 0;
return Long.parseLong(dropSuffix("L", s));
}
static long parseLong(Object s) {
return Long.parseLong((String) s);
}
static IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
static boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
static File loadImageAsFile(String snippetIDOrURL) { try {
if (isURL(snippetIDOrURL))
throw fail("not implemented");
if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL);
String snippetID = "" + parseSnippetID(snippetIDOrURL);
File file = imageSnippetCacheFile(snippetID);
if (fileSize(file) > 0) return file;
String imageURL = snippetImageURL_noHttps(snippetID);
System.err.println("Loading image: " + imageURL);
byte[] data = loadBinaryPage(imageURL);
saveBinaryFile(file, data);
return file;
} catch (Exception __e) { throw rethrow(__e); } }
// If you change this, also change DiskSnippetCache_fileToLibID
static File DiskSnippetCache_file(long snippetID) {
return new File(getGlobalCache(), "data_" + snippetID + ".jar");
}
// Data files are immutable, use centralized cache
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);
}
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(tb_mainServer() + "/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;
}
static long fileSize(String path) { return getFileSize(path); }
static long fileSize(File f) { return getFileSize(f); }
static File loadDataSnippetToFile(String snippetID) { try {
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return rl.loadLibrary(snippetID);
return loadDataSnippetToFile_noResourceLoader(snippetID);
} catch (Exception __e) { throw rethrow(__e); } }
static File loadDataSnippetToFile_noResourceLoader(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(tb_mainServer() + "/blobs/" + psI(snippetID)));
print(e);
print("Trying other server: " + hideCredentials(url));
loadBinaryPageToFile(openConnection(url), f);
print("Got bytes: " + fileSize(f));
}
// TODO: check if we hit the "LOADING" message
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); } }
static A liftLast(List l) {
if (empty(l)) return null;
int i = l(l)-1;
A a = l.get(i);
l.remove(i);
return a;
}
static List liftLast(int n, List l) {
int i = l(l)-n;
List part = cloneSubList(l, i);
removeSubList(l, i);
return part;
}
static boolean charactersEqualIC(char c1, char c2) {
if (c1 == c2) return true;
char u1 = Character.toUpperCase(c1);
char u2 = Character.toUpperCase(c2);
if (u1 == u2) return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static List dropPunctuation_keep = ll("*", "<", ">");
static List dropPunctuation(List tok) {
tok = new ArrayList(tok);
for (int i = 1; i < tok.size(); i += 2) {
String t = tok.get(i);
if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) {
tok.set(i-1, tok.get(i-1) + tok.get(i+1));
tok.remove(i);
tok.remove(i);
i -= 2;
}
}
return tok;
}
static String dropPunctuation(String s) {
return join(dropPunctuation(nlTok(s)));
}
// This is made for NL parsing.
// It's javaTok extended with "..." token, "$n" and "#n" and
// special quotes (which are converted to normal ones).
static List javaTokPlusPeriod(String s) {
List tok = new ArrayList();
if (s == null) return tok;
int l = s.length();
int i = 0;
while (i < l) {
int j = i;
char c; String cc;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j+2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l) break;
c = s.charAt(i);
cc = s.substring(i, Math.min(i+2, l));
// scan for non-whitespace
if (c == (char) 0x201C || c == (char) 0x201D) c = '"'; // normalize quotes
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
char _c = s.charAt(j);
if (_c == (char) 0x201C || _c == (char) 0x201D) _c = '"'; // normalize quotes
if (_c == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
if (j-1 >= i+1) {
tok.add(opener + s.substring(i+1, j-1) + opener);
i = j;
continue;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // for things like "this one's"
else if (Character.isDigit(c))
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else if (cc.equals("[[")) {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (cc.equals("[=") && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else if (s.substring(j, Math.min(j+3, l)).equals("..."))
j += 3;
else if (c == '$' || c == '#')
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
return tok;
}
static boolean loadBufferedImage_useImageCache = true;
static BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) { try {
ping();
if (snippetIDOrURLOrFile == null) return null;
if (isURL(snippetIDOrURLOrFile))
return imageIO_readURL(snippetIDOrURLOrFile);
if (isAbsolutePath(snippetIDOrURLOrFile))
return loadBufferedImage(new File(snippetIDOrURLOrFile));
if (!isSnippetID(snippetIDOrURLOrFile))
throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile);
String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile);
IResourceLoader rl = vm_getResourceLoader();
if (rl != null)
return loadBufferedImage(rl.loadLibrary(snippetID));
File dir = imageSnippetsCacheDir();
if (loadBufferedImage_useImageCache) {
dir.mkdirs();
File file = new File(dir, snippetID + ".png");
if (file.exists() && file.length() != 0)
try {
return ImageIO.read(file);
} catch (Throwable e) {
e.printStackTrace();
// fall back to loading from sourceforge
}
}
String imageURL = snippetImageURL_http(snippetID);
print("Loading image: " + imageURL);
BufferedImage image = imageIO_readURL(imageURL);
if (loadBufferedImage_useImageCache) {
File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis());
ImageIO.write(image, "png", tempFile);
tempFile.renameTo(new File(dir, snippetID + ".png"));
//Log.info("Cached image.");
}
//Log.info("Loaded image.");
return image;
} catch (Exception __e) { throw rethrow(__e); } }
static BufferedImage loadBufferedImage(File file) { try {
return file.isFile() ? ImageIO.read(file) : null;
} catch (Exception __e) { throw rethrow(__e); } }
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static A proxy(Class intrface, final Object target) {
if (target == null) return null;
if (isInstance(intrface, target)) return (A) target;
return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(),
new Class[] { intrface },
new proxy_InvocationHandler(target));
}
static A proxy(Object target, Class intrface) {
return proxy(intrface, target);
}
static boolean isURL(String s) {
return startsWithOneOf(s, "http://", "https://", "file:");
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
static File imageSnippetCacheFile(String snippetID) {
File dir = imageSnippetsCacheDir();
if (!loadBufferedImage_useImageCache) return null;
return new File(dir, parseSnippetID(snippetID) + ".png");
}
static String snippetImageURL_noHttps(String snippetID) {
return snippetImageURL_noHttps(snippetID, "png");
}
static String snippetImageURL_noHttps(String snippetID, String contentType) {
return snippetImageURL(snippetID, contentType)
.replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/")
.replace("https://botcompany.de/", "http://botcompany.de/");
}
static ThreadLocal