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.*;
class main {
static String autoLoadJQuery(String html) {
if (jqueryUsed(html) && !jqueryLoaded(html))
return loadJQuery2() + html;
return html;
}
// assumes jquery is used with $(...)
static boolean jqueryUsed(String html) {
if (!regexpFind("$\\s*\\(", html)) return false;
for (String script : allJavascriptFromHTML(html))
if (jcontains(jsTok(script), "$(")) return true;
return false;
}
static boolean jqueryLoaded(String html) {
for (String tag : findAllTagsNamed("script",html))
if (cic(tagParam(tag, "src"), "/jquery"))
return true;
return false;
}
static String loadJQuery2() {
return "";
}
static boolean regexpFind(String pat, String s) {
return regexpFinds(pat, s);
}
static List allJavascriptFromHTML(String html) {
return lmap(tok -> join(dropFirstAndLast(2, tok)),
findContainerTag(html, "script"));
}
static boolean jcontains(String s, String pat) {
return jfind(s, pat) >= 0;
}
static boolean jcontains(List tok, String pat) {
return jfind(tok, pat) >= 0;
}
static boolean jcontains(List tok, String pat, Object condition) {
return jfind(tok, pat, condition) >= 0;
}
static List jsTok(String s) {
return javaTok_noMLS(s);
}
static List jsTok(List tok) {
return jsTok(join(tok));
}
// tok = parsed with htmlTok
static List findAllTagsNamed(List tok, String tag) {
List out = new ArrayList();
for (int i = 1; i < l(tok); i += 2)
if (isTag(tok.get(i), tag))
out.add(tok.get(i));
return out;
}
static List findAllTagsNamed(String tag, List tok) {
return findAllTagsNamed(tok, tag);
}
// Note the reversed parameters
static List findAllTagsNamed(String tag, String html) {
return findAllTagsNamed(htmlTok(html), tag);
}
static boolean cic(Collection l, String s) {
return containsIgnoreCase(l, s);
}
static boolean cic(String[] l, String s) {
return containsIgnoreCase(l, s);
}
static boolean cic(String s, char c) {
return containsIgnoreCase(s, c);
}
static boolean cic(String a, String b) {
return containsIgnoreCase(a, b);
}
static String tagParam(String tag, String key) {
return getHtmlTagParameter(tag, key);
}
// param of opening tag
static String tagParam(List tok, String key) {
return getHtmlTagParameter(second(tok), key);
}
static boolean regexpFinds(String pat, String s) {
return regexp(pat, s).find();
}
static boolean regexpFinds(Pattern pat, String s) {
return regexp(pat, s).find();
}
static List lmap(IF1 f, Iterable l) {
return lambdaMap(f, l);
}
static List lmap(IF1 f, A[] l) {
return lambdaMap(f, l);
}
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 String join(Iterable strings) {
return join("", strings);
}
static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static List dropFirstAndLast(int n, List l) {
return cloneSubList(l, n, l(l)-n);
}
static List dropFirstAndLast(int m, int n, List l) {
return cloneSubList(l, m, l(l)-n);
}
static List dropFirstAndLast(List l) {
return dropFirstAndLast(1, l);
}
static String dropFirstAndLast(String s) {
return substring(s, 1, l(s)-1);
}
// tok must come from htmlTok
// returns all container tags found (including content) as CNC
// should be OK for both HTML and XML
static List> findContainerTag(List tok, String tag) {
List> l = new ArrayList();
for (int i = 1; i < l(tok); i += 2)
if (isOpeningTag(tok.get(i), tag)) {
int j, level = 1;
for (j = i+2; j < tok.size(); j += 2)
if (isOpeningTag(tok.get(j), tag))
++level;
else if (isTag(tok.get(j), "/" + tag)) {
--level;
if (level == 0) {
l.add(tok.subList(i-1, j+2)); // actual CNC
break;
}
}
i = j;
}
return l;
}
static List> findContainerTag(String html, String tag) {
return findContainerTag(htmlTok(html), tag);
}
static int jfind(String s, String in) {
return jfind(javaTok(s), in);
}
static int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
static int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, null);
}
static int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
static int jfind(List tok, String in, ITokCondition condition) { return jfind(tok, 1, in, condition); }
static int jfind(List tok, int startIndex, String in, ITokCondition condition) {
return jfind(tok, startIndex, in, toTokCondition(condition));
}
static int jfind(List tok, int startIdx, String in, Object condition) {
//LS tokin = jfind_preprocess(javaTok(in));
return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
}
// assumes you preprocessed tokin
static int jfind(List tok, List tokin) {
return jfind(tok, 1, tokin);
}
static int jfind(List tok, int startIdx, List tokin) {
return jfind(tok, startIdx, tokin, null);
}
static int jfind(List tok, int startIdx, String[] tokinC, Object condition) {
return findCodeTokens(tok, startIdx, false, tokinC, condition);
}
static int jfind(List tok, int startIdx, List tokin, Object condition) {
return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
}
static List jfind_preprocess(List tok) {
for (String type : litlist("quoted", "id", "int"))
replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
return tok;
}
static List javaTok_noMLS(String s) {
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') { // allow multi-line strings, but not for '
++j;
break;
} else if (c2 == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
return tok;
}
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(short[] a) { return a == null ? 0 : a.length; }
static int l(long[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(double[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Iterator i) { return iteratorCount_int_close(i); } // consumes the iterator && closes it if possible
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); }
static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o == null ? 0
: o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: o instanceof Collection ? l((Collection) o)
: o instanceof Object[] ? l((Object[]) o)
: o instanceof boolean[] ? l((boolean[]) o)
: o instanceof byte[] ? l((byte[]) o)
: o instanceof char[] ? l((char[]) o)
: o instanceof short[] ? l((short[]) o)
: o instanceof int[] ? l((int[]) o)
: o instanceof float[] ? l((float[]) o)
: o instanceof double[] ? l((double[]) o)
: o instanceof long[] ? l((long[]) o)
: (Integer) call(o, "size");
}
static boolean isTag(String token, String tag) {
return token.regionMatches(true, 0, "<" + tag + " ", 0, tag.length()+2)
|| token.regionMatches(true, 0, "<" + tag + ">", 0, tag.length()+2);
}
static List htmlTok(String s) {
return htmlcoarsetok(s);
}
static boolean containsIgnoreCase(Collection l, String s) {
if (l != null) for (String x : l)
if (eqic(x, s))
return true;
return false;
}
static boolean containsIgnoreCase(String[] l, String s) {
if (l != null) for (String x : l)
if (eqic(x, s))
return true;
return false;
}
static boolean containsIgnoreCase(String s, char c) {
return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}
static boolean containsIgnoreCase(String a, String b) {
return indexOfIgnoreCase(a, b) >= 0;
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static String getHtmlTagParameter(String tag, String key) {
return getHtmlTagParameters(tag).get(key);
}
static A second(List l) {
return get(l, 1);
}
static A second(Iterable l) {
if (l == null) return null;
Iterator it = iterator(l);
if (!it.hasNext()) return null;
it.next();
return it.hasNext() ? it.next() : null;
}
static A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static B second(Pair p) {
return p == null ? null : p.b;
}
static char second(String s) {
return charAt(s, 1);
}
static Matcher regexp(String pat, String s) {
return regexp(compileRegexp(pat), unnull(s));
}
static Matcher regexp(java.util.regex.Pattern pat, String s) {
return pat.matcher(unnull(s));
}
static java.util.regex.Pattern regexp(String pat) {
return compileRegexp(pat);
}
static List lambdaMap(IF1 f, Iterable l) {
return map(l, f);
}
static List lambdaMap(IF1 f, A[] l) {
return map(l, f);
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static Object first(Object list) {
return first((Iterable) list);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static Character first(CharSequence s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static List cloneSubList(List l, int startIndex, int endIndex) {
return newSubList(l, startIndex, endIndex);
}
static List cloneSubList(List l, int startIndex) {
return newSubList(l, startIndex);
}
static String substring(String s, int x) {
return substring(s, x, strL(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
int n = s.length();
if (y < x) y = x;
if (y > n) y = n;
if (x >= y) return "";
return s.substring(x, y);
}
// convenience method for quickly dropping a prefix
static String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
static boolean isOpeningTag(String token, String tag) {
return isTag(token, tag) && !token.endsWith("/>");
}
static boolean isOpeningTag(String token) {
return token.startsWith("<")
&& token.endsWith(">")
&& !token.endsWith("/>")
&& isLetter(token.charAt(1));
}
// TODO: extended multi-line strings
static int javaTok_n, javaTok_elements;
static boolean javaTok_opt = false;
static List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !regionMatches(s, j, "*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') { // allow multi-line strings, but not for '
++j;
break;
} else if (c2 == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j < l && !regionMatches(s, j, "]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !regionMatches(s, j, "]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
static TokCondition toTokCondition(ITokCondition condition) {
return condition == null ? null : new TokCondition() {
boolean get(List tok, int i) {
return condition.get(tok, i);
}
};
}
static Map javaTokForJFind_array_cache = synchronizedMRUCache(1000);
static String[] javaTokForJFind_array(String s) {
String[] tok = javaTokForJFind_array_cache.get(s);
if (tok == null)
javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s))));
return tok;
}
static int findCodeTokens(List tok, String... tokens) {
return findCodeTokens(tok, 1, false, tokens);
}
static int findCodeTokens(List tok, boolean ignoreCase, String... tokens) {
return findCodeTokens(tok, 1, ignoreCase, tokens);
}
static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String... tokens) {
return findCodeTokens(tok, startIdx, ignoreCase, tokens, null);
}
static HashSet findCodeTokens_specials = lithashset("*", "", "", "", "\\*");
static int findCodeTokens_bails, findCodeTokens_nonbails;
static interface findCodeTokens_Matcher {
boolean get(String token);
}
static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) {
int end = tok.size()-tokens.length*2+2, nTokens = tokens.length;
int i = startIdx | 1;
// bail out early if first token not found (works great with IndexedList)
String firstToken = tokens[0];
if (!ignoreCase && !findCodeTokens_specials.contains(firstToken)) {
// quickly scan for first token
while (i < end && !firstToken.equals(tok.get(i)))
i += 2;
}
findCodeTokens_Matcher[] matchers = new findCodeTokens_Matcher[nTokens];
for (int j = 0; j < nTokens; j++) {
String p = tokens[j];
findCodeTokens_Matcher matcher;
if (p.equals("*"))
matcher = t -> true;
else if (p.equals(""))
matcher = t -> isQuoted(t);
else if (p.equals(""))
matcher = t -> isIdentifier(t);
else if (p.equals(""))
matcher = t -> isInteger(t);
else if (p.equals("\\*"))
matcher = t -> t.equals("*");
else if (ignoreCase)
matcher = t -> eqic(p, t);
else
matcher = t -> t.equals(p);
matchers[j] = matcher;
}
outer: for (; i < end; i += 2) {
for (int j = 0; j < nTokens; j++)
if (!matchers[j].get(tok.get(i+j*2)))
continue outer;
if (condition == null || checkTokCondition(condition, tok, i-1)) // pass N index
return i;
}
return -1;
}
static String[] codeTokensAsStringArray(List tok) {
int n = max(0, (l(tok)-1)/2);
String[] out = new String[n];
for (int i = 0; i < n; i++)
out[i] = tok.get(i*2+1);
return out;
}
static ArrayList litlist(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
// syntax 1: replace all occurrences of x in l with y
static List replaceSublist(List l, List x, List y) {
if (x == null) return l;
int i = 0;
while (true) {
i = indexOfSubList(l, x, i);
if (i < 0) break;
replaceSublist(l, i, i+l(x), y);
i += l(y);
}
return l;
}
// syntax 2: splice l at fromIndex-toIndex and replace middle part with y
static List replaceSublist(List l, int fromIndex, int toIndex, List y) {
int n = y.size(), toIndex_new = fromIndex+n;
if (toIndex_new < toIndex) {
removeSubList(l, toIndex_new, toIndex);
copyListPart(y, 0, l, fromIndex, n);
} else {
copyListPart(y, 0, l, fromIndex, toIndex-fromIndex);
if (toIndex_new > toIndex)
l.addAll(toIndex, subList(y, toIndex-fromIndex));
}
return l;
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null) for (A x : a) l.add(x);
return l;
}
static String javaTok_substringN(String s, int i, int j) {
if (i == j) return "";
if (j == i+1 && s.charAt(i) == ' ') return " ";
return s.substring(i, j);
}
static String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
static int iteratorCount_int_close(Iterator i) { try {
int n = 0;
if (i != null) while (i.hasNext()) { i.next(); ++n; }
if (i instanceof AutoCloseable) ((AutoCloseable) i).close();
return n;
} catch (Exception __e) { throw rethrow(__e); } }
static Object call(Object o) {
return callF(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) {
//ret call_cached(o, method, args);
return call_withVarargs(o, method, args);
}
// TODO: process CDATA, scripts
static List htmlcoarsetok(String s) {
List tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0;
while (i < l) {
int j = i;
char c;
// scan for non-tags
while (j < l) {
if (s.charAt(j) != '<')
// regular character
++j;
else if (s.substring(j, Math.min(j+4, l)).equals(""));
j = Math.min(j+3, l);
} else {
char d = charAt(s, j+1); // character after <
if (d == '/' || isLetter(d))
// it's a tag
break;
else
++j;
}
}
tok.add(s.substring(i, j)); // add non-tag content
i = j;
if (i >= l) break;
c = s.charAt(i);
// scan over tag
if (c == '<') {
++j;
while (j < l && s.charAt(j) != '>') ++j; // TODO: strings in tag?
if (j < l) ++j;
}
tok.add(s.substring(i, j)); // add tag
i = j;
}
if ((tok.size() & 1) == 0) tok.add("");
return tok;
}
static boolean eqic(String a, String b) {
if ((a == null) != (b == null)) return false;
if (a == null) return true;
return a.equalsIgnoreCase(b);
}
static boolean eqic(char a, char b) {
if (a == b) return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2) return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
// works on lists and strings and null
static int indexOfIgnoreCase(List a, String b) {
return indexOfIgnoreCase(a, b, 0);
}
static int indexOfIgnoreCase(List a, String b, int i) {
int n = a == null ? 0 : a.size();
for (; i < n; i++)
if (eqic(a.get(i), b)) return i;
return -1;
}
static int indexOfIgnoreCase(String a, String b) {
return indexOfIgnoreCase_manual(a, b);
/*Matcher m = Pattern.compile(b, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(a);
if (m.find()) return m.start(); else ret -1;*/
}
static int indexOfIgnoreCase(String a, String b, int i) {
return indexOfIgnoreCase_manual(a, b, i);
}
static boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static boolean getHtmlTagParameters_debug = false;
static Map getHtmlTagParameters(String tag) {
if (empty(tag)) return null;
List tok = codeTokens(tok_joinMinusIdentifiers(htmlFineTok(tag)));
if (getHtmlTagParameters_debug)
printStruct(tok);
assertEquals("<", tok.get(0));
int i = 1;
if (eq(tok.get(1), "/")) ++i;
String name = tok.get(i++);
if (!isMinusIdentifier(name))
throw fail(tag + " (" + name + ")");
Map map = new HashMap();
while (i < l(tok)) {
String t = tok.get(i);
if (eqOneOf(t, "/", ">")) break;
if (!isMinusIdentifier(t))
throw fail(tag + " (" + t + ")");
++i;
String value = "1";
if (eq(tok.get(i), "=")) {
++i;
value = htmlunquote(tok.get(i++));
}
map.put(t, value);
}
return map;
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o == null) return null;
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static Object get_raw(Object o, String field) { try {
if (o == null) return null;
Field f = get_findField(o.getClass(), field);
makeAccessible(f);
return f.get(o);
} catch (Exception __e) { throw rethrow(__e); } }
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
makeAccessible(f);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static Object get(String field, Object o) {
return get(o, field);
}
static boolean get(BitSet bs, int idx) {
return bs != null && bs.get(idx);
}
static Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static char charAt(String s, int i) {
return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0';
}
static Map compileRegexp_cache = syncMRUCache(10);
static java.util.regex.Pattern compileRegexp(String pat) {
java.util.regex.Pattern p = compileRegexp_cache.get(pat);
if (p == null) {
compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat));
}
return p;
}
static String unnull(String s) {
return s == null ? "" : s;
}
static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static List unnull(List l) { return l == null ? emptyList() : l; }
static int[] unnull(int[] l) { return l == null ? emptyIntArray() : l; }
static char[] unnull(char[] l) { return l == null ? emptyCharArray() : l; }
static double[] unnull(double[] l) { return l == null ? emptyDoubleArray() : l; }
static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
//ifclass Symbol
static Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static long unnull(Long l) { return l == null ? 0L : l; }
static List map(Iterable l, Object f) { return map(f, l); }
static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null) for (Object o : l)
{ ping(); x.add(callF(f, o)); }
return x;
}
static List map(Iterable l, F1 f) { return map(f, l); }
static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null) for (A o : l)
{ ping(); x.add(callF(f, o)); }
return x;
}
static List map(IF1 f, Iterable l) { return map(l, f); }
static List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
{ ping(); x.add(f.get(o)); }
return x;
}
static List map(IF1 f, A[] l) { return map(l, f); }
static List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null) for (A o : l)
{ ping(); x.add(f.get(o)); }
return x;
}
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }
static List map(Object f, Map map) {
return map(map, f);
}
// map: func(key, value) -> list element
static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null) for (Object _e : map.entrySet()) { ping();
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(Iterable c) { return c == null || !c.iterator().hasNext(); }
static boolean empty(CharSequence s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static 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 boolean empty(Iterator i) { return i == null || !i.hasNext(); }
static boolean empty(double[] a) { return a == null || a.length == 0; }
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static boolean empty(byte[] a) { return a == null || a.length == 0; }
static boolean empty(short[] a) { return a == null || a.length == 0; }
static boolean empty(File f) { return getFileSize(f) == 0; }
static List newSubList(List l, int startIndex, int endIndex) {
return cloneList(subList(l, startIndex, endIndex));
}
static List newSubList(List l, int startIndex) {
return cloneList(subList(l, startIndex));
}
static int strL(String s) {
return s == null ? 0 : s.length();
}
static int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
static boolean isLetter(char c) {
return Character.isLetter(c);
}
static boolean regionMatches(String a, int offsetA, String b, int offsetB, int len) {
return a != null && b != null && a.regionMatches(offsetA, b, offsetB, len);
}
static boolean regionMatches(String a, int offsetA, String b) {
return regionMatches(a, offsetA, b, 0, l(b));
}
static List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j-i
&& s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
static Map synchronizedMRUCache(int maxSize) {
return synchroMap(new MRUCache(maxSize));
}
static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
// supports the usual quotings (", variable length double brackets) except ' quoting
static boolean isQuoted(String s) {
if (isNormalQuoted(s)) return true; // use the exact version
return isMultilineQuoted(s);
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static boolean isInteger(String s) {
int n = l(s);
if (n == 0) return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n) return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9') return false;
++i;
}
return true;
}
static boolean checkTokCondition(Object condition, List tok, int i) {
if (condition instanceof TokCondition)
return ((TokCondition) condition).get(tok, i);
return checkCondition(condition, tok, i);
}
static int max(int a, int b) { return Math.max(a, b); }
static int max(int a, int b, int c) { return max(max(a, b), c); }
static long max(int a, long b) { return Math.max((long) a, b); }
static long max(long a, long b) { return Math.max(a, b); }
static double max(int a, double b) { return Math.max((double) a, b); }
static float max(float a, float b) { return Math.max(a, b); }
static double max(double a, double b) { return Math.max(a, b); }
static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static double max(double[] c) {
if (c.length == 0) return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static float max(float[] c) {
if (c.length == 0) return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x) x = d;
return x;
}
static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x) x = d;
return x;
}
static int indexOfSubList(List x, List y) {
return indexOfSubList(x, y, 0);
}
static int indexOfSubList(List x, List y, int i) {
outer: for (; i+l(y) <= l(x); i++) {
for (int j = 0; j < l(y); j++)
if (neq(x.get(i+j), y.get(j)))
continue outer;
return i;
}
return -1;
}
static int indexOfSubList(List x, A[] y, int i) {
outer: for (; i+l(y) <= l(x); i++) {
for (int j = 0; j < l(y); j++)
if (neq(x.get(i+j), y[j]))
continue outer;
return i;
}
return -1;
}
static void removeSubList(List l, int from, int to) {
if (l != null) subList(l, from, to).clear();
}
static void removeSubList(List l, int from) {
if (l != null) subList(l, from).clear();
}
static void copyListPart(List a, int i1, List b, int i2, int n) {
if (a == null || b == null) return;
for (int i = 0; i < n; i++)
b.set(i2+i, a.get(i1+i));
}
static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static 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 RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
static Map> callF_cache = newDangerousWeakHashMap();
static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static void callF(VF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Runnable r) { { if (r != null) r.run(); } return null; }
static Object callF(Object f, Object... args) {
if (f instanceof String)
return callMCWithVarArgs((String) f, args); // possible SLOWDOWN over callMC
return safeCallF(f, args);
}
static Object safeCallF(Object f, Object... args) {
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1) return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
}
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
makeAccessible(m);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static 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);
// try varargs
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);
// try varargs
List methods = cache.cache.get(method);
if (methods != null) methodSearch: for (Method m : methods) {
{ if (!(m.isVarArgs())) continue; }
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) { throw rethrow(__e); } }
static String asString(Object o) {
return o == null ? null : o.toString();
}
static int indexOfIgnoreCase_manual(String a, String b) {
return indexOfIgnoreCase_manual(a, b, 0);
}
static int indexOfIgnoreCase_manual(String a, String b, int i) {
int la = strL(a), lb = strL(b);
if (la < lb) return -1;
int n = la-lb;
loop: for (; i <= n; i++) {
for (int j = 0; j < lb; j++) {
char c1 = a.charAt(i+j), c2 = b.charAt(j);
if (!eqic(c1, c2))
continue loop;
}
return i;
}
return -1;
}
static List codeTokens(List tok) {
return codeTokensOnly(tok);
}
static List tok_joinMinusIdentifiers(List tok) {
for (int i = 1; i+4 < l(tok); i += 2)
if (isMinusIdentifier(get(tok, i)) && eq(get(tok, i+2), "-") && isIdentifier(get(tok, i+4))) {
replaceSublist(tok, i, i+5, ll(join(subList(tok, i, i+5))));
i -= 2;
}
return tok;
}
static List htmlFineTok(String s) {
List tok = new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else
break;
}
tok.add(quickSubstring(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else
++j;
tok.add(quickSubstring(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
return tok;
}
static A printStruct(String prefix, A a) {
printStructure(prefix, a);
return a;
}
static A printStruct(A a) {
printStructure(a);
return a;
}
static A assertEquals(Object x, A y) {
return assertEquals(null, x, y);
}
static A assertEquals(String msg, Object x, A y) {
if (assertVerbose()) return assertEqualsVerbose(msg, x, y);
if (!(x == null ? y == null : x.equals(y)))
throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
return y;
}
static boolean isMinusIdentifier(String s) {
if (empty(s)) return false;
if (!Character.isJavaIdentifierStart(s.charAt(0))
&& !s.startsWith("-"))
return false;
for (int i = 1; i < s.length(); i++)
if (!Character.isJavaIdentifierPart(s.charAt(i)) && s.charAt(i) != '-')
return false;
return true;
}
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static String htmlunquote(String s) {
if (s.startsWith("'") && s.endsWith("'") && s.length() >= 2
|| s.startsWith("\"") && s.endsWith("\"") && s.length() >= 2)
s = s.substring(1, s.length()-1);
return htmldecode(s);
}
static Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
// Note: The error reporting only works with Java VM option --illegal-access=deny
vmBus_send("makeAccessible_error",e, f);
}
return f;
}
static Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error",e, m);
}
return m;
}
static Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error",e, c);
}
return c;
}
static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static Iterator emptyIterator() {
return Collections.emptyIterator();
}
static Map syncMRUCache(int size) {
return synchroMap(new MRUCache(size));
}
static ArrayList emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
// Try to match capacity
static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
// get correct type at once
static ArrayList emptyList(Class c) {
return new ArrayList();
}
static int[] emptyIntArray_a = new int[0];
static int[] emptyIntArray() { return emptyIntArray_a; }
static char[] emptyCharArray = new char[0];
static char[] emptyCharArray() { return emptyCharArray; }
static double[] emptyDoubleArray = new double[0];
static double[] emptyDoubleArray() { return emptyDoubleArray; }
static Map emptyMap() {
return new HashMap();
}
static Object[] emptyObjectArray_a = new Object[0];
static Object[] emptyObjectArray() { return emptyObjectArray_a; }
//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll = false;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions = false;
static Map ping_actions = newWeakHashMap();
static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl(true /* XXX */);
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized(ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
// unclear semantics as to whether return null on null
static ArrayList asList(A[] a) {
return a == null ? new ArrayList() : new ArrayList(Arrays.asList(a));
}
static ArrayList asList(int[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(long[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static ArrayList asList(float[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static ArrayList asList(double[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static 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 ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
static String getType(Object o) {
return getClassName(o);
}
static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static ArrayList cloneList(Collection l) {
if (l == null) return new ArrayList();
synchronized(collectionMutex(l)) {
return new ArrayList(l);
}
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static boolean isNormalQuoted(String s) {
int l = l(s);
if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"')) return false;
int j = 1;
while (j < l)
if (s.charAt(j) == '"')
return j == l-1;
else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
return false;
}
static boolean isMultilineQuoted(String s) {
if (!startsWith(s, "[")) return false;
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
return i < s.length() && s.charAt(i) == '[';
}
static 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 boolean checkCondition(Object condition, Object... args) {
return isTrue(callF(condition, args));
}
static boolean checkCondition(IF1 condition, A arg) {
return isTrue(callF(condition, arg));
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
static Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
// initFunction: voidfunc(Map) - is called initially, and after clearing the map
static Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
static Object callMCWithVarArgs(String method, Object... args) {
return call_withVarargs(mc(), method, args);
}
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static 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 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 final Map callOpt_cache = newDangerousWeakHashMap();
static 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);
// TODO: (super-rare) case where method exists static and non-static
// with different args
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 _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 boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static 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 String joinWithComma(Collection c) {
return join(", ", c);
}
static String joinWithComma(String... c) {
return join(", ", c);
}
static String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static List classNames(Collection l) {
return getClassNames(l);
}
static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static List codeTokensOnly(List tok) {
int n = l(tok);
List l = emptyList(n/2);
for (int i = 1; i < n; i += 2)
l.add(tok.get(i));
return l;
}
static String quickSubstring(String s, int i, int j) {
if (i == j) return "";
return s.substring(i, j);
}
static A printStructure(String prefix, A o) {
if (endsWithLetter(prefix)) prefix += ": ";
print(prefix + structureForUser(o));
return o;
}
static A printStructure(A o) {
print(structureForUser(o));
return o;
}
static ThreadLocal assertVerbose_value = new ThreadLocal();
static void assertVerbose(boolean b) {
assertVerbose_value.set(b);
}
static boolean assertVerbose() { return isTrue(assertVerbose_value.get()); }
static A assertEqualsVerbose(Object x, A y) {
assertEqualsVerbose((String) null, x, y);
return y;
}
// x = expected, y = actual
static A assertEqualsVerbose(String msg, Object x, A y) {
if (!eq(x, y)) {
throw fail((msg != null ? msg + ": " : "") + "expected: "+ x + ", got: " + y);
} else
print("OK" + (empty(msg) ? "" : " " + msg) + ": " + /*sfu*/(x));
return y;
}
static String htmldecode(final String input) {
if (input == null) return null;
final int MIN_ESCAPE = 2;
final int MAX_ESCAPE = 6;
StringWriter writer = null;
int len = input.length();
int i = 1;
int st = 0;
while (true) {
// look for '&'
while (i < len && input.charAt(i-1) != '&')
i++;
if (i >= len)
break;
// found '&', look for ';'
int j = i;
while (j < len && j < i + MAX_ESCAPE + 1 && input.charAt(j) != ';')
j++;
if (j == len || j < i + MIN_ESCAPE || j == i + MAX_ESCAPE + 1) {
i++;
continue;
}
// found escape
if (input.charAt(i) == '#') {
// numeric escape
int k = i + 1;
int radix = 10;
final char firstChar = input.charAt(k);
if (firstChar == 'x' || firstChar == 'X') {
k++;
radix = 16;
}
try {
int entityValue = Integer.parseInt(input.substring(k, j), radix);
if (writer == null)
writer = new StringWriter(input.length());
writer.append(input.substring(st, i - 1));
if (entityValue > 0xFFFF) {
final char[] chrs = Character.toChars(entityValue);
writer.write(chrs[0]);
writer.write(chrs[1]);
} else {
writer.write(entityValue);
}
} catch (NumberFormatException ex) {
i++;
continue;
}
}
else {
// named escape
CharSequence value = htmldecode_lookupMap.get(input.substring(i, j));
if (value == null) {
i++;
continue;
}
if (writer == null)
writer = new StringWriter(input.length());
writer.append(input.substring(st, i - 1));
writer.append(value);
}
// skip escape
st = j + 1;
i = st;
}
if (writer != null) {
writer.append(input.substring(st, len));
return writer.toString();
}
return input;
}
private static final String[][] htmldecode_ESCAPES = {
{"\"", "quot"}, // " - double-quote
{"&", "amp"}, // & - ampersand
{"<", "lt"}, // < - less-than
{">", "gt"}, // > - greater-than
// Mapping to escape ISO-8859-1 characters to their named HTML 3.x equivalents.
{"\u00A0", "nbsp"}, // non-breaking space
{"\u00A1", "iexcl"}, // inverted exclamation mark
{"\u00A2", "cent"}, // cent sign
{"\u00A3", "pound"}, // pound sign
{"\u00A4", "curren"}, // currency sign
{"\u00A5", "yen"}, // yen sign = yuan sign
{"\u00A6", "brvbar"}, // broken bar = broken vertical bar
{"\u00A7", "sect"}, // section sign
{"\u00A8", "uml"}, // diaeresis = spacing diaeresis
{"\u00A9", "copy"}, // copyright sign
{"\u00AA", "ordf"}, // feminine ordinal indicator
{"\u00AB", "laquo"}, // left-pointing double angle quotation mark = left pointing guillemet
{"\u00AC", "not"}, // not sign
{"\u00AD", "shy"}, // soft hyphen = discretionary hyphen
{"\u00AE", "reg"}, // registered trademark sign
{"\u00AF", "macr"}, // macron = spacing macron = overline = APL overbar
{"\u00B0", "deg"}, // degree sign
{"\u00B1", "plusmn"}, // plus-minus sign = plus-or-minus sign
{"\u00B2", "sup2"}, // superscript two = superscript digit two = squared
{"\u00B3", "sup3"}, // superscript three = superscript digit three = cubed
{"\u00B4", "acute"}, // acute accent = spacing acute
{"\u00B5", "micro"}, // micro sign
{"\u00B6", "para"}, // pilcrow sign = paragraph sign
{"\u00B7", "middot"}, // middle dot = Georgian comma = Greek middle dot
{"\u00B8", "cedil"}, // cedilla = spacing cedilla
{"\u00B9", "sup1"}, // superscript one = superscript digit one
{"\u00BA", "ordm"}, // masculine ordinal indicator
{"\u00BB", "raquo"}, // right-pointing double angle quotation mark = right pointing guillemet
{"\u00BC", "frac14"}, // vulgar fraction one quarter = fraction one quarter
{"\u00BD", "frac12"}, // vulgar fraction one half = fraction one half
{"\u00BE", "frac34"}, // vulgar fraction three quarters = fraction three quarters
{"\u00BF", "iquest"}, // inverted question mark = turned question mark
{"\u00C0", "Agrave"}, // ? - uppercase A, grave accent
{"\u00C1", "Aacute"}, // ? - uppercase A, acute accent
{"\u00C2", "Acirc"}, // ? - uppercase A, circumflex accent
{"\u00C3", "Atilde"}, // ? - uppercase A, tilde
{"\u00C4", "Auml"}, // ? - uppercase A, umlaut
{"\u00C5", "Aring"}, // ? - uppercase A, ring
{"\u00C6", "AElig"}, // ? - uppercase AE
{"\u00C7", "Ccedil"}, // ? - uppercase C, cedilla
{"\u00C8", "Egrave"}, // ? - uppercase E, grave accent
{"\u00C9", "Eacute"}, // ? - uppercase E, acute accent
{"\u00CA", "Ecirc"}, // ? - uppercase E, circumflex accent
{"\u00CB", "Euml"}, // ? - uppercase E, umlaut
{"\u00CC", "Igrave"}, // ? - uppercase I, grave accent
{"\u00CD", "Iacute"}, // ? - uppercase I, acute accent
{"\u00CE", "Icirc"}, // ? - uppercase I, circumflex accent
{"\u00CF", "Iuml"}, // ? - uppercase I, umlaut
{"\u00D0", "ETH"}, // ? - uppercase Eth, Icelandic
{"\u00D1", "Ntilde"}, // ? - uppercase N, tilde
{"\u00D2", "Ograve"}, // ? - uppercase O, grave accent
{"\u00D3", "Oacute"}, // ? - uppercase O, acute accent
{"\u00D4", "Ocirc"}, // ? - uppercase O, circumflex accent
{"\u00D5", "Otilde"}, // ? - uppercase O, tilde
{"\u00D6", "Ouml"}, // ? - uppercase O, umlaut
{"\u00D7", "times"}, // multiplication sign
{"\u00D8", "Oslash"}, // ? - uppercase O, slash
{"\u00D9", "Ugrave"}, // ? - uppercase U, grave accent
{"\u00DA", "Uacute"}, // ? - uppercase U, acute accent
{"\u00DB", "Ucirc"}, // ? - uppercase U, circumflex accent
{"\u00DC", "Uuml"}, // ? - uppercase U, umlaut
{"\u00DD", "Yacute"}, // ? - uppercase Y, acute accent
{"\u00DE", "THORN"}, // ? - uppercase THORN, Icelandic
{"\u00DF", "szlig"}, // ? - lowercase sharps, German
{"\u00E0", "agrave"}, // ? - lowercase a, grave accent
{"\u00E1", "aacute"}, // ? - lowercase a, acute accent
{"\u00E2", "acirc"}, // ? - lowercase a, circumflex accent
{"\u00E3", "atilde"}, // ? - lowercase a, tilde
{"\u00E4", "auml"}, // ? - lowercase a, umlaut
{"\u00E5", "aring"}, // ? - lowercase a, ring
{"\u00E6", "aelig"}, // ? - lowercase ae
{"\u00E7", "ccedil"}, // ? - lowercase c, cedilla
{"\u00E8", "egrave"}, // ? - lowercase e, grave accent
{"\u00E9", "eacute"}, // ? - lowercase e, acute accent
{"\u00EA", "ecirc"}, // ? - lowercase e, circumflex accent
{"\u00EB", "euml"}, // ? - lowercase e, umlaut
{"\u00EC", "igrave"}, // ? - lowercase i, grave accent
{"\u00ED", "iacute"}, // ? - lowercase i, acute accent
{"\u00EE", "icirc"}, // ? - lowercase i, circumflex accent
{"\u00EF", "iuml"}, // ? - lowercase i, umlaut
{"\u00F0", "eth"}, // ? - lowercase eth, Icelandic
{"\u00F1", "ntilde"}, // ? - lowercase n, tilde
{"\u00F2", "ograve"}, // ? - lowercase o, grave accent
{"\u00F3", "oacute"}, // ? - lowercase o, acute accent
{"\u00F4", "ocirc"}, // ? - lowercase o, circumflex accent
{"\u00F5", "otilde"}, // ? - lowercase o, tilde
{"\u00F6", "ouml"}, // ? - lowercase o, umlaut
{"\u00F7", "divide"}, // division sign
{"\u00F8", "oslash"}, // ? - lowercase o, slash
{"\u00F9", "ugrave"}, // ? - lowercase u, grave accent
{"\u00FA", "uacute"}, // ? - lowercase u, acute accent
{"\u00FB", "ucirc"}, // ? - lowercase u, circumflex accent
{"\u00FC", "uuml"}, // ? - lowercase u, umlaut
{"\u00FD", "yacute"}, // ? - lowercase y, acute accent
{"\u00FE", "thorn"}, // ? - lowercase thorn, Icelandic
{"\u00FF", "yuml"}, // ? - lowercase y, umlaut
{"\u2013", "ndash"},
{"\u2018", "lsquo"},
{"\u2019", "rsquo"},
{"\u201D", "rdquo"},
{"\u201C", "ldquo"},
{"\u2014", "mdash"},
{"'", "apos"}, // the controversial (but who cares!) '
// stackoverflow.com/questions/2083754/why-shouldnt-apos-be-used-to-escape-single-quotes
};
private static final HashMap htmldecode_lookupMap;
static {
htmldecode_lookupMap = new HashMap();
for (final CharSequence[] seq : htmldecode_ESCAPES)
htmldecode_lookupMap.put(seq[1].toString(), seq[0]);
}
static void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll(vm_busListeners_live(), msg, arg);
pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
// TODO: test if android complains about this
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isAWTThread_awt();
}
static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
if (o instanceof ThreadLocal) // TODO: remove this
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static boolean isTrue(Boolean b) {
return b != null && b.booleanValue();
}
static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static Thread currentThread() {
return Thread.currentThread();
}
static Object collectionMutex(List l) {
return l;
}
static Object collectionMutex(Object o) {
if (o instanceof List) return o;
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
static Map synchroHashMap() {
return synchronizedMap(new HashMap());
}
static char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s)-1);
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b)) return false;
m.m = new String[] {substring(a, strL(b))};
return true;
}
static boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a)) return false;
for (int i = 0; i < listL(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static Class javax() {
return getJavaX();
}
static List _registerDangerousWeakMap_preList;
static A _registerDangerousWeakMap(A map) {
return _registerDangerousWeakMap(map, null);
}
static A _registerDangerousWeakMap(A map, Object init) {
callF(init, map);
if (init instanceof String) {
final String f = (String) init;
init = new VF1