import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.fail;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.tablePopupMenuFirst;
import static loadableUtils.utils.rowSorter_setComparators;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import static loadableUtils.utils.rethrow;
import static loadableUtils.utils.concepts_internStringsLongerThan;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF1;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.structure_ClassInfo;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.RC;
import loadableUtils.utils.IConceptIndex;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.Derefable;
import loadableUtils.utils.ImageSurfaceSelector;
import loadableUtils.utils.SimpleCRUD;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import loadableUtils.utils.DynImageSurface;
import loadableUtils.utils.DynCalculatedList;
import loadableUtils.utils.GlobalID;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import javax.swing.border.*;

class main {

  static public class ThreadCount extends DynBigNumber {

    public void start() {
      try {
        super.start();
        setDescription("THREADS");
        dm_doEveryAndNow(1.0, new Runnable() {

          public void run() {
            try {
              actualUpdate();
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "actualUpdate();";
          }
        });
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public void actualUpdate() {
      AutoCloseable __9 = enter();
      try {
        setValue(threadCount());
      } finally {
        _close(__9);
      }
    }
  }

  static public boolean _moduleClass_ThreadCount = true;

  static public String programID;

  static public void _onLoad_initUtils() {
    utils.__javax = javax();
  }

  static public void _onLoad_defaultClassFinder() {
    setDefaultClassFinder(new F1<String, Class>() {

      public Class get(String name) {
        Class c = findClass_fullName(name);
        if (c != null)
          return c;
        if (name.startsWith("main$"))
          return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
        return null;
      }
    });
  }

  static public FixedRateTimer dm_doEveryAndNow(int delay, Object r) {
    return dm_ownTimer(doEveryAndNow(delay, r));
  }

  static public FixedRateTimer dm_doEveryAndNow(double delaySeconds, Object r) {
    return dm_ownTimer(doEveryAndNow(delaySeconds, r));
  }

  static public int threadCount() {
    return threadMXBean().getThreadCount();
  }

  static public void _close(AutoCloseable c) {
    if (c != null)
      try {
        c.close();
      } catch (Throwable e) {
        if (c instanceof javax.imageio.stream.ImageOutputStream)
          return;
        else
          throw rethrow(e);
      }
  }

  static public Class javax() {
    return getJavaX();
  }

  static public void setDefaultClassFinder(Object cf) {
    _defaultClassFinder_value = cf;
  }

  static public HashMap<String, Class> findClass_fullName_cache = new HashMap();

  static public Class findClass_fullName(String name) {
    synchronized (findClass_fullName_cache) {
      if (findClass_fullName_cache.containsKey(name))
        return findClass_fullName_cache.get(name);
      Class c;
      try {
        c = Class.forName(name);
      } catch (ClassNotFoundException e) {
        c = null;
      }
      findClass_fullName_cache.put(name, c);
      return c;
    }
  }

  static public Object _defaultClassFinder_value = defaultDefaultClassFinder();

  static public Object _defaultClassFinder() {
    return _defaultClassFinder_value;
  }

  static public void dm_ownTimer(Object resource, Object closerHelper) {
    call(dm_current_generic(), "ownTimer", resource, closerHelper);
  }

  static public <A> A dm_ownTimer(A resource) {
    call(dm_current_generic(), "ownTimer", resource);
    return resource;
  }

  static public FixedRateTimer doEveryAndNow(int delay, Object r) {
    return doEveryStartingNow(delay, r);
  }

  static public FixedRateTimer doEveryAndNow(double delay, Object r) {
    return doEveryStartingNow(toInt(toMS(delay)), r);
  }

  static public ThreadMXBean threadMXBean() {
    return ManagementFactory.getThreadMXBean();
  }

  static public Class __javax;

  static public Class getJavaX() {
    try {
      return __javax;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Object defaultDefaultClassFinder() {
    return new F1<String, Class>() {

      public Class get(String name) {
        Class c = findClass_fullName(name);
        if (c != null)
          return c;
        if (name.startsWith("loadableUtils.utils$"))
          return findClass_fullName("main" + name.substring(19));
        return null;
      }
    };
  }

  static public Object callF(Object f, Object... args) {
    try {
      if (f instanceof String)
        return callMC((String) f, args);
      return x30_util.callF(f, args);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> A callF(F0<A> f) {
    return f == null ? null : f.get();
  }

  static public <A> A callF(IF0<A> f) {
    return f == null ? null : f.get();
  }

  static public <A, B> B callF(F1<A, B> f, A a) {
    return f == null ? null : f.get(a);
  }

  static public <A, B> B callF(IF1<A, B> f, A a) {
    return f == null ? null : f.get(a);
  }

  static public <A> void callF(VF1<A> f, A a) {
    if (f != null)
      f.get(a);
  }

  static public Object callMC(String method, Object... args) {
    return call(mc(), method, args);
  }

  static public Object call(Object o) {
    return callF(o);
  }

  static public Object call(Object o, String method, Object... args) {
    return call_withVarargs(o, method, args);
  }

  static public FixedRateTimer doEveryStartingNow(int delay, Object r) {
    return doEvery(delay, 0, r);
  }

  static public int toInt(Object o) {
    if (o == null)
      return 0;
    if (o instanceof Number)
      return ((Number) o).intValue();
    if (o instanceof String)
      return parseInt(((String) o));
    if (o instanceof Boolean)
      return boolToInt(((Boolean) o));
    throw fail("woot not int: " + getClassName(o));
  }

  static public int toInt(long l) {
    if (l != (int) l)
      throw fail("Too large for int: " + l);
    return (int) l;
  }

  static public long toMS(double seconds) {
    return (long) (seconds * 1000);
  }

  static public Class mc() {
    return main.class;
  }

  static public Object call_withVarargs(Object o, String method, Object... args) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class) {
        Class c = (Class) o;
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findStaticMethod(method, args);
        if (me != null)
          return invokeMethod(me, null, args);
        List<Method> methods = cache.cache.get(method);
        if (methods != null)
          methodSearch: for (Method m : methods) {
            {
              if (!(m.isVarArgs()))
                continue;
            }
            {
              if (!(isStaticMethod(m)))
                continue;
            }
            Object[] newArgs = massageArgsForVarArgsCall(m, args);
            if (newArgs != null)
              return invokeMethod(m, null, newArgs);
          }
        throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
      } else {
        Class c = o.getClass();
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(method, args);
        if (me != null)
          return invokeMethod(me, o, args);
        List<Method> methods = cache.cache.get(method);
        if (methods != null)
          methodSearch: for (Method m : methods) {
            {
              if (!(m.isVarArgs()))
                continue;
            }
            Object[] newArgs = massageArgsForVarArgsCall(m, args);
            if (newArgs != null)
              return invokeMethod(m, o, newArgs);
          }
        throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public FixedRateTimer doEvery(long delay, final Object r) {
    return doEvery(delay, delay, r);
  }

  static public FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
    FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
    timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
    return vmBus_timerStarted(timer);
  }

  static public FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
    return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
  }

  static public FixedRateTimer doEvery(double delaySeconds, final Object r) {
    return doEvery(toMS(delaySeconds), r);
  }

  static public int parseInt(String s) {
    return emptyString(s) ? 0 : Integer.parseInt(s);
  }

  static public int parseInt(char c) {
    return Integer.parseInt(str(c));
  }

  static public int boolToInt(boolean b) {
    return b ? 1 : 0;
  }

  static public String getClassName(Object o) {
    return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
  }

  static final public Map<Class, _MethodCache> callOpt_cache = newDangerousWeakHashMap();

  static public Object callOpt_cached(Object o, String methodName, Object... args) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class) {
        Class c = (Class) o;
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(methodName, args);
        if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
          return null;
        return invokeMethod(me, null, args);
      } else {
        Class c = o.getClass();
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(methodName, args);
        if (me == null)
          return null;
        return invokeMethod(me, o, args);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public _MethodCache callOpt_getCache(Class c) {
    synchronized (callOpt_cache) {
      _MethodCache cache = callOpt_cache.get(c);
      if (cache == null)
        callOpt_cache.put(c, cache = new _MethodCache(c));
      return cache;
    }
  }

  static public Object invokeMethod(Method m, Object o, Object... args) {
    try {
      try {
        return m.invoke(o, args);
      } catch (InvocationTargetException e) {
        throw rethrow(getExceptionCause(e));
      } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isStaticMethod(Method m) {
    return methodIsStatic(m);
  }

  static public Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
    Class<?>[] types = m.getParameterTypes();
    int n = types.length - 1, nArgs = args.length;
    if (nArgs < n)
      return null;
    for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
      return null;
    Class varArgType = types[n].getComponentType();
    for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
      return null;
    Object[] newArgs = new Object[n + 1];
    arraycopy(args, 0, newArgs, 0, n);
    Object[] varArgs = arrayOfType(varArgType, nArgs - n);
    arraycopy(args, n, varArgs, 0, nArgs - n);
    newArgs[n] = varArgs;
    return newArgs;
  }

  static public <A> String joinWithComma(Collection<A> c) {
    return join(", ", c);
  }

  static public String joinWithComma(String... c) {
    return join(", ", c);
  }

  static public List<String> classNames(Collection l) {
    return getClassNames(l);
  }

  static public List<String> classNames(Object[] l) {
    return getClassNames(Arrays.asList(l));
  }

  static public int shorten_default = 100;

  static public String shorten(String s) {
    return shorten(s, shorten_default);
  }

  static public String shorten(String s, int max) {
    return shorten(s, max, "...");
  }

  static public 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;
  }

  static public String shorten(int max, String s) {
    return shorten(s, max);
  }

  static public String programID() {
    return getProgramID();
  }

  static public String programID(Object o) {
    return getProgramID(o);
  }

  static public TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) {
    return new SmartTimerTask(r, timer, delay, _threadInfo());
  }

  static public class SmartTimerTask extends TimerTask implements IFieldsToList {

    public Object r;

    public java.util.Timer timer;

    public long delay;

    public Object threadInfo;

    public SmartTimerTask() {
    }

    public SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) {
      this.threadInfo = threadInfo;
      this.delay = delay;
      this.timer = timer;
      this.r = r;
    }

    public String toString() {
      return shortClassName(this) + "(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")";
    }

    public Object[] _fieldsToList() {
      return new Object[] { r, timer, delay, threadInfo };
    }

    public long lastRun;

    public void run() {
      if (!licensed())
        timer.cancel();
      else {
        _threadInheritInfo(threadInfo);
        AutoCloseable __1 = tempActivity(r);
        try {
          lastRun = fixTimestamp(lastRun);
          long now = now();
          if (now >= lastRun + delay * 0.9) {
            lastRun = now;
            if (eq(false, pcallF(r)))
              timer.cancel();
          }
        } finally {
          _close(__1);
        }
      }
    }
  }

  static public <A> A vmBus_timerStarted(A timer) {
    vmBus_send("timerStarted", timer, costCenter());
    return timer;
  }

  static public boolean emptyString(String s) {
    return s == null || s.length() == 0;
  }

  static public String str(Object o) {
    return o == null ? "null" : o.toString();
  }

  static public String str(char[] c) {
    return new String(c);
  }

  static public Throwable getExceptionCause(Throwable e) {
    Throwable c = e.getCause();
    return c != null ? c : e;
  }

  static public String joinWithSpace(Collection<String> c) {
    return join(" ", c);
  }

  static public String joinWithSpace(String... c) {
    return join(" ", c);
  }

  static public boolean methodIsStatic(Method m) {
    return (m.getModifiers() & Modifier.STATIC) != 0;
  }

  static public boolean argumentCompatibleWithType(Object arg, Class type) {
    return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
  }

  static public void arraycopy(Object[] a, Object[] b) {
    if (a != null && b != null)
      arraycopy(a, 0, b, 0, min(a.length, b.length));
  }

  static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
    if (n != 0)
      System.arraycopy(src, srcPos, dest, destPos, n);
  }

  static public <A> A[] arrayOfType(Class<A> type, int n) {
    return makeArray(type, n);
  }

  static public <A> A[] arrayOfType(int n, Class<A> type) {
    return arrayOfType(type, n);
  }

  public static <A> String join(String glue, Iterable<A> strings) {
    if (strings == null)
      return "";
    if (strings instanceof Collection) {
      if (((Collection) strings).size() == 1)
        return str(first(((Collection) strings)));
    }
    StringBuilder buf = new StringBuilder();
    Iterator<A> 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));
  }

  static public <A> String join(Iterable<A> strings) {
    return join("", strings);
  }

  static public <A> String join(Iterable<A> strings, String glue) {
    return join(glue, strings);
  }

  public static String join(String[] strings) {
    return join("", strings);
  }

  static public List<String> getClassNames(Collection l) {
    List<String> out = new ArrayList();
    if (l != null)
      for (Object o : l) out.add(o == null ? null : getClassName(o));
    return out;
  }

  static public String substring(String s, int x) {
    return substring(s, x, strL(s));
  }

  static public String substring(String s, int x, int y) {
    if (s == null)
      return null;
    if (x < 0)
      x = 0;
    if (x >= s.length())
      return "";
    if (y < x)
      y = x;
    if (y > s.length())
      y = s.length();
    return s.substring(x, y);
  }

  static public String substring(String s, CharSequence l) {
    return substring(s, l(l));
  }

  static public int min(int a, int b) {
    return Math.min(a, b);
  }

  static public long min(long a, long b) {
    return Math.min(a, b);
  }

  static public float min(float a, float b) {
    return Math.min(a, b);
  }

  static public float min(float a, float b, float c) {
    return min(min(a, b), c);
  }

  static public double min(double a, double b) {
    return Math.min(a, b);
  }

  static public double min(double[] c) {
    double x = Double.MAX_VALUE;
    for (double d : c) x = Math.min(x, d);
    return x;
  }

  static public float min(float[] c) {
    float x = Float.MAX_VALUE;
    for (float d : c) x = Math.min(x, d);
    return x;
  }

  static public byte min(byte[] c) {
    byte x = 127;
    for (byte d : c) if (d < x)
      x = d;
    return x;
  }

  static public short min(short[] c) {
    short x = 0x7FFF;
    for (short d : c) if (d < x)
      x = d;
    return x;
  }

  static public int min(int[] c) {
    int x = Integer.MAX_VALUE;
    for (int d : c) if (d < x)
      x = d;
    return x;
  }

  static public String getProgramID() {
    return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
  }

  static public String getProgramID(Class c) {
    String id = (String) getOpt(c, "programID");
    if (nempty(id))
      return formatSnippetID(id);
    return "?";
  }

  static public String getProgramID(Object o) {
    return getProgramID(getMainClass(o));
  }

  static public String shortClassName(Object o) {
    if (o == null)
      return null;
    Class c = o instanceof Class ? (Class) o : o.getClass();
    String name = c.getName();
    return shortenClassName(name);
  }

  static volatile public boolean licensed_yes = true;

  static public boolean licensed() {
    if (!licensed_yes)
      return false;
    ping_okInCleanUp();
    return true;
  }

  static public void licensed_off() {
    licensed_yes = false;
  }

  static public AutoCloseable tempActivity(Object r) {
    return null;
  }

  static public long fixTimestamp(long timestamp) {
    return timestamp > now() ? 0 : timestamp;
  }

  static public long now_virtualTime;

  static public long now() {
    return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
  }

  static public boolean eq(Object a, Object b) {
    return a == b || (a == null ? b == null : b != null && a.equals(b));
  }

  static public Object pcallF(Object f, Object... args) {
    return pcallFunction(f, args);
  }

  static public <A> A pcallF(F0<A> f) {
    try {
      return f == null ? null : f.get();
    } catch (Throwable __e) {
      return null;
    }
  }

  static public <A, B> B pcallF(F1<A, B> f, A a) {
    try {
      return f == null ? null : f.get(a);
    } catch (Throwable __e) {
      return null;
    }
  }

  static public <A> void pcallF(VF1<A> f, A a) {
    try {
      if (f != null)
        f.get(a);
    } catch (Throwable __e) {
      _handleException(__e);
    }
  }

  static public void vmBus_send(String msg, Object... args) {
    Object arg = vmBus_wrapArgs(args);
    pcallFAll(vm_busListeners_live(), msg, arg);
    pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
  }

  static public void vmBus_send(String msg) {
    vmBus_send(msg, (Object) null);
  }

  static public Object costCenter() {
    return mc();
  }

  static public 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);
  }

  static public <A> A[] makeArray(Class<A> type, int n) {
    return (A[]) Array.newInstance(type, n);
  }

  static public Object first(Object list) {
    return first((Iterable) list);
  }

  static public <A> A first(List<A> list) {
    return empty(list) ? null : list.get(0);
  }

  static public <A> A first(A[] bla) {
    return bla == null || bla.length == 0 ? null : bla[0];
  }

  static public <A> A first(Iterator<A> i) {
    return i == null || !i.hasNext() ? null : i.next();
  }

  static public <A> A first(Iterable<A> i) {
    if (i == null)
      return null;
    Iterator<A> it = i.iterator();
    return it.hasNext() ? it.next() : null;
  }

  static public Character first(String s) {
    return empty(s) ? null : s.charAt(0);
  }

  static public Byte first(byte[] l) {
    return empty(l) ? null : l[0];
  }

  static public int strL(String s) {
    return s == null ? 0 : s.length();
  }

  static public boolean nempty(Collection c) {
    return !empty(c);
  }

  static public boolean nempty(CharSequence s) {
    return !empty(s);
  }

  static public boolean nempty(Object[] o) {
    return !empty(o);
  }

  static public boolean nempty(byte[] o) {
    return !empty(o);
  }

  static public boolean nempty(int[] o) {
    return !empty(o);
  }

  static public boolean nempty(Map m) {
    return !empty(m);
  }

  static public boolean nempty(Iterator i) {
    return i != null && i.hasNext();
  }

  static public boolean nempty(Object o) {
    return !empty(o);
  }

  static public String formatSnippetIDOpt(String s) {
    return isSnippetID(s) ? formatSnippetID(s) : s;
  }

  static public String formatSnippetID(String id) {
    return "#" + parseSnippetID(id);
  }

  static public String formatSnippetID(long id) {
    return "#" + id;
  }

  static public Class getMainClass() {
    return mc();
  }

  static public Class getMainClass(Object o) {
    try {
      if (o == null)
        return null;
      if (o instanceof Class && eq(((Class) o).getName(), "x30"))
        return (Class) o;
      return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String shortenClassName(String name) {
    if (name == null)
      return null;
    int i = lastIndexOf(name, "$");
    if (i < 0)
      i = lastIndexOf(name, ".");
    return i < 0 ? name : substring(name, i + 1);
  }

  static public void ping_okInCleanUp() {
    if (ping_pauseAll || ping_anyActions)
      ping_impl(true);
  }

  static public Object pcallFunction(Object f, Object... args) {
    try {
      return callFunction(f, args);
    } catch (Throwable __e) {
      _handleException(__e);
    }
    return null;
  }

  static volatile public PersistableThrowable _handleException_lastException;

  static public List _handleException_onException = synchroList(ll("printStackTrace2"));

  static public 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);
    }
  }

  static public Object vmBus_wrapArgs(Object... args) {
    return empty(args) ? null : l(args) == 1 ? args[0] : args;
  }

  static public void pcallFAll(Collection l, Object... args) {
    if (l != null)
      for (Object f : cloneList(l)) pcallF(f, args);
  }

  static public void pcallFAll(Iterator it, Object... args) {
    while (it.hasNext()) pcallF(it.next(), args);
  }

  static public Set vm_busListeners_live_cache;

  static public Set vm_busListeners_live() {
    if (vm_busListeners_live_cache == null)
      vm_busListeners_live_cache = vm_busListeners_live_load();
    return vm_busListeners_live_cache;
  }

  static public Set vm_busListeners_live_load() {
    return vm_generalIdentityHashSet("busListeners");
  }

  static public Map<String, Set> vm_busListenersByMessage_live_cache;

  static public Map<String, Set> vm_busListenersByMessage_live() {
    if (vm_busListenersByMessage_live_cache == null)
      vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
    return vm_busListenersByMessage_live_cache;
  }

  static public Map<String, Set> vm_busListenersByMessage_live_load() {
    return vm_generalHashMap("busListenersByMessage");
  }

  static public Throwable printStackTrace2(Throwable e) {
    print(getStackTrace2(e));
    return e;
  }

  static public void printStackTrace2() {
    printStackTrace2(new Throwable());
  }

  static public void printStackTrace2(String msg) {
    printStackTrace2(new Throwable(msg));
  }

  static public boolean empty(Collection c) {
    return c == null || c.isEmpty();
  }

  static public boolean empty(CharSequence s) {
    return s == null || s.length() == 0;
  }

  static public boolean empty(Map map) {
    return map == null || map.isEmpty();
  }

  static public boolean empty(Object[] o) {
    return o == null || o.length == 0;
  }

  static public boolean empty(Object o) {
    if (o instanceof Collection)
      return empty((Collection) o);
    if (o instanceof String)
      return empty((String) o);
    if (o instanceof Map)
      return empty((Map) o);
    if (o instanceof Object[])
      return empty((Object[]) o);
    if (o instanceof byte[])
      return empty((byte[]) o);
    if (o == null)
      return true;
    throw fail("unknown type for 'empty': " + getType(o));
  }

  static public boolean empty(Iterator i) {
    return i == null || !i.hasNext();
  }

  static public boolean empty(double[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(float[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(int[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(long[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(byte[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(short[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(MultiSet ms) {
    return ms == null || ms.isEmpty();
  }

  static public boolean empty(File f) {
    return getFileSize(f) == 0;
  }

  public static boolean isSnippetID(String s) {
    try {
      parseSnippetID(s);
      return true;
    } catch (RuntimeException e) {
      return false;
    }
  }

  public static long parseSnippetID(String snippetID) {
    long id = Long.parseLong(shortenSnippetID(snippetID));
    if (id == 0)
      throw fail("0 is not a snippet ID");
    return id;
  }

  static public int lastIndexOf(String a, String b) {
    return a == null || b == null ? -1 : a.lastIndexOf(b);
  }

  static public int lastIndexOf(String a, char b) {
    return a == null ? -1 : a.lastIndexOf(b);
  }

  static volatile public boolean ping_pauseAll = false;

  static public int ping_sleep = 100;

  static volatile public boolean ping_anyActions = false;

  static public Map<Thread, Object> ping_actions = newWeakHashMap();

  static public ThreadLocal<Boolean> ping_isCleanUpThread = new ThreadLocal();

  static public boolean ping() {
    if (ping_pauseAll || ping_anyActions)
      ping_impl(true);
    return true;
  }

  static public boolean ping_impl(boolean okInCleanUp) {
    try {
      if (ping_pauseAll && !isAWTThread()) {
        do Thread.sleep(ping_sleep); while (ping_pauseAll);
        return true;
      }
      if (ping_anyActions) {
        if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
          failIfUnlicensed();
        Object action = null;
        synchronized (ping_actions) {
          if (!ping_actions.isEmpty()) {
            action = ping_actions.get(currentThread());
            if (action instanceof Runnable)
              ping_actions.remove(currentThread());
            if (ping_actions.isEmpty())
              ping_anyActions = false;
          }
        }
        if (action instanceof Runnable)
          ((Runnable) action).run();
        else if (eq(action, "cancelled"))
          throw fail("Thread cancelled.");
      }
      return false;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Object callFunction(Object f, Object... args) {
    return callF(f, args);
  }

  static public <A> List<A> synchroList() {
    return Collections.synchronizedList(new ArrayList<A>());
  }

  static public <A> List<A> synchroList(List<A> l) {
    return Collections.synchronizedList(l);
  }

  static public <A> List<A> ll(A... a) {
    ArrayList l = new ArrayList(a.length);
    if (a != null)
      for (A x : a) l.add(x);
    return l;
  }

  static public PersistableThrowable persistableThrowable(Throwable e) {
    return e == null ? null : new PersistableThrowable(e);
  }

  static public Throwable innerException(Throwable e) {
    return getInnerException(e);
  }

  static public <A> ArrayList<A> cloneList(Iterable<A> l) {
    return l instanceof Collection ? cloneList((Collection) l) : asList(l);
  }

  static public <A> ArrayList<A> cloneList(Collection<A> l) {
    if (l == null)
      return new ArrayList();
    synchronized (collectionMutex(l)) {
      return new ArrayList<A>(l);
    }
  }

  static volatile public StringBuffer local_log = new StringBuffer();

  static volatile public Appendable print_log = local_log;

  static volatile public int print_log_max = 1024 * 1024;

  static volatile public int local_log_max = 100 * 1024;

  static public boolean print_silent = false;

  static public Object print_byThread_lock = new Object();

  static volatile public ThreadLocal<Object> print_byThread;

  static volatile public Object print_allThreads;

  static volatile public Object print_preprocess;

  static public void print() {
    print("");
  }

  static public <A> A print(String s, A o) {
    print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
    return o;
  }

  static public <A> A print(A o) {
    ping_okInCleanUp();
    if (print_silent)
      return o;
    String s = String.valueOf(o) + "\n";
    print_noNewLine(s);
    return o;
  }

  static public void print_noNewLine(String s) {
    Object f = getThreadLocal(print_byThread_dontCreate());
    if (f == null)
      f = print_allThreads;
    if (f != null)
      if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
        return;
    print_raw(s);
  }

  static public void print_raw(String s) {
    if (print_preprocess != null)
      s = (String) callF(print_preprocess, s);
    s = fixNewLines(s);
    Appendable loc = local_log;
    Appendable buf = print_log;
    int loc_max = print_log_max;
    if (buf != loc && buf != null) {
      print_append(buf, s, print_log_max);
      loc_max = local_log_max;
    }
    if (loc != null)
      print_append(loc, s, loc_max);
    System.out.print(s);
  }

  static public void print_autoRotate() {
  }

  static public String getStackTrace2(Throwable e) {
    return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
  }

  static public String getType(Object o) {
    return getClassName(o);
  }

  static public long getFileSize(String path) {
    return path == null ? 0 : new File(path).length();
  }

  static public long getFileSize(File f) {
    return f == null ? 0 : f.length();
  }

  static public 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 public boolean isAWTThread() {
    if (isAndroid())
      return false;
    if (isHeadless())
      return false;
    return isAWTThread_awt();
  }

  static public boolean isAWTThread_awt() {
    return SwingUtilities.isEventDispatchThread();
  }

  static public void failIfUnlicensed() {
    assertTrue("license off", licensed());
  }

  static public Thread currentThread() {
    return Thread.currentThread();
  }

  static public Throwable getInnerException(Throwable e) {
    if (e == null)
      return null;
    while (e.getCause() != null) e = e.getCause();
    return e;
  }

  static public Throwable getInnerException(Runnable r) {
    return getInnerException(getException(r));
  }

  static public <A> ArrayList<A> asList(A[] a) {
    return a == null ? new ArrayList<A>() : new ArrayList<A>(Arrays.asList(a));
  }

  static public ArrayList<Integer> asList(int[] a) {
    if (a == null)
      return null;
    ArrayList<Integer> l = emptyList(a.length);
    for (int i : a) l.add(i);
    return l;
  }

  static public ArrayList<Float> asList(float[] a) {
    if (a == null)
      return null;
    ArrayList<Float> l = emptyList(a.length);
    for (float i : a) l.add(i);
    return l;
  }

  static public ArrayList<Double> asList(double[] a) {
    if (a == null)
      return null;
    ArrayList<Double> l = emptyList(a.length);
    for (double i : a) l.add(i);
    return l;
  }

  static public <A> ArrayList<A> asList(Iterable<A> s) {
    if (s instanceof ArrayList)
      return (ArrayList) s;
    ArrayList l = new ArrayList();
    if (s != null)
      for (A a : s) l.add(a);
    return l;
  }

  static public <A> ArrayList<A> asList(Enumeration<A> e) {
    ArrayList l = new ArrayList();
    if (e != null)
      while (e.hasMoreElements()) l.add(e.nextElement());
    return l;
  }

  static public Object collectionMutex(List l) {
    return l;
  }

  static public 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;
  }

  static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1<String, Boolean> f) {
    return print_byThread().get() == null ? tempInterceptPrint(f) : null;
  }

  static public boolean endsWithLetterOrDigit(String s) {
    return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
  }

  static public Object getThreadLocal(Object o, String name) {
    ThreadLocal t = (ThreadLocal) (getOpt(o, name));
    return t != null ? t.get() : null;
  }

  static public <A> A getThreadLocal(ThreadLocal<A> tl) {
    return tl == null ? null : tl.get();
  }

  static public <A> A getThreadLocal(ThreadLocal<A> tl, A defaultValue) {
    return or(getThreadLocal(tl), defaultValue);
  }

  static public ThreadLocal<Object> print_byThread_dontCreate() {
    return print_byThread;
  }

  static public boolean isFalse(Object o) {
    return eq(false, o);
  }

  static public String fixNewLines(String s) {
    int i = indexOf(s, '\r');
    if (i < 0)
      return s;
    int l = s.length();
    StringBuilder out = new StringBuilder(l);
    out.append(s, 0, i);
    for (; i < l; i++) {
      char c = s.charAt(i);
      if (c != '\r')
        out.append(c);
      else {
        out.append('\n');
        if (i + 1 < l && s.charAt(i + 1) == '\n')
          ++i;
      }
    }
    return out.toString();
  }

  static public void print_append(Appendable buf, String s, int max) {
    try {
      synchronized (buf) {
        buf.append(s);
        if (buf instanceof StringBuffer)
          rotateStringBuffer(((StringBuffer) buf), max);
        else if (buf instanceof StringBuilder)
          rotateStringBuilder(((StringBuilder) buf), max);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public String hideCredentials(URL url) {
    return url == null ? null : hideCredentials(str(url));
  }

  static public 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=<hidden>");
  }

  static public String hideCredentials(Object o) {
    return hideCredentials(str(o));
  }

  static public String getStackTrace(Throwable throwable) {
    lastException(throwable);
    return getStackTrace_noRecord(throwable);
  }

  static public String getStackTrace_noRecord(Throwable throwable) {
    StringWriter writer = new StringWriter();
    throwable.printStackTrace(new PrintWriter(writer));
    return hideCredentials(writer.toString());
  }

  static public String getStackTrace() {
    return getStackTrace_noRecord(new Throwable());
  }

  static public 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 public String replacePrefix(String prefix, String replacement, String s) {
    if (!startsWith(s, prefix))
      return s;
    return replacement + substring(s, l(prefix));
  }

  static public Throwable innerException2(Throwable e) {
    if (e == null)
      return null;
    while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
    return e;
  }

  static public long parseLong(String s) {
    if (empty(s))
      return 0;
    return Long.parseLong(dropSuffix("L", s));
  }

  static public long parseLong(Object s) {
    return Long.parseLong((String) s);
  }

  static public Throwable getException(Runnable r) {
    try {
      callF(r);
      return null;
    } catch (Throwable e) {
      return e;
    }
  }

  static public ArrayList emptyList() {
    return new ArrayList();
  }

  static public ArrayList emptyList(int capacity) {
    return new ArrayList(max(0, capacity));
  }

  static public ArrayList emptyList(Iterable l) {
    return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
  }

  static public ArrayList emptyList(Object[] l) {
    return emptyList(l(l));
  }

  static public <A> ArrayList<A> emptyList(Class<A> c) {
    return new ArrayList();
  }

  static public String className(Object o) {
    return getClassName(o);
  }

  static public boolean eqOneOf(Object o, Object... l) {
    for (Object x : l) if (eq(o, x))
      return true;
    return false;
  }

  static public ThreadLocal<Object> print_byThread() {
    synchronized (print_byThread_lock) {
      if (print_byThread == null)
        print_byThread = new ThreadLocal();
    }
    return print_byThread;
  }

  static public AutoCloseable tempInterceptPrint(F1<String, Boolean> f) {
    return tempSetThreadLocal(print_byThread(), f);
  }

  static public <A> A or(A a, A b) {
    return a != null ? a : b;
  }

  static public void rotateStringBuffer(StringBuffer buf, int max) {
    try {
      if (buf == null)
        return;
      synchronized (buf) {
        if (buf.length() <= max)
          return;
        try {
          int newLength = max / 2;
          int ofs = buf.length() - newLength;
          String newString = buf.substring(ofs);
          buf.setLength(0);
          buf.append("[...] ").append(newString);
        } catch (Exception e) {
          buf.setLength(0);
        }
        buf.trimToSize();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void rotateStringBuilder(StringBuilder buf, int max) {
    try {
      if (buf == null)
        return;
      synchronized (buf) {
        if (buf.length() <= max)
          return;
        try {
          int newLength = max / 2;
          int ofs = buf.length() - newLength;
          String newString = buf.substring(ofs);
          buf.setLength(0);
          buf.append("[...] ").append(newString);
        } catch (Exception e) {
          buf.setLength(0);
        }
        buf.trimToSize();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean startsWithOneOf(String s, String... l) {
    for (String x : l) if (startsWith(s, x))
      return true;
    return false;
  }

  static public boolean isAGIBlueDomain(String domain) {
    return domainIsUnder(domain, theAGIBlueDomain());
  }

  static public String hostNameFromURL(String url) {
    try {
      return new URL(url).getHost();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static volatile public PersistableThrowable lastException_lastException;

  static public PersistableThrowable lastException() {
    return lastException_lastException;
  }

  static public void lastException(Throwable e) {
    lastException_lastException = persistableThrowable(e);
  }

  static public boolean startsWith(String a, String b) {
    return a != null && a.startsWith(b);
  }

  static public boolean startsWith(String a, char c) {
    return nemptyString(a) && a.charAt(0) == c;
  }

  static public 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 public 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 public String dropSuffix(String suffix, String s) {
    return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
  }

  static public int max(int a, int b) {
    return Math.max(a, b);
  }

  static public int max(int a, int b, int c) {
    return max(max(a, b), c);
  }

  static public long max(int a, long b) {
    return Math.max((long) a, b);
  }

  static public long max(long a, long b) {
    return Math.max(a, b);
  }

  static public double max(int a, double b) {
    return Math.max((double) a, b);
  }

  static public float max(float a, float b) {
    return Math.max(a, b);
  }

  static public double max(double a, double b) {
    return Math.max(a, b);
  }

  static public int max(Collection<Integer> c) {
    int x = Integer.MIN_VALUE;
    for (int i : c) x = max(x, i);
    return x;
  }

  static public 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;
  }

  static public 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;
  }

  static public byte max(byte[] c) {
    byte x = -128;
    for (byte d : c) if (d > x)
      x = d;
    return x;
  }

  static public short max(short[] c) {
    short x = -0x8000;
    for (short d : c) if (d > x)
      x = d;
    return x;
  }

  static public int max(int[] c) {
    int x = Integer.MIN_VALUE;
    for (int d : c) if (d > x)
      x = d;
    return x;
  }

  static public <A> AutoCloseable tempSetThreadLocal(final ThreadLocal<A> tl, A a) {
    if (tl == null)
      return null;
    final A prev = setThreadLocal(tl, a);
    return new AutoCloseable() {

      public String toString() {
        return "tl.set(prev);";
      }

      public void close() throws Exception {
        tl.set(prev);
      }
    };
  }

  static public boolean domainIsUnder(String domain, String mainDomain) {
    return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
  }

  static public String theAGIBlueDomain() {
    return "agi.blue";
  }

  static public boolean nemptyString(String s) {
    return s != null && s.length() > 0;
  }

  static public int listL(Collection l) {
    return l == null ? 0 : l.size();
  }

  static public boolean neq(Object a, Object b) {
    return !eq(a, b);
  }

  static public <A> A setThreadLocal(ThreadLocal<A> tl, A value) {
    if (tl == null)
      return null;
    A old = tl.get();
    tl.set(value);
    return old;
  }

  static public boolean eqic(String a, String b) {
    if ((a == null) != (b == null))
      return false;
    if (a == null)
      return true;
    return a.equalsIgnoreCase(b);
  }

  static public 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 public boolean ewic(String a, String b) {
    return endsWithIgnoreCase(a, b);
  }

  static public boolean ewic(String a, String b, Matches m) {
    return endsWithIgnoreCase(a, b, m);
  }

  static public String asString(Object o) {
    return o == null ? null : o.toString();
  }

  static public boolean endsWithIgnoreCase(String a, String b) {
    int la = l(a), lb = l(b);
    return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
  }

  static public 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;
  }

  static public boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
    return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
  }

  final static public class _MethodCache {

    final public Class c;

    final public HashMap<String, List<Method>> 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<Method> 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<Method> 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);
      }
    }
  }

  static public interface IFieldsToList {

    public Object[] _fieldsToList();
  }

  abstract static public class DynBigNumber extends DynModule {

    public String description;

    public Object value;

    public int fontSize = 40;

    public String toolTip;

    transient public JLabel label;

    transient public SimpleLiveValue<String> lvText = new SimpleLiveValue(String.class);

    transient public SimpleLiveValue<String> lvDesc = new SimpleLiveValue(String.class);

    public boolean setValue(Object value) {
      boolean changed = setField("value", value);
      makeTexts();
      return changed;
    }

    public void setDescription(String desc) {
      setField("description", desc);
      makeTexts();
    }

    public Object getValue() {
      return value;
    }

    public String getDescription() {
      return description;
    }

    public void setToolTip(String toolTip) {
      setField("toolTip", toolTip);
    }

    public void doPersist() {
      _persistenceInfo = mapMinusOrNull(_persistenceInfo, "value");
    }

    public void makeTexts() {
      lvText.set(value == null ? "-" : str(value));
      lvDesc.set(description);
    }

    public void start() {
      try {
        super.start();
        _persistenceInfo = mapPlus(_persistenceInfo, "value", false);
        makeTexts();
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public JComponent visualize() {
      return bindToolTipToLiveValue(dm_fieldLiveValue("toolTip"), jLiveValueSection(lvDesc, centerLabel(makeBold(setFontSize(fontSize, label = jLiveValueLabel(lvText))))));
    }
  }

  static public class FixedRateTimer extends java.util.Timer {

    public FixedRateTimer() {
      this(false);
    }

    public FixedRateTimer(boolean daemon) {
      this(defaultTimerName(), daemon);
    }

    public FixedRateTimer(String name) {
      this(name, false);
    }

    public FixedRateTimer(String name, boolean daemon) {
      super(name, daemon);
      _registerTimer(this);
    }

    public List<Entry> entries = synchroList();

    static public class Entry implements IFieldsToList {

      public TimerTask task;

      public long firstTime;

      public long period;

      public Entry() {
      }

      public Entry(TimerTask task, long firstTime, long period) {
        this.period = period;
        this.firstTime = firstTime;
        this.task = task;
      }

      public String toString() {
        return shortClassName(this) + "(" + task + ", " + firstTime + ", " + period + ")";
      }

      public Object[] _fieldsToList() {
        return new Object[] { task, firstTime, period };
      }
    }

    public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
      entries.add(new Entry(task, now() + delay, period));
      super.scheduleAtFixedRate(task, delay, period);
    }

    public void cancel() {
      entries.clear();
      super.cancel();
    }

    public int purge() {
      entries.clear();
      return super.purge();
    }

    public FixedRateTimer changeRate(int newPeriod) {
      Object r = ((SmartTimerTask) first(entries).task).r;
      cancel();
      return doEvery(newPeriod, r);
    }
  }

  static public class SimpleLiveValue<A> extends LiveValue<A> {

    public Class<A> type;

    volatile public A value;

    transient public List onChange = synchroList();

    public SimpleLiveValue(Class<A> type) {
      this.type = type;
    }

    public SimpleLiveValue(Class<A> type, A value) {
      this.value = value;
      this.type = type;
    }

    public Class<A> 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();
      }
    }
  }

  static abstract public class LiveValue<A> {

    abstract public Class<A> getType();

    abstract public A get();

    abstract public void onChange(Runnable l);

    abstract public void removeOnChangeListener(Runnable l);

    public void onChangeAndNow(Runnable l) {
      onChange(l);
      callF(l);
    }
  }

  static public boolean reflection_isForbiddenMethod(Method m) {
    return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
  }

  static public <A, B> void multiMapPut(Map<A, List<B>> map, A a, B b) {
    List<B> l = map.get(a);
    if (l == null)
      map.put(a, l = new ArrayList());
    l.add(b);
  }

  static public Field makeAccessible(Field f) {
    try {
      f.setAccessible(true);
    } catch (Throwable e) {
      vmBus_send("makeAccessible_error", e, f);
    }
    return f;
  }

  static public Method makeAccessible(Method m) {
    try {
      m.setAccessible(true);
    } catch (Throwable e) {
      vmBus_send("makeAccessible_error", e, m);
    }
    return m;
  }

  static public Constructor makeAccessible(Constructor c) {
    try {
      c.setAccessible(true);
    } catch (Throwable e) {
      vmBus_send("makeAccessible_error", e, c);
    }
    return c;
  }

  static public Set<Class> allInterfacesImplementedBy(Class c) {
    if (c == null)
      return null;
    HashSet<Class> set = new HashSet();
    allInterfacesImplementedBy_find(c, set);
    return set;
  }

  static public void allInterfacesImplementedBy_find(Class c, Set<Class> set) {
    if (c.isInterface() && !set.add(c))
      return;
    do {
      for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set);
    } while ((c = c.getSuperclass()) != null);
  }

  static public Method findMethod(Object o, String method, Object... args) {
    return findMethod_cached(o, method, args);
  }

  static public 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;
  }

  static public 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;
  }

  static public 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;
  }

  static public 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;
  }

  static public <A, B> Map<A, B> mapMinusOrNull(Map<A, B> map, Object... keys) {
    return nullIfEmpty(mapMinus(map, keys));
  }

  static public <A, B> Map<A, B> mapPlus(Map<A, B> m, Object... data) {
    m = cloneMap(m);
    litmap_impl(m, data);
    return m;
  }

  static public <A extends JComponent> A bindToolTipToLiveValue(final LiveValue lv, final A c) {
    bindLiveValueListenerToComponent(c, lv, new Runnable() {

      public void run() {
        try {
          setToolTipText(c, strOrNull(lv.get()));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "setToolTipText(c, strOrNull(lv.get()))";
      }
    });
    return c;
  }

  static public SimpleLiveValue dm_fieldLiveValue(String fieldName) {
    return dm_fieldLiveValue(dm_current_mandatory(), fieldName);
  }

  static public SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) {
    Lock __0 = module.lock;
    lock(__0);
    try {
      AutoCloseable __2 = module.enter();
      try {
        Class type = getFieldType(module, fieldName);
        final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName));
        dm_watchField(fieldName, new Runnable() {

          public void run() {
            try {
              Object o = get(module, fieldName);
              value.set(o);
              ;
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "ifdef dm_fieldLiveValue_debug\r\n      print(\"dm_fieldLiveValue: setting \" + fi...";
          }
        });
        value.onChange(new Runnable() {

          public void run() {
            try {
              module.setField(fieldName, value.get());
              ;
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "ifdef dm_fieldLiveValue_debug\r\n      print(\"dm_fieldLiveValue: setting 2 \" + ...";
          }
        });
        return value;
      } finally {
        _close(__2);
      }
    } finally {
      unlock(__0);
    }
  }

  static public class jLiveValueSection_class extends SingleComponentPanel {

    public LiveValue<String> liveValue;

    public String getTitle() {
      return liveValue.get();
    }

    public jLiveValueSection_class(LiveValue<String> lv, Component c) {
      super(c);
      bindLiveValueListenerToComponent(this, liveValue = lv, new Runnable() {

        public void run() {
          try {
            swingLater(new Runnable() {

              public void run() {
                try {
                  setBorder(BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED), liveValue.get()));
                  revalidate();
                } catch (Exception __e) {
                  throw rethrow(__e);
                }
              }

              public String toString() {
                return "setBorder(BorderFactory.createTitledBorder(\r\n        BorderFactory.createBeve...";
              }
            });
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "swingLater(r {\r\n      setBorder(BorderFactory.createTitledBorder(\r\n        Bo...";
        }
      });
    }
  }

  static public JPanel jLiveValueSection(final LiveValue<String> lv, final Component c) {
    return swingNu(jLiveValueSection_class.class, lv, c);
  }

  static public <A extends JLabel> A centerLabel(A l) {
    if (l != null)
      l.setHorizontalAlignment(SwingConstants.CENTER);
    return l;
  }

  static public <A extends JComponent> A makeBold(final A c) {
    if (c != null) {
      swing(new Runnable() {

        public void run() {
          try {
            c.setFont(c.getFont().deriveFont(java.awt.Font.BOLD));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.setFont(c.getFont().deriveFont(java.awt.Font.BOLD));";
        }
      });
    }
    return c;
  }

  static public <A extends JComponent> A setFontSize(final float size, final A a) {
    if (a == null)
      return a;
    {
      swing(new Runnable() {

        public void run() {
          try {
            Component _a = a;
            if (a instanceof JComboBox)
              _a = ((JComboBox) a).getEditor().getEditorComponent();
            _a.setFont(_a.getFont().deriveFont((float) size));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "Component _a = a;\r\n    if (a instanceof JComboBox)\r\n      _a = ((JComboBox) a...";
        }
      });
    }
    return a;
  }

  static public <A extends JComponent> A setFontSize(A a, float size) {
    return setFontSize(size, a);
  }

  static public JLabel jLiveValueLabel(final LiveValue lv) {
    return bindJLabelToLiveValue(jlabel(), lv);
  }

  static public String defaultTimerName_name;

  static public String defaultTimerName() {
    if (defaultTimerName_name == null)
      defaultTimerName_name = "A timer by " + programID();
    return defaultTimerName_name;
  }

  static public Set<java.util.Timer> _registerTimer_list = newWeakHashSet();

  static public void _registerTimer(java.util.Timer timer) {
    _registerTimer_list.add(timer);
  }

  static public void cleanMeUp__registerTimer() {
    cancelTimers(getAndClearList(_registerTimer_list));
  }

  static public <A extends JSpinner> A onChange(A spinner, Object r) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            spinner.addChangeListener(changeListener(r));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "spinner.addChangeListener(changeListener(r));";
        }
      });
    }
    return spinner;
  }

  static public <A extends AbstractButton> A onChange(A b, Object r) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            b.addItemListener(itemListener(r));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "b.addItemListener(itemListener(r));";
        }
      });
    }
    return b;
  }

  static public void onChange(JTextComponent tc, Object r) {
    onUpdate(tc, r);
  }

  static public <A extends JSlider> A onChange(A slider, final Object r) {
    {
      swing(new Runnable() {

        public void run() {
          try {
            slider.addChangeListener(changeListener(r));
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "slider.addChangeListener(changeListener(r));";
        }
      });
    }
    return slider;
  }

  static public JComboBox onChange(Object r, JComboBox cb) {
    return onChange(cb, r);
  }

  static public JComboBox onChange(JComboBox cb, final Object r) {
    if (isEditableComboBox(cb))
      onChange(textFieldFromComboBox(cb), r);
    else
      onSelectedItem(cb, new VF1<String>() {

        public void get(String s) {
          try {
            callF(r);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "callF(r)";
        }
      });
    return cb;
  }

  static public 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<Method> 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<Method> 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);
    }
  }

  static public String nullIfEmpty(String s) {
    return isEmpty(s) ? null : s;
  }

  static public <A, B> Map<A, B> nullIfEmpty(Map<A, B> map) {
    return isEmpty(map) ? null : map;
  }

  static public <A> List<A> nullIfEmpty(List<A> l) {
    return isEmpty(l) ? null : l;
  }

  static public <A, B> Map<A, B> mapMinus(Map<A, B> map, Object... keys) {
    if (empty(keys))
      return map;
    Map<A, B> m2 = cloneMap(map);
    for (Object key : keys) m2.remove(key);
    return m2;
  }

  static public <A, B> Map<A, B> cloneMap(Map<A, B> 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);
    }
  }

  static public <A, B> List<B> cloneMap(Iterable<A> l, IF1<A, B> f) {
    List x = emptyList(l);
    if (l != null)
      for (A o : cloneList(l)) x.add(f.get(o));
    return x;
  }

  static public HashMap litmap(Object... x) {
    HashMap map = new HashMap();
    litmap_impl(map, x);
    return map;
  }

  static public void litmap_impl(Map map, Object... x) {
    if (x != null)
      for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
        map.put(x[i], x[i + 1]);
  }

  static public <A extends JComponent> 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;
  }

  static public <A extends JComponent> A setToolTipText(final A c, final Object toolTip) {
    if (c == null)
      return null;
    {
      swing(new Runnable() {

        public void run() {
          try {
            String s = nullIfEmpty(str(toolTip));
            if (neq(s, c.getToolTipText()))
              c.setToolTipText(s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "String s = nullIfEmpty(str(toolTip));\r\n    if (neq(s, c.getToolTipText()))\r\n ...";
        }
      });
    }
    return c;
  }

  static public <A extends JComponent> A setToolTipText(Object toolTip, A c) {
    return setToolTipText(c, toolTip);
  }

  static public String strOrNull(Object o) {
    return o == null ? null : str(o);
  }

  static public 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);
    }
  }

  static public void lock(Lock lock, String msg) {
    print("Locking: " + msg);
    lock(lock);
  }

  static public void lock(Lock lock, String msg, long timeout) {
    print("Locking: " + msg);
    lockOrFail(lock, timeout);
  }

  static public ReentrantLock lock() {
    return fairLock();
  }

  static public Class getFieldType(Object o, String field) {
    return fieldType(o, field);
  }

  static public void dm_watchField(String field, Runnable onChange) {
    new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange);
  }

  static public void unlock(Lock lock, String msg) {
    if (lock == null)
      return;
    print("Unlocking: " + msg);
    lock.unlock();
  }

  static public void unlock(Lock lock) {
    if (lock == null)
      return;
    lock.unlock();
  }

  static public void swingLater(long delay, final Object r) {
    javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r)));
    timer.setRepeats(false);
    timer.start();
  }

  static public void swingLater(Object r) {
    SwingUtilities.invokeLater(toRunnable(r));
  }

  static public <A extends Component> A revalidate(final A c) {
    if (c == null || !c.isShowing())
      return c;
    {
      swing(new Runnable() {

        public void run() {
          try {
            c.revalidate();
            c.repaint();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "// magic combo to actually relayout and repaint\r\n    c.revalidate();\r\n    c.r...";
        }
      });
    }
    return c;
  }

  static public void revalidate(JFrame f) {
    revalidate((Component) f);
  }

  static public void revalidate(JInternalFrame f) {
    revalidate((Component) f);
  }

  static public <A> A swingNu(final Class<A> c, final Object... args) {
    return swingConstruct(c, args);
  }

  static public Object swing(Object f) {
    return swingAndWait(f);
  }

  static public <A> A swing(F0<A> f) {
    return (A) swingAndWait(f);
  }

  static public <A> A swing(IF0<A> f) {
    return (A) swingAndWait(f);
  }

  static public <A extends JLabel> A bindJLabelToLiveValue(final A label, final LiveValue lv) {
    bindLiveValueListenerToComponent(label, lv, new Runnable() {

      public void run() {
        try {
          setText(label, strOrNull(lv.get()));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "setText(label, strOrNull(lv.get()))";
      }
    });
    return label;
  }

  static public JLabel jlabel(final String text) {
    return swingConstruct(BetterLabel.class, text);
  }

  static public JLabel jlabel() {
    return jlabel(" ");
  }

  static public <A> Set<A> newWeakHashSet() {
    return synchroWeakHashSet();
  }

  static public void cancelTimers(Collection timers) {
    for (Object timer : timers) cancelTimer(timer);
  }

  static public <A> List<A> getAndClearList(Collection<A> l) {
    if (l == null)
      return emptyList();
    synchronized (collectionMutex(l)) {
      List<A> out = cloneList(l);
      l.clear();
      return out;
    }
  }

  static public ChangeListener changeListener(final Object r) {
    return new ChangeListener() {

      public void stateChanged(ChangeEvent e) {
        pcallF(r);
      }
    };
  }

  static public ItemListener itemListener(final Object r) {
    return new ItemListener() {

      public void itemStateChanged(ItemEvent e) {
        pcallF(r);
      }
    };
  }

  static public void onUpdate(JComponent c, final Object r) {
    if (c instanceof JTextComponent)
      ((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {

        public void insertUpdate(DocumentEvent e) {
          call(r);
        }

        public void removeUpdate(DocumentEvent e) {
          call(r);
        }

        public void changedUpdate(DocumentEvent e) {
          call(r);
        }
      });
    else if (c instanceof ItemSelectable)
      ((ItemSelectable) c).addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {
          call(r);
        }
      });
    else
      print("Warning: onUpdate doesn't know " + getClassName(c));
  }

  static public void onUpdate(List<? extends JComponent> l, Object r) {
    for (JComponent c : l) onUpdate(c, r);
  }

  static public boolean isEditableComboBox(final JComboBox cb) {
    return cb != null && swing(new F0<Boolean>() {

      public Boolean get() {
        try {
          return cb.isEditable();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret cb.isEditable();";
      }
    });
  }

  static public JTextField textFieldFromComboBox(JComboBox cb) {
    return (JTextField) cb.getEditor().getEditorComponent();
  }

  static public JComboBox onSelectedItem(final JComboBox cb, final VF1<String> f) {
    addActionListener(cb, new Runnable() {

      public void run() {
        try {
          pcallF(f, selectedItem(cb));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "pcallF(f, selectedItem(cb))";
      }
    });
    return cb;
  }

  static public boolean isEmpty(Collection c) {
    return c == null || c.isEmpty();
  }

  static public boolean isEmpty(CharSequence s) {
    return s == null || s.length() == 0;
  }

  static public boolean isEmpty(Object[] a) {
    return a == null || a.length == 0;
  }

  static public boolean isEmpty(byte[] a) {
    return a == null || a.length == 0;
  }

  static public boolean isEmpty(Map map) {
    return map == null || map.isEmpty();
  }

  static public <A extends Throwable> A printStackTrace(A e) {
    print(getStackTrace(e));
    return e;
  }

  static public void printStackTrace() {
    printStackTrace(new Throwable());
  }

  static public void printStackTrace(String msg) {
    printStackTrace(new Throwable(msg));
  }

  static public void printStackTrace(String msg, Throwable e) {
    printStackTrace(new Throwable(msg, e));
  }

  static public 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);
    }
  }

  static public ReentrantLock fairLock() {
    return new ReentrantLock(true);
  }

  static public ActionListener actionListener(final Object runnable) {
    return actionListener(runnable, null);
  }

  static public 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 public Runnable wrapAsActivity(Object r) {
    return toRunnable(r);
  }

  static public Runnable toRunnable(final Object o) {
    if (o instanceof Runnable)
      return (Runnable) o;
    return new Runnable() {

      public void run() {
        try {
          callF(o);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(o)";
      }
    };
  }

  static public <A> A swingConstruct(final Class<A> c, final Object... args) {
    return swing(new F0<A>() {

      public A get() {
        try {
          return nuObject(c, args);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret nuObject(c, args);";
      }
    });
  }

  static public void swingAndWait(Runnable r) {
    try {
      if (isAWTThread())
        r.run();
      else
        EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public 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();
    }
  }

  static public boolean setText_opt = true;

  static public <A extends JTextComponent> A setText(A c, Object text) {
    setText((JComponent) c, text);
    return c;
  }

  static public <A extends JComboBox> A setText(final A c, Object text) {
    final String s = strUnnull(text);
    {
      swing(new Runnable() {

        public void run() {
          try {
            c.getEditor().setItem(s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "c.getEditor().setItem(s);";
        }
      });
    }
    return c;
  }

  static public void setText(JLabel c, Object text) {
    setText((JComponent) c, text);
  }

  static public JButton setText(JButton c, Object text) {
    setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text)));
    return c;
  }

  static public <A extends JComponent> A setText(final A c, Object text) {
    if (c == null)
      return null;
    final String s = strUnnull(text);
    {
      swing(new Runnable() {

        public void run() {
          try {
            if (!setText_opt || neq(callOpt(c, "getText"), s))
              call(c, "setText", s);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n      call(c, \"setText\", s);";
        }
      });
    }
    return c;
  }

  static public <A> Set<A> synchroWeakHashSet() {
    return Collections.newSetFromMap((Map) newWeakHashMap());
  }

  static public void cancelTimer(javax.swing.Timer timer) {
    if (timer != null)
      timer.stop();
  }

  static public void cancelTimer(java.util.Timer timer) {
    if (timer != null)
      timer.cancel();
  }

  static public void cancelTimer(Object o) {
    if (o instanceof java.util.Timer)
      cancelTimer((java.util.Timer) o);
    else if (o instanceof javax.swing.Timer)
      cancelTimer((javax.swing.Timer) o);
    else if (o instanceof AutoCloseable) {
      try {
        ((AutoCloseable) o).close();
      } catch (Throwable __e) {
        _handleException(__e);
      }
    }
  }

  static public void addActionListener(JTextField tf, final Runnable action) {
    onEnter(tf, action);
  }

  static public 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));";
        }
      });
    }
  }

  static public 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));";
        }
      });
    }
  }

  static public String selectedItem(JList l) {
    return getSelectedItem(l);
  }

  static public String selectedItem(JComboBox cb) {
    return getSelectedItem(cb);
  }

  static public ThreadLocal<List<Object>> holdInstance_l = new ThreadLocal();

  static public AutoCloseable holdInstance(Object o) {
    if (o == null)
      return null;
    listThreadLocalAdd(holdInstance_l, o);
    return new AutoCloseable() {

      public void close() {
        listThreadLocalPopLast(holdInstance_l);
      }
    };
  }

  static public 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 public void messageBox(Throwable e) {
    printStackTrace(e);
    messageBox(hideCredentials(innerException2(e)));
  }

  static public Object nuObject(String className, Object... args) {
    try {
      return nuObject(classForName(className), args);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> A nuObject(Class<A> c, Object... args) {
    try {
      if (args.length == 0)
        return nuObjectWithoutArguments(c);
      Constructor m = nuObject_findConstructor(c, args);
      makeAccessible(m);
      return (A) m.newInstance(args);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public 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 public 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 public 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);";
      }
    };
  }

  static public String strUnnull(Object o) {
    return o == null ? "" : str(o);
  }

  static public String jlabel_textAsHTML_center_ifNeeded(String text) {
    if (swic(text, "<html>") && ewic(text, "</html>"))
      return text;
    if (!containsNewLines(text))
      return text;
    return jlabel_textAsHTML_center(text);
  }

  static public 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 public JButton onEnter(JButton btn, final Object action) {
    if (action == null || btn == null)
      return btn;
    btn.addActionListener(actionListener(action));
    return btn;
  }

  static public JList onEnter(JList list, Object action) {
    list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action)));
    return list;
  }

  static public 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 public 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 public JTextField onEnter(Object action, JTextField tf) {
    return onEnter(tf, action);
  }

  static public String getSelectedItem(JList l) {
    return (String) l.getSelectedValue();
  }

  static public String getSelectedItem(JComboBox cb) {
    return strOrNull(cb.getSelectedItem());
  }

  static public <A> void listThreadLocalAdd(ThreadLocal<List<A>> tl, A a) {
    List<A> l = tl.get();
    if (l == null)
      tl.set(l = new ArrayList());
    l.add(a);
  }

  static public <A> A listThreadLocalPopLast(ThreadLocal<List<A>> tl) {
    List<A> l = tl.get();
    if (l == null)
      return null;
    A a = popLast(l);
    if (empty(l))
      tl.set(null);
    return a;
  }

  static public boolean headless() {
    return isHeadless();
  }

  static public Map<String, Class> classForName_cache = synchroHashMap();

  static public 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);
    }
  }

  static public Map<Class, Constructor> nuObjectWithoutArguments_cache = newDangerousWeakHashMap();

  static public Object nuObjectWithoutArguments(String className) {
    try {
      return nuObjectWithoutArguments(classForName(className));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> A nuObjectWithoutArguments(Class<A> 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);
    }
  }

  static public 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 public List<Class> getClasses(Object[] array) {
    List<Class> l = emptyList(l(array));
    for (Object o : array) l.add(_getClass(o));
    return l;
  }

  static public Runnable asRunnable(Object o) {
    return toRunnable(o);
  }

  static public void _inheritThreadInfo(Object info) {
    _threadInheritInfo(info);
  }

  static public boolean swic(String a, String b) {
    return startsWithIgnoreCase(a, b);
  }

  static public 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 public boolean containsNewLines(String s) {
    return containsNewLine(s);
  }

  static public String jlabel_textAsHTML_center(String text) {
    return "<html><div style=\"text-align: center;\">" + replace(htmlencode(text), "\n", "<br>") + "</div></html>";
  }

  static public KeyListener enterKeyListener(final Object action) {
    return new KeyAdapter() {

      public void keyPressed(KeyEvent ke) {
        if (ke.getKeyCode() == KeyEvent.VK_ENTER)
          pcallF(action);
      }
    };
  }

  static public 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 public AbstractAction abstractAction(String name, final Object runnable) {
    return new AbstractAction(name) {

      public void actionPerformed(ActionEvent evt) {
        pcallF(runnable);
      }
    };
  }

  static public <A> A popLast(List<A> l) {
    return liftLast(l);
  }

  static public <A> List<A> popLast(int n, List<A> l) {
    return liftLast(n, l);
  }

  static public Map synchroHashMap() {
    return Collections.synchronizedMap(new HashMap());
  }

  static public Class<?> _getClass(String name) {
    try {
      return Class.forName(name);
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  static public Class _getClass(Object o) {
    return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
  }

  static public Class _getClass(Object realm, String name) {
    try {
      return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  static public boolean startsWithIgnoreCase(String a, String b) {
    return regionMatchesIC(a, 0, b, 0, b.length());
  }

  static public boolean containsNewLine(String s) {
    return contains(s, '\n');
  }

  static public <A> List<A> replace(List<A> 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 public <A> List<A> replace(A a, A b, List<A> l) {
    return replace(l, a, b);
  }

  static public String replace(String s, String a, String b) {
    return s == null ? null : a == null || b == null ? s : s.replace(a, b);
  }

  static public String replace(String s, char a, char b) {
    return s == null ? null : s.replace(a, b);
  }

  static public String htmlencode(Object o) {
    return htmlencode(str(o));
  }

  static public 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("&#x");
        out.append(intToHex_flexLength(cp));
        out.append(';');
        i += Character.charCount(cp) - 1;
      } else
        out.append(c);
    }
    return out.toString();
  }

  static public <A> A liftLast(List<A> l) {
    if (empty(l))
      return null;
    int i = l(l) - 1;
    A a = l.get(i);
    l.remove(i);
    return a;
  }

  static public <A> List<A> liftLast(int n, List<A> l) {
    int i = l(l) - n;
    List<A> part = cloneSubList(l, i);
    removeSubList(l, i);
    return part;
  }

  static public Class<?> getClass(String name) {
    try {
      return Class.forName(name);
    } catch (ClassNotFoundException e) {
      return null;
    }
  }

  static public Class getClass(Object o) {
    return o instanceof Class ? (Class) o : o.getClass();
  }

  static public 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);
    }
  }

  static public String classNameToVM(String name) {
    return name.replace(".", "$");
  }

  static public boolean contains(Collection c, Object o) {
    return c != null && c.contains(o);
  }

  static public boolean contains(Object[] x, Object o) {
    if (x != null)
      for (Object a : x) if (eq(a, o))
        return true;
    return false;
  }

  static public boolean contains(String s, char c) {
    return s != null && s.indexOf(c) >= 0;
  }

  static public boolean contains(String s, String b) {
    return s != null && s.indexOf(b) >= 0;
  }

  static public boolean contains(BitSet bs, int i) {
    return bs != null && bs.get(i);
  }

  static public String intToHex_flexLength(int i) {
    return Integer.toHexString(i);
  }

  static public <A> List<A> cloneSubList(List<A> l, int startIndex, int endIndex) {
    return newSubList(l, startIndex, endIndex);
  }

  static public <A> List<A> cloneSubList(List<A> l, int startIndex) {
    return newSubList(l, startIndex);
  }

  static public void removeSubList(List l, int from, int to) {
    if (l != null)
      subList(l, from, to).clear();
  }

  static public void removeSubList(List l, int from) {
    if (l != null)
      subList(l, from).clear();
  }

  static public <A> List<A> newSubList(List<A> l, int startIndex, int endIndex) {
    return cloneList(subList(l, startIndex, endIndex));
  }

  static public <A> List<A> newSubList(List<A> l, int startIndex) {
    return cloneList(subList(l, startIndex));
  }

  static public <A> List<A> subList(List<A> l, int startIndex) {
    return subList(l, startIndex, l(l));
  }

  static public <A> List<A> subList(int startIndex, int endIndex, List<A> l) {
    return subList(l, startIndex, endIndex);
  }

  static public <A> List<A> subList(List<A> l, int startIndex, int endIndex) {
    if (l == null)
      return null;
    int n = l(l);
    startIndex = Math.max(0, startIndex);
    endIndex = Math.min(n, endIndex);
    if (startIndex >= endIndex)
      return ll();
    if (startIndex == 0 && endIndex == n)
      return l;
    return l.subList(startIndex, endIndex);
  }

  static public interface IF0<A> {

    public A get();
  }

  static public class Var<A> implements IVar<A> {

    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());
    }
  }

  static public class Dyn_FieldWatcher {

    public DynModule module;

    public String field;

    public Object value;

    public Runnable action;

    public Dyn_FieldWatcher(DynModule module, String field, Runnable action) {
      this.action = action;
      this.field = field;
      this.module = module;
      value = get(module, field);
      module.onChange(new Runnable() {

        public void run() {
          try {
            check();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "check();";
        }
      });
      module.onFieldChange(new VF1<String>() {

        public void get(String f) {
          try {
            if (eq(f, field))
              check();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (eq(f, field))\r\n        check();";
        }
      });
    }

    public void check() {
      Object newValue = get(module, field);
      if (eq(value, newValue))
        return;
      value = newValue;
      dm_q(module, action);
    }
  }

  static public interface IVar<A> {

    public void set(A a);

    public A get();

    default public boolean has() {
      return get() != null;
    }

    default public void clear() {
      set(null);
    }
  }

  static public Q dm_q() {
    return dm_current_mandatory().q();
  }

  static public void dm_q(Runnable r) {
    dm_inQ(r);
  }

  static public void dm_q(DynModule module, Runnable r) {
    module.q().add(r);
  }

  static public <A> A dm_q(IF0<A> f) {
    return dm_evalInQ(if0ToF0(f));
  }

  static public <A> A set(A o, String field, Object value) {
    if (o == null)
      return null;
    if (o instanceof Class)
      set((Class) o, field, value);
    else
      try {
        Field f = set_findField(o.getClass(), field);
        makeAccessible(f);
        smartSet(f, o, value);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    return o;
  }

  static public void set(Class c, String field, Object value) {
    if (c == null)
      return;
    try {
      Field f = set_findStaticField(c, field);
      makeAccessible(f);
      smartSet(f, null, value);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  static public Field set_findStaticField(Class<?> c, String field) {
    Class _c = c;
    do {
      for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
        return f;
      _c = _c.getSuperclass();
    } while (_c != null);
    throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
  }

  static public Field set_findField(Class<?> c, String field) {
    Class _c = c;
    do {
      for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
        return f;
      _c = _c.getSuperclass();
    } while (_c != null);
    throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
  }

  static public void dm_inQ(Runnable r) {
    dm_q().add(r);
  }

  static public <A> A dm_evalInQ(F0<A> f) {
    return dm_evalInQ(dm_current_mandatory(), f);
  }

  static public <A> A dm_evalInQ(DynModule module, F0<A> f) {
    return evalInQ(module.q(), f);
  }

  static public <A> F0<A> if0ToF0(IF0<A> f) {
    return f == null ? null : new F0<A>() {

      public A get() {
        try {
          return f.get();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret f.get();";
      }
    };
  }

  static public void smartSet(Field f, Object o, Object value) throws Exception {
    try {
      f.set(o, value);
    } catch (Exception e) {
      Class type = f.getType();
      if (type == int.class && value instanceof Long)
        value = ((Long) value).intValue();
      if (type == LinkedHashMap.class && value instanceof Map) {
        f.set(o, asLinkedHashMap((Map) value));
        return;
      }
      try {
        if (f.getType() == Concept.Ref.class) {
          f.set(o, ((Concept) o).new Ref((Concept) value));
          return;
        }
        if (o instanceof Concept.Ref) {
          f.set(o, ((Concept.Ref) o).get());
          return;
        }
      } catch (Throwable _e) {
      }
      throw e;
    }
  }

  static public <A> A evalInQ(Q q, final F0<A> f) {
    if (isInQ(q))
      return callF(f);
    final Var<Either<A, Throwable>> var = new Var();
    q.add(new Runnable() {

      public void run() {
        try {
          try {
            var.set(main.<A, Throwable>eitherA(callF(f)));
          } catch (Throwable e) {
            var.set(main.<A, Throwable>eitherB(e));
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "try {\r\n      var.set(main.<A, Throwable> eitherA(callF(f)));\r\n    } catch (Th...";
      }
    });
    return returnOrThrow_either(waitForVarToBeNotNull(var));
  }

  static public <A, B> LinkedHashMap<A, B> asLinkedHashMap(Map<A, B> map) {
    if (map instanceof LinkedHashMap)
      return (LinkedHashMap) map;
    LinkedHashMap<A, B> m = new LinkedHashMap();
    if (map != null)
      synchronized (collectionMutex(map)) {
        m.putAll(map);
      }
    return m;
  }

  static public boolean isInQ(Q q) {
    return q != null && isCurrentThread(q.rst.thread);
  }

  static public <A, B> Either<A, B> eitherA(A a) {
    return new Either(1, a);
  }

  static public <A, B> Either<A, B> eitherB(B b) {
    return new Either(2, b);
  }

  static public <A> A returnOrThrow_either(Either<A, Throwable> e) {
    if (isEitherB(e))
      throw rethrow(e.b());
    return eitherAOpt(e);
  }

  static public <A> A waitForVarToBeNotNull(Var<A> v) {
    try {
      synchronized (v) {
        while (!v.has()) v.wait();
        return v.get();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isCurrentThread(Thread t) {
    return t != null && t == currentThread();
  }

  static public <A, B> boolean isEitherB(Either<A, B> e) {
    return eitherIsB(e);
  }

  static public <A, B> A eitherAOpt(Either<A, B> e) {
    return e != null && e.isA() ? e.a() : null;
  }

  static public <A, B> boolean eitherIsB(Either<A, B> e) {
    return e != null && e.isB();
  }

  static public class Either<A, B> {

    public byte which;

    public Object value;

    public Either() {
    }

    public Either(int which, Object value) {
      this.which = (byte) which;
      this.value = value;
    }

    public boolean isA() {
      return which == 1;
    }

    public boolean isB() {
      return which == 2;
    }

    public A a() {
      if (which != 1)
        _failMe();
      return (A) value;
    }

    public B b() {
      if (which != 2)
        _failMe();
      return (B) value;
    }

    public void _failMe() {
      throw fail("Either object is of wrong type: " + shortClassName(value));
    }
  }

  static public String b(Object contents, Object... params) {
    return tag("b", contents, params);
  }

  static public String tag(String tag) {
    return htag(tag);
  }

  static public String tag(String tag, Object contents, Object... params) {
    return htag(tag, str(contents), params);
  }

  static public String tag(String tag, StringBuilder contents, Object... params) {
    return htag(tag, contents, params);
  }

  static public String tag(String tag, StringBuffer contents, Object... params) {
    return htag(tag, contents, params);
  }

  static public String htag(String tag) {
    return htag(tag, "");
  }

  static public String htag(String tag, Object contents, Object... params) {
    String openingTag = hopeningTag(tag, params);
    String s = str(contents);
    if (empty(s) && neqic(tag, "script"))
      return dropLast(openingTag) + "/>";
    return openingTag + s + "</" + tag + ">";
  }

  static public String hopeningTag(String tag, Map params) {
    return hopeningTag(tag, mapToParams(params));
  }

  static public String hopeningTag(String tag, Object... params) {
    StringBuilder buf = new StringBuilder();
    buf.append("<" + tag);
    for (int i = 0; i < l(params); i += 2) {
      String name = (String) get(params, i);
      Object val = get(params, i + 1);
      if (nempty(name) && val != null) {
        if (val == html_valueLessParam())
          buf.append(" " + name);
        else {
          String s = str(val);
          if (!empty(s))
            buf.append(" " + name + "=" + htmlQuote(s));
        }
      }
    }
    buf.append(">");
    return str(buf);
  }

  static public boolean neqic(String a, String b) {
    return !eqic(a, b);
  }

  static public boolean neqic(char a, char b) {
    return !eqic(a, b);
  }

  static public String[] dropLast(String[] a, int n) {
    n = Math.min(n, a.length);
    String[] b = new String[a.length - n];
    System.arraycopy(a, 0, b, 0, b.length);
    return b;
  }

  static public <A> List<A> dropLast(List<A> l) {
    return subList(l, 0, l(l) - 1);
  }

  static public <A> List<A> dropLast(int n, List<A> l) {
    return subList(l, 0, l(l) - n);
  }

  static public <A> List<A> dropLast(Iterable<A> l) {
    return dropLast(asList(l));
  }

  static public String dropLast(String s) {
    return substring(s, 0, l(s) - 1);
  }

  static public String dropLast(String s, int n) {
    return substring(s, 0, l(s) - n);
  }

  static public String dropLast(int n, String s) {
    return dropLast(s, n);
  }

  static public Object[] mapToParams(Map map) {
    return mapToObjectArray(map);
  }

  static public Object html_valueLessParam_cache;

  static public Object html_valueLessParam() {
    if (html_valueLessParam_cache == null)
      html_valueLessParam_cache = html_valueLessParam_load();
    return html_valueLessParam_cache;
  }

  static public Object html_valueLessParam_load() {
    return new Object();
  }

  static public String htmlQuote(String s) {
    return "\"" + htmlencode_forParams(s) + "\"";
  }

  static public Object[] mapToObjectArray(Map map) {
    List l = new ArrayList();
    for (Object o : keys(map)) {
      l.add(o);
      l.add(map.get(o));
    }
    return toObjectArray(l);
  }

  static public Object[] mapToObjectArray(Object f, Collection l) {
    int n = l(l);
    Object[] array = new Object[n];
    if (n != 0) {
      Iterator it = iterator(l);
      for (int i = 0; i < n; i++) array[i] = callF(f, it.next());
    }
    return array;
  }

  static public Object[] mapToObjectArray(Object f, Object[] l) {
    int n = l(l);
    Object[] array = new Object[n];
    for (int i = 0; i < n; i++) array[i] = callF(f, l[i]);
    return array;
  }

  static public String htmlencode_forParams(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 == '>') {
        out.append("&#");
        out.append((int) c);
        out.append(';');
      } else
        out.append(c);
    }
    return out.toString();
  }

  static public <A, B> Set<A> keys(Map<A, B> map) {
    return map == null ? new HashSet() : map.keySet();
  }

  static public Set keys(Object map) {
    return keys((Map) map);
  }

  static public <A> Set<A> keys(MultiSet<A> ms) {
    return ms.keySet();
  }

  static public Object[] toObjectArray(Collection c) {
    List l = asList(c);
    return l.toArray(new Object[l.size()]);
  }

  static public <A> Iterator<A> iterator(Iterable<A> c) {
    return c == null ? emptyIterator() : c.iterator();
  }

  static public Iterator emptyIterator() {
    return Collections.emptyIterator();
  }
}