Warning : session_start(): open(/var/lib/php/sessions/sess_eo7o9mpa08aqksuel4nh047728, 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.componentPopupMenu_getEvent;
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 net.dv8tion.jda.core.*;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.hooks.*;
import net.dv8tion.jda.core.events.message.*;
import net.dv8tion.jda.core.events.message.react.*;
import java.text.*;
import java.text.NumberFormat;
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 boolean _moduleClass_DiscordBot;
public static class DiscordBot extends DynPrintLogAndEnabled {
public transient JDA bot;
public transient Set msgsReactedTo = new HashSet();
public transient double deleteDelay = 60.0;
public void start() {
super.start();
logModuleOutput();
bot = discordBot(new ListenerAdapter() {
public void onMessageReceived(MessageReceivedEvent e) {
try {
{
if (!enabled || !licensed())
return;
}
{
if (e.getAuthor().isBot())
return;
}
print("Channel type: " + e.getChannelType());
boolean isPrivate = e.getChannelType() == ChannelType.PRIVATE;
print("Msg from " + e.getAuthor().getName() + ": " + e.getMessage().getContentDisplay());
String content = trim(e.getMessage().getContentRaw());
if (empty(content))
return;
GazelleEvalContext ctx = dm_gazelle_stdEvalContext(dm_gazelle_allRulesWithComment("discord"));
GazelleTree tree = new GazelleTree(ctx, content);
List l = dm_gazelle_getChildren(tree);
if (empty(l))
return;
String answer = lines_rtrim(collect("line", l));
e.getChannel().sendMessage(answer).queue(msg -> {
final long msgId = msg.getIdLong();
print("I sent msg: " + msgId);
doLater(deleteDelay, new Runnable() {
public void run() {
try {
{
if (contains(msgsReactedTo, msgId))
return;
}
print("Deleting msg " + msg.getIdLong());
msg.delete().queue();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "//ret if dontDelete!;\r\n return if contains(msgsReactedTo, msgId);\r...";
}
});
});
} catch (Throwable __e) {
_handleException(__e);
}
}
public void onMessageReactionAdd(MessageReactionAddEvent e) {
{
if (!enabled || !licensed())
return;
}
MessageReaction r = e.getReaction();
boolean bot = e.getUser().isBot();
long msgId = r.getMessageIdLong();
add(msgsReactedTo, msgId);
print("User " + e.getUser() + (bot ? " (bot)" : "") + " reacted to message " + msgId + " with " + r.getReactionEmote());
if (bot)
return;
}
});
print("Started bot");
}
public void cleanMeUp() {
if (bot != null) {
try {
print("Shutting down bot");
bot.shutdown();
print("Bot shut down");
} catch (Throwable __e) {
_handleException(__e);
}
}
bot = null;
}
}
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 C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
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 boolean logModuleOutput_installed;
public static void logModuleOutput() {
if (logModuleOutput_installed)
return;
logModuleOutput_installed = true;
final File logFile = getProgramFile("output.txt");
final LineBuffer buf = new LineBuffer(new VF1() {
public void get(String line) {
try {
appendToTextFile(logFile, "[" + localDateWithMilliseconds() + "] " + line + "\n");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "appendToTextFile(logFile, \"[\" + localDateWithMilliseconds() + \"] \" + line + \"...";
}
});
print_forAllThreads(new VF1() {
public void get(String s) {
try {
buf.append(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "buf.append(s);";
}
});
}
public static JDA discordBot(final VF1 onMessage) {
return discordBot(new ListenerAdapter() {
@Override
public void onMessageReceived(MessageReceivedEvent e) {
if (e.getAuthor().isBot()) {
print(" Msg from bot, skipping");
return;
}
pcallF(onMessage, e);
}
});
}
public static JDA discordBot(ListenerAdapter listener) {
try {
JDABuilder builder = new JDABuilder(AccountType.BOT);
File tokenFile = javaxSecretDir("discord-bot-token");
builder.setToken(assertNempty("Need: " + tokenFile, trim(loadTextFile(tokenFile))));
builder.addEventListener(listener);
return builder.build();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static volatile boolean licensed_yes = true;
public static boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
public static void licensed_off() {
licensed_yes = false;
}
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 GazelleEvalContext dm_gazelle_stdEvalContext() {
return dm_gazelle_stdEvalContext(dm_allRulesFromRulesModuleWithCommentsAndIDs());
}
public static GazelleEvalContext dm_gazelle_stdEvalContext(List> rules) {
GazelleEvalContext ctx = new GazelleEvalContext();
ctx.engine = new RuleEngine2();
ctx.engine.addRules2(rules);
ctx.engine.callFunctionOnString = new F2() {
public Object get(String function, String s) {
try {
return dm_callFunctionOnString(function, s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_callFunctionOnString(function, s)";
}
};
MultiMap statementsByRule = ai_gazelle_indexStatementsByRule(dm_gazelle_statementsFromAppliedRules());
ctx.dataByRule = mapValues("ai_gazelle_analyzeStatementsForRule", multiMapToMap(statementsByRule));
return ctx;
}
public static List> dm_gazelle_allRulesWithComment(final String comment) {
return filter(dm_allRulesFromRulesModuleWithCommentsAndIDs(), new F1, Boolean>() {
public Boolean get(T3 t) {
try {
return cic(tlft(t.b), comment);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cic(tlft(t.b), comment)";
}
});
}
public static List dm_gazelle_getChildren(GazelleTree tree, Object... __) {
return gazelle_getChildren(tree, paramsPlus(__, "makeEvalContext", "dm_gazelle_stdEvalContext"));
}
public static String lines_rtrim(Collection lines) {
return rtrim_fromLines(lines);
}
public static List collect(Collection c, String field) {
return collectField(c, field);
}
public static List collect(String field, Collection c) {
return collectField(c, field);
}
public static java.util.Timer doLater(long delay, final Object r) {
ping();
final java.util.Timer timer = new java.util.Timer();
timer.schedule(timerTask(r, timer), delay);
return timer;
}
public static java.util.Timer doLater(double delaySeconds, final Object r) {
return doLater(toMS(delaySeconds), r);
}
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 RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
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 void add(BitSet bs, int i) {
bs.set(i);
}
public static boolean add(Collection c, A a) {
return c != null && c.add(a);
}
public static void add(Container c, Component x) {
addToContainer(c, x);
}
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 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 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 File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
public static File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
public static void appendToTextFile(File file, String contents) {
try {
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
if (contents != null) {
FileOutputStream fileOutputStream = new FileOutputStream(file, true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String localDateWithMilliseconds(long time) {
SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss''SSSS");
return format.format(time);
}
public static String localDateWithMilliseconds() {
return localDateWithMilliseconds(now());
}
public static void print_forAllThreads(Object f) {
assertNull("todo", print_allThreads);
print_allThreads = f;
}
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 File javaxSecretDir_dir;
public static File javaxSecretDir() {
return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret");
}
public static File javaxSecretDir(String sub) {
return newFile(javaxSecretDir(), sub);
}
public static A assertNempty(A a) {
return assertNempty("empty", a);
}
public static A assertNempty(String msg, A a) {
if (empty(a))
throw fail(msg + ": " + a);
return a;
}
public static String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(File f, String defaultContents) {
try {
checkFileNotTooBigToRead(f);
if (f == null || !f.exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(f);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(String fileName, String defaultContents) {
return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
}
public static String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
} finally {
reader.close();
}
return str(builder);
}
public static List> dm_allRulesFromRulesModuleWithCommentsAndIDs() {
return collectThreeFieldsAsTriple("text", "comments", "globalID", (List) dm_requireAndCall("#1021352/Rules", "concepts"));
}
public static A dm_callFunctionOnString(String code, String s) {
return (A) callF(dm_codeWithHintsToFunctionOnString(code), s);
}
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"));
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 List filter(Iterable c, Object pred) {
if (pred instanceof F1)
return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null)
for (Object o : c) if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
public static List filter(Object pred, Iterable c) {
return filter(c, pred);
}
public static List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o).booleanValue())
x.add(o);
return x;
}
public static List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
public static boolean cic(Collection l, String s) {
return containsIgnoreCase(l, s);
}
public static boolean cic(String[] l, String s) {
return containsIgnoreCase(l, s);
}
public static boolean cic(String s, char c) {
return containsIgnoreCase(s, c);
}
public static boolean cic(String a, String b) {
return containsIgnoreCase(a, b);
}
public static List tlft(String s) {
return toLinesFullTrim(s);
}
public static List tlft(File f) {
return toLinesFullTrim(f);
}
public static List gazelle_getChildren(GazelleTree tree, Object... __) {
if (tree == null)
return null;
if (tree.children != null)
return tree.children;
tree.children = new ArrayList();
double qualityCutOff = optPar("qualityCutOff", __, -0.75);
List dialogHistory = optPar("dialogHistory", __);
if (tree.ctx == null)
tree.setContext(assertNotNull("evalContext", (GazelleEvalContext) callF(assertNotNull("makeEvalContext", optPar("makeEvalContext", __)))));
GazelleEvalContext ctx = tree.ctx;
RuleEngine2 engine = ctx.engine;
Map inputMap = litmap("standard", tree.line);
List history = concatLists(dialogHistory, tree.history());
for (int i = 0; i < l(history); i++) inputMap.put("dialog-" + (l(history) - i), history.get(i));
for (RuleEngine2.SimplifyWithRule rule : engine.splitterRules()) {
try {
Object f = rule.function();
Collection out = (Collection) ((f instanceof String ? callF(engine.callFunctionOnString, (String) f, tree.line) : callF(f, tree.line)));
if (l(out) < 2)
continue;
GazelleTree child = new GazelleTree(joinWithVBar(out));
child.isSplitNode = true;
tree.add(child);
for (String line : out) child.add(new GazelleTree(line));
} catch (Throwable __e) {
_handleException(__e);
}
}
List l = sortByMethodDesc("qualitySum", ai_ruleEngine2_rulesForInput_5_allConditions(engine, inputMap, "debug", false, "tree", tree));
for (RuleEngine2_MatchedRule r : l) {
if (r.relativeQuality() < qualityCutOff)
continue;
String line = r.outText();
GazelleTree child = new GazelleTree(line);
child.mr = r;
ai_gazelle_analyzeStatementsForRule_Data data = ctx.dataByRule.get(r.rule.globalID);
child.prediction = data == null ? null : ai_gazelle_predictor1_onData(r, data);
tree.add(child);
}
sortByCalculatedFieldDesc(tree.children, new F1() {
public Integer get(GazelleTree c) {
try {
return ai_goodBadToInt(c.prediction);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ai_goodBadToInt(c.prediction)";
}
});
return tree.children;
}
public static Object[] paramsPlus(Object[] a1, Object... a2) {
if (l(a2) == 2 && a2[0] == null)
return a1;
return concatArrays(assertEvenLength(a1), assertEvenLength(a2));
}
public static String rtrim_fromLines(Collection lines) {
StringBuilder buf = new StringBuilder();
if (lines != null) {
boolean first = true;
for (Object line : lines) {
if (first)
first = false;
else
buf.append('\n');
buf.append(str(line));
}
}
return buf.toString();
}
public static List collectField(Collection c, String field) {
List l = new ArrayList();
if (c != null)
for (Object a : c) l.add(getOpt(a, field));
return l;
}
public static List collectField(String field, Collection c) {
return collectField(c, field);
}
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 TimerTask timerTask(final Object r, final java.util.Timer timer) {
return new TimerTask() {
public void run() {
if (!licensed())
timer.cancel();
else
pcallF(r);
}
};
}
public static long toMS(double seconds) {
return (long) (seconds * 1000);
}
public static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || b != null && a.equals(b);
}
public static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
public static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
public static List synchroList(List l) {
return Collections.synchronizedList(l);
}
public static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return 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 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 void addToContainer(final Container a, final Component b) {
if (a != null && b != null) {
swing(new Runnable() {
public void run() {
try {
a.add(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.add(b);";
}
});
}
}
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 Map> javaTokNPunctuationWithBrackets_cache = synchronizedMRUCache(1000);
public static List javaTokNPunctuationWithBrackets(String s) {
List tok = javaTokNPunctuationWithBrackets_cache.get(s);
if (tok == null)
javaTokNPunctuationWithBrackets_cache.put(s, tok = javaTokNPunctuationWithBrackets_uncached(s));
return tok;
}
public static List javaTokNPunctuationWithBrackets_uncached(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 String getStackTrace2(Throwable e) {
return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
}
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 File getProgramDir() {
return programDir();
}
public static File getProgramDir(String snippetID) {
return programDir(snippetID);
}
public static SimpleDateFormat simpleDateFormat_local(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(localTimeZone());
return sdf;
}
public static long now_virtualTime;
public static long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
public static A assertNull(A a) {
assertTrue(a == null);
return a;
}
public static A assertNull(String msg, A a) {
assertTrue(msg, a == null);
return a;
}
public static Object pcallFunction(Object f, Object... args) {
try {
return callFunction(f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
public static String _userHome;
public static String userHome() {
if (_userHome == null) {
if (isAndroid())
_userHome = "/storage/sdcard0/";
else
_userHome = System.getProperty("user.home");
}
return _userHome;
}
public static File userHome(String path) {
return new File(userDir(), path);
}
public static File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
public static File newFile(String name) {
return name == null ? null : new File(name);
}
public static ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal();
public static void checkFileNotTooBigToRead(File f) {
callF(checkFileNotTooBigToRead_tl.get(), f);
}
public static String str(Object o) {
return o == null ? "null" : o.toString();
}
public static String str(char[] c) {
return new String(c);
}
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 Object dm_codeWithHintsToFunctionOnString(String code) {
return dm_codeWithHintsToFunctionOnString(code, "");
}
public static Object dm_codeWithHintsToFunctionOnString(String code, String hints) {
return dm_requireAndCallModule("#1021247/FunctionsOnStrings", "getFunction", code, hints);
}
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 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 A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
public static List ai_gazelle_statementsFromAppliedRule(RuleEngine2_MatchedRule r, String judgement) {
if (r == null || r.rule == null)
return new ArrayList();
if (nempty(judgement) && neq(judgement, "good"))
judgement = "bad";
String ruleID = r.rule.globalID;
String ruleIn = first(r.rule.in);
if (ruleIn == null)
return new ArrayList();
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 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 boolean containsIgnoreCase(Collection l, String s) {
if (l != null)
for (String x : l) if (eqic(x, s))
return true;
return false;
}
public static boolean containsIgnoreCase(String[] l, String s) {
if (l != null)
for (String x : l) if (eqic(x, s))
return true;
return false;
}
public static boolean containsIgnoreCase(String s, char c) {
return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}
public static boolean containsIgnoreCase(String a, String b) {
return indexOfIgnoreCase(a, b) >= 0;
}
public static List toLinesFullTrim(String s) {
List l = new ArrayList();
for (String line : toLines(s)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
public static List toLinesFullTrim(File f) {
List l = new ArrayList();
for (String line : linesFromFile(f)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
public static A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
public static A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
public static A optPar(Object[] params, String name) {
return optParam(params, name);
}
public static A optPar(String name, Object[] params) {
return optParam(params, name);
}
public static A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
public static A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
public static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
public static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
public static HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
public static void litmap_impl(Map map, Object... x) {
for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
map.put(x[i], x[i + 1]);
}
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 String joinWithVBar(Iterable l) {
return join(" | ", 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 List ai_ruleEngine2_rulesForInput_5_allConditions(RuleEngine2 engine, Map inputsByType, Object... __) {
List notDone = ai_ruleEngine2_rulesForInput_5(engine, inputsByType, __);
List done = new ArrayList();
boolean debug = boolPar("debug", __);
while (nempty(notDone)) {
List l = notDone;
notDone = new ArrayList();
for (RuleEngine2_MatchedRule mr : l) {
if (!mr.moreConditions()) {
if (debug)
print("Done: " + mr.ruleID());
done.add(mr);
} else {
if (debug)
print("Matching step " + mr.iCond + " in " + mr.ruleID());
if (ai_ruleEngine2_matchStep(mr, inputsByType, false)) {
if (debug)
print("Step succeeded");
notDone.add(mr);
} else
done.add(mr);
}
}
}
return done;
}
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 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 int ai_goodBadToInt(String s) {
if (eq(s, "good"))
return 1;
if (eq(s, "bad"))
return -1;
return 0;
}
public static Object[] concatArrays(Object[]... arrays) {
int l = 0;
for (Object[] a : arrays) l += l(a);
Object[] x = new Object[l];
int i = 0;
for (Object[] a : arrays) if (a != null) {
System.arraycopy(a, 0, x, i, l(a));
i += l(a);
}
return x;
}
public static Object[] assertEvenLength(Object[] a) {
assertTrue(even(l(a)));
return a;
}
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 Throwable getInnerException(Throwable e) {
if (e == null)
return null;
while (e.getCause() != null) e = e.getCause();
return e;
}
public static Throwable getInnerException(Runnable r) {
return getInnerException(getException(r));
}
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 Object swing(Object f) {
return swingAndWait(f);
}
public static A swing(F0 f) {
return (A) swingAndWait(f);
}
public static Map synchronizedMRUCache(int maxSize) {
return synchroMap(new MRUCache(maxSize));
}
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 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 String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
public static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
public static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
public static Throwable unwrapTrivialExceptionWraps(Throwable e) {
if (e == null)
return e;
while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause();
return e;
}
public static String replacePrefix(String prefix, String replacement, String s) {
if (!startsWith(s, prefix))
return s;
return replacement + substring(s, l(prefix));
}
public static Throwable innerException2(Throwable e) {
if (e == null)
return null;
while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
return e;
}
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 File programDir_mine;
public static File programDir() {
return programDir(getProgramID());
}
public static File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
if (me) {
String c = caseID();
if (nempty(c))
dir = newFile(dir, c);
}
return dir;
}
public static File programDir(String snippetID, String subPath) {
return new File(programDir(snippetID), subPath);
}
public static TimeZone localTimeZone() {
return getTimeZone(standardTimeZone());
}
public static Object callFunction(Object f, Object... args) {
return callF(f, args);
}
public static File userDir() {
return new File(userHome());
}
public static File userDir(String path) {
return new File(userHome(), path);
}
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 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 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 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 void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null)
map.put(key, value);
}
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 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 Object callAndMake(String functionName, Object... args) {
return callAndMake_orDirect(functionName, args);
}
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 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 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 Pair pair(A a, B b) {
return new Pair(a, b);
}
public static Pair pair(A a) {
return new Pair(a, a);
}
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 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 int indexOfIgnoreCase(List a, String b) {
return indexOfIgnoreCase(a, b, 0);
}
public static int indexOfIgnoreCase(List a, String b, int i) {
int n = l(a);
for (; i < n; i++) if (eqic(a.get(i), b))
return i;
return -1;
}
public static int indexOfIgnoreCase(String a, String b) {
return indexOfIgnoreCase_manual(a, b);
}
public static IterableIterator toLines(File f) {
return linesFromFile(f);
}
public static List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
public static int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
public static CloseableIterableIterator linesFromFile(File f) {
try {
if (!f.exists())
return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
return linesFromReader(utf8bufferedReader(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
public static A optParam(ThreadLocal tl) {
return optPar(tl);
}
public static A optParam(Object[] opt, String name, A defaultValue) {
if (!even(l(opt)))
throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name))
return (A) opt[i + 1];
return defaultValue;
}
public static A optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
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 List ai_ruleEngine2_rulesForInput_5(RuleEngine2 engine, Map inputsByType, Object... __) {
List l = new ArrayList();
for (RuleEngine2.Rule rule : engine.rules) {
if (rule instanceof RuleEngine2.SimplifyWithRule) {
if (((RuleEngine2.SimplifyWithRule) rule).isSplitRule)
continue;
String in = inputsByType.get("standard");
Object f = ((RuleEngine2.SimplifyWithRule) rule).function();
Object arg = ((RuleEngine2.SimplifyWithRule) rule).callOnTree ? optPar("tree", __) : in;
if (arg == null)
continue;
Object result = f instanceof String ? arg instanceof String ? callF(engine.callFunctionOnString, (String) f, arg) : callAndMake((String) f, arg) : callF(f, arg);
if (result == null)
continue;
List list = result instanceof Collection ? allToString((Collection) result) : ll(str(result));
for (String x : list) {
if (nempty(x) && neq(x, in)) {
final RuleEngine2_MatchedRule matched = new RuleEngine2_MatchedRule();
matched.rule = ((RuleEngine2.SimplifyWithRule) rule);
matched.out = x;
l.add(matched);
}
}
continue;
}
final RuleEngine2_MatchedRule matched = new RuleEngine2_MatchedRule();
matched.rule = rule;
matched.map = ciMap();
matched.tokenizationFunction = or(matchAny_firstGroup("tokenize with *", rule.comments), "javaTokNPunctuationWithBrackets");
if (!ai_ruleEngine2_matchStep(matched, inputsByType, true))
continue;
l.add(matched);
}
return l;
}
public static boolean boolPar(ThreadLocal tl) {
return boolOptParam(tl);
}
public static boolean boolPar(Object[] __, String name) {
return boolOptParam(__, name);
}
public static boolean boolPar(String name, Object[] __) {
return boolOptParam(__, name);
}
public static boolean boolPar(String name, Object[] params, boolean defaultValue) {
return optParam(params, name, defaultValue);
}
public static boolean ai_ruleEngine2_matchStep(final RuleEngine2_MatchedRule matched, Map inputsByType, boolean fillRemainingConditions) {
RuleEngine2.Rule rule = matched.rule;
TextAndType in = rule.insWithType.get(matched.iCond);
matched.iCond++;
String cond = in.text;
String tokenize = matched.tokenizationFunction;
List tokC = (List) callAndMake(tokenize, cond);
String input = inputsByType.get(in.type);
if (input == null)
return false;
List tokI = (List) callAndMake(tokenize, input);
tokI = ai_applyWordSplitPattern1(tokC, tokI);
Map map = zipTwoListsToCIMap_strict_withoutEquals(tokC, tokI);
if (map == null)
return false;
if (!addMapToMapWithoutOverwritingIC(matched.map, map))
return false;
matched.matchedLines.add(pair(tokC, tokI));
if (fillRemainingConditions) {
matched.remainingConditions = nullIfEmpty(map(dropFirst(matched.iCond, 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)";
}
}));
matched.remainingConditionsWithType = nullIfEmpty(map(dropFirst(matched.iCond, rule.insWithType), new F1() {
public TextAndType get(TextAndType in) {
try {
return new TextAndType(matched.applyMappingTo(in.text), in.type);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "TextAndType(matched.applyMappingTo(in.text), in.type)";
}
}));
}
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)));
}
return true;
}
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 List sortByCalculatedFieldDesc_inPlace(List l, final Object f) {
sort(l, new Comparator () {
public int compare(A b, A a) {
return stdcompare((Object) callF(f, a), (Object) callF(f, b));
}
});
return l;
}
public static List sortByCalculatedFieldDesc_inPlace(Object f, List c) {
return sortByCalculatedFieldDesc_inPlace(c, f);
}
public static boolean even(int i) {
return (i & 1) == 0;
}
public static boolean even(long i) {
return (i & 1) == 0;
}
public static Throwable getException(Runnable r) {
try {
callF(r);
return null;
} catch (Throwable e) {
return e;
}
}
public static String className(Object o) {
return getClassName(o);
}
public static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
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 Map synchroMap() {
return synchroHashMap();
}
public static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
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 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 volatile PersistableThrowable lastException_lastException;
public static PersistableThrowable lastException() {
return lastException_lastException;
}
public static void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
public static String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
public static boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b))
return false;
return parseSnippetID(a) == parseSnippetID(b);
}
public static File javaxDataDir_dir;
public static File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
public static File javaxDataDir(String... subs) {
return newFile(javaxDataDir(), subs);
}
public static volatile String caseID_caseID;
public static String caseID() {
return caseID_caseID;
}
public static void caseID(String id) {
caseID_caseID = id;
}
public static TimeZone getTimeZone(String name) {
return TimeZone.getTimeZone(name);
}
public static String standardTimeZone_name = "Europe/Berlin";
public static String standardTimeZone() {
return standardTimeZone_name;
}
public static A dm_callModule(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __90 = dm_enter(mod);
try {
return call(mod, method, args);
} finally {
_close(__90);
}
}
public static String dm_requireModule(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
public static Map emptyMap() {
return new HashMap();
}
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 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 findClass_cache = new HashMap();
public static Class findClass(String name) {
synchronized (findClass_cache) {
if (findClass_cache.containsKey(name))
return findClass_cache.get(name);
if (!isJavaIdentifier(name))
return null;
Class c;
try {
c = Class.forName("main$" + name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_cache.put(name, c);
return c;
}
}
public static void setOptAllDyn(DynamicObject o, Map fields) {
if (fields == null)
return;
HashMap fieldMap = instanceFieldsMap(o);
for (Map.Entry e : fields.entrySet()) {
String field = e.getKey();
Object val = e.getValue();
boolean has = fieldMap.containsKey(field);
if (has)
setOpt(o, field, val);
else {
o.fieldValues.put(intern(field), val);
}
}
}
public static void setOptAll_pcall(Object o, Map fields) {
if (fields == null)
return;
for (String field : keys(fields)) try {
setOpt(o, field, fields.get(field));
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
public static void setOptAll_pcall(Object o, Object... values) {
warnIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
try {
setOpt(o, field, value);
} catch (Throwable __e) {
print(exceptionToStringShort(__e));
}
}
}
public static String intern(String s) {
return fastIntern(s);
}
public static void pcallOpt_noArgs(Object o, String method) {
try {
callOpt_noArgs(o, method);
} catch (Throwable __e) {
_handleException(__e);
}
}
public static List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
public static List subList(List l, int startIndex, int endIndex) {
if (l == null)
return null;
startIndex = Math.max(0, startIndex);
endIndex = Math.min(l(l), endIndex);
if (startIndex >= endIndex)
return ll();
return l.subList(startIndex, endIndex);
}
public static int[] toIntArray(List l) {
int[] a = new int[l(l)];
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
return a;
}
public static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
public static TreeSet ciSet() {
return caseInsensitiveSet();
}
public static boolean jmatch(String pat, String s) {
return jmatch(pat, s, null);
}
public static boolean jmatch(String pat, String s, Matches matches) {
if (s == null)
return false;
return jmatch(pat, javaTok(s), matches);
}
public static boolean jmatch(String pat, List toks) {
return jmatch(pat, toks, null);
}
public static boolean jmatch(String pat, List toks, Matches matches) {
List tokpat = javaTok(pat);
String[] m = match2(tokpat, toks);
if (m == null)
return false;
else {
if (matches != null)
matches.m = m;
return true;
}
}
public static boolean warn_on = true;
public static void warn(String s) {
if (warn_on)
print("Warning: " + s);
}
public static void warn(String s, List warnings) {
warn(s);
if (warnings != null)
warnings.add(s);
}
public static A popLast(List l) {
return liftLast(l);
}
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 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 codeTokensOnly(List tok) {
List l = new ArrayList();
for (int i = 1; i < tok.size(); i += 2) l.add(tok.get(i));
return l;
}
public static String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
public static int max(int a, int b) {
return Math.max(a, b);
}
public static int max(int a, int b, int c) {
return max(max(a, b), c);
}
public static long max(int a, long b) {
return Math.max((long) a, b);
}
public static long max(long a, long b) {
return Math.max(a, b);
}
public static double max(int a, double b) {
return Math.max((double) a, b);
}
public static float max(float a, float b) {
return Math.max(a, b);
}
public static double max(double a, double b) {
return Math.max(a, b);
}
public static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
public static double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
public static float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
public static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
public static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
public static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
public static boolean isCISet(Iterable l) {
return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator();
}
public static TreeSet caseInsensitiveSet() {
return new TreeSet(caseInsensitiveComparator());
}
public static TreeSet caseInsensitiveSet(Collection c) {
return toCaseInsensitiveSet(c);
}
public static void addAll(Collection c, Iterable b) {
if (c != null && b != null)
for (A a : b) c.add(a);
}
public static boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
public static boolean addAll(Collection c, B... b) {
return c != null && c.addAll(Arrays.asList(b));
}
public static List uniquifyList(Collection l) {
if (l == null)
return null;
if (l(l) < 2)
return asList(l);
HashSet set = new HashSet();
List out = new ArrayList();
for (A a : l) if (set.add(a))
out.add(a);
return out;
}
public static String asString(Object o) {
return o == null ? null : o.toString();
}
public static int indexOfIgnoreCase_manual(String a, String b) {
int la = l(a), lb = l(b);
if (la < lb)
return -1;
int n = la - lb;
loop: for (int i = 0; i <= n; i++) {
for (int j = 0; j < lb; j++) {
char c1 = a.charAt(i + j), c2 = b.charAt(j);
if (!eqic(c1, c2))
continue loop;
}
return i;
}
return -1;
}
public static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
public Object next() {
throw fail();
}
public boolean hasNext() {
return false;
}
};
public static CloseableIterableIterator emptyCloseableIterableIterator() {
return emptyCloseableIterableIterator_instance;
}
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 CloseableIterableIterator linesFromReader(Reader r) {
final BufferedReader br = bufferedReader(r);
return iteratorFromFunction_f0_autoCloseable(new F0() {
public String get() {
try {
return readLineFromReaderWithClose(br);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret readLineFromReaderWithClose(br);";
}
}, _wrapIOCloseable(r));
}
public static BufferedReader utf8bufferedReader(InputStream in) {
try {
return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static BufferedReader utf8bufferedReader(File f) {
try {
return utf8bufferedReader(newFileInputStream(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
public static GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
public static List allToString(Collection c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
public static List allToString(Object[] c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
public static TreeMap ciMap() {
return caseInsensitiveMap();
}
public static