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 java.text.NumberFormat;
class main {
static void dm_benchAndProfileFor5Seconds(Runnable r) {
dm_showPoorMansProfile(new Runnable() { public void run() { try { benchFor5Seconds(r) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "benchFor5Seconds(r)"; }});
}
static A dm_benchAndProfileFor5Seconds(IF0 f) {
return dm_showPoorMansProfile(() -> benchFor5Seconds(f));
}
static void dm_showPoorMansProfile(Runnable r) {
dm_showText("Profile", profileToString(r));
}
static A dm_showPoorMansProfile(IF0 f) {
Var v = new Var();
dm_showPoorMansProfile(new Runnable() { public void run() { try { v.set(f.get()) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "v.set(f.get())"; }});
return v.get();
}
// returns minimal time needed
static long benchFor5Seconds(String desc, Runnable r) {
return benchForNSeconds(desc, r, 5);
}
static long benchFor5Seconds(Runnable r) {
return benchFor5Seconds(str(r), r);
}
// returns result of function
static A benchFor5Seconds(IF0 f) { return benchFor5Seconds(str(f), f); }
static A benchFor5Seconds(String desc, IF0 f) {
benchFor5Seconds(new Runnable() { public void run() { try { f.get() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "f.get()"; }});
return f.get();
}
static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
static String dm_showText(String text) {
return dm_showNewModuleWithFields("#1016122/TextArea", "text", text);
}
static String dm_showText(String title, String text) {
String mod = dm_showText(text);
dm_setModuleName(mod, title);
return mod;
}
// convenience synonym for dm_showLines
static String dm_showText(Iterable l) {
return dm_showLines(l);
}
static String profileToString(Runnable r) {
poorMansProfiling();
try {
r.run();
} catch (Throwable __e) { _handleException(__e); }
return poorMansProfiling_stopAndRenderResults();
}
// returns minimal time needed
static long benchForNSeconds(String desc, Runnable r, int n) {
long start = sysNow(), min = -1, print = sysNow();
int seconds = 1;
long count = 0, sum = 0;
while (seconds <= n) {
long time = nanos();
r.run();
++count;
time = nanos()-time;
min = min < 0 ? time : min(min, time);
sum += time;
double avg = doubleRatio(sum, count);
if (sysNow() >= start+seconds*1000) {
printAndSetConsoleTitleIfMain(
"avg=" + formatDouble(nanosToMS(avg), 3) + " ms, " +
"min=" + formatDouble(nanosToMS(min), 3) + " ms: " +
desc + " (" + seconds + "/" + n + " s, last=" + formatDouble(nanosToMS(time), 3) + " ms, " + n2(count) + "/s)");
++seconds;
count = sum = 0;
}
}
return min;
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
static String dm_showNewModuleWithFields(String moduleLibID, Object... params) {
return dm_showNewModuleWithParams(moduleLibID, params);
}
static void dm_setModuleName(Object module, String name) {
dm_callModule(module, "setModuleName", name);
}
static void dm_setModuleName(String name) {
dm_setModuleName(dm_current_mandatory_generic(), name);
}
static String dm_showLines(Iterable l) {
return dm_showText(lines(l));
}
static MultiSet poorMansProfiling_results = new MultiSet();
static int poorMansProfiling_samples;
static java.util.Timer poorMansProfiling_timer;
static Lock poorMansProfiling_lock = lock();
static int poorMansProfiling_defaultInterval = 100;
static Thread poorMansProfiling_threadToSample; // otherwise sample all threads
static void poorMansProfiling() {
poorMansProfiling(poorMansProfiling_defaultInterval);
}
static void poorMansProfiling(Thread thread) {
poorMansProfiling(poorMansProfiling_defaultInterval, thread);
}
static void poorMansProfiling(int interval) {
poorMansProfiling(interval, null);
}
static void poorMansProfiling(int interval, Thread thread) {
Lock __0 = poorMansProfiling_lock; lock(__0); try {
poorMansProfiling_threadToSample = thread;
poorMansProfiling_stop();
poorMansProfiling_clear();
poorMansProfiling_timer = doEvery_daemon(interval, new Runnable() { public void run() { try {
Map map =
poorMansProfiling_threadToSample != null
? litmap(poorMansProfiling_threadToSample, poorMansProfiling_threadToSample.getStackTrace())
: runnableThreadsWithStackTraces();
Lock __1 = poorMansProfiling_lock; lock(__1); try {
poorMansProfiling_samples++;
for (Thread t : keys(map)) {
{ if (isSystemThread(t)) continue; }
StringBuilder buf = new StringBuilder();
for (StackTraceElement e : map.get(t))
buf.append(e).append("\n");
poorMansProfiling_results.add(str(buf));
}
} finally { unlock(__1); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Map map =\r\n poorMansProfiling_threadToSampl..."; }});
} finally { unlock(__0); } }
static void poorMansProfiling_stop() {
Lock __2 = poorMansProfiling_lock; lock(__2); try {
if (poorMansProfiling_timer != null) {
stopTimer(poorMansProfiling_timer);
poorMansProfiling_timer = null;
}
} finally { unlock(__2); } }
static void poorMansProfiling_clear() {
Lock __3 = poorMansProfiling_lock; lock(__3); try {
poorMansProfiling_results.clear();
poorMansProfiling_samples = 0;
} finally { unlock(__3); } }
static MultiSet poorMansProfiling_results() {
return new MultiSet(poorMansProfiling_results);
}
static MultiSet poorMansProfiling_stopAndGetResults() {
Lock __4 = poorMansProfiling_lock; lock(__4); try {
poorMansProfiling_stop();
return poorMansProfiling_results();
} finally { unlock(__4); } }
static volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll("printStackTrace2"));
static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3); // not using pcall here - it could lead to endless loops
}
}
static String poorMansProfiling_stopAndRenderResults() {
return poorMansProfiling_renderFullResults(poorMansProfiling_stopAndGetResults());
}
static long sysNow() {
ping();
return System.nanoTime()/1000000;
}
static long nanos() {
return nanoTime();
}
static int min(int a, int b) {
return Math.min(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static float min(float a, float b) { return Math.min(a, b); }
static float min(float a, float b, float c) { return min(min(a, b), c); }
static double min(double a, double b) {
return Math.min(a, b);
}
static double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x) x = d;
return x;
}
static short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x) x = d;
return x;
}
static int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x) x = d;
return x;
}
static double doubleRatio(double x, double y) {
return y == 0 ? 0 : x/y;
}
static void printAndSetConsoleTitleIfMain(String s) {
print(s);
if (isMain()) consoleTitle(s);
}
static String formatDouble(double d, int digits) {
String format = digits <= 0 ? "0" : "0." + rep(digits, '#');
return decimalFormatEnglish(format, d);
}
static double nanosToMS(double nanoseconds) {
return nsToMS(nanoseconds);
}
static String n2(long l) { return formatWithThousands(l); }
static String n2(Collection l) { return n2(l(l)); }
static String n2(Map map) { return n2(l(map)); }
static String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
static String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
static String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static String n2(Map m, String singular) {
return n2(l(m), singular);
}
static String n2(Object[] a, String singular) { return n2(l(a), singular); }
static String n2(Object[] a, String singular, String plural) { return n_fancy2(a, singular, plural); }
static String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static Object call(Object o) {
return callF(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) {
//ret call_cached(o, method, args);
return call_withVarargs(o, method, args);
}
static Class javax() {
return getJavaX();
}
static Throwable printStackTrace2(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace2(e));
return e;
}
static void printStackTrace2() {
printStackTrace2(new Throwable());
}
static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static String dm_showNewModuleWithParams(String moduleLibID, Object... params) {
String moduleID = dm_makeNewModuleWithParams(moduleLibID, params);
dm_showModule(moduleID);
return moduleID;
}
static Object dm_callModule(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null) return null;
AutoCloseable __1 = dm_enter(mod); try {
return call(mod, method, args);
} finally { _close(__1); }}
static Object dm_current_mandatory_generic() {
return assertNotNull("No module set", dm_current_generic());
}
static String lines(Iterable lines) { return fromLines(lines); }
static String lines(Object[] lines) { return fromLines(asList(lines)); }
static List lines(String s) { return toLines(s); }
static void lock(Lock lock) { try {
ping();
if (lock == null) return;
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
print("Locking interrupted! I probably deadlocked, oops.");
printStackTrace(e);
rethrow(e);
}
ping();
} catch (Exception __e) { throw rethrow(__e); } }
static void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static ReentrantLock lock() {
return fairLock();
}
// firstDelay = delay
static FixedRateTimer doEvery_daemon(long delay, final Object r) {
return doEvery_daemon(delay, delay, r);
}
static FixedRateTimer doEvery_daemon(long delay, long firstDelay, final Object r) {
FixedRateTimer timer = new FixedRateTimer(true);
timer.scheduleAtFixedRate(smartTimerTask(r, timer, delay), firstDelay, delay);
return timer;
}
static FixedRateTimer doEvery_daemon(double delaySeconds, final Object r) {
return doEvery_daemon(toMS(delaySeconds), r);
}
static HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static 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 Map runnableThreadsWithStackTraces() {
Map map = filterMap((__16, __17) -> isThreadRunnable_x(__16, __17),Thread.getAllStackTraces());
map.remove(currentThread());
return map;
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
// convenience shortcut for keys_gen
static Set keys(Object map) {
return keys((Map) map);
}
static Set keys(MultiSet ms) {
return ms.keySet();
}
static boolean isSystemThread(Thread t) {
ThreadGroup g = t.getThreadGroup();
return g != null && g.getName().equals("system");
}
static void unlock(Lock lock, String msg) {
if (lock == null) return;
print("Unlocking: " + msg);
lock.unlock();
}
static void unlock(Lock lock) {
if (lock == null) return;
lock.unlock();
}
static void stopTimer(java.util.Timer timer) {
if (timer != null) timer.cancel();
}
static List synchroList() {
return Collections.synchronizedList(new ArrayList());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null) for (A x : a) l.add(x);
return l;
}
static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static Throwable innerException(Throwable e) {
return getInnerException(e);
}
static boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static ArrayList cloneList(Collection l) {
if (l == null) return new ArrayList();
synchronized(collectionMutex(l)) {
return new ArrayList(l);
}
}
static Map> callF_cache = newDangerousWeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static A callF(IF0 f) {
return f == null ? null : f.get();
}
static B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static void callF(VF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Object f, Object... args) { try {
if (f instanceof String)
return callMCWithVarArgs((String) f, args); // possible SLOWDOWN over callMC
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1) return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) { throw rethrow(__e); } }
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
makeAccessible(m);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static ThreadLocal poorMansProfiling_renderFullResults_backwards = new ThreadLocal();
static String poorMansProfiling_renderFullResults(final MultiSet traces) {
int samples = poorMansProfiling_samples;
boolean backwards = isTrue(getAndClearThreadLocal(poorMansProfiling_renderFullResults_backwards));
final int n = traces.size();
int percent = ratioToIntPercent(l(traces), samples);
return (samples == 0 ? "Nothing sampled"
: percent + "% core activity [" + n2(samples, "sample") + " taken]") + "\n\n"
+ joinMap(backwards ? traces.lowestFirst() : traces.highestFirst(), new F1() { public Object get(String trace) { try {
return traces.get(trace) + "/" + n + "\n" + trace + "\n\n";
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "traces.get(trace) + \"/\" + n + \"\\n\" + trace + \"\\n\\n\""; }});
}
//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll = false;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions = false;
static Map ping_actions = newWeakHashMap();
static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl(true /* XXX */);
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
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 long nanoTime() {
return System.nanoTime();
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
static boolean print_silent = false; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal