Warning : session_start(): open(/var/lib/php/sessions/sess_tjqm1nv27olfd87d8nl8k0tj45, 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.empty;
import static x30_pkg.x30_util.nempty;
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 static x30_pkg.x30_util.asList;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils.print_byThread;
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.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
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 loadableUtils.utils.F0;
import loadableUtils.utils.F1;
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.RGBImage;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
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 javax.swing.undo.UndoManager;
import java.text.NumberFormat;
import java.awt.datatransfer.StringSelection;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.nio.file.Files;
import java.nio.file.Path;
class main {
public static class Entry {
public String line;
public String conditions;
public String rule;
public String prediction;
public String judgement = "";
public String struct;
public transient RuleEngine2_MatchedRule mr;
public static String _fieldOrder = "line conditions prediction judgement struct";
}
public static boolean _moduleClass_TestRuleEngine2;
public static class TestRuleEngine2 extends DynObjectTable {
public String input, processedInput;
public transient ReliableSingleThread rstCalc = dm_rstWithPostDelay(this, new Runnable() {
public void run() {
try {
calc();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "calc();";
}
}, 500);
public transient int maxResults = 500;
public transient boolean skipBadPredictions = true;
public String switchableFields() {
return "skipBadPredictions maxResults";
}
public void start() {
super.start();
withSearcher = true;
fieldsInOrder = true;
hideFields = litset("rule", "mr");
}
public JComponent visualize() {
JComponent tf = dm_textField("input");
onChangeAndNow(tf, rstCalc);
return northCenterAndSouthWithMargins(centerAndEastWithMargin(tf, jbutton("Make rule...", runnableThread(new Runnable() {
public void run() {
try {
dm_gazelle_newRuleDialog(input, input);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_gazelle_newRuleDialog(input, input)";
}
}))), super.visualize(), rightAlignedButtons(tableDependentButton(table(), "Mark good", rMark("good")), tableDependentButton(table(), "Mark bad", rMark("bad")), tableDependentButton(table(), "Mark funny", rMark("funny"))));
}
public Runnable rMark(final String judgement) {
return runnableThread(new Runnable() {
public void run() {
try {
Entry e = selected();
print("Selected: " + e);
e.judgement = judgement;
fireDataChanged();
saveEntry(e);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Entry e = selected();\r\n print(\"Selected: \" + e);\r\n e.judgement = ju...";
}
});
}
public void calc() {
String input = this.input;
final RuleEngine2 engine = new RuleEngine2();
engine.addRules2(dm_allRulesFromRulesModuleWithCommentsAndIDs());
MultiMap statementsByRule = ai_gazelle_indexStatementsByRule(dm_gazelle_statementsFromAppliedRules());
final Map dataByRule = mapValues("ai_gazelle_analyzeStatementsForRule", multiMapToMap(statementsByRule));
final LinkedHashSet queue = new LinkedHashSet();
queue.add(input);
final Set done = new HashSet();
final Set lines = new HashSet();
List list = new ArrayList();
boolean changes = true;
while (l(list) < maxResults && nempty(queue)) {
String input2 = popFirst(queue);
done.add(input2);
List l = ai_ruleEngine2_rulesForInput_3(engine, input2);
l = sortByMethodDesc("qualitySum", l);
List newList = new ArrayList();
for (RuleEngine2_MatchedRule r : l) {
String modifiedRule = engine.formatForUser(r.applyMapping().asText());
String line = r.applyMappingTo(r.rule.out);
addIfNotInOtherSet(queue, done, line);
ai_gazelle_analyzeStatementsForRule_Data data = dataByRule.get(r.rule.globalID);
String prediction = data == null ? null : ai_gazelle_predictor1_onData(r, data);
if (skipBadPredictions && eq(prediction, "bad"))
continue;
newList.add(nu(Entry.class, "line", line, "conditions", join(" | ", r.remainingConditions), "prediction", prediction, "rule", modifiedRule, "struct", struct(r), "mr", r));
}
list.addAll(newList);
for (Entry e : newList) {
{
if (e.mr == null)
continue;
}
for (String line : ai_gazelle_makeIWantToKnows(e.mr)) {
if (!lines.add(line))
continue;
list.add(nu(Entry.class, "line", line, "struct", "iwtk " + e.mr.rule.globalID));
addIfNotInOtherSet(queue, done, line);
}
}
}
setList(list);
processedInput = input;
}
public void saveEntry(Entry e) {
dm_gazelle_saveAppliedRule("modifiedRule", e.rule, "judgement", e.judgement, "matchedRuleStruct", e.struct);
}
}
public static A callF(Object f, Object... args) {
try {
if (f instanceof String)
return (A) callMC((String) f, args);
return (A) x30_util.callF(f, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A callF(F0 f) {
return f == null ? null : f.get();
}
public static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
public static void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
public static Object callMC(String method, Object... args) {
return call(mc(), method, args);
}
public static Object call(Object o) {
return callF(o);
}
public static A call(Object o, String method, Object... args) {
return x30_util.call(o, method, args);
}
public static void _onLoad_initUtils() {
utils.__javax = javax();
}
public static void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
public Class get(String name) {
try {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (startsWith(name, "main$"))
return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + substring(name, 4));
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Class c = findClass_fullName(name);\r\n if (c != null) ret c;\r\n if (start...";
}
});
}
public static String programID() {
return getProgramID();
}
public static String programID(Object o) {
return getProgramID(o);
}
public static volatile StringBuffer local_log = new StringBuffer();
public static volatile Appendable print_log = local_log;
public static volatile int print_log_max = 1024 * 1024;
public static volatile int local_log_max = 100 * 1024;
public static boolean print_silent;
public static Object print_byThread_lock = new Object();
public static volatile ThreadLocal print_byThread;
public static volatile Object print_allThreads;
public static void print() {
print("");
}
public static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
public static A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
public static void print_noNewLine(String s) {
Object f = print_byThread == null ? null : print_byThread.get();
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);
}
public static void print_raw(String 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);
}
public static ReliableSingleThread dm_rstWithPostDelay(DynModule m, int delay, Runnable r) {
return dm_rst(m, rstWithPostDelay(delay, r));
}
public static ReliableSingleThread dm_rstWithPostDelay(DynModule m, Runnable r, int delay) {
return dm_rstWithPostDelay(m, delay, r);
}
public static ReliableSingleThread dm_rstWithPostDelay(DynModule m, double seconds, Runnable r) {
return dm_rst(m, rstWithPostDelay(seconds, r));
}
public static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
public static HashSet litset(A... items) {
return lithashset(items);
}
public static JTextField dm_textField(String field) {
return dm_fieldTextField(field);
}
public static void onChangeAndNow(JComponent c, Object r) {
onUpdateAndNow(c, r);
}
public static void onChangeAndNow(List extends JComponent> l, Object r) {
onUpdateAndNow(l, r);
}
public static JPanel northCenterAndSouthWithMargins(Component n, Component c, Component s) {
return applyDefaultMargin(northCenterAndSouth(withBottomMargin(n), c, withTopMargin(s)));
}
public static JPanel centerAndEastWithMargin(Component c, Component e) {
return centerAndEastWithMarginInbetween(c, e);
}
public static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
public static JButton jbutton(String text) {
return newButton(text, null);
}
public static JButton jbutton(Action action) {
return swingNu(JButton.class, action);
}
public static Runnable runnableThread(final Runnable r) {
return new Runnable() {
public void run() {
try {
startThread(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startThread(r)";
}
};
}
public static void dm_gazelle_newRuleDialog(String in, String out) {
final JTextField tf1 = jtextfield(in);
final JTextField tf2 = jtextfield(out);
showFormTitled("Make a rule", "When", tf1, "Then", tf2, new Runnable() {
public void run() {
try {
Pair p = dm_gazelle_addRule(gtt(tf1), gtt(tf2));
infoBox(p.b ? "Rule " + p.a + " added" : "Rule already there: " + p.a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Pair p = dm_gazelle_addRule(gtt(tf1), gtt(tf2));\r\n info...";
}
});
}
public static JPanel rightAlignedButtons(Object... params) {
return jRightAlignedButtons(params);
}
public static JButton tableDependentButton(JTable tbl, String text, Object action) {
return tableDependButton(tbl, jbutton(text, action));
}
public static List> dm_allRulesFromRulesModuleWithCommentsAndIDs() {
return collectThreeFieldsAsTriple("text", "comments", "globalID", (List) dm_requireAndCall("#1021352/Rules", "concepts"));
}
public static MultiMap ai_gazelle_indexStatementsByRule(List statements) {
MultiMap mm = new MultiMap();
for (Matches m : getMatchesX_all("Rule *: ...", statements)) mm.put(m.unq(0), m.rest());
return mm;
}
public static class dm_gazelle_statementsFromAppliedRules_ByRule {
public String ruleID;
public TreeSet statements = new TreeSet();
}
public static List dm_gazelle_statementsFromAppliedRules() {
List concepts = cloneList((List) dm_requireAndCall("#1021413/AppliedRules", "concepts"));
print("Got " + n2(concepts, "concept"));
Map ruleMap = new HashMap();
for (Object c : concepts) {
try {
String judgement = getString("judgement", c);
String struct = getString("matchedRuleStruct", c);
RuleEngine2_MatchedRule mr = unstruct(struct);
String ruleID = mr.rule.globalID;
dm_gazelle_statementsFromAppliedRules_ByRule r = getOrCreate_f1(ruleMap, ruleID, new F1() {
public dm_gazelle_statementsFromAppliedRules_ByRule get(String ruleID) {
try {
return nu(dm_gazelle_statementsFromAppliedRules_ByRule.class, "ruleID", ruleID);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "nu(dm_gazelle_statementsFromAppliedRules_ByRule, +ruleID)";
}
});
r.statements.addAll(ai_gazelle_statementsFromAppliedRule(mr, judgement));
} catch (Throwable __e) {
_handleException(__e);
}
}
List out = new ArrayList();
for (dm_gazelle_statementsFromAppliedRules_ByRule r : values(ruleMap)) for (String s : r.statements) out.add("Rule " + r.ruleID + ": " + s);
return out;
}
public static Map mapValues(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map)) m.put(key, callF(func, map.get(key)));
return m;
}
public static Map mapValues(Map map, Object func) {
return mapValues(func, map);
}
public static class ai_gazelle_analyzeStatementsForRule_Data {
public Set possibleVars, usedVars, unusedVars, varsUsedInGood, varsUsedInBad, varsUsedInGoodOnly, varsUsedInBadOnly;
public Set unclearVars;
public MultiMap goodMappings, badMappings, alwaysGoodMappings, alwaysBadMappings;
public List> completeGoodMappings, completeBadMappings;
}
public static ai_gazelle_analyzeStatementsForRule_Data ai_gazelle_analyzeStatementsForRule(Collection l) {
Set possibleVars = asCISet(matchAny_firstGroups("possible variable *", l));
Set usedVars = asCISet(matchX_any_firstGroups("... variable * was used", l));
Set unusedVars = asCISet(listMinusSet(possibleVars, usedVars));
Set varsUsedInGood = asCISet(matchX_any_firstGroups("in a good mapping, variable * was used", l));
Set varsUsedInBad = asCISet(matchX_any_firstGroups("in a bad mapping, variable * was used", l));
Set unclearVars = setIntersection(varsUsedInGood, varsUsedInBad);
MultiMap goodMappings = uniquifyMultiMapValues(pairsToMultiMap(matchX_any_firstAndSecondGroups("in a good mapping, variable * was mapped to *", l)));
MultiMap badMappings = uniquifyMultiMapValues(pairsToMultiMap(matchX_any_firstAndSecondGroups("in a bad mapping, variable * was mapped to *", l)));
MultiMap alwaysGoodMappings = multiMapDiff(goodMappings, badMappings);
MultiMap alwaysBadMappings = multiMapDiff(badMappings, goodMappings);
List> completeGoodMappings = map("safeUnstruct", matchX_any_firstGroups("a good mapping is *", l));
List> completeBadMappings = map("safeUnstruct", matchX_any_firstGroups("a bad mapping is *", l));
return nu(ai_gazelle_analyzeStatementsForRule_Data.class, "possibleVars", possibleVars, "usedVars", usedVars, "unusedVars", unusedVars, "varsUsedInGood", varsUsedInGood, "varsUsedInBad", varsUsedInBad, "unclearVars", unclearVars, "varsUsedInGoodOnly", setDiff(varsUsedInGood, varsUsedInBad), "varsUsedInBadOnly", setDiff(varsUsedInBad, varsUsedInGood), "goodMappings", goodMappings, "badMappings", badMappings, "alwaysGoodMappings", alwaysGoodMappings, "alwaysBadMappings", alwaysBadMappings, "completeGoodMappings", completeGoodMappings, "completeBadMappings", completeBadMappings);
}
public static Map > multiMapToMap(MultiMap m) {
return m == null ? null : m.data;
}
public static A popFirst(List l) {
if (empty(l))
return null;
A a = first(l);
l.remove(0);
return a;
}
public static A popFirst(Collection l) {
if (empty(l))
return null;
A a = first(l);
l.remove(a);
return a;
}
public static List ai_ruleEngine2_rulesForInput_3(RuleEngine2 engine, String q) {
q = unnull(q);
List l = new ArrayList();
for (RuleEngine2.Rule rule : engine.rules) {
String cond = first(rule.in);
String tokenize = or(matchAny_firstGroup("tokenize with *", rule.comments), "javaTokNPunctuationWithBrackets");
List tokI = (List) callAndMake(tokenize, q);
List tokC = (List) callAndMake(tokenize, cond);
tokI = ai_applyWordSplitPattern1(tokC, tokI);
Map map = zipTwoListsToCIMap_strict_withoutEquals(tokC, tokI);
if (map == null)
continue;
final RuleEngine2_MatchedRule matched = new RuleEngine2_MatchedRule();
matched.rule = rule;
matched.map = map;
matched.matchedLines.add(pair(tokC, tokI));
matched.tokenizationFunction = tokenize;
matched.remainingConditions = nullIfEmpty(map(dropFirst(rule.in), new F1() {
public String get(String s) {
try {
return matched.applyMappingTo(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "matched.applyMappingTo(s)";
}
}));
Map, Integer> qualities = ai_ruleEngine2_mappingQualities(rule);
for (String a : keys(map)) {
String b = map.get(a);
mapPut(matched.mappingQuality, a, qualities.get(pair(a, b)));
}
l.add(matched);
}
return l;
}
public static List sortByMethodDesc(Collection c, final String method) {
return sortByCalculatedFieldDesc(c, new F1 () {
public Object get(A a) {
try {
return callOpt(a, method);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callOpt(a, method)";
}
});
}
public static List sortByMethodDesc(String method, Collection c) {
return sortByMethodDesc(c, method);
}
public static boolean addIfNotInOtherSet(Collection c, Set set, A a) {
return c != null && !contains(set, a) && c.add(a);
}
public static String ai_gazelle_predictor1_onData(RuleEngine2_MatchedRule r, ai_gazelle_analyzeStatementsForRule_Data data) {
return containsAny(keys(r.map), data.varsUsedInBadOnly) ? "bad" : "good";
}
public static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || b != null && a.equals(b);
}
public static A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(Iterable strings) {
return join("", strings);
}
public static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
public static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
public static Collection ai_gazelle_makeIWantToKnows(RuleEngine2_MatchedRule r) {
LinkedHashSet out = new LinkedHashSet();
if (r != null) {
String s = first(r.remainingConditions);
if (s != null)
out.add("I want to know whether " + s);
}
return out;
}
public static void dm_gazelle_saveAppliedRule(Object... params) {
dm_requireAndCall("#1021413/AppliedRules", "uniqConcept", (Object) params);
}
public static Class mc() {
return main.class;
}
public static Class javax() {
return getJavaX();
}
public static void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
public static HashMap findClass_fullName_cache = new HashMap();
public static 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;
}
}
public static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
public static boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
public 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;
}
public 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;
}
public static String substring(String s, int x) {
return substring(s, x, strL(s));
}
public static 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);
}
public static List javaTokNPunctuationWithBrackets(String s) {
return tok_combineRoundOrCurlyBrackets_keep(javaTokNPunctuation_bracketsInC(s));
}
public static List javaTokNoQuotes(String s) {
return quotelessJavaTok(s);
}
public static List javaTokNoQuotesWithBrackets(String s) {
return tok_combineRoundOrCurlyBrackets_keep(javaTokNoQuotes(s));
}
public static Object _defaultClassFinder_value;
public static Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
public static String programID;
public static String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
public static String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
public static String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
public static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
public static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
public static boolean isFalse(Object o) {
return eq(false, o);
}
public static 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();
}
public static void print_append(Appendable _buf, String s, int max) {
try {
synchronized (_buf) {
_buf.append(s);
if (!(_buf instanceof StringBuilder))
return;
StringBuilder buf = (StringBuilder) (_buf);
max /= 2;
if (buf.length() > max)
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);
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static ReliableSingleThread dm_rst(DynModule mod, Runnable r) {
return dm_rst(mod, new ReliableSingleThread(r));
}
public static ReliableSingleThread dm_rst(DynModule mod, ReliableSingleThread rst) {
rst.enter = dm_rEnter(mod);
return rst;
}
public static ReliableSingleThread rstWithPostDelay(final int delay, final Runnable r) {
return new ReliableSingleThread(new Runnable() {
public void run() {
try {
pcallF(r);
sleep(delay);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcallF(r);\r\n sleep(delay);";
}
});
}
public static ReliableSingleThread rstWithPostDelay(double seconds, Runnable r) {
return rstWithPostDelay(toMS_int(seconds), r);
}
public static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
public static HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
public static JTextField dm_fieldTextField(String field) {
return jLiveValueTextField_bothWays(dm_fieldLiveValue(field));
}
public static void onUpdateAndNow(JComponent c, final Object r) {
onUpdate(c, r);
callF(r);
}
public static void onUpdateAndNow(List extends JComponent> l, Object r) {
for (JComponent c : l) onUpdate(c, r);
callF(r);
}
public static A applyDefaultMargin(final A c) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMarg...";
}
});
}
return c;
}
public static JPanel northCenterAndSouth(Component n, Component c, Component s) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.NORTH, wrap(n));
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
}
public static int withBottomMargin_defaultWidth = 6;
public static JPanel withBottomMargin(Component c) {
return withBottomMargin(withBottomMargin_defaultWidth, c);
}
public static JPanel withBottomMargin(final int w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(0, 0, w, 0));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static int withTopMargin_defaultWidth = 6;
public static JPanel withTopMargin(Component c) {
return withTopMargin(withTopMargin_defaultWidth, c);
}
public static JPanel withTopMargin(final int w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(w, 0, 0, 0));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static JPanel centerAndEastWithMarginInbetween(Component c, final Component e) {
return centerAndEast(c, withLeftMargin(e));
}
public static boolean newButton_autoToolTip = true;
public static JButton newButton(final String text, final Object action) {
return swing(new F0() {
public JButton get() {
try {
String text2 = dropPrefix("[disabled] ", text);
final JButton btn = new JButton(text2);
if (l(text2) < l(text))
btn.setEnabled(false);
if (newButton_autoToolTip) {
btn.setToolTipText(btn.getText());
}
if (action != null)
btn.addActionListener(actionListener(action, btn));
return btn;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S text2 = dropPrefix(\"[disabled] \", text);\r\n final JButton btn = new JButt...";
}
});
}
public static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
public static Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
public static Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
public static Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
public static JTextField jtextfield() {
return jTextField();
}
public static JTextField jtextfield(String text) {
return jTextField(text);
}
public static JTextField jtextfield(Object o) {
return jTextField(o);
}
public static int showForm_defaultGap = 4;
public static int showForm_gapBetweenColumns = 10;
public static JPanel showFormTitled(final String title, final Object... _parts) {
JDesktopPane desktop = mainDesktopPane();
if (desktop != null)
return showInternalFrameFormTitled(desktop, title, _parts);
return swing(new F0() {
public JPanel get() {
try {
final Var frame = new Var();
JPanel panel = showForm_makePanel(false, _parts);
frame.set(showForm_makeFrame(title, panel));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final new Var frame;\r\n JPanel panel = showForm_makePanel(false, _p...";
}
});
}
public static JPanel showForm_makePanel(Boolean internalFrame, Object... _parts) {
List out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts));
return vstackWithSpacing(out, showForm_defaultGap);
}
public static Pair dm_gazelle_addRule(String when, String then) {
return (Pair) quickImport(dm_call(dm_gazelle_rulesModule(), "addRule", when, then));
}
public static String gtt(JTextComponent c) {
return getTextTrim(c);
}
public static String gtt(JComboBox cb) {
return getTextTrim(cb);
}
public static JWindow infoBox(String text) {
return infoMessage(text);
}
public static JWindow infoBox(String text, double seconds) {
return infoMessage(text, seconds);
}
public static JWindow infoBox(Throwable e) {
return infoMessage(e);
}
public static JPanel jRightAlignedButtons(Object... params) {
List l = new ArrayList();
for (int i = 0; i < l(params); i += 2) if (params[i] != null)
if (params[i] instanceof JComponent)
l.add((JComponent) params[i--]);
else
l.add(jbutton((String) params[i], params[i + 1]));
return jRightAlignedLine(l);
}
public static JButton tableDependButton(JTable tbl, JButton b) {
tableDependButtons(tbl, ll(b));
return b;
}
public static JButton tableDependButton(JTable tbl, String text, Object action) {
return tableDependButton(tbl, jbutton(text, action));
}
public static List> collectThreeFieldsAsTriple(final String fieldA, final String fieldB, final String fieldC, Iterable l) {
return map(l, new F1>() {
public T3 get(C c) {
try {
return t3((A) getOpt(c, fieldA), (B) getOpt(c, fieldB), (C) getOpt(c, fieldC));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "t3((A) getOpt(c, fieldA), (B) getOpt(c, fieldB), (C) getOpt(c, fieldC))";
}
});
}
public static A dm_requireAndCall(String moduleLibID, String method, Object... args) {
return dm_requireAndCallModule(moduleLibID, method, args);
}
public static List getMatchesX_all(String pat, Iterable l) {
Matches m = new Matches();
List out = new ArrayList();
for (String s : unnull(l)) if (matchX(pat, s, m)) {
out.add(m);
m = new Matches();
}
return out;
}
public static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
public static ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
public static String n2(long l) {
return formatWithThousands(l);
}
public static String n2(Collection l) {
return n2(l(l));
}
public static String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
public static String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
public static String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
public static String n2(Collection l, String singular) {
return n2(l(l), singular);
}
public static String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
public static String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
public static String n2(Map m, String singular) {
return n2(l(m), singular);
}
public static String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
public static String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
public static String getString(Map map, Object key) {
return map == null ? null : (String) map.get(key);
}
public static String getString(List l, int idx) {
return (String) get(l, idx);
}
public static String getString(Object o, Object key) {
if (o instanceof Map)
return getString((Map) o, key);
if (key instanceof String)
return (String) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
public static String getString(String key, Object o) {
return getString(o, (Object) key);
}
public static A unstruct(String text) {
return (A) unstructure(text);
}
public static B getOrCreate_f1(Map map, A key, F1 create) {
try {
B b = map.get(key);
if (b == null)
mapPut(map, key, b = callF(create, key));
return b;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static List ai_gazelle_statementsFromAppliedRule(RuleEngine2_MatchedRule r, String judgement) {
if (nempty(judgement) && neq(judgement, "good"))
judgement = "bad";
String ruleID = r.rule.globalID;
String ruleIn = first(r.rule.in);
Map varMap = r.map;
String tokenize = r.tokenizationFunction;
List tok = (List) (callAndMake(tokenize, ruleIn));
List tokC = codeTokens(tok);
Set possibleVars = asCISet(tokC);
List statements = new ArrayList();
for (String a : keys(varMap)) {
String b = varMap.get(a);
statements.add(format("in a * mapping, variable " + quote(a) + " was used", judgement));
statements.add(format("in a * mapping, variable " + quote(a) + " was mapped to " + quote(b), judgement));
}
for (String var : possibleVars) statements.add("possible variable " + quote(var));
statements.add(format("a * mapping is *", judgement, sfu(varMap)));
return statements;
}
public static volatile PersistableThrowable _handleException_lastException;
public static List _handleException_onException = synchroList(ll("printStackTrace2"));
public static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3);
}
}
public static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
public static Collection values(MultiMap mm) {
return mm == null ? emptyList() : concatLists(values(mm.data));
}
public static Map similarEmptyMap(Map m) {
if (m instanceof TreeMap)
return new TreeMap(((TreeMap) m).comparator());
if (m instanceof LinkedHashMap)
return new LinkedHashMap();
return new HashMap();
}
public static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
public static Set keys(Object map) {
return keys((Map) map);
}
public static Set keys(MultiMap mm) {
return mm.keySet();
}
public static TreeSet asCISet(Iterable c) {
return toCaseInsensitiveSet(c);
}
public static TreeSet asCISet(String... x) {
return toCaseInsensitiveSet(x);
}
public static List matchAny_firstGroups(String pat, Iterable l) {
Matches m = new Matches();
List out = new ArrayList();
for (String s : unnull(l)) if (match(pat, s, m))
out.add(m.unq(0));
return out;
}
public static List matchX_any_firstGroups(String pat, Iterable l) {
Matches m = new Matches();
List out = new ArrayList();
for (String s : unnull(l)) if (matchX(pat, s, m))
out.add(m.unq(0));
return out;
}
public static List listMinusSet(Iterable l, Collection stuff) {
if (empty(stuff))
return asList(l);
Set set = asSet(stuff);
List l2 = new ArrayList();
for (A a : l) if (!set.contains(a))
l2.add(a);
return l2;
}
public static List listMinusSet(Iterable l, Collection stuff, Collection stuff2) {
return listMinusSet(listMinusSet(l, stuff), stuff2);
}
public static Set setIntersection(Set a, Collection b) {
Set set = similarEmptySet(a);
Set bSet = asSet(b);
for (A x : a) if (bSet.contains(x))
set.add(x);
return set;
}
public static MultiMap uniquifyMultiMapValues(MultiMap mm) {
return mm == null ? null : new MultiMap(mapValues("uniquify", mm.data));
}
public static MultiMap pairsToMultiMap(List> l) {
MultiMap mm = new MultiMap();
for (Pair p : unnull(l)) mm.put(p.a, p.b);
return mm;
}
public static List> matchX_any_firstAndSecondGroups(String pat, Iterable l) {
Matches m = new Matches();
List> out = new ArrayList();
for (String s : unnull(l)) if (matchX(pat, s, m))
out.add(pair(m.unq(0), m.unq(1)));
return out;
}
public static MultiMap multiMapDiff(MultiMap mm1, MultiMap mm2) {
return pairsToMultiMap(listMinusSet(multiMapToPairs(mm1), multiMapToPairs(mm2)));
}
public static List map(Iterable l, Object f) {
return map(f, l);
}
public static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) x.add(callF(f, o));
return x;
}
public static List map(Iterable l, F1 f) {
return map(f, l);
}
public static List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) x.add(callF(f, o));
return x;
}
public static List map(Object f, Object[] l) {
return map(f, asList(l));
}
public static List map(Object[] l, Object f) {
return map(f, l);
}
public static List map(Object f, Map map) {
return map(map, f);
}
public static 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;
}
public static A safeUnstruct(String s) {
return (A) unstructure(s, true);
}
public static Set setDiff(Set l, Collection stuff) {
return setMinusSet(l, stuff);
}
public static Object first(Object list) {
return first((Iterable) list);
}
public static A first(List list) {
return empty(list) ? null : list.get(0);
}
public static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
public static A first(IterableIterator i) {
return first((Iterator ) i);
}
public static A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
public static A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
public static Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
public static A first(Pair p) {
return p == null ? null : p.a;
}
public static A first(T3 t) {
return t == null ? null : t.a;
}
public static String unnull(String s) {
return s == null ? "" : s;
}
public static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
public static List unnull(List l) {
return l == null ? emptyList() : l;
}
public static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
public static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
public static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
public static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
public static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
public static A or(A a, A b) {
return a != null ? a : b;
}
public static String matchAny_firstGroup(String pat, Iterable l) {
Matches m = new Matches();
return matchAny(pat, l, m) ? m.unq(0) : null;
}
public static Object callAndMake(String functionName, Object... args) {
return callAndMake_orDirect(functionName, args);
}
public static List ai_applyWordSplitPattern1(List tokP, List tokI) {
List indices = indicesOfSubList(tokP, ll("", "{}", ""));
if (empty(indices))
return tokI;
List tokI_original = tokI;
tokI = cloneList(tokI);
for (int i : indices) {
String l = get(tokP, i - 1), r = get(tokP, i + 3);
if (startsWith(l, "$") && isIdentifier(l) && isIdentifier(r)) {
String x = get(tokI, i - 1);
if (!ewic(x, r))
return tokI_original;
tokI.set(i - 1, dropLast(x, l(r)));
tokI.add(i, "");
tokI.add(i + 1, "{}");
tokI.add(i + 2, "");
tokI.add(i + 3, takeLast(x, l(r)));
}
}
return tokI;
}
public static Map zipTwoListsToCIMap_strict_withoutEquals(List l1, List l2) {
int n = l(l1);
if (n != l(l2))
return null;
Map map = ciMap();
for (int i = 0; i < n; i++) if (!strictPutICIfKeyNotEqualToValue(map, l1.get(i), l2.get(i)))
return null;
return map;
}
public static Pair pair(A a, B b) {
return new Pair(a, b);
}
public static Pair pair(A a) {
return new Pair(a, a);
}
public static String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
public static Map nullIfEmpty(Map map) {
return isEmpty(map) ? null : map;
}
public static List nullIfEmpty(List l) {
return isEmpty(l) ? null : l;
}
public static String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
public static String[] dropFirst(String[] a) {
return drop(1, a);
}
public static Object[] dropFirst(Object[] a) {
return drop(1, a);
}
public static List dropFirst(List l) {
return dropFirst(1, l);
}
public static List dropFirst(int n, Iterable i) {
return dropFirst(n, toList(i));
}
public static List dropFirst(Iterable i) {
return dropFirst(toList(i));
}
public static List dropFirst(int n, List l) {
return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
public static List dropFirst(List l, int n) {
return dropFirst(n, l);
}
public static String dropFirst(int n, String s) {
return substring(s, n);
}
public static String dropFirst(String s) {
return substring(s, 1);
}
public static Map, Integer> ai_ruleEngine2_mappingQualities(RuleEngine2.Rule rule) {
Map, Integer> map = new HashMap();
Matches m = new Matches();
for (String s : rule.comments) if (match("changing * to * is *", s, m)) {
int value = eqic(m.unq(0), "ok") ? 1 : eqic(m.unq(0), "bad") ? -1 : 0;
map.put(pair(m.unq(1), m.unq(2)), value);
}
return map;
}
public static void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null)
map.put(key, value);
}
public static List sortByCalculatedFieldDesc(Collection c, final Object f) {
return sortByCalculatedFieldDesc_inPlace(cloneList(c), f);
}
public static List sortByCalculatedFieldDesc(Object f, Collection c) {
return sortByCalculatedFieldDesc(c, f);
}
public static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
public static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
public static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
public static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
public static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
public static boolean containsAny(Collection a, Collection b) {
if (empty(a))
return false;
Set set = asSet(b);
for (A x : a) if (contains(set, x))
return true;
return false;
}
public static String str(Object o) {
return o == null ? "null" : o.toString();
}
public static String str(char[] c) {
return new String(c);
}
public static Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A nuObject(Class c, Object... args) {
try {
if (args.length == 0)
return nuObjectWithoutArguments(c);
Constructor m = nuObject_findConstructor(c, args);
m.setAccessible(true);
return (A) m.newInstance(args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
public static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
public static void setAll(Object o, Map fields) {
if (fields == null)
return;
for (String field : keys(fields)) set(o, field, fields.get(field));
}
public static void setAll(Object o, Object... values) {
failIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
set(o, field, value);
}
}
public static Class __javax;
public static Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
public static int strL(String s) {
return s == null ? 0 : s.length();
}
public static int listL(Collection l) {
return l == null ? 0 : l.size();
}
public static boolean neq(Object a, Object b) {
return !eq(a, b);
}
public static int withMargin_defaultWidth = 6;
public static JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
public static JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
public static JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
public static JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static Throwable printStackTrace2(Throwable e) {
print(getStackTrace2(e));
return e;
}
public static void printStackTrace2() {
printStackTrace2(new Throwable());
}
public static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
public static List tok_combineRoundOrCurlyBrackets_keep(List tok) {
List l = new ArrayList();
for (int i = 0; i < l(tok); i++) {
String t = tok.get(i);
if (odd(i) && eqOneOf(t, "{", "(")) {
int j = findEndOfBracketPart(tok, i);
l.add(joinSubList(tok, i, j));
i = j - 1;
} else
l.add(t);
}
return l;
}
public static List javaTokNPunctuation_bracketsInC(String s) {
List tok = javaTok(s);
for (int i = 1; i < l(tok); i += 2) {
int j = i;
String t;
char c;
while (j < l(tok) && l(t = tok.get(j)) == 1 && !Character.isLetterOrDigit(c = t.charAt(0)) && "{}()".indexOf(c) < 0) j += 2;
if (j > i)
replaceSubList(tok, i - 1, j, ll(joinSubList(tok, i - 1, j)));
}
return tok;
}
public static List quotelessJavaTok(String s) {
ArrayList tok = new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
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);
if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
return tok;
}
public static String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
public static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
public static String formatSnippetID(long id) {
return "#" + id;
}
public static Class getMainClass() {
return mc();
}
public static 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);
}
}
public static volatile boolean ping_pauseAll;
public static int ping_sleep = 100;
public static volatile boolean ping_anyActions;
public static Map ping_actions = newWeakHashMap();
public static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
public static boolean ping() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
public static 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);
}
}
public static F0 dm_rEnter(final DynModule mod) {
return mod == null ? null : new F0() {
public AutoCloseable get() {
try {
return mod.enter();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret mod.enter();";
}
};
}
public static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
public static A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
public static B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
public static volatile boolean sleep_noSleep;
public static void sleep(long ms) {
ping();
if (ms < 0)
return;
if (isAWTThread() && ms > 100)
throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void sleep() {
try {
if (sleep_noSleep)
throw fail("nosleep");
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static int toMS_int(double seconds) {
return toInt_checked((long) (seconds * 1000));
}
public static JTextField jLiveValueTextField_bothWays(final SimpleLiveValue lv) {
final JTextField ta = jTextField();
bindTextComponentToLiveValue_bothWays(ta, lv);
return ta;
}
public static SimpleLiveValue dm_fieldLiveValue(String fieldName) {
return dm_fieldLiveValue(dm_current_mandatory(), fieldName);
}
public static SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) {
Lock __319 = module.lock;
lock(__319);
try {
Class type = getFieldType(module, fieldName);
final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName));
module.onChange(new Runnable() {
public void run() {
try {
Object o = get(module, fieldName);
value.set(o);
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting \" + fi...";
}
});
value.onChange(new Runnable() {
public void run() {
try {
module.setField(fieldName, value.get());
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting 2 \" + ...";
}
});
return value;
} finally {
unlock(__319);
}
}
public static void onUpdate(JComponent c, final Object r) {
if (c instanceof JTextComponent)
((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
call(r);
}
public void removeUpdate(DocumentEvent e) {
call(r);
}
public void changedUpdate(DocumentEvent e) {
call(r);
}
});
else if (c instanceof ItemSelectable)
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
call(r);
}
});
else
print("Warning: onUpdate doesn't know " + getClassName(c));
}
public static void onUpdate(List extends JComponent> l, Object r) {
for (JComponent c : l) onUpdate(c, r);
}
public static Object swing(Object f) {
return swingAndWait(f);
}
public static A swing(F0 f) {
return (A) swingAndWait(f);
}
public static Component wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
public static Component wrap_2(Object swingable) {
if (swingable == null)
return null;
Component c;
if (swingable instanceof Component)
c = (Component) swingable;
else
c = (Component) callOpt(swingable, "swing");
if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
public static JPanel centerAndEast(final Component c, final Component e) {
return (JPanel) swing(new F0() {
public Object get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.EAST, wrap(e));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT...";
}
});
}
public static int withLeftMargin_defaultWidth = 6;
public static JPanel withLeftMargin(Component c) {
return withLeftMargin(withLeftMargin_defaultWidth, c);
}
public static JPanel withLeftMargin(final int margin, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(0, margin, 0, 0));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
public static ActionListener actionListener(final Object runnable) {
return actionListener(runnable, null);
}
public static ActionListener actionListener(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener)
return (ActionListener) runnable;
final Object info = _threadInfo();
return new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
_threadInheritInfo(info);
AutoCloseable __180 = holdInstance(instanceToHold);
try {
callF(runnable);
} finally {
_close(__180);
}
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
public static A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () {
public A get() {
try {
return nuObject(c, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret nuObject(c, args);";
}
});
}
public static String defaultThreadName_name;
public static String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
public static Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
public static Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
public static Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
public static Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
public static 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)";
}
};
}
public static Map _registerThread_threads;
public static Object _onRegisterThread;
public static 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;
}
public static void _registerThread() {
_registerThread(Thread.currentThread());
}
public static JTextField jTextField() {
return jTextField("");
}
public static JTextField jTextField(final String text) {
return swing(new F0() {
public JTextField get() {
try {
JTextField tf = new JTextField(unnull(text));
standardTextFieldPopupMenu(tf);
jenableUndoRedo(tf);
tf.selectAll();
return tf;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JTextField tf = new JTextField(unnull(text));\r\n standardTextFieldPopupMenu...";
}
});
}
public static JTextField jTextField(Object o) {
return jTextField(strOrEmpty(o));
}
public static JDesktopPane mainDesktopPane_value;
public static JDesktopPane mainDesktopPane() {
return mainDesktopPane_value;
}
public static JPanel showInternalFrameFormTitled(final JDesktopPane desktop, final String title, final Object... _parts) {
JPanel panel = showForm_makePanel(true, _parts);
showForm_makeInternalFrame(desktop, title, panel);
return panel;
}
public static JFrame showForm_makeFrame(String title, JPanel panel) {
return handleEscapeKey(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400));
}
public static List showForm_arrange1(List> l) {
int minW = showForm_leftWidth(l);
List out = new ArrayList();
for (List row : l) out.add(westAndCenter(withRightMargin(showForm_gapBetweenColumns, jMinWidth(minW, first(row))), second(row)));
return out;
}
public static List> showForm_makeComponents(final Boolean internalFrame, Object... _parts) {
List> l = new ArrayList();
List parts = asList(_parts);
JButton submitButton = null;
for (int i = 0; i < l(parts); i++) {
final Object o = parts.get(i), next = get(parts, i + 1);
if (o instanceof String && next instanceof Component)
setComponentID((Component) next, (String) o);
if (o instanceof Component || o instanceof String || next instanceof Component) {
l.add(mapLL("wrapForSmartAdd", o == null ? new JPanel() : o instanceof String ? humanizeFormLabel((String) o) : o, next));
if (next instanceof JButton && submitButton == null)
submitButton = (JButton) next;
i++;
} else if (isRunnable(o))
l.add(mapLL("wrapForSmartAdd", null, submitButton = jbutton(showFormSubmitButtonName(), new Runnable() {
public void run() {
try {
Object result = call(o);
if (neq(Boolean.FALSE, result)) {
if (isTrue(internalFrame))
disposeInternalFrame(heldInstance(JButton.class));
else if (isFalse(internalFrame))
disposeFrame(heldInstance(JButton.class));
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Object result = call(o);\r\n if (neq(Boolean.FALSE, result)) {\r\n ...";
}
})));
else
print("showForm: Unknown element type: " + getClassName(o));
}
if (submitButton != null) {
final JButton _submitButton = submitButton;
onEnterInAllTextFields(concatLists(l), new Runnable() {
public void run() {
try {
clickButton(_submitButton);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "clickButton(_submitButton)";
}
});
}
for (List row : l) {
JComponent left = first(row);
if (left instanceof JLabel)
makeBold((JLabel) left).setVerticalAlignment(JLabel.TOP);
}
return l;
}
public static int vstackWithSpacing_default = 10;
public static JPanel vstackWithSpacing(final List parts) {
return vstackWithSpacing(parts, vstackWithSpacing_default);
}
public static JPanel vstackWithSpacing(final List parts, final int spacing) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(spacing / 2, 0, spacing / 2, 0);
smartAddWithLayout(panel, gbc, toObjectArray(nonNulls(parts)));
gbc.weighty = 1;
gbc.insets = new Insets(0, 0, 0, 0);
panel.add(jrigid(), gbc);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new GridBagLayout);\r\n new GridBagConstraints gbc...";
}
});
}
public static JPanel vstackWithSpacing(Component... parts) {
return vstackWithSpacing(asList(parts), vstackWithSpacing_default);
}
public static Object quickImport(Object o) {
return quickExport(o, mc());
}
public static A dm_call(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __16 = dm_enter(mod);
try {
return (A) call(mod, method, args);
} finally {
_close(__16);
}
}
public static String dm_gazelle_rulesModule() {
return dm_require("#1021352/Rules");
}
public static String getTextTrim(JTextComponent c) {
return trim(getText(c));
}
public static String getTextTrim(JComboBox cb) {
return trim(getText(cb));
}
public static String getTextTrim(JComponent c) {
if (c instanceof JLabel)
return trim(((JLabel) c).getText());
if (c instanceof JComboBox)
return getTextTrim((JComboBox) c);
return getTextTrim((JTextComponent) c);
}
public static boolean infoMessage_alwaysOnTop = true;
public static double infoMessage_defaultTime = 5.0;
public static JWindow infoMessage(String text) {
return infoMessage(text, infoMessage_defaultTime);
}
public static JWindow infoMessage(final String text, final double seconds) {
printHidingCredentials(text);
return infoMessage_noprint(text, seconds);
}
public static JWindow infoMessage_noprint(String text) {
return infoMessage_noprint(text, infoMessage_defaultTime);
}
public static JWindow infoMessage_noprint(final String _text, final double seconds) {
final String text = hideCredentials(_text);
if (empty(text))
return null;
logQuotedWithDate(infoBoxesLogFile(), text);
if (isHeadless())
return null;
return (JWindow) swingAndWait(new F0() {
public Object get() {
try {
final JWindow window = showWindow(infoMessage_makePanel(text));
window.setSize(300, 150);
moveToTopRightCorner(window);
if (infoMessage_alwaysOnTop)
window.setAlwaysOnTop(true);
window.setVisible(true);
if (seconds != 0)
disposeWindowAfter(iround(seconds * 1000), window);
return window;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JWindow window = showWindow(infoMessage_makePanel(text));\r\n window.s...";
}
});
}
public static JWindow infoMessage(Throwable e) {
printStackTrace(e);
return infoMessage(exceptionToStringShort(e));
}
public static JPanel jRightAlignedLine(Component... components) {
return jrightAlignedLine(components);
}
public static JPanel jRightAlignedLine(List extends Component> components) {
return jrightAlignedLine(components);
}
public static void tableDependButtons(final JTable table, List extends Component> buttons) {
for (Component c : buttons) if (c instanceof JButton) {
final JButton b = (JButton) (c);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
b.setEnabled(table.getSelectedRow() >= 0);
}
});
b.setEnabled(table.getSelectedRow() >= 0);
}
}
public static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
public static T3 t3(A a, B b, C c) {
return new T3(a, b, c);
}
public static A dm_requireAndCallModule(String moduleLibID, String method, Object... args) {
return dm_callModule(dm_requireModule(moduleLibID), method, args);
}
public static boolean matchX(String pat, String s) {
return matchX(pat, s, null);
}
public static boolean matchX(String pat, String s, Matches m) {
if (endsWith(pat, "..."))
return matchStartX(pat, s, m);
if (startsWith(pat, "..."))
return matchEndX(pat, s, m);
return match(pat, s, m);
}
public static Object collectionMutex(Object o) {
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
public static String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
public static double fraction(double d) {
return d % 1;
}
public static String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
public static String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
public static String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
public static String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
public static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
public static Object unstructure(String text) {
return unstructure(text, false);
}
public static Object unstructure(String text, final boolean allDynamic) {
return unstructure(text, allDynamic, null);
}
public static int structure_internStringsLongerThan = 50;
public static int unstructure_unquoteBufSize = 100;
public static int unstructure_tokrefs;
public abstract static class unstructure_Receiver {
public abstract void set(Object o);
}
public static Object unstructure(String text, boolean allDynamic, Object classFinder) {
if (text == null)
return null;
return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
}
public static Object unstructure_reader(BufferedReader reader) {
return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
}
public static Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object _classFinder) {
final boolean debug = unstructure_debug;
final class X {
public int i = -1;
public final Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder();
public HashMap refs = new HashMap();
public HashMap tokrefs = new HashMap();
public HashSet concepts = new HashSet();
public HashMap classesMap = new HashMap();
public List stack = new ArrayList();
public String curT;
public char[] unquoteBuf = new char[unstructure_unquoteBufSize];
public String unquote(String s) {
return unquoteUsingCharArray(s, unquoteBuf);
}
public String t() {
return curT;
}
public String tpp() {
String t = curT;
consume();
return t;
}
public void parse(final unstructure_Receiver out) {
String t = t();
int refID = 0;
if (structure_isMarker(t, 0, l(t))) {
refID = parseInt(t.substring(1));
consume();
}
final int _refID = refID;
final int tokIndex = i;
parse_inner(refID, tokIndex, new unstructure_Receiver() {
public void set(Object o) {
if (_refID != 0)
refs.put(_refID, o);
if (o != null)
tokrefs.put(tokIndex, o);
out.set(o);
}
});
}
public void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) {
String t = t();
Class c = classesMap.get(t);
if (c == null) {
if (t.startsWith("\"")) {
String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
out.set(s);
return;
}
if (t.startsWith("'")) {
out.set(unquoteCharacter(tpp()));
return;
}
if (t.equals("bigint")) {
out.set(parseBigInt());
return;
}
if (t.equals("d")) {
out.set(parseDouble());
return;
}
if (t.equals("fl")) {
out.set(parseFloat());
return;
}
if (t.equals("sh")) {
consume();
t = tpp();
if (t.equals("-")) {
t = tpp();
out.set((short) (-parseInt(t)));
return;
}
out.set((short) parseInt(t));
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("false") || t.equals("f")) {
consume();
out.set(false);
return;
}
if (t.equals("true") || t.equals("t")) {
consume();
out.set(true);
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("File")) {
consume();
File f = new File(unquote(tpp()));
out.set(f);
return;
}
if (t.startsWith("r") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = refs.get(ref);
if (o == null)
print("Warning: unsatisfied back reference " + ref);
out.set(o);
return;
}
if (t.startsWith("t") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = tokrefs.get(ref);
if (o == null)
print("Warning: unsatisfied token reference " + ref);
out.set(o);
return;
}
if (t.equals("hashset")) {
parseHashSet(out);
return;
}
if (t.equals("lhs")) {
parseLinkedHashSet(out);
return;
}
if (t.equals("treeset")) {
parseTreeSet(out);
return;
}
if (t.equals("ciset")) {
parseCISet(out);
return;
}
if (eqOneOf(t, "hashmap", "hm")) {
consume();
parseMap(new HashMap(), out);
return;
}
if (t.equals("lhm")) {
consume();
parseMap(new LinkedHashMap(), out);
return;
}
if (t.equals("sync")) {
consume();
if (t().equals("tm")) {
consume();
{
parseMap(synchronizedTreeMap(), out);
return;
}
}
if (t().equals("[")) {
parseList(synchroList(), out);
return;
}
{
parseMap(synchronizedMap(), out);
return;
}
}
if (t.equals("{")) {
parseMap(out);
return;
}
if (t.equals("[")) {
this.parseList(new ArrayList(), out);
return;
}
if (t.equals("bitset")) {
parseBitSet(out);
return;
}
if (t.equals("array") || t.equals("intarray")) {
parseArray(out);
return;
}
if (t.equals("ba")) {
consume();
String hex = unquote(tpp());
out.set(hexToBytes(hex));
return;
}
if (t.equals("boolarray")) {
consume();
int n = parseInt(tpp());
String hex = unquote(tpp());
out.set(boolArrayFromBytes(hexToBytes(hex), n));
return;
}
if (t.equals("class")) {
out.set(parseClass());
return;
}
if (t.equals("l")) {
parseLisp(out);
return;
}
if (t.equals("null")) {
consume();
out.set(null);
return;
}
if (eq(t, "c")) {
consume("c");
t = t();
assertTrue(isJavaIdentifier(t));
concepts.add(t);
}
}
if (eq(t, "j")) {
consume("j");
out.set(parseJava());
return;
}
if (c == null && !isJavaIdentifier(t))
throw new RuntimeException("Unknown token " + (i + 1) + ": " + t);
consume();
String className, fullClassName;
if (eq(t(), ".")) {
consume();
className = fullClassName = t + "." + assertIdentifier(tpp());
} else {
className = t;
fullClassName = "main$" + t;
}
if (c == null) {
if (allDynamic)
c = null;
else
c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
if (c != null)
classesMap.put(className, c);
}
boolean hasBracket = eq(t(), "(");
if (hasBracket)
consume();
boolean hasOuter = hasBracket && eq(t(), "this$1");
DynamicObject dO = null;
Object o = null;
final String thingName = t;
if (c != null) {
o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c);
if (o instanceof DynamicObject)
dO = (DynamicObject) o;
} else {
if (concepts.contains(t) && (c = findClass("Concept")) != null)
o = dO = (DynamicObject) nuEmptyObject(c);
else
dO = new DynamicObject();
dO.className = className;
}
if (refID != 0)
refs.put(refID, o != null ? o : dO);
tokrefs.put(tokIndex, o != null ? o : dO);
final LinkedHashMap fields = new LinkedHashMap();
final Object _o = o;
final DynamicObject _dO = dO;
if (hasBracket) {
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), ")")) {
consume(")");
objRead(_o, _dO, fields);
out.set(_o != null ? _o : _dO);
} else {
final String key = unquote(tpp());
if (!eq(tpp(), "="))
throw fail("= expected, got " + t() + " after " + quote(key) + " in object " + thingName);
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object value) {
fields.put(key, value);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \")\")) {\r\n consume(\")\");\r\n objRead(_o, _dO, ...";
}
});
} else {
objRead(o, dO, fields);
out.set(o != null ? o : dO);
}
}
public void objRead(Object o, DynamicObject dO, Map fields) {
if (o != null)
if (dO != null) {
setOptAllDyn(dO, fields);
} else {
setOptAll_pcall(o, fields);
}
else
for (String field : keys(fields)) dO.fieldValues.put(intern(field), fields.get(field));
if (o != null)
pcallOpt_noArgs(o, "_doneLoading");
}
public void parseSet(final Set set, final unstructure_Receiver out) {
this.parseList(new ArrayList(), new unstructure_Receiver() {
public void set(Object o) {
set.addAll((List) o);
out.set(set);
}
});
}
public void parseLisp(final unstructure_Receiver out) {
throw fail("class Lisp not included");
}
public void parseBitSet(final unstructure_Receiver out) {
consume("bitset");
consume("{");
final BitSet bs = new BitSet();
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "}")) {
consume("}");
out.set(bs);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
bs.set((Integer) o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n ...";
}
});
}
public void parseList(final List list, final unstructure_Receiver out) {
consume("[");
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "]")) {
consume("]");
out.set(list);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
list.add(o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"]\")) {\r\n consume(\"]\");\r\n out.set(list);\r\n ...";
}
});
}
public void parseArray(final unstructure_Receiver out) {
final String type = tpp();
consume("{");
final List list = new ArrayList();
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "}")) {
consume("}");
out.set(type.equals("intarray") ? toIntArray(list) : list.toArray());
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
list.add(o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(type.equals(\"...";
}
});
}
public Object parseClass() {
consume("class");
consume("(");
String name = unquote(tpp());
consume(")");
Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : findClass_fullName(name);
if (c != null)
return c;
DynamicObject dO = new DynamicObject();
dO.className = "java.lang.Class";
name = dropPrefix("main$", name);
dO.fieldValues.put("name", name);
return dO;
}
public Object parseBigInt() {
consume("bigint");
consume("(");
String val = tpp();
if (eq(val, "-"))
val = "-" + tpp();
consume(")");
return new BigInteger(val);
}
public Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tpp());
consume(")");
return Double.parseDouble(val);
}
public Object parseFloat() {
consume("fl");
String val;
if (eq(t(), "(")) {
consume("(");
val = unquote(tpp());
consume(")");
} else {
val = unquote(tpp());
}
return Float.parseFloat(val);
}
public void parseHashSet(unstructure_Receiver out) {
consume("hashset");
parseSet(new HashSet(), out);
}
public void parseLinkedHashSet(unstructure_Receiver out) {
consume("lhs");
parseSet(new LinkedHashSet(), out);
}
public void parseTreeSet(unstructure_Receiver out) {
consume("treeset");
parseSet(new TreeSet(), out);
}
public void parseCISet(unstructure_Receiver out) {
consume("ciset");
parseSet(ciSet(), out);
}
public void parseMap(unstructure_Receiver out) {
parseMap(new TreeMap(), out);
}
public Object parseJava() {
String j = unquote(tpp());
Matches m = new Matches();
if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
else {
warn("Unknown Java object: " + j);
return null;
}
}
public void parseMap(final Map map, final unstructure_Receiver out) {
consume("{");
stack.add(new Runnable() {
public boolean v;
public Object key;
public void run() {
if (v) {
v = false;
stack.add(this);
if (!eq(tpp(), "="))
throw fail("= expected, got " + t() + " in map of size " + l(map));
parse(new unstructure_Receiver() {
public void set(Object value) {
map.put(key, value);
if (eq(t(), ","))
consume();
}
});
} else {
if (eq(t(), "}")) {
consume("}");
out.set(map);
} else {
v = true;
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
key = o;
}
});
}
}
}
});
}
public void consume() {
curT = tok.next();
++i;
}
public void consume(String s) {
if (!eq(t(), s)) {
throw fail(quote(s) + " expected, got " + quote(t()));
}
consume();
}
public void parse_x(unstructure_Receiver out) {
consume();
parse(out);
while (nempty(stack)) popLast(stack).run();
}
}
Boolean b = DynamicObject_loading.get();
DynamicObject_loading.set(true);
try {
final Var v = new Var();
X x = new X();
x.parse_x(new unstructure_Receiver() {
public void set(Object o) {
v.set(o);
}
});
unstructure_tokrefs = x.tokrefs.size();
return v.get();
} finally {
DynamicObject_loading.set(b);
}
}
public static boolean unstructure_debug;
public static List codeTokens(List tok) {
return codeTokensOnly(tok);
}
public static String format(String pat, Object... args) {
return format3(pat, args);
}
public static String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
public static String quote(String s) {
if (s == null)
return "null";
StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
quote_impl(s, out);
return out.toString();
}
public static void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
public static String sfu(Object o) {
return structureForUser(o);
}
public static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
public static List synchroList(List l) {
return Collections.synchronizedList(l);
}
public static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
public static Throwable innerException(Throwable e) {
return getInnerException(e);
}
public static ArrayList emptyList() {
return new ArrayList();
}
public static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
public static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
public static ArrayList emptyList(Class c) {
return new ArrayList();
}
public static List concatLists(Collection ... lists) {
List l = new ArrayList();
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
public static List concatLists(Collection extends Collection > lists) {
List l = new ArrayList();
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
public static TreeSet toCaseInsensitiveSet(Iterable c) {
if (isCISet(c))
return (TreeSet) c;
TreeSet set = caseInsensitiveSet();
addAll(set, c);
return set;
}
public static TreeSet toCaseInsensitiveSet(String... x) {
TreeSet set = caseInsensitiveSet();
addAll(set, x);
return set;
}
public static Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array) if (o != null)
set.add(o);
return set;
}
public static Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array) if (o != null)
set.add(o);
return set;
}
public static Set asSet(Iterable l) {
if (l instanceof Set)
return (Set) l;
HashSet set = new HashSet();
for (A o : unnull(l)) if (o != null)
set.add(o);
return set;
}
public static Set similarEmptySet(Collection m) {
if (m instanceof TreeSet)
return new TreeSet(((TreeSet) m).comparator());
if (m instanceof LinkedHashSet)
return new LinkedHashSet();
return new HashSet();
}
public static List uniquify(Collection l) {
return uniquifyList(l);
}
public static List> multiMapToPairs(MultiMap mm) {
List> out = new ArrayList();
for (A key : keys(mm)) for (B value : mm.get(key)) out.add(pair(key, value));
return out;
}
public static Set setMinusSet(Set l, Collection stuff) {
if (empty(stuff))
return l;
Set set = asSet(stuff);
Set l2 = similarEmptySet(l);
for (A a : l) if (!set.contains(a))
l2.add(a);
return l2;
}
public static Map emptyMap() {
return new HashMap();
}
public static boolean matchAny(Collection patterns, String s, Matches m) {
for (String pattern : patterns) if (match(pattern, s, m))
return true;
return false;
}
public static boolean matchAny(Collection patterns, String s) {
return matchAny(patterns, s, null);
}
public static boolean matchAny(String pat, Iterable l) {
return matchAny(pat, l, null);
}
public static boolean matchAny(String pat, Iterable l, Matches m) {
if (l != null)
for (String s : l) if (match(pat, s, m))
return true;
return false;
}
public static Object callAndMake_orDirect(String functionName, List args) {
return callAndMake_orDirect(functionName, toObjectArray(args));
}
public static Object callAndMake_orDirect(String functionName, Object... args) {
if (functionName == null)
return null;
if (hasMethod(mc(), functionName, args))
return callMC(functionName, args);
else
return makeAndCall_cached(functionName, args);
}
public static List indicesOfSubList(List x, List y) {
List l = new ArrayList();
int i = 0;
while (true) {
int j = indexOfSubList(x, y, i);
if (j < 0)
break;
l.add(j);
i = j + 1;
}
return l;
}
public static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
public static boolean ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
public static boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
public static String[] dropLast(String[] a, int n) {
n = Math.min(n, a.length);
String[] b = new String[a.length - n];
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
public static List dropLast(List l) {
return subList(l, 0, l(l) - 1);
}
public static List dropLast(int n, List l) {
return subList(l, 0, l(l) - n);
}
public static List dropLast(Iterable l) {
return dropLast(asList(l));
}
public static String dropLast(String s) {
return substring(s, 0, l(s) - 1);
}
public static String dropLast(String s, int n) {
return substring(s, 0, l(s) - n);
}
public static String dropLast(int n, String s) {
return dropLast(s, n);
}
public static List takeLast(List l, int n) {
return newSubList(l, l(l) - n);
}
public static List takeLast(int n, List l) {
return takeLast(l, n);
}
public static String takeLast(int n, String s) {
return substring(s, l(s) - n);
}
public static String takeLast(String s, int n) {
return substring(s, l(s) - n);
}
public static TreeMap ciMap() {
return caseInsensitiveMap();
}
public static boolean strictPutICIfKeyNotEqualToValue(Map map, String key, String value) {
if (eqic(key, value))
return true;
return strictPutIC(map, key, value);
}
public static boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
public static boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
public static boolean isEmpty(Object[] a) {
return a == null || a.length == 0;
}
public static boolean isEmpty(byte[] a) {
return a == null || a.length == 0;
}
public static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
public static String[] drop(int n, String[] a) {
n = Math.min(n, a.length);
String[] b = new String[a.length - n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
public static Object[] drop(int n, Object[] a) {
n = Math.min(n, a.length);
Object[] b = new Object[a.length - n];
System.arraycopy(a, n, b, 0, b.length);
return b;
}
public static ArrayList toList(A[] a) {
return asList(a);
}
public static ArrayList toList(int[] a) {
return asList(a);
}
public static ArrayList toList(Set s) {
return asList(s);
}
public static ArrayList toList(Iterable s) {
return asList(s);
}
public static boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
public static boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
public static List sortByCalculatedFieldDesc_inPlace(List l, final Object f) {
sort(l, new Comparator () {
public int compare(A b, A a) {
return stdcompare(callF(f, a), callF(f, b));
}
});
return l;
}
public static List sortByCalculatedFieldDesc_inPlace(Object f, List c) {
return sortByCalculatedFieldDesc_inPlace(c, f);
}
public static Map classForName_cache = synchroHashMap();
public static Class classForName(String name) {
try {
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = Class.forName(name));
return c;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
public static Object nuObjectWithoutArguments(String className) {
try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A nuObjectWithoutArguments(Class c) {
try {
if (nuObjectWithoutArguments_cache == null)
return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
Constructor m = nuObjectWithoutArguments_cache.get(c);
if (m == null)
nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
return (A) m.newInstance();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
m.setAccessible(true);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
public static List getClasses(Object[] array) {
List l = new ArrayList();
for (Object o : array) l.add(_getClass(o));
return l;
}
public static boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class)
return arg instanceof Boolean;
if (type == int.class)
return arg instanceof Integer;
if (type == long.class)
return arg instanceof Long;
if (type == float.class)
return arg instanceof Float;
if (type == short.class)
return arg instanceof Short;
if (type == char.class)
return arg instanceof Character;
if (type == byte.class)
return arg instanceof Byte;
if (type == double.class)
return arg instanceof Double;
return type.isInstance(arg);
}
public static void set(Object o, String field, Object value) {
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
f.setAccessible(true);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void set(Class c, String field, Object value) {
try {
Field f = set_findStaticField(c, field);
f.setAccessible(true);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
public static Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
public static void failIfOddCount(Object... list) {
if (odd(l(list)))
throw fail("Odd list size: " + list);
}
public static String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
public static boolean odd(int i) {
return (i & 1) != 0;
}
public static boolean odd(long i) {
return (i & 1) != 0;
}
public static boolean odd(BigInteger i) {
return odd(toInt(i));
}
public static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
public static int findEndOfBracketPart(List cnc, int i) {
int j = i + 2, level = 1;
while (j < cnc.size()) {
if (eqOneOf(cnc.get(j), "{", "("))
++level;
else if (eqOneOf(cnc.get(j), "}", ")"))
--level;
if (level == 0)
return j + 1;
++j;
}
return cnc.size();
}
public static String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
public static String joinSubList(List l, int i) {
return join(subList(l, i));
}
public static int javaTok_n, javaTok_elements;
public static boolean javaTok_opt;
public static List javaTok(String s) {
++javaTok_n;
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;
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);
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 == '\'') {
++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)) || "'".indexOf(s.charAt(j)) >= 0));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} 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;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
public static List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
public static List replaceSubList(List l, List x, List y) {
return replaceSublist(l, x, y);
}
public static List replaceSubList(List l, int fromIndex, int toIndex, List y) {
return replaceSublist(l, fromIndex, toIndex, y);
}
public 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);
}
public static String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
public static boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
public static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
public static void failIfUnlicensed() {
assertTrue("license off", licensed());
}
public static Thread currentThread() {
return Thread.currentThread();
}
public static Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
public static Object sleepQuietly_monitor = new Object();
public static void sleepQuietly() {
try {
assertFalse(isAWTThread());
synchronized (sleepQuietly_monitor) {
sleepQuietly_monitor.wait();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static int toInt_checked(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
public static A bindTextComponentToLiveValue_bothWays(final A tc, final SimpleLiveValue lv) {
bindLiveValueListenerToComponent(tc, lv, new Runnable() {
public void run() {
try {
setTextKeepCaret(tc, lv.get());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "setTextKeepCaret(tc, lv.get())";
}
});
onChange(tc, new Runnable() {
public void run() {
try {
lv.set(getText(tc));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "lv.set(getText(tc))";
}
});
return tc;
}
public static void lock(Lock lock) {
try {
ping();
if (lock == null)
return;
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
print("Locking interrupted! I probably deadlocked, oops.");
printStackTrace(e);
rethrow(e);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
public static void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
public static ReentrantLock lock() {
return fairLock();
}
public static Class getFieldType(Object o, String field) {
return fieldType(o, field);
}
public static void unlock(Lock lock, String msg) {
if (lock == null)
return;
print("Unlocking: " + msg);
lock.unlock();
}
public static void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
}
public static void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
public static A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), c);
return c;
}
public static JScrollPane jscroll(final Component c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret new JScrollPane(c);";
}
});
}
public static JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
public static JLabel jlabel() {
return jlabel(" ");
}
public static ThreadLocal> holdInstance_l = new ThreadLocal();
public static AutoCloseable holdInstance(Object o) {
if (o == null)
return null;
listThreadLocalAdd(holdInstance_l, o);
return new AutoCloseable() {
public void close() {
listThreadLocalPopLast(holdInstance_l);
}
};
}
public static 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);
}
}
public static void messageBox(final String msg) {
if (headless())
print(msg);
else {
swing(new Runnable() {
public void run() {
try {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES...";
}
});
}
}
public static void messageBox(Throwable e) {
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
public static 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 }";
}
};
}
public static WeakReference weakRef(A a) {
return newWeakReference(a);
}
public static JTextField standardTextFieldPopupMenu(final JTextField tf) {
final WeakReference ref = weakRef(tf);
componentPopupMenuItem(tf, "Copy text to clipboard", new Runnable() {
public void run() {
try {
copyTextToClipboard(ref.get().getText());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyTextToClipboard(ref.get().getText())";
}
});
componentPopupMenuItem(tf, "Paste", new Runnable() {
public void run() {
try {
ref.get().paste();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ref.get().paste()";
}
});
return tf;
}
public static A jenableUndoRedo(final A textcomp) {
{
swing(new Runnable() {
public void run() {
try {
final UndoManager undo = new UndoManager();
vm_generalWeakSet("Undo Managers").add(undo);
textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() {
public void run() {
try {
if (undo.canUndo())
undo.undo();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (undo.canUndo()) undo.undo()";
}
}));
textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() {
public void run() {
try {
if (undo.canRedo())
undo.redo();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (undo.canRedo()) undo.redo()";
}
}));
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final new UndoManager undo;\r\n vm_generalWeakSet(\"Undo Managers\").add(undo)...";
}
});
}
return textcomp;
}
public static String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
public static JInternalFrame showForm_makeInternalFrame(JDesktopPane desktop, String title, JPanel panel) {
JInternalFrame f = addInternalFrame(desktop, title, withMargin(panel));
minInternalFrameWidth(f, 400);
packInternalFrameVertically(f);
centerInternalFrame(f);
return f;
}
public static JFrame handleEscapeKey(final JFrame frame) {
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
frame.getRootPane().registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
frame.dispose();
}
}, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
return frame;
}
public static JFrame minFrameWidth(JFrame frame, int w) {
if (frame != null && frame.getWidth() < w)
frame.setSize(w, frame.getHeight());
return frame;
}
public static JFrame minFrameWidth(int w, JFrame frame) {
return minFrameWidth(frame, w);
}
public static JFrame showPackedFrame(String title, Component contents) {
return packFrame(showFrame(title, contents));
}
public static JFrame showPackedFrame(Component contents) {
return packFrame(showFrame(contents));
}
public static int showForm_leftWidth(List> l) {
int minW = 0;
for (List row : l) minW = max(minW, getMinimumSize(first(row)).width);
return minW;
}
public static JPanel westAndCenter(final Component w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.WEST, wrap(w));
panel.add(BorderLayout.CENTER, wrap(c));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST...";
}
});
}
public static int withRightMargin_defaultWidth = 6;
public static JPanel withRightMargin(Component c) {
return withRightMargin(withRightMargin_defaultWidth, c);
}
public static JPanel withRightMargin(final int w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, w));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
public static A jMinWidth(final int w, final A c) {
if (c == null)
return null;
return swing(new F0 () {
public A get() {
try {
Dimension size = c.getMinimumSize();
c.setMinimumSize(new Dimension(w, size.height));
return jPreferWidth(w, c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Dimension size = c.getMinimumSize();\r\n c.setMinimumSize(new Dimension(/*ma...";
}
});
}
public static A second(List l) {
return get(l, 1);
}
public static A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
public static B second(Pair p) {
return p == null ? null : p.b;
}
public static B second(T3 t) {
return t == null ? null : t.b;
}
public static void setComponentID(Component c, String id) {
if (c != null)
componentID_map.put(c, id);
}
public static List mapLL(Object f, Object... data) {
return map(f, ll(data));
}
public static Component wrapForSmartAdd(Object o) {
if (o == null)
return jpanel();
if (o instanceof String)
return jlabel((String) o);
return wrap(o);
}
public static Map humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5");
public static String humanizeFormLabel(String s) {
if (containsSpace(s))
return s;
return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID"));
}
public static boolean isRunnable(Object o) {
return o instanceof Runnable || hasMethod(o, "get");
}
public static String showFormSubmitButtonName() {
return "Submit";
}
public static void disposeInternalFrame(Component c) {
final JInternalFrame f = getInternalFrame(c);
if (f != null) {
swing(new Runnable() {
public void run() {
try {
f.dispose();
setOpt(f, "lastFocusOwner", null);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "f.dispose();\r\n setOpt(f, \"lastFocusOwner\" , null); // Help GC";
}
});
}
}
public static A heldInstance(Class c) {
List l = holdInstance_l.get();
for (int i = l(l) - 1; i >= 0; i--) {
Object o = l.get(i);
if (isInstanceOf(o, c))
return (A) o;
}
throw fail("No instance of " + className(c) + " held");
}
public static void disposeFrame(final Component c) {
disposeWindow(c);
}
public static void onEnterInAllTextFields(JComponent c, Object action) {
if (action == null)
return;
for (Component tf : allChildren(c)) onEnterIfTextField(tf, action);
}
public static void onEnterInAllTextFields(List c, Object action) {
for (Object o : unnull(c)) if (o instanceof JComponent)
onEnterInAllTextFields((JComponent) o, action);
}
public static void clickButton(final JButton b) {
if (b != null) {
swing(new Runnable() {
public void run() {
try {
if (b.isEnabled())
b.doClick();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (b.isEnabled())\r\n b.doClick();";
}
});
}
}
public static A makeBold(final A c) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
c.setFont(c.getFont().deriveFont(Font.BOLD));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.setFont(c.getFont().deriveFont(Font.BOLD));";
}
});
}
return c;
}
public static JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) {
for (Object o : parts) panel.add(wrapForSmartAdd(o), layout);
return panel;
}
public static JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) {
return smartAddWithLayout(panel, layout, asList(flattenArray2(parts)));
}
public static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
public static List nonNulls(List l) {
return withoutNulls(l);
}
public static Map nonNulls(Map map) {
return withoutNulls(map);
}
public static Component jrigid() {
return javax.swing.Box.createRigidArea(new Dimension(0, 0));
}
public static Object quickExport(Object o, Object dest) {
return quickExport_impl(o, dest, new IdentityHashMap(), new HashMap());
}
public static Object quickExport(Object o, Object dest, int expectedNumberOfObjects) {
return quickExport_impl(o, dest, new IdentityHashMap(expectedNumberOfObjects), new HashMap());
}
public static Object quickExport_impl(Object o, Object dest, IdentityHashMap seen, HashMap classMap) {
try {
if (o == null || o instanceof String || o instanceof Number)
return o;
Object oo = seen.get(o);
if (oo != null)
return oo;
if (o instanceof Object[]) {
Object[] l = (Object[]) o;
Object[] destO = newObjectArrayOfSameType(l, l.length);
seen.put(o, destO);
for (int i = 0; i < l.length; i++) destO[i] = quickExport_impl(l[i], dest, seen, classMap);
return destO;
}
if (o instanceof List) {
List l = (List) (o);
List destO = new ArrayList(l.size());
seen.put(o, destO);
for (int i = 0; i < l.size(); i++) destO.add(quickExport_impl(l.get(i), dest, seen, classMap));
return destO;
}
if (o instanceof Map) {
Map m = (Map) (o);
Map destO = new HashMap();
seen.put(o, destO);
for (Object e : ((Map) o).entrySet()) destO.put(quickExport_impl(((Map.Entry) e).getKey(), dest, seen, classMap), quickExport_impl(((Map.Entry) e).getValue(), dest, seen, classMap));
return destO;
}
Class c = o.getClass();
String className = c.getName();
if (className.startsWith("main$")) {
Class destClass = classMap.get(c);
if (destClass == null) {
if (!classMap.containsKey(c)) {
if (!isAnonymousClassName(className))
destClass = getClass_vmName(dest, className);
classMap.put(c, destClass);
}
if (destClass == null)
return o;
}
if (c == destClass)
return o;
Object destO = nuObjectWithoutArguments(destClass);
seen.put(o, destO);
while (c != Object.class) {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
field.setAccessible(true);
Object value = field.get(o);
setOpt(destO, field.getName(), quickExport_impl(value, dest, seen, classMap));
}
c = c.getSuperclass();
}
return destO;
}
return o;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Object dm_getModule(Object moduleOrID) {
if (eq(moduleOrID, ""))
return null;
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
public static AutoCloseable dm_enter(Object mod) {
return (AutoCloseable) callOpt(dm_getModule(mod), "enter");
}
public static String dm_require(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
public static String trim(String s) {
return s == null ? null : s.trim();
}
public static String trim(StringBuilder buf) {
return buf.toString().trim();
}
public static String trim(StringBuffer buf) {
return buf.toString().trim();
}
public static String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
public static String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
public static String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return l.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret l.getText();";
}
});
}
public static String getText(final JComboBox cb) {
if (cb == null)
return null;
if (isEditableComboBox(cb))
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
public static A printHidingCredentials(A o) {
print(hideCredentials(str(o)));
return o;
}
public static String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
public static String hideCredentials(String url) {
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
public static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
public static void logQuotedWithDate(String s) {
logQuotedWithTime(s);
}
public static void logQuotedWithDate(String logFile, String s) {
logQuotedWithTime(logFile, s);
}
public static void logQuotedWithDate(File logFile, String s) {
logQuotedWithTime(logFile, s);
}
public static File infoBoxesLogFile() {
return new File(javaxDataDir(), "Logs/infoBoxes.txt");
}
public static JWindow showWindow(Component c) {
JWindow w = new JWindow();
w.add(wrap(c));
return w;
}
public static JPanel infoMessage_makePanel(String text) {
final JTextArea ta = wrappedTextArea(text);
onClick(ta, new Runnable() {
public void run() {
try {
disposeWindow(ta);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "disposeWindow(ta)";
}
});
int size = 14;
if (l(text) <= 50)
size *= 2;
else if (l(text) < 100)
size = iround(size * 1.5);
ta.setFont(typeWriterFont(size));
JScrollPane sp = jscroll(ta);
return withMargin(sp);
}
public static int moveToTopRightCorner_inset = 20;
public static A moveToTopRightCorner(A a) {
return moveToTopRightCorner(moveToTopRightCorner_inset, moveToTopRightCorner_inset, a);
}
public static A moveToTopRightCorner(int insetX, int insetY, A a) {
Window w = getWindow(a);
if (w != null)
w.setLocation(getScreenSize().width - w.getWidth() - insetX, insetY);
return a;
}
public static A disposeWindowAfter(int delay, final A w) {
if (w != null)
swingLater(delay, new Runnable() {
public void run() {
try {
w.dispose();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "w.dispose();";
}
});
return w;
}
public static A disposeWindowAfter(A w, double seconds) {
return disposeWindowAfter(toMS_int(seconds), w);
}
public static int iround(double d) {
return (int) Math.round(d);
}
public static int iround(Number n) {
return iround(toDouble(n));
}
public static Throwable printStackTrace(Throwable e) {
print(getStackTrace(e));
return e;
}
public static void printStackTrace() {
printStackTrace(new Throwable());
}
public static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
public static String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
public static JPanel jrightAlignedLine(final Component... components) {
return swing(new F0() {
public RightAlignedLine get() {
try {
return new RightAlignedLine(components);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret RightAlignedLine(components);";
}
});
}
public static JPanel jrightAlignedLine(List extends Component> components) {
return jrightAlignedLine(asArray(Component.class, components));
}
public static A dm_callModule(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __269 = dm_enter(mod);
try {
return call(mod, method, args);
} finally {
_close(__269);
}
}
public static String dm_requireModule(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
public static boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
public static boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
public static boolean endsWith(String a, String b, Matches m) {
if (!endsWith(a, b))
return false;
m.m = new String[] { dropLast(l(b), a) };
return true;
}
public static boolean matchStartX(String pat, String s, Matches matches) {
return matchStart(dropSuffix("...", pat), s, matches);
}
public static boolean matchEndX(String pat, String s, Matches matches) {
return matchEnd(dropPrefix("...", pat), s, matches);
}
public static String className(Object o) {
return getClassName(o);
}
public static String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
public static Producer javaTokC_noMLS_iterator(final String s) {
return javaTokC_noMLS_iterator(s, 0);
}
public static Producer javaTokC_noMLS_iterator(final String s, final int startIndex) {
return new Producer() {
public final int l = s.length();
public int i = startIndex;
public String next() {
if (i >= l)
return null;
int j = i;
char c, d;
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;
}
i = j;
if (i >= l)
return null;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') {
++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));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else
++j;
String t = quickSubstring(s, i, j);
i = j;
return t;
}
};
}
public static Producer javaTokC_noMLS_onReader(final BufferedReader r) {
final class X implements Producer {
public StringBuilder buf = new StringBuilder();
public char c, d, e = 'x';
public X() {
nc();
nc();
nc();
}
public void nc() {
try {
c = d;
d = e;
if (e == '\0')
return;
int i = r.read();
e = i < 0 ? '\0' : i == '\0' ? '_' : (char) i;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void ncSave() {
if (c != '\0') {
buf.append(c);
nc();
}
}
public String next() {
while (c != '\0') {
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
nc();
else if (c == '/' && d == '*') {
do nc(); while (c != '\0' && !(c == '*' && d == '/'));
nc();
nc();
} else if (c == '/' && d == '/') {
do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0);
} else
break;
}
if (c == '\0')
return null;
if (c == '\'' || c == '"') {
char opener = c;
ncSave();
while (c != '\0') {
if (c == opener || c == '\n') {
ncSave();
break;
} else if (c == '\\') {
ncSave();
ncSave();
} else
ncSave();
}
} else if (Character.isJavaIdentifierStart(c))
do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\'');
else if (Character.isDigit(c)) {
do ncSave(); while (Character.isDigit(c));
if (c == 'L')
ncSave();
} else
ncSave();
String t = buf.toString();
buf.setLength(0);
return t;
}
}
return new X();
}
public static String unquoteUsingCharArray(String s, char[] buf) {
if (s == null)
return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i + 1, s.length() - i - 1);
}
}
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length() - 1 : s.length();
if (l > buf.length)
return unquote(s);
int n = 0;
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
buf[n++] = (char) Integer.parseInt(code, 8);
continue;
}
switch(nextChar) {
case '\"':
ch = '\"';
break;
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\'':
ch = '\'';
break;
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
char[] x = Character.toChars(code);
int lx = x.length;
for (int j = 0; j < lx; j++) buf[n++] = x[j];
i += 5;
continue;
default:
ch = nextChar;
}
i++;
}
buf[n++] = ch;
}
return new String(buf, 0, n);
}
}
return s;
}
public static boolean structure_isMarker(String s, int i, int j) {
if (i >= j)
return false;
if (s.charAt(i) != 'm')
return false;
++i;
while (i < j) {
char c = s.charAt(i);
if (c < '0' || c > '9')
return false;
++i;
}
return true;
}
public static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
public static int parseInt(char c) {
return Integer.parseInt(str(c));
}
public static String internIfLongerThan(String s, int l) {
return s == null ? null : l(s) >= l ? intern(s) : s;
}
public static String unquote(String s) {
if (s == null)
return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i + 1, s.length() - i - 1);
}
}
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length() - 1 : s.length();
StringBuilder sb = new StringBuilder(l - 1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch(nextChar) {
case '\"':
ch = '\"';
break;
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\'':
ch = '\'';
break;
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s;
}
public static char unquoteCharacter(String s) {
assertTrue(s.startsWith("'") && s.length() > 1);
return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length() - 1 : s.length()) + "\"").charAt(0);
}
public static double parseDouble(String s) {
return Double.parseDouble(s);
}
public static float parseFloat(String s) {
return Float.parseFloat(s);
}
public static boolean isLongConstant(String s) {
if (!s.endsWith("L"))
return false;
s = s.substring(0, l(s) - 1);
return isInteger(s);
}
public static long parseLong(String s) {
if (s == null)
return 0;
return Long.parseLong(dropSuffix("L", s));
}
public static long parseLong(Object s) {
return Long.parseLong((String) s);
}
public 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;
}
public static SortedMap synchronizedTreeMap() {
return synchroTreeMap();
}
public static List parseList(String s) {
return (List) safeUnstructure(s);
}
public static Map synchronizedMap() {
return synchroMap();
}
public static Map synchronizedMap(Map map) {
return synchroMap(map);
}
public static byte[] hexToBytes(String s) {
if (odd(l(s)))
throw fail("Hex string has odd length: " + quote(shorten(10, s)));
int n = l(s) / 2;
byte[] bytes = new byte[n];
for (int i = 0; i < n; i++) {
int a = parseHexChar(s.charAt(i * 2));
int b = parseHexChar(s.charAt(i * 2 + 1));
if (a < 0 || b < 0)
throw fail("Bad hex byte: " + quote(substring(s, i * 2, i * 2 + 2)) + " at " + i * 2 + "/" + l(s));
bytes[i] = (byte) ((a << 4) | b);
}
return bytes;
}
public static boolean[] boolArrayFromBytes(byte[] a, int n) {
boolean[] b = new boolean[n];
int m = min(n, l(a) * 8);
for (int i = 0; i < m; i++) b[i] = (a[i / 8] & 1 << (i & 7)) != 0;
return b;
}
public 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;
}
public static String assertIdentifier(String s) {
return assertIsIdentifier(s);
}
public static A nuStubInnerObject(Class c) {
return nuStubInnerObject(c, null);
}
public static A nuStubInnerObject(Class c, Object classFinder) {
try {
Class outerType = getOuterClass(c, classFinder);
Constructor m = c.getDeclaredConstructor(outerType);
m.setAccessible(true);
return (A) m.newInstance(new Object[] { null });
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Map nuEmptyObject_cache = newDangerousWeakHashMap();
public static A nuEmptyObject(Class c) {
try {
Constructor ctr;
synchronized (nuEmptyObject_cache) {
ctr = nuEmptyObject_cache.get(c);
if (ctr == null) {
nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c));
ctr.setAccessible(true);
}
}
try {
return (A) ctr.newInstance();
} catch (InstantiationException e) {
if (empty(e.getMessage()))
if ((c.getModifiers() & Modifier.ABSTRACT) != 0)
throw fail("Can't instantiate abstract class " + className(c), e);
else
throw fail("Can't instantiate " + className(c), e);
else
throw rethrow(e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static Constructor nuEmptyObject_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (m.getParameterTypes().length == 0)
return m;
throw fail("No default constructor declared in " + c.getName());
}
public static HashMap