e) {
return e == null ? null : new IterableIterator() {
public boolean hasNext() {
return e.hasMoreElements();
}
public A next() {
return e.nextElement();
}
};
}
public static Object swingCall(final Object o, final String method, final Object... args) {
return swing(new F0() {
public Object get() {
try {
return call(o, method, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret call(o, method, args);";
}
});
}
public static Color toColor(RGB rgb) {
return rgb == null ? null : rgb.getColor();
}
public static Color toColor(int rgb) {
return new Color(rgb);
}
public static Color toColor(String hex) {
return awtColor(hex);
}
public static void copyImagePart(BufferedImage src, int srcx, int srcy, BufferedImage dest, int destx, int desty, int w, int h) {
Graphics2D g = dest.createGraphics();
BufferedImage sub = src.getSubimage(srcx, srcy, w, h);
g.drawImage(sub, destx, desty, null);
g.dispose();
}
public static void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
public static boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
public static boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
public static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
public static boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
public static boolean containsNewLines(String s) {
return containsNewLine(s);
}
public static String jlabel_textAsHTML_center(String text) {
return "" + replace(htmlencode(text), "\n", " ") + "
";
}
public static String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
public static double fraction(double d) {
return d % 1;
}
public static String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
public static String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
public static String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
public static String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
public static String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
public static A 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 A setHorizontalAlignment(final int pos, final A a) {
swingCall(a, "setHorizontalAlignment", pos);
return a;
}
public static A setHorizontalAlignment(final int pos, final A a) {
swingCall(a, "setHorizontalAlignment", pos);
return a;
}
public static A setHorizontalAlignment(final int pos, final A a) {
swingCall(a, "setHorizontalAlignment", pos);
return a;
}
public static JLabel jLabel(String text) {
return jlabel(text);
}
public static JLabel jLabel() {
return jlabel();
}
public static JPanel centerAndNorth(final Component c, final Component n) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.NORTH, wrap(n));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT...";
}
});
}
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 void pcallF(VF1 f, A a) {
try {
if (f != null)
f.get(a);
} catch (Throwable __e) {
_handleException(__e);
}
}
public static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
public static void addActionListener(JTextField tf, final Runnable action) {
onEnter(tf, action);
}
public static void addActionListener(final JComboBox cb, final Runnable action) {
if (cb != null) {
swing(new Runnable() {
public void run() {
try {
cb.addActionListener(actionListener(action));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cb.addActionListener(actionListener(action));";
}
});
}
}
public static void addActionListener(final AbstractButton b, final Runnable action) {
if (b != null) {
swing(new Runnable() {
public void run() {
try {
b.addActionListener(actionListener(action));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "b.addActionListener(actionListener(action));";
}
});
}
}
public static String selectedItem(JList l) {
return getSelectedItem(l);
}
public static String selectedItem(JComboBox cb) {
return getSelectedItem(cb);
}
public static JComboBox jComboBox(final String... items) {
return jcombobox(items);
}
public static JComboBox jComboBox(Collection items) {
return jcombobox(items);
}
public static ThreadLocal bindComboBoxToLiveValue_debug = new ThreadLocal();
public static A bindComboBoxToLiveValue(final A cb, final SimpleLiveValue lv) {
final boolean debug = isTrue(bindComboBoxToLiveValue_debug.get());
bindLiveValueListenerToComponent(cb, lv, new Runnable() {
public void run() {
try {
selectItem(cb, lv.get());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "selectItem(cb, lv.get())";
}
});
onChange(cb, new Runnable() {
public void run() {
try {
String s = getText(cb);
if (debug)
print("ComboBox: " + s);
lv.set(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "String s = getText(cb); // also works on editable combo boxes\r\n if (debug)...";
}
});
return cb;
}
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 Class getFieldType(Object o, String field) {
return fieldType(o, field);
}
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 List toLinesFullTrim(String s) {
List l = new ArrayList();
for (String line : toLines(s)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
public static List toLinesFullTrim(File f) {
List l = new ArrayList();
for (String line : linesFromFile(f)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
public static Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
public static String joinWithSpace(Collection c) {
return join(" ", c);
}
public static String joinWithSpace(String... c) {
return join(" ", c);
}
public static boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
public static boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
public static void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, min(a.length, b.length));
}
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
public static A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
public static A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(Iterable strings) {
return join("", strings);
}
public static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
public static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
public static List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
public static boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
public static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
public static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
public static Thread currentThread() {
return Thread.currentThread();
}
public static A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
public static volatile PersistableThrowable _handleException_lastException;
public static List _handleException_onException = synchroList(ll("printStackTrace2"));
public static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3);
}
}
public static WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
public static TreeMap caseInsensitiveMap() {
return new TreeMap(caseInsensitiveComparator());
}
public static int max(int a, int b) {
return Math.max(a, b);
}
public static int max(int a, int b, int c) {
return max(max(a, b), c);
}
public static long max(int a, long b) {
return Math.max((long) a, b);
}
public static long max(long a, long b) {
return Math.max(a, b);
}
public static double max(int a, double b) {
return Math.max((double) a, b);
}
public static float max(float a, float b) {
return Math.max(a, b);
}
public static double max(double a, double b) {
return Math.max(a, b);
}
public static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
public static double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
public static float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
public static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
public static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
public static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
public static A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
return c;
}
public static JComponent componentToJComponent(Component c) {
if (c instanceof JComponent)
return (JComponent) c;
if (c instanceof JFrame)
return ((JFrame) c).getRootPane();
if (c == null)
return null;
throw fail("boohoo " + getClassName(c));
}
public static B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
public static B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
public static boolean even(int i) {
return (i & 1) == 0;
}
public static boolean even(long i) {
return (i & 1) == 0;
}
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 java.awt.Color awtColor(String hex) {
byte[] b = bytesFromHex(dropPrefix("#", hex));
return new Color(ubyteToInt(b[0]), ubyteToInt(b[1]), ubyteToInt(b[2]));
}
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 boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
public static boolean endsWithIgnoreCase(String a, String b) {
int la = l(a), lb = l(b);
return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
}
public static boolean endsWithIgnoreCase(String a, String b, Matches m) {
if (!endsWithIgnoreCase(a, b))
return false;
m.m = new String[] { substring(a, 0, l(a) - l(b)) };
return true;
}
public static boolean containsNewLine(String s) {
return contains(s, '\n');
}
public static String htmlencode(Object o) {
return htmlencode(str(o));
}
public static String htmlencode(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 > 127 || c == '"' || c == '<' || c == '>' || 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();
}
public static String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
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 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 Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
public static JTextField onEnter(final JTextField tf, final Object action) {
if (action == null || tf == null)
return tf;
tf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
tf.selectAll();
callF(action);
} catch (Throwable __e) {
messageBox(__e);
}
}
});
return tf;
}
public static JButton onEnter(JButton btn, final Object action) {
if (action == null || btn == null)
return btn;
btn.addActionListener(actionListener(action));
return btn;
}
public static JList onEnter(JList list, Object action) {
list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action)));
return list;
}
public static JComboBox onEnter(final JComboBox cb, final Object action) {
{
swing(new Runnable() {
public void run() {
try {
if (cb.isEditable()) {
JTextField text = (JTextField) cb.getEditor().getEditorComponent();
onEnter(text, action);
} else {
cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
cb.getActionMap().put("enter", abstractAction("", new Runnable() {
public void run() {
try {
cb.hidePopup();
callF(action);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cb.hidePopup(); callF(action);";
}
}));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (cb.isEditable()) {\r\n JTextField text = (JTextField) cb.getEditor().g...";
}
});
}
return cb;
}
public static JTable onEnter(final JTable table, final Object action) {
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
table.getActionMap().put("Enter", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
callF(action, table.getSelectedRow());
}
});
return table;
}
public static JTextField onEnter(Object action, JTextField tf) {
return onEnter(tf, action);
}
public static ActionListener actionListener(final Object runnable) {
return actionListener(runnable, null);
}
public 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 __1654 = holdInstance(instanceToHold);
try {
callF(runnable);
} finally {
_close(__1654);
}
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
public static String getSelectedItem(JList l) {
return (String) l.getSelectedValue();
}
public static String getSelectedItem(JComboBox cb) {
return strOrNull(cb.getSelectedItem());
}
public static JComboBox jcombobox(final String... items) {
return swing(new F0() {
public JComboBox get() {
try {
return new JComboBox(items);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret new JComboBox(items);";
}
});
}
public static JComboBox jcombobox(Collection items) {
return jcombobox(toStringArray(items));
}
public static JComboBox jcombobox(Collection items, String selectedItem) {
return selectItem(selectedItem, jcombobox(items));
}
public static A bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) {
if (lv != null)
bindToComponent(component, new Runnable() {
public void run() {
try {
lv.onChangeAndNow(listener);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef bindLiveValueListenerToComponent_debug\r\n print(\"bindLiveValueL...";
}
}, new Runnable() {
public void run() {
try {
lv.removeOnChangeListener(listener);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "lv.removeOnChangeListener(listener)";
}
});
return component;
}
public static JComboBox selectItem(final String item, final JComboBox cb) {
if (cb != null) {
swing(new Runnable() {
public void run() {
try {
cb.setSelectedItem(item);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cb.setSelectedItem(item);";
}
});
}
return cb;
}
public static JComboBox selectItem(final JComboBox cb, final String item) {
return selectItem(item, cb);
}
public static JList selectItem(JList list, A item) {
{
swing(new Runnable() {
public void run() {
try {
selectRow(list, jlist_indexOf(list, item));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "selectRow(list, jlist_indexOf(list, item));";
}
});
}
return list;
}
public static String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
public static String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
public static String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return l.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret l.getText();";
}
});
}
public static String getText(final JComboBox cb) {
if (cb == null)
return null;
if (isEditableComboBox(cb))
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
public static A printStackTrace(A e) {
print(getStackTrace(e));
return e;
}
public static void printStackTrace() {
printStackTrace(new Throwable());
}
public static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
public static void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
public static void lockOrFail(Lock lock, long timeout) {
try {
ping();
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ReentrantLock fairLock() {
return new ReentrantLock(true);
}
public static IterableIterator toLines(File f) {
return linesFromFile(f);
}
public static List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
public static int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
public static CloseableIterableIterator linesFromFile(File f) {
try {
if (!f.exists())
return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
return linesFromReader(utf8bufferedReader(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static CloseableIterableIterator linesFromFile(String path) {
return linesFromFile(newFile(path));
}
public static boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class)
return arg instanceof Boolean;
if (type == int.class)
return arg instanceof Integer;
if (type == long.class)
return arg instanceof Long;
if (type == float.class)
return arg instanceof Float;
if (type == short.class)
return arg instanceof Short;
if (type == char.class)
return arg instanceof Character;
if (type == byte.class)
return arg instanceof Byte;
if (type == double.class)
return arg instanceof Double;
return type.isInstance(arg);
}
public static int min(int a, int b) {
return Math.min(a, b);
}
public static long min(long a, long b) {
return Math.min(a, b);
}
public static float min(float a, float b) {
return Math.min(a, b);
}
public static float min(float a, float b, float c) {
return min(min(a, b), c);
}
public static double min(double a, double b) {
return Math.min(a, b);
}
public static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
public static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
public static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
public static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
public static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
public static A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
public static Object first(Object list) {
return first((Iterable) list);
}
public static A first(List list) {
return empty(list) ? null : list.get(0);
}
public static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
public static A first(IterableIterator i) {
return first((Iterator ) i);
}
public static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
public static A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
public static Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
public static A first(Pair p) {
return p == null ? null : p.a;
}
public static Throwable printStackTrace2(Throwable e) {
print(getStackTrace2(e));
return e;
}
public static void printStackTrace2() {
printStackTrace2(new Throwable());
}
public static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
public static String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
public static volatile boolean licensed_yes = true;
public static boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
public static void licensed_off() {
licensed_yes = false;
}
public static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
public static List synchroList(List l) {
return Collections.synchronizedList(l);
}
public static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
public static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
public static Throwable innerException(Throwable e) {
return getInnerException(e);
}
public static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
public static ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
public static Comparator caseInsensitiveComparator() {
return betterCIComparator();
}
public static Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
public static byte[] bytesFromHex(String s) {
return hexToBytes(s);
}
public static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
public static int ubyteToInt(byte b) {
return b & 0x0FF;
}
public static Runnable asRunnable(Object o) {
return toRunnable(o);
}
public static void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
public static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
public static 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 intToHex_flexLength(int i) {
return Integer.toHexString(i);
}
public static Map classForName_cache = synchroHashMap();
public static Class classForName(String name) {
try {
if (classForName_cache == null)
return Class.forName(name);
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 Object callFunction(Object f, Object... args) {
return callF(f, args);
}
public 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...";
}
});
}
}
public static void messageBox(Throwable e) {
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
public static KeyListener enterKeyListener(final Object action) {
return new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER)
pcallF(action);
}
};
}
public 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))";
}
};
}
public static AbstractAction abstractAction(String name, final Object runnable) {
return new AbstractAction(name) {
public void actionPerformed(ActionEvent evt) {
pcallF(runnable);
}
};
}
public static ThreadLocal> holdInstance_l = new ThreadLocal();
public static AutoCloseable holdInstance(Object o) {
if (o == null)
return null;
listThreadLocalAdd(holdInstance_l, o);
return new AutoCloseable() {
public void close() {
listThreadLocalPopLast(holdInstance_l);
}
};
}
public static String strOrNull(Object o) {
return o == null ? null : str(o);
}
public static String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++) a[i] = it.next();
return a;
}
public static String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
public static void selectRow(final JTable table, final int i) {
if (table != null) {
swing(new Runnable() {
public void run() {
try {
if (i >= 0 && i < table.getRowCount()) {
table.setRowSelectionInterval(i, i);
scrollRowToVisible(table, i);
} else
table.clearSelection();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (i >= 0 && i < table.getRowCount()) {\r\n table.setRowSelectionInterval...";
}
});
}
}
public static void selectRow(final JList list, final int i) {
if (list != null) {
swing(new Runnable() {
public void run() {
try {
if (i >= 0 && i < listRowCount(list))
list.setSelectedIndex(i);
else
list.clearSelection();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (i >= 0 && i < listRowCount(list))\r\n list.setSelectedIndex(i);\r\n e...";
}
});
}
}
public static int jlist_indexOf(JList list, A item) {
return swing(new F0() {
public Integer get() {
try {
ListModel model = list.getModel();
int n = model.getSize();
for (int i = 0; i < n; i++) if (eq(model.getElementAt(i), item))
return i;
return -1;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ListModel model = list.getModel();\r\n int n = model.getSize();\r\n for ...";
}
});
}
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 CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
public Object next() {
throw fail();
}
public boolean hasNext() {
return false;
}
};
public static CloseableIterableIterator emptyCloseableIterableIterator() {
return emptyCloseableIterableIterator_instance;
}
public static CloseableIterableIterator linesFromReader(Reader r) {
final BufferedReader br = bufferedReader(r);
return iteratorFromFunction_f0_autoCloseable(new F0() {
public String get() {
try {
return readLineFromReaderWithClose(br);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret readLineFromReaderWithClose(br);";
}
}, _wrapIOCloseable(r));
}
public static BufferedReader utf8bufferedReader(InputStream in) {
try {
return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static BufferedReader utf8bufferedReader(File f) {
try {
return utf8bufferedReader(newFileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
public static GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
public static File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
public static File newFile(String name) {
return name == null ? null : new File(name);
}
public static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
public static long parseLong(String s) {
if (empty(s))
return 0;
return Long.parseLong(dropSuffix("L", s));
}
public static long parseLong(Object s) {
return Long.parseLong((String) s);
}
public static Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
public static Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
public static Object collectionMutex(List l) {
return l;
}
public static Object collectionMutex(Object o) {
if (o instanceof List)
return 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 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 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 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 Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
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 boolean headless() {
return isHeadless();
}
public static String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
public static String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url)))
return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
public static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
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 void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null)
tl.set(l = new ArrayList());
l.add(a);
}
public 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;
}
public static void scrollRowToVisible(JTable t, int rowIndex) {
int colIndex = 0;
if (!(t.getParent() instanceof JViewport))
return;
JViewport viewport = (JViewport) t.getParent();
Rectangle rect = t.getCellRect(rowIndex, colIndex, true);
Rectangle viewRect = viewport.getViewRect();
int x = viewRect.x;
int y = viewRect.y;
if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)) {
} else if (rect.x < viewRect.x) {
x = rect.x;
} else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
x = rect.x - viewRect.width + rect.width;
}
if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)) {
} else if (rect.y < viewRect.y) {
y = rect.y;
} else if (rect.y > (viewRect.y + viewRect.height - rect.height)) {
y = rect.y - viewRect.height + rect.height;
}
viewport.setViewPosition(new Point(x, y));
}
public static int listRowCount(JList list) {
return list == null ? 0 : swing(new F0() {
public Integer get() {
try {
return list.getModel().getSize();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret list.getModel().getSize();";
}
});
}
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 BufferedReader bufferedReader(Reader r) {
return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
}
public static CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) {
class IFF2 extends CloseableIterableIterator {
public A a;
public boolean done = false;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
return _a;
}
public void getNext() {
if (done || a != null)
return;
a = f.get();
done = a == null;
}
public void close() throws Exception {
if (closeable != null)
closeable.close();
}
}
;
return new IFF2();
}
public static String readLineFromReaderWithClose(BufferedReader r) {
try {
String s = r.readLine();
if (s == null)
r.close();
return s;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
return c == null ? null : new AutoCloseable() {
public String toString() {
return "c.close();\r\n _registerIO(c, null, false);";
}
public void close() throws Exception {
c.close();
_registerIO(c, null, false);
}
};
}
public static A _registerIOWrap(A wrapper, Object wrapped) {
return wrapper;
}
public static FileInputStream newFileInputStream(File path) throws IOException {
return newFileInputStream(path.getPath());
}
public static FileInputStream newFileInputStream(String path) throws IOException {
FileInputStream f = new FileInputStream(path);
_registerIO(f, path, true);
return f;
}
public static int gzInputStream_defaultBufferSize = 65536;
public static GZIPInputStream gzInputStream(File f) {
try {
return gzInputStream(new FileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static GZIPInputStream gzInputStream(File f, int bufferSize) {
try {
return gzInputStream(new FileInputStream(f), bufferSize);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static GZIPInputStream gzInputStream(InputStream in) {
return gzInputStream(in, gzInputStream_defaultBufferSize);
}
public static GZIPInputStream gzInputStream(InputStream in, int bufferSize) {
try {
return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Throwable 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 String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
public static Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
public static String className(Object o) {
return getClassName(o);
}
public static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
public static 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 String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
public static String quote(String s) {
if (s == null)
return "null";
StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
quote_impl(s, out);
return out.toString();
}
public static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
public static int shorten_default = 100;
public static String shorten(String s) {
return shorten(s, shorten_default);
}
public static String shorten(String s, int max) {
return shorten(s, max, "...");
}
public static String shorten(String s, int max, String shortener) {
if (s == null)
return "";
if (max < 0)
return s;
return s.length() <= max ? s : substring(s, 0, min(s.length(), max - l(shortener))) + shortener;
}
public static String shorten(int max, String s) {
return shorten(s, max);
}
public static int parseHexChar(char c) {
if (c >= '0' && c <= '9')
return charDiff(c, '0');
if (c >= 'a' && c <= 'f')
return charDiff(c, 'a') + 10;
if (c >= 'A' && c <= 'F')
return charDiff(c, 'A') + 10;
return -1;
}
public static Class> 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 boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x))
return true;
return false;
}
public static boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
public static String hostNameFromURL(String url) {
try {
return new URL(url).getHost();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A popLast(List l) {
return liftLast(l);
}
public static void _registerIO(Object object, String path, boolean opened) {
}
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 boolean domainIsUnder(String domain, String mainDomain) {
return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
}
public static String theAGIBlueDomain() {
return "agi.blue";
}
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 char stringToChar(String s) {
if (l(s) != 1)
throw fail("bad stringToChar: " + s);
return firstChar(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 char firstChar(String s) {
return s.charAt(0);
}
public static String asString(Object o) {
return o == null ? null : o.toString();
}
public static class ChessOCR_SquareImagesCollector {
public Set imageMD5s = new HashSet();
public List allImages = syncList();
public VF2 onBoardFound;
public void loadImagesFromAGIBlue() {
for (Pair __34 : agiBlue_chess_trainingImagesWithPositions()) {
String name = pairA(__34);
String fen = pairB(__34);
Map map = pairsToCIMap(agiBlue_lookupMultipleKeys(agiBlue_chessBoardRecognitionTrainingImagesSliceID(), name, ll("Input image", "Segmenter used", "Chess board found", "Board location")));
if (!isYes(map.get("Chess board found"))) {
print("Chess board not found, skipping");
continue;
}
BufferedImage img = loadImage2(parseImageSnippetURL(map.get("input image")));
Rect r = safeUnstructRect(map.get("Board location"));
if (r == null) {
print("No board? Skipping");
continue;
}
print("Board: " + r.w + "*" + r.h);
callF(onBoardFound, name, r);
if (abs(r.w - r.h) > 3) {
print("Board not square, skipping");
continue;
}
BufferedImage board = clipBufferedImage(img, r);
List position = chess_parseFEN(fen);
printStruct("position", position);
List> squareImages = map2("cloneBufferedImage", bufferedImageMNGrid(board, 8, 8));
for (int row = 0; row < 8; row++) {
String fenLine = position.get(row);
List images = squareImages.get(row);
for (int col = 0; col < 8; col++) if (imageMD5s.add(imageMD5(images.get(col))))
allImages.add(new ChessOCR_PieceImage(chess_xyToSquare(col, row), chess_parseFENSymbol(fenLine.charAt(col)), images.get(col)));
}
}
print("Have " + n2(allImages, "chess square image"));
}
public List> allImages() {
return map(cloneList(allImages), i -> pair(i.piece, i.img));
}
}
public static final class _MethodCache {
public final Class c;
public final HashMap> cache = new HashMap();
public _MethodCache(Class c) {
this.c = c;
_init();
}
public void _init() {
Class _c = c;
while (_c != null) {
for (Method m : _c.getDeclaredMethods()) if (!reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
_c = _c.getSuperclass();
}
for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
}
public Method findMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public Method findStaticMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (isStaticMethod(me) && call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
public static class MultiMap {
public Map > data = new HashMap >();
public MultiMap() {
}
public MultiMap(boolean useTreeMap) {
if (useTreeMap)
data = new TreeMap();
}
public MultiMap(MultiMap map) {
putAll(map);
}
public MultiMap(Map > data) {
this.data = data;
}
public void put(A key, B value) {
synchronized (data) {
List list = data.get(key);
if (list == null)
data.put(key, list = _makeEmptyList());
list.add(value);
}
}
public void add(A key, B value) {
put(key, value);
}
public void addAll(A key, Collection values) {
putAll(key, values);
}
public void addAllIfNotThere(A key, Collection values) {
synchronized (data) {
for (B value : values) setPut(key, value);
}
}
public void setPut(A key, B value) {
synchronized (data) {
if (!containsPair(key, value))
put(key, value);
}
}
public boolean containsPair(A key, B value) {
synchronized (data) {
return get(key).contains(value);
}
}
public void putAll(A key, Collection values) {
synchronized (data) {
if (nempty(values))
getActual(key).addAll(values);
}
}
public void removeAll(A key, Collection values) {
synchronized (data) {
for (B value : values) remove(key, value);
}
}
public List get(A key) {
synchronized (data) {
List list = data.get(key);
return list == null ? Collections.emptyList() : list;
}
}
public List getActual(A key) {
synchronized (data) {
List list = data.get(key);
if (list == null)
data.put(key, list = _makeEmptyList());
return list;
}
}
public void clean(A key) {
synchronized (data) {
List list = data.get(key);
if (list != null && list.isEmpty())
data.remove(key);
}
}
public Set keySet() {
synchronized (data) {
return data.keySet();
}
}
public Set keys() {
synchronized (data) {
return data.keySet();
}
}
public void remove(A key) {
synchronized (data) {
data.remove(key);
}
}
public void remove(A key, B value) {
synchronized (data) {
List list = data.get(key);
if (list != null) {
list.remove(value);
if (list.isEmpty())
data.remove(key);
}
}
}
public void clear() {
synchronized (data) {
data.clear();
}
}
public boolean containsKey(A key) {
synchronized (data) {
return data.containsKey(key);
}
}
public B getFirst(A key) {
synchronized (data) {
List list = get(key);
return list.isEmpty() ? null : list.get(0);
}
}
public void addAll(MultiMap map) {
putAll(map);
}
public void putAll(MultiMap map) {
synchronized (data) {
for (A key : map.keySet()) putAll(key, map.get(key));
}
}
public void putAll(Map map) {
synchronized (data) {
if (map != null)
for (Map.Entry e : map.entrySet()) put(e.getKey(), e.getValue());
}
}
public int keysSize() {
synchronized (data) {
return l(data);
}
}
public int size() {
synchronized (data) {
int n = 0;
for (List l : data.values()) n += l(l);
return n;
}
}
public List reverseGet(B b) {
synchronized (data) {
List l = new ArrayList();
for (A key : data.keySet()) if (data.get(key).contains(b))
l.add(key);
return l;
}
}
public Map > asMap() {
synchronized (data) {
return cloneMap(data);
}
}
public boolean isEmpty() {
synchronized (data) {
return data.isEmpty();
}
}
public List _makeEmptyList() {
return new ArrayList();
}
public Collection> allLists() {
synchronized (data) {
return new ArrayList(data.values());
}
}
public List allValues() {
return concatLists(values(data));
}
public Object mutex() {
return data;
}
public String toString() {
return "mm" + str(data);
}
}
public static interface IF0 {
public A get();
}
public static class SimpleLiveValue extends LiveValue {
public Class type;
public volatile A value;
public transient List onChange = synchroList();
public SimpleLiveValue(Class type) {
this.type = type;
}
public SimpleLiveValue(Class type, A value) {
this.value = value;
this.type = type;
}
public Class getType() {
return type;
}
public A get() {
return value;
}
public void onChange(Runnable l) {
onChange.add(l);
}
public void onChangeAndNow(Runnable l) {
onChange(l);
callF(l);
}
public void removeOnChangeListener(Runnable l) {
onChange.remove(l);
}
public void fireChanged() {
pcallFAll(onChange);
}
public void set(A a) {
if (neq(value, a)) {
value = a;
fireChanged();
}
}
}
public abstract static class CloseableIterableIterator extends IterableIterator implements AutoCloseable {
public void close() throws Exception {
}
}
public static interface IF2 {
public C get(A a, B b);
}
public static class Var implements IVar {
public Var() {
}
public Var(A v) {
this.v = v;
}
public A v;
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() {
return v;
}
public synchronized boolean has() {
return v != null;
}
public synchronized void clear() {
v = null;
}
public String toString() {
return str(get());
}
}
public static class ReliableSingleThread implements Runnable {
public Object runnable;
public boolean trigger = false;
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 __1107 = callF(enter);
try {
thread = startThread(name, new Runnable() {
public void run() {
try {
AutoCloseable __1108 = callF(enter);
try {
_run();
} finally {
_close(__1108);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __1108 = callF(enter); try {\r\n _run();\r\n } finally ...";
}
});
} finally {
_close(__1107);
}
}
}
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 synchronized boolean triggered() {
return trigger;
}
public void cleanMeUp() {
cancel();
}
}
public abstract static class LiveValue {
public abstract Class getType();
public abstract A get();
public abstract void onChange(Runnable l);
public abstract void removeOnChangeListener(Runnable l);
public void onChangeAndNow(Runnable l) {
onChange(l);
callF(l);
}
}
public abstract static class IterableIterator implements Iterator , Iterable {
public Iterator iterator() {
return this;
}
public void remove() {
unsupportedOperation();
}
}
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 ChessOCR_PieceImage {
public static String _fieldOrder = "square piece img";
public String square;
public String piece;
public BufferedImage img;
public ChessOCR_PieceImage() {
}
public ChessOCR_PieceImage(String square, String piece, BufferedImage img) {
this.img = img;
this.piece = piece;
this.square = square;
}
public String toString() {
return "ChessOCR_PieceImage(" + square + ", " + piece + ", " + img + ")";
}
}
public abstract static class VF2 {
public abstract void get(A a, B b);
}
public static interface IVar {
public void set(A a);
public A get();
public boolean has();
public void clear();
}
public static List syncList() {
return synchroList();
}
public static List syncList(List l) {
return synchroList(l);
}
public static List> agiBlue_chess_trainingImagesWithPositions() {
return agiBlue_pagesAndValuesForKey(agiBlue_chessBoardRecognitionTrainingImagesSliceID(), "FEN");
}
public static A pairA(Pair p) {
return p == null ? null : p.a;
}
public static B pairB(Pair p) {
return p == null ? null : p.b;
}
public static Map pairsToCIMap(Collection extends Pair> l) {
Map map = ciMap();
if (l != null)
for (Pair p : l) map.put(p.a, p.b);
return map;
}
public static List> agiBlue_lookupMultipleKeys(String sliceID, String q, Collection keys) {
return map((List>) agiBlue_loadBotPage("lookupMultipleKeys", paramsPlus_noOverwrite(paramsWithSameKey("key", keys), "slice", sliceID, "q", q)), map -> pair(map.get("key"), map.get("value")));
}
public static String agiBlue_chessBoardRecognitionTrainingImagesSliceID() {
return "jxoivvjqucrsrque";
}
public static List isYes_yesses = litlist("y", "yes", "yeah", "y", "yup", "yo", "corect", "sure", "ok", "afirmative");
public static boolean isYes(String s) {
return isYes_yesses.contains(collapseWord(toLowerCase(get(parse3(s), 1))));
}
public static BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
public static BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
public static String parseImageSnippetURL(String url) {
String id = regexpExtract("\\d+$", url);
return id == null ? null : "#" + id;
}
public static Rect safeUnstructRect(String s) {
return (Rect) safeUnstructureAllowingRect(s);
}
public static float abs(float f) {
return Math.abs(f);
}
public static int abs(int i) {
return Math.abs(i);
}
public static double abs(double d) {
return Math.abs(d);
}
public static BufferedImage clipBufferedImage(BufferedImage src, Rectangle clip) {
return clipBufferedImage(src, new Rect(clip));
}
public static BufferedImage clipBufferedImage(BufferedImage src, Rect r) {
if (src == null || r == null)
return null;
r = intersectRects(r, new Rect(0, 0, src.getWidth(), src.getHeight()));
if (rectEmpty(r))
return null;
return src.getSubimage(r.x, r.y, r.w, r.h);
}
public static BufferedImage clipBufferedImage(BufferedImage src, int x, int y, int w, int h) {
return clipBufferedImage(src, new Rect(x, y, w, h));
}
public static List chess_parseFEN(String fen) {
List l = splitAtSlash(dropAfterSpace(fen));
if (l(l) != 8)
return null;
return map("chess_parseFENLine", l);
}
public static A printStruct(String prefix, A a) {
printStructure(prefix, a);
return a;
}
public static A printStruct(A a) {
printStructure(a);
return a;
}
public static List> map2(F1 f, Iterable> l) {
return mapTwoLevelsDown(f, l);
}
public static List> map2(Object f, Iterable> l) {
return mapTwoLevelsDown(f, l);
}
public static BufferedImage cloneBufferedImage(BufferedImage image) {
return copyImage(image);
}
public static List> bufferedImageMNGrid(int cols, int rows, BufferedImage img) {
List> out = new ArrayList();
for (List l : gridOfRects3(img.getWidth(), img.getHeight(), cols, rows)) out.add(map(r -> clipBufferedImage(img, r), l));
return out;
}
public static List> bufferedImageMNGrid(BufferedImage img, int cols, int rows) {
return bufferedImageMNGrid(cols, rows, img);
}
public static String imageMD5(BufferedImage img) {
return md5OfBufferedImage(img);
}
public static String chess_xyToSquare(int x, int y) {
return strCharPlus('A', x) + (8 - y);
}
public static String chess_parseFENSymbol(char c) {
if (isUpper(c))
return "white " + chess_parseFENSymbol2(lower(c));
else if (isLower(c))
return "black " + chess_parseFENSymbol2(c);
else
return "empty";
}
public static String chess_parseFENSymbol2(char c) {
if (c == 'k')
return "king";
if (c == 'q')
return "queen";
if (c == 'r')
return "rook";
if (c == 'n')
return "knight";
if (c == 'b')
return "bishop";
if (c == 'p')
return "pawn";
return str(c);
}
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 boolean reflection_isForbiddenMethod(Method m) {
return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}
public static void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
public static void multiMapPut(MultiMap mm, A key, B value) {
if (mm != null && key != null && value != null)
mm.put(key, value);
}
public static Field makeAccessible(Field f) {
f.setAccessible(true);
return f;
}
public static Method makeAccessible(Method m) {
m.setAccessible(true);
return m;
}
public static Set allInterfacesImplementedBy(Class c) {
if (c == null)
return null;
HashSet set = new HashSet();
allInterfacesImplementedBy_find(c, set);
return set;
}
public static void allInterfacesImplementedBy_find(Class c, Set set) {
if (c.isInterface() && !set.add(c))
return;
do {
for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set);
} while ((c = c.getSuperclass()) != null);
}
public static Method findMethod(Object o, String method, Object... args) {
return findMethod_cached(o, method, args);
}
public static boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
public static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
print("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) {
Object arg = args[i];
if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
if (debug)
print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
return false;
}
}
return true;
}
public static Method findStaticMethod(Class c, String method, Object... args) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (!m.getName().equals(method))
continue;
if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args))
continue;
return m;
}
c = c.getSuperclass();
}
return null;
}
public static boolean findStaticMethod_checkArgs(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length)
return false;
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i])))
return false;
return true;
}
public static Map putAll(Map a, Map extends A, ? extends B> b) {
if (a != null && b != null)
a.putAll(b);
return a;
}
public static void put(Map map, A a, B b) {
if (map != null)
map.put(a, b);
}
public static void put(List l, int i, A a) {
if (l != null && i >= 0 && i < l(l))
l.set(i, a);
}
public static void remove(List l, int i) {
if (l != null && i >= 0 && i < l(l))
l.remove(i);
}
public static void remove(Collection l, A a) {
if (l != null)
l.remove(a);
}
public static Set keySet(Map map) {
return map == null ? new HashSet() : map.keySet();
}
public static Set keySet(Object map) {
return keys((Map) map);
}
public static Set keySet(MultiSet ms) {
return ms.keySet();
}
public static Set keySet(MultiMap mm) {
return mm.keySet();
}
public static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
public static Set keys(Object map) {
return keys((Map) map);
}
public static Set keys(MultiSet ms) {
return ms.keySet();
}
public static Set keys(MultiMap mm) {
return mm.keySet();
}
public static A reverseGet(List l, int idx) {
if (l == null || idx < 0)
return null;
int n = l(l);
return idx < n ? l.get(n - 1 - idx) : null;
}
public static Map cloneMap(Map map) {
if (map == null)
return new HashMap();
synchronized (map) {
return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map);
}
}
public static List concatLists(Collection ... lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
public static List concatLists(Collection extends Collection > lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
public static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
public static Collection values(MultiMap mm) {
return mm == null ? emptyList() : concatLists(values(mm.data));
}
public static 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 Class _run(String progID, String... args) {
Class main = hotwire(progID);
callMain(main, args);
return main;
}
public static volatile boolean sleep_noSleep = false;
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 void cancelAndInterruptThread(Thread t) {
if (t == null)
return;
cancelThread(t);
t.interrupt();
}
public static Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
public static UnsupportedOperationException unsupportedOperation() {
throw new UnsupportedOperationException();
}
public static int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
public static List> agiBlue_pagesAndValuesForKey(String slice, String key) {
List> l = new ArrayList();
for (Map map : (List) loadJSONPage(agiBlueURL() + "/bot/entriesForKey" + hquery("slice", slice, "key", key))) l.add(pair((String) map.get("q"), (String) map.get("value")));
return l;
}
public static TreeMap ciMap() {
return caseInsensitiveMap();
}
public static Object agiBlue_loadBotPage(String cmd, Object... params) {
return loadJSONPage(agiBlueURL() + "/bot" + addSlashPrefix(cmd) + hquery(params));
}
public static Object[] paramsPlus_noOverwrite(Object[] a1, Object... a2) {
if (a2 == null || l(a2) == 2 && a2[0] == null)
return a1;
if (a1 == null)
return a2;
return concatArrays(assertEvenLength(a1), assertEvenLength(a2));
}
public static Object[] paramsWithSameKey(Object key, Collection values) {
return paramsWithSameKey(key, asObjectArray(values));
}
public static Object[] paramsWithSameKey(Object key, Object... values) {
int n = l(values);
Object[] o = new Object[n * 2];
for (int i = 0; i < n; i++) {
o[i * 2] = key;
o[i * 2 + 1] = values[i];
}
return o;
}
public static ArrayList litlist(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
public 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();
}
public static List toLowerCase(List strings) {
List x = new ArrayList();
for (String s : strings) x.add(s.toLowerCase());
return x;
}
public 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;
}
public static String toLowerCase(String s) {
return s == null ? "" : s.toLowerCase();
}
public static List parse3(String s) {
return dropPunctuation(javaTokPlusPeriod(s));
}
public static boolean loadBufferedImage_useImageCache = true;
public 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();
}
}
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"));
}
return image;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static BufferedImage loadBufferedImage(File file) {
try {
return file.isFile() ? ImageIO.read(file) : null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String regexpExtract(String pat, String s) {
if (s == null)
return null;
Matcher m = regexpMatcher(pat, s);
return m.find() ? m.group() : null;
}
public static Object safeUnstructureAllowingRect(String s) {
return safeUnstructureAllowingCertainClasses_preferUtils(s, "Rect");
}
public static Rect intersectRects(Rect a, Rect b) {
int x = max(a.x, b.x), y = max(a.y, b.y);
int x2 = min(a.x + a.w, b.x + b.w), y2 = min(a.y + a.h, b.y + b.h);
return new Rect(x, y, x2 - x, y2 - y);
}
public static boolean rectEmpty(Rect r) {
return r == null || r.w <= 0 || r.h <= 0;
}
public static List splitAtSlash(String s) {
return trimAll(asList(s.split("/")));
}
public static String dropAfterSpace(String s) {
return s == null ? null : substring(s, 0, smartIndexOf(s, ' '));
}
public static String chess_parseFENLine(String s) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < l(s); i++) {
char c = s.charAt(i);
if (isDigit(c))
buf.append(spaces(charDiff(c, '0')));
else
buf.append(c);
}
return str(buf);
}
public static void printStructure(String prefix, Object o) {
if (endsWithLetter(prefix))
prefix += ": ";
print(prefix + structureForUser(o));
}
public static void printStructure(Object o) {
print(structureForUser(o));
}
public static List> mapTwoLevelsDown(F1 f, Iterable> l) {
List> out = new ArrayList();
if (l != null)
for (List x : l) out.add(map(f, x));
return out;
}
public static List> mapTwoLevelsDown(Object f, Iterable> l) {
List> out = new ArrayList();
if (l != null)
for (List x : l) out.add((List) (List) map(f, x));
return out;
}
public static BufferedImage copyImage(BufferedImage bi) {
if (bi == null)
return null;
ColorModel cm = bi.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = bi.copyData(bi.getRaster().createCompatibleWritableRaster());
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
public static List> gridOfRects3(int w, int h, int cols, int rows) {
return gridOfRects3(new Rect(0, 0, w, h), cols, rows);
}
public static List> gridOfRects3(Rect r, int cols, int rows) {
List> l = new ArrayList();
for (int row = 0; row < rows; row++) {
List line = new ArrayList();
int y1 = r.y + iround(r.h * (double) row / rows);
int y2 = r.y + iround(r.h * (double) (row + 1) / rows);
for (int col = 0; col < cols; col++) {
int x1 = r.x + iround(r.w * (double) col / cols);
int x2 = r.x + iround(r.w * (double) (col + 1) / cols);
line.add(new Rect(x1, y1, x2 - x1, y2 - y1));
}
l.add(line);
}
return l;
}
public static String md5OfBufferedImage(BufferedImage img) {
return img == null ? null : rgbMD5(new RGBImage(img));
}
public static String strCharPlus(char a, int b) {
return str(charPlus(a, b));
}
public static boolean isUpper(char c) {
return isUpperCase(c);
}
public static String lower(String s) {
return s == null ? null : s.toLowerCase();
}
public static char lower(char c) {
return Character.toLowerCase(c);
}
public static boolean isLower(char c) {
return isLowerCase(c);
}
public static Method findMethod_cached(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
_MethodCache cache = callOpt_getCache(((Class) o));
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
return m;
return null;
} else {
_MethodCache cache = callOpt_getCache(o.getClass());
List methods = cache.cache.get(method);
if (methods != null)
for (Method m : methods) if (findMethod_checkArgs(m, args, false))
return m;
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Class> hotwire(String src) {
assertFalse(_inCore());
Class j = getJavaX();
if (isAndroid()) {
synchronized (j) {
List libraries = new ArrayList();
File srcDir = (File) call(j, "transpileMain", src, libraries);
if (srcDir == null)
throw fail("transpileMain returned null (src=" + quote(src) + ")");
Object androidContext = get(j, "androidContext");
return (Class) call(j, "loadx2android", srcDir, src);
}
} else {
Class c = (Class) (call(j, "hotwire", src));
hotwire_copyOver(c);
return c;
}
}
public static A callMain(A c, String... args) {
callOpt(c, "main", new Object[] { args });
return c;
}
public static void callMain() {
callMain(mc());
}
public static 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 void cancelThread(Thread t) {
if (t == null)
return;
ping();
synchronized (ping_actions) {
ping_actions.put(t, "cancelled");
ping_anyActions = true;
}
}
public static Iterator emptyIterator() {
return Collections.emptyIterator();
}
public static Object loadJSONPage(String url) {
return jsonDecode(loadPage(url));
}
public static boolean agiBlueURL_noHTTPS = false;
public static String agiBlueURL_url = "https://agi.blue";
public static String agiBlueURL() {
return agiBlueURL_noHTTPS ? replacePrefix("https://", "http://", agiBlueURL_url) : agiBlueURL_url;
}
public static String hquery(Map params) {
return htmlQuery(params);
}
public static String hquery(Object... data) {
return htmlQuery(data);
}
public static String addSlashPrefix(String s) {
return addPrefix("/", s);
}
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[] assertEvenLength(Object[] a) {
assertTrue(even(l(a)));
return a;
}
public static Object[] asObjectArray(Collection l) {
return toObjectArray(l);
}
public 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);
}
public static List dropPunctuation_keep = ll("*", "<", ">");
public static List dropPunctuation(List tok) {
tok = new ArrayList(tok);
for (int i = 1; i < tok.size(); i += 2) {
String t = tok.get(i);
if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) {
tok.set(i - 1, tok.get(i - 1) + tok.get(i + 1));
tok.remove(i);
tok.remove(i);
i -= 2;
}
}
return tok;
}
public static String dropPunctuation(String s) {
return join(dropPunctuation(nlTok(s)));
}
public static List javaTokPlusPeriod(String s) {
List tok = new ArrayList();
if (s == null)
return tok;
int l = s.length();
int i = 0;
while (i < l) {
int j = i;
char c;
String cc;
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j + 2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l)
break;
c = s.charAt(i);
cc = s.substring(i, Math.min(i + 2, l));
if (c == (char) 0x201C || c == (char) 0x201D)
c = '"';
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
char _c = s.charAt(j);
if (_c == (char) 0x201C || _c == (char) 0x201D)
_c = '"';
if (_c == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
if (j - 1 >= i + 1) {
tok.add(opener + s.substring(i + 1, j - 1) + opener);
i = j;
continue;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
else if (Character.isDigit(c))
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else if (cc.equals("[[")) {
do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (cc.equals("[=") && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else if (s.substring(j, Math.min(j + 3, l)).equals("..."))
j += 3;
else if (c == '$' || c == '#')
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
return tok;
}
public static boolean isURL(String s) {
return startsWithOneOf(s, "http://", "https://", "file:");
}
public static BufferedImage imageIO_readURL(String url) {
try {
if (startsWith(url, "https:"))
disableCertificateValidation();
return ImageIO.read(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean isAbsolutePath(String s) {
return s != null && new File(s).isAbsolute();
}
public static boolean isAbsolutePath(File f) {
return f != null && f.isAbsolute();
}
public static IResourceLoader vm_getResourceLoader() {
return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader"));
}
public static File imageSnippetsCacheDir() {
return javaxCachesDir("Image-Snippets");
}
public static String snippetImageURL_http(String snippetID) {
return snippetImageURL_http(snippetID, "png");
}
public static String snippetImageURL_http(String snippetID, String contentType) {
return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080");
}
public static Matcher regexpMatcher(String pat, String s) {
return compileRegexp(pat).matcher(unnull(s));
}
public static Object safeUnstructureAllowingCertainClasses_preferUtils(String s, String... allowedClasses) {
Set allowedClassesSet = new HashSet();
for (String name : unnull(allowedClasses)) {
allowedClassesSet.add("main$" + name);
allowedClassesSet.add("loadableUtils.utils$" + name);
}
Object classFinder = new F1() {
public Object get(String name) {
try {
if (!allowedClassesSet.contains(name))
throw fail("Class not allowed to unstructure: " + name);
if (name.startsWith("main$")) {
String name2 = "loadableUtils.utils$" + substring(name, 5);
Class c = classForNameOpt(name2);
if (c != null)
return c;
}
return classForName(name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!allowedClassesSet.contains(name)) fail(\"Class not allowed to unstructure...";
}
};
return unstructure(s, false, classFinder);
}
public static List trimAll(Collection