Warning : session_start(): open(/var/lib/php/sessions/sess_7shkma4elsfcgq92p1mc2bhskl, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import 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.sendToLocalBotOpt;
import static loadableUtils.utils.sendToLocalBotQuietly;
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.hasBot;
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 loadableUtils.utils.SynchronizedArrayList;
import org.eclipse.collections.impl.map.mutable.primitive.*;
import org.eclipse.collections.api.tuple.primitive.*;
import java.text.NumberFormat;
class main {
static public class AModule extends DynPrintLog {
static public boolean _switchableField_query = true;
public String query = "world";
transient public LineCompedSingle lc;
transient public List> productions;
transient public Map prodLengths;
transient public int iFirstPair, iFirstFile;
transient public Map literalIndex;
transient public MultiMap prodIndex;
transient public Map> fileOffsetMap;
public void start() {
try {
super.start();
startThread("Start", new Runnable() {
public void run() {
try {
AutoCloseable __12 = enter();
try {
try {
dm_reloadOnFieldChange("query");
LineCompCompressor comp = new LineCompCompressor();
lc = lcString2(comp, "hello world world");
productions = new ArrayList();
productions.addAll(rep(null, l(lc.literals)));
iFirstPair = l(productions);
productions.addAll(intPairsToLists(lc.pairs));
iFirstFile = l(productions);
productions.add(lc.main);
prodLengths = new HashMap();
fileOffsetMap = new HashMap();
for (int i = iFirstFile; i < l(productions); i++) {
List prod = productions.get(i);
List l = new ArrayList();
int ofs = 0;
for (int x : prod) {
l.add(ofs);
ofs += getProdLength(x);
}
fileOffsetMap.put(i, l);
}
literalIndex = indexList(lc.literals);
prodIndex = new MultiMap();
for (int iProd = 0; iProd < l(productions); iProd++) {
List prod = productions.get(iProd);
for (Pair __10 : iterateListWithIndex(prod)) {
int i = pairA(__10);
int x = pairB(__10);
prodIndex.put(x, intPair(iProd, i));
}
}
print("literalIndex", literalIndex);
print("prodIndex", prodIndex);
List queryList = characters(query);
List queryLiterals = new ArrayList();
for (Character c : queryList) {
Integer iLit = literalIndex.get(c);
if (iLit == null) {
print("literal not found");
return;
}
queryLiterals.add(iLit);
}
print("queryLiterals", queryLiterals);
print("Result", reconstitute(queryLiterals, 0));
} catch (Throwable __e) {
_handleException(__e);
}
} finally {
_close(__12);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __12 = enter(); try { try {\n dm_reloadOnFieldChange query();...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public int getProdLength(int i) {
if (i < iFirstPair)
return 1;
Integer x = prodLengths.get(i);
if (x != null)
return x;
prodLengths.put(i, x = intSum(lmap(__30 -> getProdLength(__30), productions.get(i))));
return x;
}
public List reconstitute(List baseList, int i) {
List needLeft = subList(baseList, 0, i);
List needRight = subList(baseList, i + 1);
return reconstitute(baseList.get(i), lcUncompressItems(lc, needLeft), lcUncompressItems(lc, needRight));
}
public List reconstitute(int item, String needLeft, String needRight) {
print("Reconstituing " + quote(lcUncompressItem(lc, item)));
print(" needLeft: " + quote(needLeft));
print(" needRight: " + quote(needRight));
List l = prodIndex.get(item);
print("Found: " + l);
List out = new ArrayList();
search: for (IntPair p : l) {
int iProd = p.a;
List prod = productions.get(iProd);
int j = p.b;
boolean isFile = iProd >= iFirstFile;
if (isFile) {
int iChar = fileOffsetMap.get(iProd).get(j);
print("Reached file level: " + iProd + "/" + iChar + " with " + quote(needLeft) + "/" + quote(needRight));
if (nempty(needLeft))
throw fail();
int iRight = j + 1;
while (nempty(needRight)) {
if (j >= l(prod))
continue search;
String rest = itemStartsWith(prod.get(iRight), needRight);
if (rest == null)
continue search;
needRight = rest;
++iRight;
}
out.add(intPair(iProd, iChar));
} else {
if (j == 0) {
String rest = itemStartsWith(prod.get(1), needRight);
print("checking right: " + quote(lcUncompressItem(lc, prod.get(1))) + " => " + quote(rest));
if (rest == null)
continue;
out.addAll(reconstitute(iProd, needLeft, rest));
} else {
String rest = itemEndsWith(prod.get(0), needLeft);
print("checking left: " + quote(lcUncompressItem(lc, prod.get(0))) + " => " + quote(rest));
if (rest == null)
continue;
out.addAll(reconstitute(iProd, rest, needRight));
}
}
}
return out;
}
public String itemStartsWith(int i, String need) {
if (empty(need))
return need;
String have = lcUncompressItem(lc, i);
int l = lCommonPrefix(have, need);
if (l < l(need) && l < l(have))
return null;
return substring(need, l);
}
public String itemEndsWith(int i, String need) {
if (empty(need))
return need;
String have = lcUncompressItem(lc, i);
int l = lCommonSuffix(have, need);
if (l < l(need) && l < l(have))
return null;
return dropLast(need, l);
}
}
static public boolean _moduleClass_AModule = true;
static public String programID;
static public void _onLoad_initUtils() {
utils.__javax = javax();
}
static public void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
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 ThreadLocal dynamicObjectIsLoading_threadLocal() {
return DynamicObject_loading;
}
static public Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static public Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
static public Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static public void dm_reloadOnFieldChange(String... fields) {
for (String field : unnull(fields)) dm_onFieldChange(field, new Runnable() {
public void run() {
try {
dm_reloadModule();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_reloadModule();";
}
});
}
static public LineCompedSingle lcString2(String text) {
return lcString2(new LineCompCompressor(), text);
}
static public LineCompedSingle lcString2(LineCompCompressor compressor, String text) {
Map data = litmap("", text);
compressor.byteMode = true;
compressor.loadTexts(data);
compressor.verify = true;
compressor.run();
List literals = new ArrayList();
List pairs = new ArrayList();
for (LineCompCompressor.Chunk c : compressor.chunks) if (c instanceof LineCompCompressor.CPair)
pairs.add(new IntPair(((LineCompCompressor.CPair) c).i1, ((LineCompCompressor.CPair) c).i2));
else
literals.add(charFromHex(((LineCompCompressor.CPrim) c).s));
return new LineCompedSingle(literals, pairs, firstValue(compressor.finalEncodings));
}
static public String rep(int n, char c) {
return repeat(c, n);
}
static public String rep(char c, int n) {
return repeat(c, n);
}
static public List rep(A a, int n) {
return repeat(a, n);
}
static public List rep(int n, A a) {
return repeat(n, a);
}
static public List> intPairsToLists(Iterable l) {
return lmap(__31 -> intPairToList(__31), l);
}
static public Map indexList(List l) {
return listIndex(l);
}
static public IterableIterator> iterateListWithIndex(Collection l) {
return iff(new Object() {
public Iterator it = iterator(l);
public int i;
public Object get() {
if (!it.hasNext())
return endMarker();
return pair(i++, it.next());
}
});
}
static public A pairA(Pair p) {
return p == null ? null : p.a;
}
static public B pairB(Pair p) {
return p == null ? null : p.b;
}
static public IntPair intPair(int a, int b) {
return new IntPair(a, b);
}
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 print_byThread;
static volatile public Object print_allThreads;
static volatile public Object print_preprocess;
static public void print() {
print("");
}
static public A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
static public 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 List characters(final String s) {
return stringAsCharacterList(s);
}
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 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 int intSum(Collection c, String field) {
int sum = 0;
for (Object o : unnull(c)) sum += toInt(getOpt(o, field));
return sum;
}
static public int intSum(Iterable l) {
int sum = 0;
for (Integer i : unnull(l)) if (i != null)
sum += i;
return sum;
}
static public List lmap(IF1 f, Iterable l) {
return lambdaMap(f, l);
}
static public List lmap(IF1 f, A[] l) {
return lambdaMap(f, l);
}
static public List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static public List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static public List subList(List 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 String lcUncompressItems(LineCompedSingle lc, List indices) {
return joinMap(i -> lcUncompressItem(lc, i), indices);
}
static public String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
static public String quote(String s) {
if (s == null)
return "null";
StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
quote_impl(s, out);
return out.toString();
}
static public void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static public String lcUncompressItem(LineCompedSingle lc, int idx) {
StringBuilder buf = new StringBuilder();
uncompressLineCompedSingle_step(lc, buf, ll(idx));
return str(buf);
}
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 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(MultiMap mm) {
return mm == null || mm.isEmpty();
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public int lCommonPrefix(String a, String b) {
int i = 0, n = min(l(a), l(b));
while (i < n && a.charAt(i) == b.charAt(i)) ++i;
return i;
}
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 lCommonSuffix(String a, String b) {
int i = 0;
while (i < a.length() && i < b.length() && a.charAt(a.length() - 1 - i) == b.charAt(b.length() - 1 - i)) ++i;
return i;
}
static public A[] dropLast(A[] a) {
return dropLast(a, 1);
}
static public A[] dropLast(A[] a, int n) {
if (a == null)
return null;
n = Math.min(n, a.length);
A[] b = arrayOfSameType(a, a.length - n);
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static public List dropLast(List l) {
return subList(l, 0, l(l) - 1);
}
static public List dropLast(int n, List l) {
return subList(l, 0, l(l) - n);
}
static public List dropLast(Iterable 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 Class javax() {
return getJavaX();
}
static public void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
static public HashMap 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 AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
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 Object _defaultClassFinder_value = defaultDefaultClassFinder();
static public Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
static public String defaultThreadName_name;
static public String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static public Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
static public Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
static public Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static public Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
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 Map _registerThread_threads;
static public Object _onRegisterThread;
static public Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static public void _registerThread() {
_registerThread(Thread.currentThread());
}
static public String unnull(String s) {
return s == null ? "" : s;
}
static public Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static public List unnull(List l) {
return l == null ? emptyList() : l;
}
static public Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static public Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static public A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static public Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public void dm_onFieldChange(String field, Runnable onChange) {
dm_watchField(field, onChange);
}
static public void dm_reloadModule(Object module) {
dm_reloadModuleInBackground(module);
}
static public void dm_reloadModule() {
dm_reloadModuleInBackground();
}
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 char charFromHex(String s) {
return (char) hexToInt(s);
}
static public B firstValue(Map map) {
return first(values(map));
}
static public B firstValue(MultiSetMap map) {
return map == null ? null : first(firstValue(map.data));
}
static public String repeat(char c, int n) {
n = Math.max(n, 0);
char[] chars = new char[n];
for (int i = 0; i < n; i++) chars[i] = c;
return new String(chars);
}
static public List repeat(A a, int n) {
n = Math.max(n, 0);
List l = new ArrayList(n);
for (int i = 0; i < n; i++) l.add(a);
return l;
}
static public List repeat(int n, A a) {
return repeat(a, n);
}
static public List intPairToList(IntPair p) {
return p == null ? null : ll(p.a, p.b);
}
static public Map listIndex(List l) {
Map map = new HashMap();
for (int i = 0; i < l(l); i++) map.put(l.get(i), i);
return map;
}
static public IterableIterator iff(Object f) {
return iteratorFromFunction_withEndMarker(f);
}
static public IterableIterator iff(F0 f) {
return iteratorFromFunction_withEndMarker(f);
}
static public IterableIterator iff(IF0 f) {
return iteratorFromFunction_withEndMarker(f);
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public Object endMarker() {
return iteratorFromFunction_endMarker;
}
static public Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
static public boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
static public void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
static public Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static public A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static public A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static public ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static public boolean isFalse(Object o) {
return eq(false, o);
}
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 callF(F0 f) {
return f == null ? null : f.get();
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public void callF(VF1 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 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 List stringAsCharacterList(final String s) {
if (s == null)
return null;
return new RandomAccessAbstractList() {
final public int l = l(s);
public int size() {
return l;
}
public Character get(int i) {
return s.charAt(i);
}
};
}
static public List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(l);
}
static public List 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 boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static public ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
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 List lambdaMap(IF1 f, Iterable l) {
return map(l, f);
}
static public List lambdaMap(IF1 f, A[] l) {
return map(l, f);
}
static public String joinMap(Object f, Iterable l) {
return join(map(f, l));
}
static public String joinMap(Iterable l, Object f) {
return joinMap(f, l);
}
static public String joinMap(Iterable l, IF1 f) {
return joinMap(f, l);
}
static public String joinMap(IF1 f, Iterable l) {
return join(map(f, l));
}
static public String joinMap(String separator, Map map, IF2 f) {
return join(separator, map(map, f));
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public String uncompressLineCompedSingle(LineCompedSingle lc) {
StringBuilder buf = new StringBuilder();
uncompressLineCompedSingle_step(lc, buf, lc.main);
return str(buf);
}
static public void uncompressLineCompedSingle_step(LineCompedSingle lc, StringBuilder buf, List chunks) {
for (int idx : chunks) if (idx < l(lc.literals))
buf.append(lc.literals.get(idx));
else
uncompressLineCompedSingle_step(lc, buf, intPairToList(lc.pairs.get(idx - l(lc.literals))));
}
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 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 int strL(String s) {
return s == null ? 0 : s.length();
}
static public A[] arrayOfSameType(A[] a, int n) {
return newObjectArrayOfSameType(a, n);
}
static public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static public ArrayList asList(double[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static public ArrayList asList(Iterable s) {
if (s instanceof ArrayList)
return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s) l.add(a);
return l;
}
static public ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null)
while ((a = p.next()) != null) l.add(a);
return l;
}
static public ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public Class __javax;
static public Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object iteratorFromFunction_endMarker = new Object();
static public IterableIterator iteratorFromFunction_withEndMarker(final Object f) {
class IFF extends IterableIterator {
public A a;
public boolean have, done;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
have = false;
return _a;
}
public void getNext() {
if (done || have)
return;
Object o = callF(f);
if (o == iteratorFromFunction_endMarker) {
done = true;
return;
}
a = (A) o;
have = true;
}
}
;
return new IFF();
}
static public IterableIterator iteratorFromFunction_withEndMarker(final F0 f) {
return iteratorFromFunction_withEndMarker_f0(f);
}
static public ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
static public AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
static public String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
static public Object defaultDefaultClassFinder() {
return new F1() {
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 String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static public Runnable _topLevelErrorHandling(final Runnable runnable) {
final Object info = _threadInfo();
return new Runnable() {
public void run() {
try {
try {
_threadInheritInfo(info);
runnable.run();
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }";
}
};
}
static public WeakReference weakRef(A a) {
return newWeakReference(a);
}
static public Class mc() {
return main.class;
}
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 ArrayList emptyList(Class c) {
return new ArrayList();
}
static public Map emptyMap() {
return new HashMap();
}
static public Object[] emptyObjectArray_a = new Object[0];
static public Object[] emptyObjectArray() {
return emptyObjectArray_a;
}
static public void dm_watchField(String field, Runnable onChange) {
new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange);
}
static public void dm_reloadModuleInBackground(Object module) {
dm_callOS("reloadModuleInBackground", dm_getStem(module));
}
static public void dm_reloadModuleInBackground() {
dm_reloadModuleInBackground(dm_current_mandatory_generic());
}
static public int hexToInt(String s) {
return Integer.parseInt(s, 16);
}
static public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public A first(IterableIterator i) {
return first((Iterator ) i);
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public A first(Pair p) {
return p == null ? null : p.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static public Collection values(Object map) {
return values((Map) map);
}
static public Collection values(MultiMap mm) {
return mm == null ? emptyList() : concatLists(values(mm.data));
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
static volatile public boolean ping_pauseAll = false;
static public int ping_sleep = 100;
static volatile public boolean ping_anyActions = false;
static public Map ping_actions = newWeakHashMap();
static public ThreadLocal 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 A or(A a, A b) {
return a != null ? a : b;
}
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 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 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 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 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 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 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 public List map(Iterable l, Object f) {
return map(f, l);
}
static public List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) x.add(callF(f, o));
return x;
}
static public List map(Iterable l, F1 f) {
return map(f, l);
}
static public List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(callF(f, o));
return x;
}
static public List map(IF1 f, Iterable l) {
return map(l, f);
}
static public List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
static public List map(IF1 f, A[] l) {
return map(l, f);
}
static public List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
static public List map(Object f, Object[] l) {
return map(f, asList(l));
}
static public List map(Object[] l, Object f) {
return map(f, l);
}
static public List map(Object f, Map map) {
return map(map, f);
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Map map, IF2 f) {
return map(map, (Object) f);
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static public String join(Iterable strings) {
return join("", strings);
}
static public String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static public String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static public A[] newObjectArrayOfSameType(A[] a, int n) {
return (A[]) Array.newInstance(a.getClass().getComponentType(), n);
}
static public IterableIterator iteratorFromFunction_withEndMarker_f0(final F0 f) {
class IFF2 extends IterableIterator {
public A a;
public boolean have, done;
public boolean hasNext() {
getNext();
return !done;
}
public A next() {
getNext();
if (done)
throw fail();
A _a = a;
a = null;
have = false;
return _a;
}
public void getNext() {
if (done || have)
return;
Object o = f.get();
if (o == iteratorFromFunction_endMarker) {
done = true;
return;
}
a = (A) o;
have = true;
}
}
;
return new IFF2();
}
static public AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null)
return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
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|cookie)=[^&\\s\"]*", "$1$2=");
}
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 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 WeakReference newWeakReference(A a) {
return a == null ? null : new WeakReference(a);
}
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 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 Object dm_callOS(String functionName, Object... args) {
return call(dm_os(), functionName, args);
}
static public Object dm_getStem(Object moduleOrID) {
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
moduleOrID = dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_getStemByID(moduleOrID);
return or(getOpt(dm_getModule(moduleOrID), "_host"), moduleOrID);
}
static public List concatLists(Iterable ... lists) {
List l = new ArrayList();
if (lists != null)
for (Iterable list : lists) addAll(l, list);
return l;
}
static public List concatLists(Collection extends Iterable > lists) {
List l = new ArrayList();
if (lists != null)
for (Iterable list : lists) addAll(l, list);
return l;
}
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 final public Map 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 String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static public List classNames(Collection l) {
return getClassNames(l);
}
static public List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static public Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
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 boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static public A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
static public boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x))
return true;
return false;
}
static public boolean startsWithOneOf(String s, Matches m, String... l) {
for (String x : l) if (startsWith(s, x, m))
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 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 Object dm_os() {
{
Object __1 = vm_generalMap_get("stefansOS");
if (__1 != null)
return __1;
}
return creator();
}
static public boolean isString(Object o) {
return o instanceof String;
}
static public boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static public Object dm_getService(String serviceName) {
return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName)));
}
static public boolean isStringOrIntOrLong(Object o) {
return o instanceof String || o instanceof Integer || o instanceof Long;
}
static public Object dm_getStemByID(Object id) {
return dm_callOS("getModuleByID", str(id));
}
static public Object dm_getModule(Object moduleOrID) {
if (moduleOrID == null || eq(moduleOrID, ""))
return null;
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
return dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
static public void addAll(Collection c, Iterable b) {
if (c != null && b != null)
for (A a : b) c.add(a);
}
static public boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static public boolean addAll(Collection c, B... b) {
return c != null && c.addAll(Arrays.asList(b));
}
static public Map addAll(Map a, Map extends A, ? extends B> b) {
if (a != null)
a.putAll(b);
return a;
}
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 Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static public String joinWithSpace(Iterable 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, Math.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[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
static public A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
static public List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
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);
}
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 Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static public WeakReference creator_class;
static public Object creator() {
return creator_class == null ? null : creator_class.get();
}
static public boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static public Object vmBus_query(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
{
Object __1 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg);
if (__1 != null)
return __1;
}
return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public Object vmBus_query(String msg) {
return vmBus_query(msg, (Object) null);
}
static public String assertIdentifier(String s) {
return assertIsIdentifier(s);
}
static public String assertIdentifier(String msg, String s) {
return assertIsIdentifier(msg, s);
}
static public Object dm_resolveModule(Object moduleOrStem) {
return dm_callOS("resolveModule", moduleOrStem);
}
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[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
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 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 Map vm_generalMap_map;
static public Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
static public Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
static public Object pcallFAll_returnFirstNotNull(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
Object __1 = pcallF(f, args);
if (__1 != null)
return __1;
}
return null;
}
static public Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) {
while (it.hasNext()) {
Object __2 = pcallF(it.next(), args);
if (__2 != null)
return __2;
}
return null;
}
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 vm_busListenersByMessage_live_cache;
static public Map 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 vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static public String assertIsIdentifier(String s) {
if (!isIdentifier(s))
throw fail("Not an identifier: " + quote(s));
return s;
}
static public String assertIsIdentifier(String msg, String s) {
if (!isIdentifier(s))
throw fail(msg + " - Not an identifier: " + quote(s));
return s;
}
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 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 Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static public A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public void pcallF(VF1 f, A a) {
try {
if (f != null)
f.get(a);
} catch (Throwable __e) {
_handleException(__e);
}
}
static public boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
}
static public String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
static public Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
static public Object callFunction(Object f, Object... args) {
return callF(f, args);
}
final static public class _MethodCache {
final public Class c;
final public HashMap> cache = new HashMap();
public _MethodCache(Class c) {
this.c = c;
_init();
}
public void _init() {
Class _c = c;
while (_c != null) {
for (Method m : _c.getDeclaredMethods()) if (!isAbstract(m) && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
_c = _c.getSuperclass();
}
for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
}
public Method findMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public Method findStaticMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (isStaticMethod(me) && call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
static public class LineCompedSingle implements IFieldsToList {
public List literals;
public List pairs;
public List main;
public LineCompedSingle() {
}
public LineCompedSingle(List literals, List pairs, List main) {
this.main = main;
this.pairs = pairs;
this.literals = literals;
}
public String toString() {
return shortClassName(this) + "(" + literals + ", " + pairs + ", " + main + ")";
}
public Object[] _fieldsToList() {
return new Object[] { literals, pairs, main };
}
public long roughCount() {
return l(literals) + l(pairs) * 2 + l(main);
}
public int nLiterals() {
return l(literals);
}
public int nItems() {
return l(literals) + l(pairs);
}
}
static public class MultiMap {
public Map > data = new HashMap >();
public MultiMap() {
}
public MultiMap(boolean useTreeMap) {
if (useTreeMap)
data = new TreeMap();
}
public MultiMap(MultiMap map) {
putAll(map);
}
public MultiMap(Map > data) {
this.data = data;
}
public void put(A key, B value) {
synchronized (data) {
List list = data.get(key);
if (list == null)
data.put(key, list = _makeEmptyList());
list.add(value);
}
}
public void add(A key, B value) {
put(key, value);
}
public void addAll(A key, Collection values) {
putAll(key, values);
}
public void addAllIfNotThere(A key, Collection values) {
synchronized (data) {
for (B value : values) setPut(key, value);
}
}
public void setPut(A key, B value) {
synchronized (data) {
if (!containsPair(key, value))
put(key, value);
}
}
public boolean containsPair(A key, B value) {
synchronized (data) {
return get(key).contains(value);
}
}
public void putAll(A key, Collection values) {
synchronized (data) {
if (nempty(values))
getActual(key).addAll(values);
}
}
public void removeAll(A key, Collection values) {
synchronized (data) {
for (B value : values) remove(key, value);
}
}
public List get(A key) {
synchronized (data) {
List list = data.get(key);
return list == null ? Collections.emptyList() : list;
}
}
public List getActual(A key) {
synchronized (data) {
List list = data.get(key);
if (list == null)
data.put(key, list = _makeEmptyList());
return list;
}
}
public void clean(A key) {
synchronized (data) {
List list = data.get(key);
if (list != null && list.isEmpty())
data.remove(key);
}
}
public Set keySet() {
synchronized (data) {
return data.keySet();
}
}
public Set keys() {
synchronized (data) {
return data.keySet();
}
}
public void remove(A key) {
synchronized (data) {
data.remove(key);
}
}
public void remove(A key, B value) {
synchronized (data) {
List list = data.get(key);
if (list != null) {
list.remove(value);
if (list.isEmpty())
data.remove(key);
}
}
}
public void clear() {
synchronized (data) {
data.clear();
}
}
public boolean containsKey(A key) {
synchronized (data) {
return data.containsKey(key);
}
}
public B getFirst(A key) {
synchronized (data) {
List list = get(key);
return list.isEmpty() ? null : list.get(0);
}
}
public void addAll(MultiMap map) {
putAll(map);
}
public void putAll(MultiMap map) {
synchronized (data) {
for (A key : map.keySet()) putAll(key, map.get(key));
}
}
public void putAll(Map map) {
synchronized (data) {
if (map != null)
for (Map.Entry e : map.entrySet()) put(e.getKey(), e.getValue());
}
}
public int keysSize() {
synchronized (data) {
return l(data);
}
}
public int size() {
synchronized (data) {
int n = 0;
for (List l : data.values()) n += l(l);
return n;
}
}
public List reverseGet(B b) {
synchronized (data) {
List l = new ArrayList();
for (A key : data.keySet()) if (data.get(key).contains(b))
l.add(key);
return l;
}
}
public Map > asMap() {
synchronized (data) {
return cloneMap(data);
}
}
public boolean isEmpty() {
synchronized (data) {
return data.isEmpty();
}
}
public List _makeEmptyList() {
return new ArrayList();
}
public Collection> allLists() {
synchronized (data) {
return new ArrayList(data.values());
}
}
public Collection> values() {
return allLists();
}
public List allValues() {
return concatLists(data.values());
}
public Object mutex() {
return data;
}
public String toString() {
return "mm" + str(data);
}
}
static public interface IF0 {
public A get();
}
static public interface IF2 {
public C get(A a, B b);
}
final static public class LineCompCompressor {
public int safety = 0;
abstract static public class Chunk {
abstract public String text(List chunks);
public IntPair getPair() {
return null;
}
}
static public class CPair extends Chunk implements IFieldsToList {
public int i1;
public int i2;
public CPair() {
}
public CPair(int i1, int i2) {
this.i2 = i2;
this.i1 = i1;
}
public String toString() {
return shortClassName(this) + "(" + i1 + ", " + i2 + ")";
}
public boolean equals(Object o) {
if (!(o instanceof CPair))
return false;
CPair x = (CPair) o;
return eq(i1, x.i1) && eq(i2, x.i2);
}
public int hashCode() {
int h = 64355773;
h = boostHashCombine(h, _hashCode(i1));
h = boostHashCombine(h, _hashCode(i2));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { i1, i2 };
}
public CPair(IntPair p) {
i1 = p.a;
i2 = p.b;
}
public String text(List chunks) {
return linesLL_rtrim(chunks.get(i1).text(chunks), chunks.get(i2).text(chunks));
}
public IntPair getPair() {
return new IntPair(i1, i2);
}
}
static public class CPrim extends Chunk implements IFieldsToList {
public String s;
public CPrim() {
}
public CPrim(String s) {
this.s = s;
}
public String toString() {
return shortClassName(this) + "(" + s + ")";
}
public boolean equals(Object o) {
if (!(o instanceof CPrim))
return false;
CPrim x = (CPrim) o;
return eq(s, x.s);
}
public int hashCode() {
int h = 64372105;
h = boostHashCombine(h, _hashCode(s));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { s };
}
public String text(List chunks) {
return s;
}
}
public boolean verbose = false, verboseCompressionSteps = false;
public boolean verboseStats = false;
public boolean sortLines = true;
public boolean verify = true;
public boolean byteMode = false;
public boolean caseInsensitive = false;
public LineComp_PairIndex pairIndex = new LineComp_PairIndex();
public Map> textIDToLines;
public List allUniqueLines;
public List chunks = new ArrayList();
public int primChunks;
public Map lineIndex;
public Map> simpleEncodings;
public Map> finalEncodings;
public LongIntHashMap existingPairsIndex = new LongIntHashMap();
public int round, printStatsEvery = 0, printStatsInFirstRounds = 10;
public int printStatsEveryNSeconds = 60;
public Map fullIndex;
public LineCompCompressor() {
}
public LineCompCompressor(Map texts) {
loadTexts(texts);
}
public void loadTexts(Map texts) {
textIDToLines = mapValuesToLinkedHashMap(__49 -> myToLines(__49), texts);
}
public List myToLines(String s) {
List l = byteMode ? lambdaMap(__32 -> charToHex(__32), characters(s)) : toLines_nOnly_reversible(s);
return l;
}
public String myFromLines(List l) {
return byteMode ? join(mapI("hexToChar", l)) : fromLines_rtrim(l);
}
public void run() {
List allLines = concatLists(values(textIDToLines));
if (verboseCompressionSteps)
print("Uniquifying " + nLines(allLines));
allUniqueLines = uniquify(allLines);
if (verboseCompressionSteps)
print("Have " + n2(allUniqueLines, "unique line"));
allLines = null;
if (sortLines)
sortInPlace(allUniqueLines);
if (verboseCompressionSteps)
print("Sorted " + nLines(allUniqueLines));
for (String line : allUniqueLines) chunks.add(new CPrim(line));
primChunks = l(chunks);
List _lines = collect("s", chunks);
lineIndex = caseInsensitive ? ciListIndex(_lines) : listIndex(_lines);
_lines = null;
simpleEncodings = mapValues(textIDToLines, (IF1, List>) (lines -> wrapIntArrayAsImmutableList(mapToIntArray(lines, line -> lineIndex.get(line)))));
if (verboseCompressionSteps)
print("Have simple encodings");
finalEncodings = compressPairs();
if (verbose || verify)
printAndCheckEncodings(finalEncodings);
}
public void saveAsTextFile(File f) {
String out = exportEncoding(finalEncodings);
saveTextFile(f, out);
if (verify)
checkDecompression(f, textIDToLines);
}
public void checkDecompression(File file, Map> textIDToLines) {
BufferedReader reader = bufferedUtf8Reader(file);
try {
LineCompReader lcr = new LineCompReader(reader);
assertEquals(keysList(textIDToLines), asList(lcr.versions()));
for (String version : keys(textIDToLines)) assertEquals(lcr.textForVersion(version), lines_rtrim(textIDToLines.get(version)));
if (verbose)
print("Decompression OK for " + nVersions(textIDToLines));
} finally {
_close(reader);
}
}
public String asText() {
return exportEncoding(finalEncodings);
}
public String exportEncoding(Map> encodings) {
List buf = new ArrayList();
buf.add((byteMode ? "BYTECOMP " : "LINECOMP ") + primChunks);
for (Chunk c : chunks) {
if (c instanceof CPair)
buf.add(((CPair) c).i1 + " " + ((CPair) c).i2);
else
buf.add(((CPrim) c).s);
}
for (String id : keys(encodings)) {
List l = encodings.get(id);
buf.add(id + "=" + joinWithSpace(l));
}
return lines_rtrim(buf);
}
public Map> compressPairs() {
pairIndex.verbose = verboseCompressionSteps;
pairIndex.init();
for (String version : keys(simpleEncodings)) {
List l = simpleEncodings.get(version);
pairIndex.newChain(version, l);
}
pairIndex.haveChains();
simpleEncodings = null;
return compressChains(keys(pairIndex.chains));
}
public Map> compressChains(Collection files) {
NotTooOften nto = new NotTooOften(printStatsEveryNSeconds * 1000);
IntPair toCompress;
while ((toCompress = pairIndex.mostPopularDuplicate()) != null) {
ping();
if (safety > 0 && --safety <= 0)
throw fail("safety");
++round;
if (verboseStats)
if (printStatsEvery > 0 && (round % printStatsEvery) == 0 || round <= printStatsInFirstRounds || nto.get())
printStats();
int count = pairIndex.getCount(toCompress);
Integer idx = makeCPair(toCompress);
int dups = pairIndex.numberOfDuplicates();
if (verboseCompressionSteps)
print("Compressing pair " + toCompress + " (count=" + count + ") -> " + idx + ", " + (dups - 1) + " remaining");
pairIndex.replacePair(toCompress.a, toCompress.b, idx);
}
if (verboseStats)
printStats();
return mapToValues(f -> pairIndex.chains.get(f).toList(), files);
}
public Integer makeCPair(IntPair p) {
long l = intPairToLong(p);
String text = null;
if (fullIndex != null) {
text = itemToString(p.a) + itemToString(p.b);
Integer idx = fullIndex.get(text);
if (idx != null)
return idx;
}
int idx = existingPairsIndex.getIfAbsent(l, -1);
if (idx < 0) {
idx = addAndReturnIndex(chunks, new CPair(p));
existingPairsIndex.put(l, idx);
if (fullIndex != null)
fullIndex.put(text, idx);
}
return idx;
}
public void printAndCheckEncodings(Map> encodings) {
for (String id : keys(encodings)) {
List encoded = encodings.get(id);
if (verbose)
print(id + ": " + joinWithSpace(encoded));
String x = myFromLines(textIDToLines.get(id)), y = decode(encoded);
if (caseInsensitive)
assertEqualsIC(x, y);
else
assertEquals_quote(x, y);
}
}
public String decode(List encoded) {
List l = lambdaMap(__33 -> chunkText(__33), encoded);
if (byteMode)
l = lines(lines(l));
return myFromLines(l);
}
public String chunkText(int idx) {
return chunks.get(idx).text(chunks);
}
public void printStats() {
print("Round: " + round);
pairIndex.printStats();
}
public String itemToString(int idx) {
StringBuilder buf = new StringBuilder();
itemToString_step(buf, idx);
return str(buf);
}
public void itemToString_step(StringBuilder buf, int idx) {
Chunk c = chunks.get(idx);
if (c instanceof CPair) {
itemToString_step(buf, ((CPair) c).i1);
itemToString_step(buf, ((CPair) c).i2);
} else {
String s = ((CPrim) c).s;
buf.append(byteMode ? charFromHex(s) : s + "\n");
}
}
public int nLiterals() {
return primChunks;
}
public int nItems() {
return l(chunks);
}
public IntPair getPair(int idx) {
return chunks.get(idx).getPair();
}
}
static abstract public class IterableIterator implements Iterator , Iterable {
public Iterator iterator() {
return this;
}
public void remove() {
unsupportedOperation();
}
}
static public class Dyn_FieldWatcher {
public DynModule module;
public String field;
public Object value;
public Runnable action;
transient public IF1 cloneValue;
public Object cloneValue(Object o) {
return cloneValue != null ? cloneValue.get(o) : cloneValue_base(o);
}
final public Object cloneValue_fallback(IF1 _f, Object o) {
return _f != null ? _f.get(o) : cloneValue_base(o);
}
public Object cloneValue_base(Object o) {
return o;
}
public Dyn_FieldWatcher(DynModule module, String field, Runnable action) {
this(module, field, action, null);
}
public Dyn_FieldWatcher(DynModule module, String field, Runnable action, IF1 cloneValue) {
this.cloneValue = cloneValue;
this.action = action;
this.field = field;
this.module = module;
value = cloneValue(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() {
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 = cloneValue(get(module, field));
if (eq(value, newValue))
return;
value = newValue;
dm_q(module, action);
}
}
abstract static public class RandomAccessAbstractList extends AbstractList implements RandomAccess {
}
static final public class IntPair implements Comparable, IFieldsToList {
public int a;
public int b;
public IntPair() {
}
public IntPair(int a, int b) {
this.b = b;
this.a = a;
}
public String toString() {
return shortClassName(this) + "(" + a + ", " + b + ")";
}
public Object[] _fieldsToList() {
return new Object[] { a, b };
}
public boolean equals(Object o) {
if (!(o instanceof IntPair))
return false;
IntPair x = (IntPair) o;
return a == x.a && b == x.b;
}
public int hashCode() {
int h = -672893111;
h = boostHashCombine(h, _hashCode(a));
h = boostHashCombine(h, _hashCode(b));
return h;
}
public int compareTo(IntPair p) {
if (p == null)
return 1;
int pa = p.a;
if (a < pa)
return -1;
if (a > pa)
return 1;
return Integer.compare(b, p.b);
}
}
static public class Pair implements Comparable> {
public A a;
public B b;
public Pair() {
}
public Pair(A a, B b) {
this.b = b;
this.a = a;
}
public int hashCode() {
return hashCodeFor(a) + 2 * hashCodeFor(b);
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Pair))
return false;
Pair t = (Pair) o;
return eq(a, t.a) && eq(b, t.b);
}
public String toString() {
return "<" + a + ", " + b + ">";
}
public int compareTo(Pair p) {
if (p == null)
return 1;
int i = ((Comparable ) a).compareTo(p.a);
if (i != 0)
return i;
return ((Comparable) b).compareTo(p.b);
}
}
static public interface IFieldsToList {
public Object[] _fieldsToList();
}
final static public class LineComp_PairIndex {
public boolean verbose = false;
public boolean inOrder = true;
public LongObjectHashMap> nodes = new LongObjectHashMap();
public MultiSetMap byCount = null;
public LinkedHashMap chains = new LinkedHashMap();
public Ch firstChain;
public int totalPairCount;
public int initialNodesSetCapacity = 1;
public void init() {
}
public void haveChains() {
if (byCount == null) {
byCount = multiSetMap_innerCompactHashSet_outerRevTreeMap();
for (Set set : nodes.values()) byCount.put(set.size(), first(set).pair());
}
}
static public class Ch {
public Node tail;
public Ch(LineComp_PairIndex pi, List l) {
int count = 0;
for (int i : unnull(l)) {
add(pi, i);
if (((++count) % oneMillion()) == 0)
print("Added " + n2(count) + " entries to chain");
}
}
public List toList() {
List l = new ArrayList();
Node node = tail;
while (node != null) {
l.add(node.value);
node = node.prev;
}
return reverseInPlace(l);
}
public void add(LineComp_PairIndex pi, int i) {
Node n = new Node();
n.ch = this;
n.value = i;
n.prev = tail;
if (tail != null)
tail.next = n;
tail = n;
pi.addToIndex(n.prev);
}
}
static public class Node {
public Ch ch;
public int value;
public Node prev, next;
public int a() {
return value;
}
public int b() {
return next == null ? -1 : next.value;
}
public IntPair pair() {
return next == null ? null : new IntPair(a(), b());
}
}
public IntPair nodeToPair(Node n) {
return n == null ? null : n.pair();
}
public void addToIndex(Node n) {
IntPair p = nodeToPair(n);
if (p == null)
return;
int count = nodes_getSize(p);
nodes_add(p, n);
if (byCount != null) {
if (count != 0)
byCount.remove(count, p);
byCount.put(count + 1, p);
}
}
public void removeFromIndex(Node n) {
IntPair p = nodeToPair(n);
if (p == null)
return;
int count = nodes_getSize(p);
if (count == 0)
throw fail("Can't remove pair " + p);
nodes_remove(p, n);
byCount.remove(count, p);
if (--count > 0)
byCount.put(count, p);
}
public IntPair mostPopularDuplicate() {
return toInt(firstKey(byCount)) < 2 ? null : firstValue(byCount);
}
public int numberOfDuplicates() {
return byCount.size() - l(byCount.get(1));
}
public int getCount(IntPair p) {
return nodes_getSize(p);
}
public void replacePair(int pa, int pb, int replaceWith) {
IntPair p = new IntPair(pa, pb);
Set set = nodes.get(intPairToLong(p));
if (set != null)
for (Node n : cloneList(set)) {
{
if (n.a() != pa || n.b() != pb)
continue;
}
replacePair(n, replaceWith);
}
}
public void replacePair(Node node, int replaceWith) {
removeFromIndex(node.prev);
removeFromIndex(node);
removeFromIndex(node.next);
node.value = replaceWith;
deleteNode(node.next);
addToIndex(node.prev);
addToIndex(node);
}
public void deleteNode(Node node) {
if (node.next != null)
node.next.prev = node.prev;
else
getChain(node).tail = node.prev;
if (node.prev != null)
node.prev.next = node.next;
node.value = -1;
}
public void newChain(String version, List encoding) {
Ch ch = new Ch(this, encoding);
chains.put(version, ch);
}
public int nodes_getSize(IntPair p) {
return l(nodes.get(intPairToLong(p)));
}
public void nodes_add(IntPair p, Node n) {
++totalPairCount;
long l = intPairToLong(p);
LinkedHashSet set = nodes.get(l);
if (set == null)
nodes.put(l, set = new LinkedHashSet(initialNodesSetCapacity));
set.add(n);
}
public void nodes_remove(IntPair p, Node n) {
--totalPairCount;
long l = intPairToLong(p);
LinkedHashSet set = nodes.get(l);
if (set == null || !set.remove(n))
throw fail("Consistency error");
if (set.isEmpty())
nodes.remove(l);
}
public void printStats() {
print("Different pairs: " + l(nodes));
print("Different counts: " + byCount.keysSize() + " (highest count: " + firstKey(byCount) + ")");
long count = 0, waste = 0, newWaste = 0;
long count1 = 0, waste1 = 0;
for (HashSet set : nodes.values()) {
count1 += set.size();
int capacity = hashSetCapacity(set);
waste1 += capacity - set.size();
}
for (CompactHashSet set : (Collection) (Collection) values(byCount.data)) {
count += set.size();
waste += set.capacity() - set.size();
set.shrinkToFactor(0.5);
newWaste += set.capacity() - set.size();
}
print("Nodes set count: " + count1 + ". Waste: " + waste1);
print("Set count: " + count + ". Waste: " + waste + (waste == newWaste ? "" : " => " + newWaste));
print("Duplicates: " + n2(totalPairCount - byCount.count(1)));
}
public Ch getChain(Node node) {
return node.ch;
}
}
static public class NotTooOften {
public long minDelay;
public long lastTime;
public NotTooOften() {
}
public NotTooOften(long minDelay) {
this.minDelay = minDelay;
}
public boolean canDoAgain_willDoIfTrue() {
if (lastTime == 0 || now() >= lastTime + minDelay) {
lastTime = now();
return true;
}
return false;
}
public boolean yo() {
return canDoAgain_willDoIfTrue();
}
public boolean get() {
return canDoAgain_willDoIfTrue();
}
}
static public class LineCompReader {
public List literals = new ArrayList();
public int[] literalOffsets;
public List pairs = new ArrayList();
public LinkedHashMap> versions = new LinkedHashMap();
public LineCompReader(File f) {
BufferedReader reader = rawByteReader_possiblyGZipped(f);
try {
load(reader);
} finally {
_close(reader);
}
}
public LineCompReader(InputStream in) {
load(rawBytesReader(in));
}
public LineCompReader(BufferedReader reader) {
load(reader);
}
public void load(BufferedReader reader) {
try {
String s = readLineIgnoreCR(reader);
int ofs = l(s) + 1;
Matches m = new Matches();
if (!startsWith(s, "LINECOMP ", m))
throw fail("Not a LINECOMP file");
int nLiterals = parseInt(m.rest());
IntBuffer offsets = new IntBuffer();
for (int i = 0; i < nLiterals; i++) {
String line = readLineIgnoreCR(reader);
literals.add(assertNotNull(line));
offsets.add(ofs);
ofs += l(line) + 1;
}
offsets.add(ofs);
literalOffsets = offsets.toArray();
while (licensed()) {
s = readLineIgnoreCR(reader);
if (s == null || contains(s, "="))
break;
try {
pairs.add(assertNotNull(listToIntPair(parseInts(splitAtSpace(s)))));
} catch (Throwable _e) {
print("On line " + (nLiterals + l(pairs)));
throw rethrow(_e);
}
}
while (contains(s, "=")) {
int i = indexOf(s, '=');
versions.put(takeFirst(s, i), parseInts(splitAtSpace(substring(s, i + 1))));
s = readLineIgnoreCR(reader);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public Set versions() {
return keys(versions);
}
public String getText(String version) {
return textForVersion(version);
}
public String textForVersion(String version) {
List encoded = versions.get(version);
if (encoded == null)
return null;
List buf = new ArrayList();
for (int idx : encoded) decode(idx, buf);
return myFromLines(buf);
}
public String myFromLines(List l) {
return fromLines_rtrim(l);
}
public void decode(int idx, List buf) {
if (idx < l(literals))
buf.add(literals.get(idx));
else {
IntPair p = pairs.get(idx - l(literals));
decode(p.a, buf);
decode(p.b, buf);
}
}
public Map lineCountsForPairs = new HashMap();
public Map byteCountsForPairs = new HashMap();
public int lineCountForPointer(int idx) {
return idx < l(literals) ? 1 : lineCountForPair(idx);
}
public long byteCountForPointer(int idx) {
return idx < l(literals) ? l(literals.get(idx)) + 1 : byteCountForPair(idx);
}
public int lineCountForPair(int idx) {
Integer c = lineCountsForPairs.get(idx);
if (c == null) {
IntPair p = pairs.get(idx - l(literals));
c = lineCountForPointer(p.a) + lineCountForPointer(p.b);
lineCountsForPairs.put(idx, c);
}
return c;
}
public long byteCountForPair(int idx) {
Long c = byteCountsForPairs.get(idx);
if (c == null) {
IntPair p = pairs.get(idx - l(literals));
c = byteCountForPointer(p.a) + byteCountForPointer(p.b);
byteCountsForPairs.put(idx, c);
}
return c;
}
public int lineCountForVersion(String version) {
List encoded = versions.get(version);
if (encoded == null)
return 0;
int n = 0;
for (int i : encoded) n += lineCountForPointer(i);
return n;
}
public long byteCountForVersion(String version) {
List encoded = versions.get(version);
if (encoded == null)
return 0;
long n = 0;
for (int i : encoded) n += byteCountForPointer(i);
return max(0, n - 1);
}
public long totalByteCount() {
return longSum(lambdaMap(__34 -> byteCountForVersion(__34), versions()));
}
}
static public class MultiSetMap {
public Map > data = new HashMap >();
public int size;
public MultiSetMap() {
}
public MultiSetMap(boolean useTreeMap) {
if (useTreeMap)
data = new TreeMap();
}
public MultiSetMap(MultiSetMap map) {
putAll(map);
}
public MultiSetMap(Map > data) {
this.data = data;
}
public boolean put(A key, B value) {
synchronized (data) {
Set set = data.get(key);
if (set == null)
data.put(key, set = _makeEmptySet());
if (!set.add(value))
return false;
{
++size;
return true;
}
}
}
public boolean add(A key, B value) {
return put(key, value);
}
public void addAll(A key, Collection values) {
synchronized (data) {
putAll(key, values);
}
}
public void addAllIfNotThere(A key, Collection values) {
synchronized (data) {
for (B value : values) setPut(key, value);
}
}
public void setPut(A key, B value) {
synchronized (data) {
if (!containsPair(key, value))
put(key, value);
}
}
public boolean containsPair(A key, B value) {
synchronized (data) {
return get(key).contains(value);
}
}
public void putAll(A key, Collection values) {
synchronized (data) {
for (B value : values) put(key, value);
}
}
public void removeAll(A key, Collection values) {
synchronized (data) {
for (B value : values) remove(key, value);
}
}
public Set get(A key) {
synchronized (data) {
Set set = data.get(key);
return set == null ? Collections.emptySet() : set;
}
}
public Set getActual(A key) {
synchronized (data) {
Set set = data.get(key);
if (set == null)
data.put(key, set = _makeEmptySet());
return set;
}
}
public void clean(A key) {
synchronized (data) {
Set list = data.get(key);
if (list != null && list.isEmpty())
data.remove(key);
}
}
public Set keySet() {
synchronized (data) {
return data.keySet();
}
}
public Set keys() {
synchronized (data) {
return data.keySet();
}
}
public void remove(A key) {
synchronized (data) {
size -= l(data.get(key));
data.remove(key);
}
}
public void remove(A key, B value) {
synchronized (data) {
Set set = data.get(key);
if (set != null) {
if (set.remove(value)) {
--size;
if (set.isEmpty())
data.remove(key);
}
}
}
}
public void clear() {
synchronized (data) {
data.clear();
size = 0;
}
}
public boolean containsKey(A key) {
synchronized (data) {
return data.containsKey(key);
}
}
public B getFirst(A key) {
synchronized (data) {
return first(get(key));
}
}
public void addAll(MultiSetMap map) {
putAll(map);
}
public void putAll(MultiSetMap map) {
synchronized (data) {
for (A key : map.keySet()) putAll(key, map.get(key));
}
}
public void putAll(Map map) {
synchronized (data) {
if (map != null)
for (Map.Entry e : map.entrySet()) put(e.getKey(), e.getValue());
}
}
public int keysSize() {
synchronized (data) {
return l(data);
}
}
public int size() {
synchronized (data) {
return size;
}
}
public int getSize(A key) {
return l(data.get(key));
}
public int count(A key) {
return getSize(key);
}
public Set reverseGet(B b) {
synchronized (data) {
Set l = new HashSet();
for (A key : data.keySet()) if (data.get(key).contains(b))
l.add(key);
return l;
}
}
public Map > asMap() {
synchronized (data) {
return cloneMap(data);
}
}
public boolean isEmpty() {
synchronized (data) {
return data.isEmpty();
}
}
public Set _makeEmptySet() {
return new HashSet();
}
public Collection> allLists() {
synchronized (data) {
return new HashSet(data.values());
}
}
public List allValues() {
return concatLists(values(data));
}
public Object mutex() {
return data;
}
public String toString() {
return "mm" + str(data);
}
public Pair firstEntry() {
if (empty(data))
return null;
Map.Entry > entry = data.entrySet().iterator().next();
return pair(entry.getKey(), first(entry.getValue()));
}
}
static public class IntBuffer {
public int[] data;
public int size;
public IntBuffer() {
}
public IntBuffer(int size) {
if (size != 0)
data = new int[size];
}
public void add(int i) {
if (size >= lIntArray(data))
data = resizeIntArray(data, Math.max(1, lIntArray(data) * 2));
data[size++] = i;
}
public int[] toArray() {
return size == 0 ? null : resizeIntArray(data, size);
}
public void reset() {
size = 0;
}
}
static public class CompactHashSet extends java.util.AbstractSet {
final static public int INITIAL_SIZE = 3;
public final static double LOAD_FACTOR = 0.75;
final static public Object nullObject = new Object();
final static public Object deletedObject = new Object();
public int elements;
public int freecells;
public A[] objects;
public CompactHashSet() {
this(INITIAL_SIZE);
}
public CompactHashSet(int size) {
objects = (A[]) new Object[(size == 0 ? 1 : size)];
elements = 0;
freecells = objects.length;
}
public CompactHashSet(Collection c) {
this(c.size());
addAll(c);
}
@Override
public Iterator iterator() {
return new CompactHashIterator ();
}
@Override
public int size() {
return elements;
}
@Override
public boolean isEmpty() {
return elements == 0;
}
@Override
public boolean contains(Object o) {
return find(o) != null;
}
synchronized public A find(Object o) {
if (o == null)
o = nullObject;
int hash = o.hashCode();
int index = (hash & 0x7FFFFFFF) % objects.length;
int offset = 1;
while (objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) {
index = ((index + offset) & 0x7FFFFFFF) % objects.length;
offset = offset * 2 + 1;
if (offset == -1)
offset = 2;
}
return objects[index];
}
public boolean removeIfSame(Object o) {
A value = find(o);
if (value == o) {
remove(value);
return true;
}
return false;
}
@Override
synchronized public boolean add(Object o) {
if (o == null)
o = nullObject;
int hash = o.hashCode();
int index = (hash & 0x7FFFFFFF) % objects.length;
int offset = 1;
int deletedix = -1;
while (objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) {
if (objects[index] == deletedObject)
deletedix = index;
index = ((index + offset) & 0x7FFFFFFF) % objects.length;
offset = offset * 2 + 1;
if (offset == -1)
offset = 2;
}
if (objects[index] == null) {
if (deletedix != -1)
index = deletedix;
else
freecells--;
elements++;
objects[index] = (A) o;
if (1 - (freecells / (double) objects.length) > LOAD_FACTOR)
rehash();
return true;
} else
return false;
}
@Override
synchronized public boolean remove(Object o) {
if (o == null)
o = nullObject;
int hash = o.hashCode();
int index = (hash & 0x7FFFFFFF) % objects.length;
int offset = 1;
while (objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) {
index = ((index + offset) & 0x7FFFFFFF) % objects.length;
offset = offset * 2 + 1;
if (offset == -1)
offset = 2;
}
if (objects[index] != null) {
objects[index] = (A) deletedObject;
elements--;
return true;
} else
return false;
}
@Override
synchronized public void clear() {
elements = 0;
for (int ix = 0; ix < objects.length; ix++) objects[ix] = null;
freecells = objects.length;
}
@Override
synchronized public Object[] toArray() {
Object[] result = new Object[elements];
Object[] objects = this.objects;
int pos = 0;
for (int i = 0; i < objects.length; i++) if (objects[i] != null && objects[i] != deletedObject) {
if (objects[i] == nullObject)
result[pos++] = null;
else
result[pos++] = objects[i];
}
return result;
}
@Override
synchronized public T[] toArray(T[] a) {
int size = elements;
if (a.length < size)
a = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
A[] objects = this.objects;
int pos = 0;
for (int i = 0; i < objects.length; i++) if (objects[i] != null && objects[i] != deletedObject) {
if (objects[i] == nullObject)
a[pos++] = null;
else
a[pos++] = (T) objects[i];
}
return a;
}
public void rehash() {
int garbagecells = objects.length - (elements + freecells);
if (garbagecells / (double) objects.length > 0.05)
rehash(objects.length);
else
rehash(objects.length * 2 + 1);
}
public void rehash(int newCapacity) {
int oldCapacity = objects.length;
@SuppressWarnings("unchecked")
A[] newObjects = (A[]) new Object[newCapacity];
for (int ix = 0; ix < oldCapacity; ix++) {
Object o = objects[ix];
if (o == null || o == deletedObject)
continue;
int hash = o.hashCode();
int index = (hash & 0x7FFFFFFF) % newCapacity;
int offset = 1;
while (newObjects[index] != null) {
index = ((index + offset) & 0x7FFFFFFF) % newCapacity;
offset = offset * 2 + 1;
if (offset == -1)
offset = 2;
}
newObjects[index] = (A) o;
}
objects = newObjects;
freecells = objects.length - elements;
}
public class CompactHashIterator implements Iterator {
public int index;
public int lastReturned = -1;
@SuppressWarnings("empty-statement")
public CompactHashIterator() {
synchronized (CompactHashSet.this) {
for (index = 0; index < objects.length && (objects[index] == null || objects[index] == deletedObject); index++) ;
}
}
@Override
public boolean hasNext() {
synchronized (CompactHashSet.this) {
return index < objects.length;
}
}
@SuppressWarnings("empty-statement")
@Override
public T next() {
synchronized (CompactHashSet.this) {
int length = objects.length;
if (index >= length) {
lastReturned = -2;
throw new NoSuchElementException();
}
lastReturned = index;
for (index += 1; index < length && (objects[index] == null || objects[index] == deletedObject); index++) ;
if (objects[lastReturned] == nullObject)
return null;
else
return (T) objects[lastReturned];
}
}
@Override
public void remove() {
synchronized (CompactHashSet.this) {
if (lastReturned == -1 || lastReturned == -2)
throw new IllegalStateException();
if (objects[lastReturned] != null && objects[lastReturned] != deletedObject) {
objects[lastReturned] = (A) deletedObject;
elements--;
}
}
}
}
synchronized public int capacity() {
return objects.length;
}
synchronized public boolean shrinkToFactor(double factor) {
if (factor > LOAD_FACTOR)
throw fail("Shrink factor must be equal to or smaller than load factor: " + factor + " / " + LOAD_FACTOR);
int newCapacity = max(INITIAL_SIZE, iround(size() / factor));
if (newCapacity >= capacity())
return false;
rehash(newCapacity);
return true;
}
}
static public char hexToChar(String s) {
return charFromHex(s);
}
static public boolean isAbstract(Class c) {
return (c.getModifiers() & Modifier.ABSTRACT) != 0;
}
static public boolean isAbstract(Method m) {
return (m.getModifiers() & Modifier.ABSTRACT) != 0;
}
static public boolean reflection_isForbiddenMethod(Method m) {
return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
}
static public void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
static public void multiMapPut(MultiMap mm, A key, B value) {
if (mm != null && key != null && value != null)
mm.put(key, value);
}
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 allInterfacesImplementedBy(Class c) {
if (c == null)
return null;
HashSet set = new HashSet();
allInterfacesImplementedBy_find(c, set);
return set;
}
static public void allInterfacesImplementedBy_find(Class c, Set set) {
if (c.isInterface() && !set.add(c))
return;
do {
for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set);
} while ((c = c.getSuperclass()) != null);
}
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 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 public Map putAll(Map a, Map extends A, ? extends B> b) {
if (a != null && b != null)
a.putAll(b);
return a;
}
static public void put(Map map, A a, B b) {
if (map != null)
map.put(a, b);
}
static public void put(List l, int i, A a) {
if (l != null && i >= 0 && i < l(l))
l.set(i, a);
}
static public void remove(List l, int i) {
if (l != null && i >= 0 && i < l(l))
l.remove(i);
}
static public void remove(Collection l, A a) {
if (l != null)
l.remove(a);
}
static public Set keySet(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keySet(Object map) {
return keys((Map) map);
}
static public Set keySet(MultiSet ms) {
return ms.keySet();
}
static public Set keySet(MultiMap mm) {
return mm.keySet();
}
static public Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keys(Object map) {
return keys((Map) map);
}
static public Set keys(MultiSet ms) {
return ms.keySet();
}
static public Set keys(MultiMap mm) {
return mm.keySet();
}
static public Set keys(MultiSetMap mm) {
return mm.keySet();
}
static public A reverseGet(List l, int idx) {
if (l == null || idx < 0)
return null;
int n = l(l);
return idx < n ? l.get(n - 1 - idx) : null;
}
static public Map cloneMap(Map map) {
if (map == null)
return new HashMap();
synchronized (map) {
return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map);
}
}
static public List cloneMap(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : cloneList(l)) x.add(f.get(o));
return x;
}
static public int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}
static public int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static public String linesLL_rtrim(Object... x) {
return lines_rtrim(ll(x));
}
static public LinkedHashMap mapValuesToLinkedHashMap(Object func, Map map) {
LinkedHashMap m = new LinkedHashMap();
for (Object key : keys(map)) m.put(key, callF(func, map.get(key)));
return m;
}
static public LinkedHashMap mapValuesToLinkedHashMap(Map map, IF1 f) {
return mapValuesToLinkedHashMap(f, map);
}
static public LinkedHashMap mapValuesToLinkedHashMap(IF1 f, Map map) {
return mapValuesToLinkedHashMap((Object) f, map);
}
static public LinkedHashMap mapValuesToLinkedHashMap(Map map, Object func) {
return mapValuesToLinkedHashMap(func, map);
}
static public String charToHex(char c) {
return bytesToHex(charToBytes(c));
}
static public List toLines_nOnly_reversible(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0, n = s.length();
if (n != 0)
while (true) {
int i = smartIndexOf(s, '\n', start);
lines.add(s.substring(start, i));
if (i == n)
break;
start = i + 1;
}
return lines;
}
static public class mapI_It extends IterableIterator {
public Object f;
public Iterator i;
public mapI_It() {
}
public mapI_It(Object f, Iterator i) {
this.i = i;
this.f = f;
}
public boolean hasNext() {
return i.hasNext();
}
public Object next() {
return callF(f, i.next());
}
public String toString() {
return formatFunctionCall("mapI", f, i);
}
}
static public IterableIterator mapI(final Object f, final Iterator i) {
return new mapI_It(f, i);
}
static public IterableIterator mapI(IterableIterator i, Object f) {
return mapI((Iterator) i, f);
}
static public IterableIterator mapI(Object f, IterableIterator i) {
return mapI((Iterator) i, f);
}
static public IterableIterator mapI(Iterator i, Object f) {
return mapI(f, i);
}
static public IterableIterator mapI(Iterable i, IF1 f) {
return mapI(i, (Object) f);
}
static public IterableIterator mapI(Iterator