Warning : session_start(): open(/var/lib/php/sessions/sess_pciclqqjmc4tqsdukika42ci8f, 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 java.text.*;
import java.text.NumberFormat;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.datatransfer.StringSelection;
class main {
abstract static class VirtualMechLists {
abstract String mL_raw(String listName);
void append(String listName, String text) {}
void setText(String listName, String text) {}
}
static String mechLibID = "#1400124";
static Object onOutput; // VF1
static boolean authorized;
static List bots;
abstract static class AbstractThinkBot {
transient VF1 super String> postMessage;
transient List recentHistory = new ArrayList();
abstract void thinkAbout(String input);
void postMessage(String s) {
callF(postMessage, s);
}
}
public static void main(final String[] args) throws Exception {
mech_useLibrary(mechLibID);
List> classes = botClasses();
print("Have think classes: " + classNames(classes));
makeBots();
bot();
}
static List> botClasses() {
return myNonAbstractClassesImplementing(AbstractThinkBot.class);
}
static void makeBots() {
bots = map("nuWithoutArguments",botClasses());
}
static boolean telegram_amIAuthorized() {
return authorized;
}
static String answer(String s) {
AutoCloseable __2 = tempSetThreadLocal(telegram_msg_tl(), new HashMap()); try {
final List output = new ArrayList();
for (AbstractThinkBot bot : bots) try {
bot.postMessage = new VF1() { public void get(String s) { try {
print(">> " + s);
pcallF(onOutput, s);
output.add(s);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "print(\">> \" + s);\n pcallF(onOutput, s);\n output.add(s);"; }};
bot.thinkAbout(s);
} catch (Throwable __e) { _handleException(__e); }
return rtrim(lines(output));
} finally { _close(__2); }}
static class TelegramThinkBot extends AbstractThinkBot {
void thinkAbout(String s) {
s = trim(s);
final Matches m = new Matches();
String procedure = nlLookup(mechMap("Telegram Procedures"), s, m);
if (procedure != null) {
procedure = expandDollarRefsToMatches(procedure, m, true);
print(">> " + procedure);
postMessage(strOrNull(javaEvalOrInterpret(procedure)));
}
print("s=" + s);
String language = "english";
if (swic_trim(s, "!german ", m)) {
language = "german";
s = m.rest();
print("s=" + s);
}
ai_setLanguage(language);
if (swic_trim(s, "!say ", m))
postMessage(m.rest());
if (eq(s, "!gac"))
postMessage(random_gac36k());
if (swic_trim(s, "!parse ", m))
postMessage(ai_renderCulledParseTree(ai_parseToTreeWithGuessing(m.rest())));
if (swic_trim(s, "!simplify ", m))
postMessage(lines(ai_parseTree_simplifiedTexts(ai_parseToTreeWithGuessing(m.rest()))));
if (telegram_amIAuthorized()) {
if (eq(s, "!fresh")) dm_refreshTranspiler();
if (swic_trim(s, "!eval ", m))
postMessage(pcallOrExceptionText(new F0() { Object get() { try { return strOrNull(javaEvalOrInterpret(m.rest())) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "strOrNull(javaEvalOrInterpret(m.rest()))"; }}));
if (swic_trim(s, "!rule ", m)) {
String rule = m.rest();
List rules = trimAll(ai_unparsedTalkRules());
if (!contains(rules, rule)) { // TODO: ignore global IDs
appendToMechList_noUniq("NL Logic Examples", "\n" + rule);
postMessage("Rule saved. Have " + n2(l(rules)+1, "rule") + ".");
}
}
if (swic_trim(s, "!fact ", m)) {
String fact = m.rest();
List facts = mL("Random facts");
if (!contains(facts, fact)) {
appendToMechList_noUniq("Random facts", fact);
postMessage("Fact saved. Have " + n2(l(facts)+1, "fact") + ".");
}
}
}
}
}
static class TelegramFactsBot extends AbstractThinkBot {
String evalExp(Exp e, NLLogicChecker_v2.Matching m) {
String code = nlLogic_text(e);
print("Eval'ing: " + code);
AutoCloseable __3 = tempAdd(hotwire_copyOver_after, new VF1() { public void get(Class c) { try { copyFields(mc(), c, "telegram_msg_tl") ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "copyFields(mc(), c, 'telegram_msg_tl)"; }}); try {
String result = str(evalWithDollarVars(code, m.matches));
print("Result: " + shorten(result, 100));
return result;
} finally { _close(__3); }}
void thinkAbout(final String s) {
final Map msg = telegram_msg();
NLLogicChecker_v2 c = new NLLogicChecker_v2() {
List entities;
boolean checkExpression(Exp e, Matching m) {
Matches mm = new Matches();
if (e instanceof Func) {
// FUNCTION CONDITIONS
if (eq(((Func) e).name, "verbPhraseFromThirdPerson"))
return nlLogic_stringFunction("ai_verbPhraseFromThirdPerson", ((Func) e), m.matches);
else if (eq(((Func) e).name, "singular"))
return nlLogic_stringFunction("singular", ((Func) e), m.matches);
else if (eq(((Func) e).name, "eval"))
return eq("true", evalExp(((Func) e).arg, m));
else if (eq(((Func) e).name, "entity")) {
if (entities == null) {
long time = sysNow();
final String switched = switcheroo(s);
print("Switched >> " + switched);
entities = evalWithTimeoutOrNull(5000, new F0>() { List get() { try { return
mapMethod("text", ai_extractEntities_v1(switched))
; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "mapMethod('text, ai_extractEntities_v1(switched))"; }});
print("Entities (" + elapsedMS(time) + " ms): " + joinWithComma(entities));
if (entities == null) entities = new ArrayList();
}
for (String entity : entities)
if (matcher.match(nlLogic_text(((Func) e).arg), entity, m.matches)) return true;
} else if (startsWith(((Func) e).name, "line", mm) && isInteger(mm.rest())) {
int n = parseInt(mm.rest())-nlLogic_numberOfLinesReferenced(checkingRule.get().in);
String line = n == 0 ? s : getString(get(recentHistory, l(recentHistory)+n), "text");
print("Recent: " + recentHistory);
String pat = nlLogic_text(((Func) e).arg);
print("n=" + n + ", Matching " + ((Func) e) + " with " + line);
return matcher.match(pat, line, m.matches);
} else if (eq(((Func) e).name, "unknownIf")) {
String statement = nlLogic_text(apply(((Func) e).arg, m));
print("Checking statement: " + statement);
return !cic(facts, statement) && !cic(facts, "Untrue: " + statement);
} else if (eq(((Func) e).name, "inputContainsTokens"))
return call_verbose("jcontains",s, nlLogic_text(((Func) e).arg));
else if (eq(((Func) e).name, "inputStartsWith"))
return call_verbose("startsWith",s, nlLogic_text(((Func) e).arg));
else if (eq(((Func) e).name, "followingUpOn")) {
String text = nlLogic_text(((Func) e).arg);
// e.g. "lhnshnhcklhabvmu with input=$input"
if (!match("* with input=*", text, mm) || !isDollarVar(mm.get(1))) return false;
String ruleID = mm.unq(0), dollarInput = mm.get(1);
Map /*prev = last(recentHistory),*/ prevPrev = nextToLast(recentHistory);
String msgID = getString(prevPrev, "globalID");
String input = getString(prevPrev, "text");
print("followingUpOn: msgID=" + msgID + ", input=" + input);
printStruct("prevPrev", prevPrev);
//printStruct(+prev);
String pat = "Rule " + ruleID + " fired on message " + msgID + " ";
print("pat=" + pat);
for (String ruleFired : mL("Telegram Rule Fires"))
if (swic(ruleFired, pat))
return print("result=", strictPutIC(m.matches, dollarInput, input));
return false;
}
}
if (e instanceof Eq) {
// EQUATION CONDITIONS
Exp r = ((Eq) e).right;
String var = nlLogic_text(((Eq) e).left);
if (r instanceof Func) try {
if (eq(((Func) r).name, "eval"))
return new NLStringMatcher_singleDollarVar().match(var, evalExp(((Func) r).arg, m), m.matches);
} catch (Throwable __e) { _handleException(__e); }
}
if (e instanceof Literal) {
// TEXT CONDITIONS
String text = nlLogic_text(e);
if (eq(text, "authorized"))
return telegram_amIAuthorized();
}
return super.checkExpression(e, m);
}
};
c.matcher = new NLStringMatcher_dollarVars_underscores();
c.input = s;
c.facts = mL_facts();
List unparsedRules = ai_unparsedTalkRules();
for (String listName : mL("Rule & Fact Lists"))
for (String x : splitAtEmptyLines(mL_raw(listName)))
if (anyJavaTokens(x))
if (nlLogic_parseRule(x) != null)
unparsedRules.add(x);
else
c.facts.add(x);
unparsedRules = sortedByCalculatedField(unparsedRules, new F1() { Object get(String s) { try { return jcontains(s, "entity(") ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "jcontains(s, \"entity(\")"; }});
List rules = map_pcall("nlLogic_parseRule",unparsedRules);
for (IfThen r : rules) {
{ if (r == null) continue; }
Exp out = r.out;
if (out instanceof Func)
if (eq(((Func) out).name, "sayIfTrue")) {
r.out = new Func("output", ((Func) out).arg);
r.in = new And(r.in, new Func("fact", ((Func) out).arg));
print(r);
}
}
final String msgGlobalID = getString(msg, "globalID");
if (nempty(msgGlobalID))
applyNLLogicFacts_v3_onRuleFired.set(new VF2() { public void get(IfThen rule, NLLogicChecker_v2.Matching m) { try {
if (empty(rule.globalID)) return;
String fact = format("Rule * fired on message * at *", rule.globalID, msgGlobalID, localDateWithMilliseconds());
if (nempty(m.matches))
fact += " with vars " + dropPrefix("lhm", struct(m.matches));
addToMechList("Telegram Rule Fires", fact);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (empty(rule.globalID)) ret;\n S fact = format(\"Rule * fired on messa..."; }});
applyNLLogicFacts_v3(c, new VF1() { public void get(Exp e) { try {
// Rule fired!
if (e instanceof Func) {
if (eq(((Func) e).name, "output"))
postMessage(nlLogic_text(((Func) e).arg));
else if (eq(((Func) e).name, "fact")) {
String fact = nlLogic_text(((Func) e).arg);
if (!contains(mL("Random facts"), fact) && mech_changed(addToMechList("Derived facts", fact)))
postMessage("Storing fact: " + fact);
} else if (eq(((Func) e).name, "storeRule")) {
String rule = nlLogic_text(((Func) e).arg);
if (mech_changed(appendToMechList_noUniq("NL Logic Examples", "\n" + rule)))
postMessage("Rule stored");
}
}
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "// Rule fired!\n \n if (e cast Func) {\n if (eq(e.name, 'output..."; }}, rules);
}
}
static class TelegramInitiativeBot extends AbstractThinkBot {
List < Pair < String , IfThen > > activeTempRules = new ArrayList();
void thinkAbout(String s) {
if (eq(s, "!initiative")) {
List rules = mL_parsedNLRulesWithoutIDs("Initiative rules");
for (IfThen rule : shuffledIterator(rules)) {
Pair p = nlLogic_extractFirstCondition(rule.in);
if (p == null) continue;
if (nlLogic_isFunc(p.a, "initiative")) {
postMessage(nlLogic_text(((Func) p.a).arg));
IfThen temp = new IfThen(p.b, rule.out);
print("Have temp rule: " + sfu(temp));
activeTempRules.add(pair(aGlobalID(), temp));
return;
}
}
}
applyNLLogicFacts_v2(s, new VF1() { public void get(String s) { try { postMessage(s) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "postMessage(s)"; }},
new ArrayList(), activeTempRules);
activeTempRules.clear();
}
}
static Object nuWithoutArguments(String className) {
return nuObjectWithoutArguments(className);
}
static A nuWithoutArguments(Class c) {
return nuObjectWithoutArguments(c);
}
static String ai_verbPhraseFromThirdPerson(String s) {
List tok = javaTok(s);
for (int i = 1; i < l(tok); i += 2)
if (endsWithIC(tok.get(i), "s")) {
tok.set(i, dropLast(tok.get(i)));
break;
}
return join(tok);
}
static Map singular_specials = litmap(
"children", "child", "images", "image", "chess", "chess");
static Set singular_specials2 = litset("time", "machine", "line");
static String singular(String s) {
if (s == null) return null;
{ String _a_1247 = singular_specials.get(s); if (!empty(_a_1247)) return _a_1247; }
//try answer hippoSingulars().get(lower(s));
if (singular_specials2.contains(dropSuffix("s", afterLastSpace(s))))
return dropSuffix("s", s);
if (s.endsWith("ness")) return s;
if (s.endsWith("ges")) return dropSuffix("s", s);
if (endsWith(s, "bases")) return dropLast(s);
s = dropSuffix("es", s);
s = dropSuffix("s", s);
return s;
}
static boolean jcontains(String s, String pat) {
return jfind(s, pat) >= 0;
}
static boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static boolean startsWith(String a, char c) {
return nempty(a) && a.charAt(0) == c;
}
static boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b)) return false;
m.m = new String[] {substring(a, l(b))};
return true;
}
static boolean startsWith(List a, List b) {
if (a == null || l(b) > l(a)) return false;
for (int i = 0; i < l(b); i++)
if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static IfThen nlLogic_parseRule(String s) {
IfThen rule = new IfThen();
List tok = javaTokPlusBrackets2(s);
if (isSquareBracketed(get(tok, 1))) {
List tokOptions = javaTokPlusBrackets2(deSquareBracket(get(tok, 1)));
Matches m = new Matches();
for (String option : tok_splitAtComma(tokOptions)) {
if (startsWith_trim(option, "id: ", m))
rule.globalID = m.rest();
else
rule.options = linkedHashSet_addWithAutoInit(rule.options, option);
}
tok = dropFirst(2, tok);
}
List l = splitAtDoubleArrow(tok);
if (l(l) != 2) return null;
rule.in = nlLogic_parseExpression(first(l));
rule.out = nlLogic_parseExpression(second(l));
return rule;
}
static Map> callF_cache = newDangerousWeakHashMap();
static A callF(F0 f) {
return f == null ? null : f.get();
}
static B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static void callF(VF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(Object f, Object... args) { try {
if (f instanceof String)
return callMC((String) f, args);
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null) return null;
Class c = f.getClass();
ArrayList methods;
synchronized(callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1) return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) { throw rethrow(__e); } }
// used internally
static ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods())
if (m.getName().equals("get")) {
m.setAccessible(true);
l.add(m);
}
if (!l.isEmpty()) break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static void mech_useLibrary(String libID) {
if (nempty(libID))
mechMode().readMode = loadLibrary(libID);
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot
// in bytes - will cut to half that
static volatile int print_log_max = 1024*1024;
static volatile int local_log_max = 100*1024;
//static int print_maxLineLength = 0; // 0 = unset
static boolean print_silent; // total mute if set
static Object print_byThread_lock = new Object();
static volatile ThreadLocal print_byThread; // special handling by thread - prefers F1
static volatile Object print_allThreads;
static void print() {
print("");
}
static A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
// slightly overblown signature to return original object...
static A print(A o) {
ping();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
Object f = print_byThread == null ? null : print_byThread.get();
if (f == null) f = print_allThreads;
if (f != null)
// We do need the general callF machinery here as print_byThread is sometimes shared between modules
if (isFalse(
f instanceof F1 ? ((F1) f).get(s) :
callF(f, s))) return;
print_raw(s);
}
static void print_raw(String s) {
s = fixNewLines(s);
// TODO if (print_maxLineLength != 0)
StringBuffer loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static List classNames(Collection l) {
return getClassNames(l);
}
static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static Android3 bot(String greeting) {
return makeAndroid3(greeting);
}
static Android3 bot(Android3 a) {
return makeBot(a);
}
static Android3 bot(String greeting, Object responder) {
return makeBot(greeting, responder);
}
static Android3 bot() {
return makeBot();
}
static List> myNonAbstractClassesImplementing(Class base) {
List> l = new ArrayList();
for (String name : myInnerClasses()) {
Class c = _getClass("main$" + name);
if (c != null && !isAbstract(c) && isSubtypeOf(c, base))
l.add(c);
}
return l;
}
static List map(Iterable l, Object f) {
return map(f, l);
}
static List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null) for (Object o : l)
x.add(callF(f, o));
return x;
}
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;
}
static List map(Object f, Object[] l) { return map(f, asList(l)); }
static List map(Object[] l, Object f) { return map(f, l); }
static List map(Object f, Map map) {
return map(map, f);
}
// map: func(key, value) -> list element
static List map(Map map, Object f) {
List x = new ArrayList();
if (map != null) for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() { public void close() {
tl.set(prev);
}};
}
static ThreadLocal telegram_msg_tl() {
return telegram_msg_tl;
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static A pcallF(F0 f) { try {
return f == null ? null : f.get();
} catch (Throwable __e) { return null; } }
static B pcallF(F1 f, A a) { try {
return f == null ? null : f.get(a);
} catch (Throwable __e) { return null; } }
static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll("printStackTrace2"));
static void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e2) {
printStackTrace2(e2); // pcall could lead to endless loops
}
}
public static String rtrim(String s) {
if (s == null) return null;
int i = s.length();
while (i > 0 && " \t\r\n".indexOf(s.charAt(i-1)) >= 0)
--i;
return i < s.length() ? s.substring(0, i) : s;
}
static String lines(Collection lines) { return fromLines(lines); }
static List lines(String s) { return toLines(s); }
static void _close(AutoCloseable c) { try {
if (c != null) c.close();
} catch (Exception __e) { throw rethrow(__e); } }
static String trim(String s) { return s == null ? null : s.trim(); }
static String trim(StringBuilder buf) { return buf.toString().trim(); }
static String trim(StringBuffer buf) { return buf.toString().trim(); }
static A nlLookup(Map map, String s) {
return lookupByNLMatch(map, s);
}
static A nlLookup(Map map, String s, Matches m) {
return lookupByNLMatch(map, s, m);
}
static List nlLookup(MultiMap map, String s) {
return lookupByNLMatch(map, s);
}
static Map mechMap(String listName) {
return mechMapCI(listName);
}
static String expandDollarRefsToMatches(String s, Matches m) {
return expandDollarRefsToMatches(s, m, false);
}
static String expandDollarRefsToMatches(String s, Matches m, boolean alwaysQuote) {
List tok = javaTok(s);
for (int i = 1; i < l(tok); i += 2) {
String t = tok.get(i);
if (!t.startsWith("$")) continue;
t = dropFirst(t);
int j = parseIntAtEnd(t);
if (j < 1) continue;
String x = get(m.m, j-1);
if (x == null) continue;
if (alwaysQuote || startsWith(t, "q"))
x = quote(x);
tok.set(i, x);
}
return join(tok);
}
static String strOrNull(Object o) {
return o == null ? null : str(o);
}
static Object javaEvalOrInterpret(String code) {
if (canQuickEval(code)) return quickEval(code);
Pair> p = tok_parseFunctionCall(code);
if (p != null)
return callAndMake(p.a, toObjectArray(map("javaEvalOrInterpret",p.b)));
return javaEval(code);
}
static boolean swic_trim(String a, String b, Matches m) {
if (!swic(a, b)) return false;
m.m = new String[] {trim(substring(a, l(b)))};
return true;
}
static ThreadLocal ai_setLanguage_value = new ThreadLocal();
static void ai_setLanguage(String language) {
ai_setLanguage_value.set(language);
}
static void _onLoad_ai_setLanguage() {
_threadInfo_addMakerAndRetriever(
new VF1() { public void get(Map map) { try { mapPut(map, "ai_setLanguage_value", ai_setLanguage_value.get()) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "mapPut(map, 'ai_setLanguage_value, ai_setLanguage_value!)"; }},
new VF1() { public void get(Map map) { try { ai_setLanguage((String) map.get("ai_setLanguage_value")) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ai_setLanguage((S) map.get('ai_setLanguage_value))"; }});
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || a.equals(b);
}
static String random_gac36k() {
return random(keys(gac36k()));
}
static String ai_renderCulledParseTree(PTElement e) {
ai_cullParseTree(e);
return ai_renderParseTree(e);
}
static PTElement ai_parseToTreeWithGuessing(String input) {
List words = ai_uncategorizedWordsInSentence(input);
//print("Have " + n2(words, "unknown word"));
AI_BottomUpParser1 parser = new AI_BottomUpParser1();
parser.wordsToCategories = new DerivedMap(ai_wordToCategories());
Map> guessMap = new HashMap();
AutoCloseable __148 = tempSetThreadLocal(ai_getWordToCategoryWeight_map, guessMap); try {
for (String word : words) {
Map map = ai_guessCategoriesForUnknownWord_weighted(word);
guessMap.put(word, map);
parser.wordsToCategories.put(word, keys(map));
}
return ai_parseBottomUpToTree(parser, input);
} finally { _close(__148); }}
static LinkedHashSet ai_parseTree_simplifiedTexts(PTElement e) {
LinkedHashSet out = new LinkedHashSet();
ai_parseTree_simplifiedTexts_collect(e, out);
return out;
}
static void ai_parseTree_simplifiedTexts_collect(PTElement e, LinkedHashSet out) {
if (e == null) return;
PTElement ee = ai_parseTree_descendToComposite(e);
if (ee == null) { out.add(e.text()); return; }
e = ee;
if (e instanceof ChoosePart) {
ai_Reconstructed r = ((ChoosePart) e).reconstruction;
WeightedProduction prod = r.production;
//print("Hint: " + prod.simplificationHint + " in prod: " + sfu(prod));
//if (eq(prod.simplificationHint, "L")) out.add(r.a.text());
//else if (eq(prod.simplificationHint, "R")) out.add(r.b.text());
PTElement e1 = first(e.children), e2 = second(e.children);
List a = asList(ai_parseTree_simplifiedTexts(e1));
List b = asList(ai_parseTree_simplifiedTexts(e2));
String hint = prod.simplificationHint;
if (eqOneOf(hint, "L", "B")) insertFirst(b, "");
/*else XXX*/ if (eqOneOf(hint, "R", "B")) insertFirst(a, "");
//print("L " + className(e1) + " " + className(ai_parseTree_descendToComposite(e1)) + " " + r.a.text() + " => " + a);
//print("R " + className(e2) + " " + className(ai_parseTree_descendToComposite(e2)) + " " + r.b.text() + " => " + b);
/*for (S aa : a)
for (S bb : b)
out.add(trim(aa + " " + bb));*/
for (Pair p : combineZigZag(a, b))
out.add(trim(p.a + " " + p.b));
// Add full text too
out.add(((ChoosePart) e).word.text());
}
}
static void dm_refreshTranspiler() {
call(dm_moduleOfType("#1017065/Transpiler"), "refresh");
}
static String pcallOrExceptionText(Object f, Object... args) {
try {
return str(callF(f, args));
} catch (Throwable e) {
_handleException(e);
return exceptionToStringShort(e);
}
}
static List trimAll(Collection l) {
List l2 = new ArrayList();
if (l != null) for (String s : l)
l2.add(trim(s));
return l2;
}
static List ai_unparsedTalkRules() {
return splitAtEmptyLines(mL_raw("NL Logic Examples"));
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static String appendToMechList_noUniq(String name, String text) {
return botAppendToMechList(name, text);
}
static String n2(long l) { return formatWithThousands(l); }
static String n2(Collection l) { return n2(l(l)); }
static String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
static String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static String n2(Map m, String singular) {
return n2(l(m), singular);
}
static String n2(Object[] a, String singular) { return n2(l(a), singular); }
static String n2(Object[] a, String singular, String plural) { return n_fancy2(a, singular, plural); }
static int l(Object[] a) { return a == null ? 0 : a.length; }
static int l(boolean[] a) { return a == null ? 0 : a.length; }
static int l(byte[] a) { return a == null ? 0 : a.length; }
static int l(short[] a) { return a == null ? 0 : a.length; }
static int l(long[] a) { return a == null ? 0 : a.length; }
static int l(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] a) { return a == null ? 0 : a.length; }
static int l(double[] a) { return a == null ? 0 : a.length; }
static int l(char[] a) { return a == null ? 0 : a.length; }
static int l(Collection c) { return c == null ? 0 : c.size(); }
static int l(Map m) { return m == null ? 0 : m.size(); }
static int l(CharSequence s) { return s == null ? 0 : s.length(); } static long l(File f) { return f == null ? 0 : f.length(); }
static int l(Object o) {
return o == null ? 0
: o instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: o instanceof Collection ? l((Collection) o)
: o instanceof Object[] ? l((Object[]) o)
: (Integer) call(o, "size");
}
static List mL(String name) {
return mechList_opt(name);
}
static String nlLogic_text(Exp e) {
return e == null ? null : e.text();
}
static AutoCloseable tempAdd(final Collection l, final A a) {
if (l == null || l.contains(a)) return null;
l.add(a);
return new AutoCloseable() { public void close() throws Exception { l.remove(a); }};
}
static A copyFields(Object x, A y, String... fields) {
if (empty(fields)) { // assume we should copy all fields
Map map = objectToMap(x);
for (String field : map.keySet())
setOpt(y, field, map.get(field));
} else
for (String field : fields) {
Object o = getOpt(x, field);
if (o != null)
setOpt(y, field, o);
}
return y;
}
static A copyFields(Object x, A y, Collection fields) {
return copyFields(x, y, asStringArray(fields));
}
static Class mc() {
return main.class;
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static Object evalWithDollarVars(String code, final Map values) {
Pair, Object> p = prepareEvalWithDollarVars(code);
return call(p.b, "calc", toObjectArray(map(p.a, new F1() { String get(String var) { try { return mapGet(values, var) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "mapGet(values, var)"; }})));
}
static int shorten_default = 100;
static String shorten(String s) { return shorten(s, shorten_default); }
static String shorten(String s, int max) {
return shorten(s, max, "...");
}
static String shorten(String s, int max, String shortener) {
if (s == null) return "";
if (max < 0) return s;
return s.length() <= max ? s : substring(s, 0, min(s.length(), max-l(shortener))) + shortener;
}
static String shorten(int max, String s) { return shorten(s, max); }
static ThreadLocal telegram_msg_tl = new ThreadLocal();
static Map telegram_msg() {
return telegram_msg_tl.get();
}
static void telegram_msg(Map msg) {
telegram_msg_tl.set(msg);
}
static boolean nlLogic_stringFunction(String f, Func e, Map matches) {
List l = tok_splitAtComma(javaTokWithBrackets(nlLogic_text(e.arg)));
if (l(l) != 2) return false;
l = mapReplaceVars2(l, matches);
if (isDollarVar(second(l)) && !isDollarVar(first(l)))
return strictPutIC(matches, second(l), ai_verbPhraseFromThirdPerson(first(l)));
return eqic(second(l), first(l));
}
static long sysNow() {
return System.nanoTime()/1000000;
}
static List switcheroo_themap = ll(
"mine", "yours",
"my", "your",
"you are", "i am",
"are you", "am i",
"you're", "i'm",
"you've", "i've",
"me", "you",
"i", "you");
static String switcheroo(String s) {
List tok = nlTok5(s);
for (int i = 1; i < l(tok); i += 2) {
for (int j = 0; j < l(switcheroo_themap); j += 2) {
String x = switcheroo_themap.get(j), y = switcheroo_themap.get(j+1);
List tokx = nlTok5(x), toky = nlTok5(y);
switcheroo_matchReplace(tok, i, tokx, toky);
switcheroo_matchReplace(tok, i, toky, tokx);
}
}
return join(map("switcheroo_dropAsterisk", tok));
}
static String switcheroo_dropAsterisk(String t) {
return startsWith(t, "*") && l(t) > 1 ? substring(t, 1) : t;
}
static void switcheroo_matchReplace(List tok, int i, List tokx, List toky) {
//printFormat("Matching * * *", i, get(tok, i), tokx);
if (switcheroo_tokRegionMatch(tok, i, tokx)) {
//printFormat("Replacing * *", tokx, toky);
for (int j = 0; j*2+1 < l(tokx); j++)
tok.set(i+j*2, "*" + toky.get(1+j*2));
}
}
static boolean switcheroo_tokRegionMatch(List tok, int i, List tokx) {
for (int j = 0; j*2+1 < l(tokx); j++)
if (!eqic(get(tok, i+j*2), get(tokx, 1+j*2)))
return false;
return true;
}
static Object evalWithTimeoutOrNull(final Object f, int timeoutMS) {
return evalWithTimeoutOrNull(timeoutMS, f);
}
static Object evalWithTimeoutOrNull(int timeoutMS, final Object f) {
return eitherAOpt(evalWithTimeout(timeoutMS, f));
}
static Object evalWithTimeoutOrNull(double timeoutSeconds, final Object f) {
return eitherAOpt(evalWithTimeout(timeoutSeconds, f));
}
static A evalWithTimeoutOrNull(int timeoutMS, F0 f) {
return (A) eitherAOpt(evalWithTimeout(timeoutMS, f));
}
static A evalWithTimeoutOrNull(double timeoutSeconds, F0 f) {
return (A) eitherAOpt(evalWithTimeout(timeoutSeconds, f));
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
f.setAccessible(true);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(Object o, String field) {
try {
Field f = get_findField(o.getClass(), field);
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static List mapMethod(Iterable c, final String methodName) {
return map(c, new F1() { Object get(Object o) { try { return callOpt(o, methodName) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callOpt(o, methodName)"; }});
}
static List mapMethod(String methodName, Iterable c) {
return mapMethod(c, methodName);
}
static List mapMethod(String methodName, Enumeration c) {
return mapMethod(methodName, enumerationToIterator(c));
}
static List ai_extractEntities_v1(String input) {
input = ai_lookupCurlyCheatSheet(input);
return ai_extractEntities_v1(ai_parseToCulledTree(input));
}
static List ai_extractEntities_v1(PTElement tree) {
HashSet toSkip = new HashSet();
List out = new ArrayList();
for (PTElement e : ai_scanParseTreeForCategory(tree, "")) {
if (toSkip.contains(e)) continue;
print("Entity found: " + e.text());
out.add(e);
PTElement ee = ai_parseTree_simplifyNode(e);
if (ee != null && ee != e)
toSkip.add(ee);
}
return out;
}
static long elapsedMS(long time) {
return sysNow()-time;
}
static String joinWithComma(Collection c) {
return join(", ", c);
}
static String joinWithComma(String... c) {
return join(", ", c);
}
static boolean isInteger(String s) {
if (s == null) return false;
int n = l(s);
if (n == 0) return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n) return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9') return false;
++i;
}
return true;
}
static int parseInt(String s) {
return empty(s) ? 0 : Integer.parseInt(s);
}
static int parseInt(char c) {
return Integer.parseInt(str(c));
}
static int nlLogic_numberOfLinesReferenced(Exp e) {
if (e instanceof And)
return max(nlLogic_numberOfLinesReferenced(((And) e).a), nlLogic_numberOfLinesReferenced(((And) e).b));
if (e instanceof Func) {
Matches m = new Matches();
if (startsWith(((Func) e).name, "line", m))
return parseIntOpt(m.rest());
}
return 0;
}
static String getString(Map map, Object key) {
return map == null ? null : (String) map.get(key);
}
static String getString(List l, int idx) {
return (String) get(l, idx);
}
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));
}
static boolean cic(Collection l, String s) {
return containsIgnoreCase(l, s);
}
static boolean cic(String[] l, String s) {
return containsIgnoreCase(l, s);
}
static boolean cic(String s, char c) {
return containsIgnoreCase(s, c);
}
static boolean cic(String a, String b) {
return containsIgnoreCase(a, b);
}
static A call_verbose(Object f, Object... args) {
return callFVerbose(f, args);
}
static boolean match(String pat, String s) {
return match3(pat, s);
}
static boolean match(String pat, String s, Matches matches) {
return match3(pat, s, matches);
}
static boolean isDollarVar(String s) {
return startsWith(s, '$') && isJavaIdentifierAfter(s, 1);
}
static A nextToLast(List l) {
return get(l, l(l)-2);
}
static A printStruct(String prefix, A a) {
printStructure(prefix, a);
return a;
}
static A printStruct(A a) {
printStructure(a);
return a;
}
static boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static boolean swic(String a, String b, Matches m) {
if (!swic(a, b)) return false;
m.m = new String[] {substring(a, l(b))};
return true;
}
static boolean strictPutIC(Map map, String key, String value) {
if (!(map != null && key != null && value != null)) return true;
String old = map.get(key);
if (old == null) { map.put(key, value); return true; }
return eqic(old, value);
}
static List mL_facts() {
return concatLists(mL("Random facts"), mL("Derived facts"));
}
static List splitAtEmptyLines(String text) {
List lines = toLines(text);
int n = l(lines), i = 0;
List parts = new ArrayList();
while (true) {
while (i < n && emptyAfterTrim(lines.get(i))) ++i;
if (i >= n) break;
int j = i;
while (j < n && !emptyAfterTrim(lines.get(j))) ++j;
parts.add(fromLines(subList(lines, i, j)));
i = j;
}
return parts;
}
static String mL_raw(String name) {
return mechList_raw(name);
}
static boolean anyJavaTokens(String s) {
return !noJavaTokens(s);
}
// f: A -> Comparable
static List sortedByCalculatedField(Collection c, Object f) {
return sortByCalculatedField(c, f);
}
static List map_pcall(Iterable l, Object f) {
return map_pcall(f, l);
}
static List map_pcall(Object f, Iterable l) {
List x = new ArrayList();
for (Object o : unnull(l)) try { x.add(callF(f, o)); } catch (Throwable __e) { _handleException(__e); }
return x;
}
static boolean nempty(Collection c) {
return !isEmpty(c);
}
static boolean nempty(CharSequence s) {
return !isEmpty(s);
}
static boolean nempty(Object[] o) { return !isEmpty(o); }
static boolean nempty(byte[] o) { return !isEmpty(o); }
static boolean nempty(Map m) {
return !isEmpty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean nempty(Object o) { return !empty(o); }
static boolean empty(Collection c) { return c == null || c.isEmpty(); }
static boolean empty(CharSequence s) { return s == null || s.length() == 0; }
static boolean empty(Map map) { return map == null || map.isEmpty(); }
static boolean empty(Object[] o) { return o == null || o.length == 0; }
static boolean empty(Object o) {
if (o instanceof Collection) return empty((Collection) o);
if (o instanceof String) return empty((String) o);
if (o instanceof Map) return empty((Map) o);
if (o instanceof Object[]) return empty((Object[]) o);
if (o instanceof byte[]) return empty((byte[]) o);
if (o == null) return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(float[] a) { return a == null || a.length == 0; }
static boolean empty(int[] a) { return a == null || a.length == 0; }
static boolean empty(long[] a) { return a == null || a.length == 0; }
static boolean empty(byte[] a) { return a == null || a.length == 0; }
static String format(String pat, Object... args) {
return format3(pat, args);
}
static String localDateWithMilliseconds(long time) {
SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss''SSSS");
return format.format(time);
}
static String localDateWithMilliseconds() {
return localDateWithMilliseconds(now());
}
static String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static String struct(Object o) {
return structure(o);
}
static String struct(Object o, structure_Data data) {
return structure(o, data);
}
static String addToMechList(String name, String text) {
return botAppendToMechList_uniqCI(name, text);
}
static String addToMechList(String name, Collection lines) {
return addToMechList(name, lines(lines));
}
static ThreadLocal applyNLLogicFacts_v3_verbose = new ThreadLocal();
static ThreadLocal> applyNLLogicFacts_v3_onRuleFired = new ThreadLocal();
static void applyNLLogicFacts_v3(String input, VF1 out) {
applyNLLogicFacts_v3(input, out, mL_facts());
}
static void applyNLLogicFacts_v3(String input, VF1 out, List facts) {
applyNLLogicFacts_v3(input, out, facts, ai_mL_parsedLogicExamples2());
}
static void applyNLLogicFacts_v3(String input, VF1 out, List facts, List rules) {
NLLogicChecker_v2 c = new NLLogicChecker_v2();
c.matcher = new NLStringMatcher_dollarVars();
addAll(c.facts, facts);
c.input = input;
applyNLLogicFacts_v3(c, out, rules);
}
static void applyNLLogicFacts_v3(NLLogicChecker_v2 c, VF1 vfOut, List rules) {
VF2 onRuleFired = optParam(applyNLLogicFacts_v3_onRuleFired);
for (IfThen rule : rules) try {
NLLogicChecker_v2.Matching m = new NLLogicChecker_v2.Matching();
m.verbose = isTrue(applyNLLogicFacts_v3_verbose.get());
if (m.verbose)
print("Checking rule: " + rule);
if (c.checkRule(rule, m)) {
print("Matched " + quote(c.input) + " with rule " + quote(rule));
printStruct(m.matches);
callF(onRuleFired, rule, m);
Map matches = new HashMap(); // matches made in evaluating RHS of rule
for (Exp out : m.output)
for (Exp e : nlLogic_unrollAnd(out))
if (e instanceof Func)
callF(vfOut, c.apply(((Func) e), m));
else if (e instanceof Eq) {
Exp r = ((Eq) e).right;
String var = nlLogic_text(((Eq) e).left);
if (r instanceof Func)
if (isStandardFunction(((Func) r).name) && ((Func) r).arg instanceof Sentence && noJavaTokens(nlLogic_text(((Func) r).arg)))
matches.put(var, str(callAndMake(((Func) r).name)));
}
}
} catch (Throwable __e) { _handleException(__e); }
}
static boolean mech_changed(String result) {
return cic(result, "changed");
}
static List mL_parsedNLRulesWithoutIDs(String listName) {
return map_pcall("nlLogic_parseRule",mL_rulesWithoutIDs(listName));
}
static IterableIterator shuffledIterator(final List l) {
return new IterableIterator () {
int n = l(l);
int i = 0;
Map shuffled = new HashMap();
public boolean hasNext() { return i < n; }
public A next() {
int j = random(i, n);
A a = get(i), b = get(j);
shuffled.put(j, a);
shuffled.remove(i);
++i;
return b;
}
A get(int i) {
return shuffled.containsKey(i) ? shuffled.get(i) : l.get(i);
}
};
}
// returns (first condition, rest) or null on null; rest may be null
static Pair nlLogic_extractFirstCondition(Exp e) {
if (e == null) return null;
if (e instanceof And)
return pair(((And) e).a, ((And) e).b);
return pair(e, null);
}
static boolean nlLogic_isFunc(Exp e, String name) {
return e instanceof Func && eq(((Func) e).name, name);
}
static String sfu(Object o) { return structureForUser(o); }
static Pair pair(A a, B b) {
return new Pair(a, b);
}
static Pair pair(A a) {
return new Pair(a, a);
}
static String aGlobalID() {
return randomID(globalIDLength());
}
static ThreadLocal applyNLLogicFacts_v2_verbose = new ThreadLocal();
static void applyNLLogicFacts_v2(String input, VF1 super String> postMessage) {
applyNLLogicFacts_v2(input, postMessage, mL_facts());
}
static void applyNLLogicFacts_v2(String input, VF1 super String> postMessage, List facts) {
applyNLLogicFacts_v2(input, postMessage, facts, ai_mL_parsedLogicExamples());
}
static void applyNLLogicFacts_v2(String input, VF1 super String> postMessage, List facts, List> rules) {
NLLogicChecker_v2 c = new NLLogicChecker_v2();
c.matcher = new NLStringMatcher_dollarVars();
addAll(c.facts, facts);
c.input = input;
applyNLLogicFacts_v2(c, postMessage, rules);
}
static void applyNLLogicFacts_v2(NLLogicChecker_v2 c, VF1 super String> postMessage, List> rules) {
for (Pair idAndRule : rules) try {
IfThen rule = idAndRule.b;
NLLogicChecker_v2.Matching m = new NLLogicChecker_v2.Matching();
m.verbose = isTrue(applyNLLogicFacts_v2_verbose.get());
if (m.verbose)
print("Checking rule: " + rule);
if (c.checkRule(rule, m)) {
print("Matched " + quote(c.input) + " with rule " + quote(rule));
printStruct(m.matches);
Map matches = new HashMap(); // matches made in evaluating RHS of rule
for (Exp out : m.output)
for (Exp e : nlLogic_unrollAnd(out))
if (e instanceof Func) {
if (eq(((Func) e).name, "output") && ((Func) e).arg instanceof Sentence)
callF(postMessage, addAndReturn(c.posted, replaceVars(nlLogic_text(((Func) e).arg), matches)));
} else if (e instanceof Eq) {
Exp r = ((Eq) e).right;
String var = nlLogic_text(((Eq) e).left);
if (r instanceof Func)
if (isStandardFunction(((Func) r).name) && ((Func) r).arg instanceof Sentence && noJavaTokens(nlLogic_text(((Func) r).arg)))
matches.put(var, str(callAndMake(((Func) r).name)));
}
}
} catch (Throwable __e) { _handleException(__e); }
}
static Throwable printStackTrace2(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace2(e));
return e;
}
static void printStackTrace2() {
printStackTrace2(new Throwable());
}
static void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static Object nuObjectWithoutArguments(String className) { try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) { throw rethrow(__e); } }
static A nuObjectWithoutArguments(Class c) { try {
if (nuObjectWithoutArguments_cache == null)
// in class init
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); } }
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());
}
// TODO: extended multi-line strings
static int javaTok_n, javaTok_elements;
static boolean javaTok_opt;
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;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') { // allow multi-line strings, but not for '
++j;
break;
} else if (c2 == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
static boolean endsWithIC(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static String[] dropLast(String[] a, int n) {
n = Math.min(n, a.length);
String[] b = new String[a.length-n];
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static List dropLast(List l) {
return subList(l, 0, l(l)-1);
}
static List dropLast(int n, List l) {
return subList(l, 0, l(l)-n);
}
static List dropLast(Iterable l) {
return dropLast(asList(l));
}
static String dropLast(String s) {
return substring(s, 0, l(s)-1);
}
static String dropLast(String s, int n) {
return substring(s, 0, l(s)-n);
}
static String dropLast(int n, String s) {
return dropLast(s, n);
}
public static String join(String glue, Iterable strings) {
if (strings == null) return "";
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static String join(Iterable strings) {
return join("", strings);
}
static String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
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]);
}
static HashSet litset(A... items) {
return lithashset(items);
}
static String dropSuffix(String suffix, String s) {
return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s;
}
static String afterLastSpace(String s) {
return s == null ? null : substring(s, s.lastIndexOf(' ')+1);
}
static boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
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;
}
static int jfind(String s, String in) {
return jfind(javaTok(s), in);
}
static int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
static int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, null);
}
static int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
static int jfind(List tok, int startIdx, String in, Object condition) {
List tokin = javaTok(in);
jfind_preprocess(tokin);
return jfind(tok, startIdx, tokin, condition);
}
// assumes you preprocessed tokin
static int jfind(List tok, List tokin) {
return jfind(tok, 1, tokin);
}
static int jfind(List tok, int startIdx, List tokin) {
return jfind(tok, startIdx, tokin, null);
}
static int jfind(List tok, int startIdx, List tokin, Object condition) {
return findCodeTokens(tok, startIdx, false, toStringArray(codeTokensOnly(tokin)), condition);
}
static List jfind_preprocess(List tok) {
for (String type : litlist("quoted", "id", "int"))
replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
return tok;
}
static String substring(String s, int x) {
return substring(s, x, l(s));
}
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);
}
static String substring(String s, IntRange r) {
return r == null ? null : substring(s, r.start, r.end);
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static List javaTokPlusBrackets2(String s) {
return tok_combineRoundCurlySquareBrackets_keep(javaTok(s));
}
static boolean isSquareBracketed(String s) {
return s != null && s.startsWith("[") && s.endsWith("]");
}
static String deSquareBracket(String s) {
if (startsWith(s, "[") && endsWith(s, "]"))
return substring(s, 1, l(s)-1);
return s;
}
static List tok_splitAtComma(String s) {
return tok_splitAtComma(javaTok(s));
}
static List tok_splitAtComma(List tok) {
List out = new ArrayList();
for (int i = 0; i < l(tok); i++) {
int j = smartIndexOf(tok, ",", i);
out.add(joinSubList(tok, i+1, j-1));
i = j;
}
return out;
}
static boolean startsWith_trim(String a, String b, Matches m) {
if (!startsWith(a, b)) return false;
m.m = new String[] {trim(substring(a, l(b)))};
return true;
}
static Set linkedHashSet_addWithAutoInit(Set set, A a) {
if (set == null) set = new LinkedHashSet();
set.add(a);
return set;
}
static String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
static String[] dropFirst(String[] a) {
return drop(1, a);
}
static Object[] dropFirst(Object[] a) {
return drop(1, a);
}
static List dropFirst(List l) {
return dropFirst(1, l);
}
static List dropFirst(int n, Iterable i) { return dropFirst(n, toList(i)); }
static List dropFirst(Iterable i) { return dropFirst(toList(i)); }
static List dropFirst(int n, List l) {
return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
static List dropFirst(List l, int n) {
return dropFirst(n, l);
}
static String dropFirst(int n, String s) { return substring(s, n); }
static String dropFirst(String s) { return substring(s, 1); }
static List splitAtDoubleArrow(String s) {
return splitAtDoubleArrow(javaTok(s));
}
static List splitAtDoubleArrow(List tok) {
List l = new ArrayList();
int i = 0;
while (i < l(tok)) {
int j = indexOfSubList(tok, ll("=", "", ">"), i);
if (i >= l(tok)) break;
if (j < 0) j = l(tok);
l.add(trimJoin(tok.subList(i, j)));
i = j+3;
}
return l;
}
static Exp nlLogic_parseExpression(String s) {
List tok = javaTokPlusBrackets(s);
// a && b
Pair p = splitAtTokens_once(tok, ll("&", "", "&"));
if (p != null)
return new And(nlLogic_parseExpression(first(p)), nlLogic_parseExpression(second(p)));
// !a
if (eqGet(tok, 1, "!"))
return new ExpNot(nlLogic_parseExpression(join(dropFirst(2, tok))));
// function
if (l(tok) == 5 && isIdentifier(tok.get(1)) && isRoundBracketed(tok.get(3)))
return new Func(tok.get(1), nlLogic_parseExpression(deRoundBracket(tok.get(3))));
// a = b
List l = splitAtTokens(tok, ll("="));
if (l(l) == 2)
return new Eq(nlLogic_parseExpression(first(l)), nlLogic_parseExpression(second(l)));
// default
return new Sentence2(l(tok) == 3 && isQuoted(tok.get(1)) ? unquote(second(tok)) : join(tok));
}
static Object first(Object list) {
return empty((List) list) ? null : ((List) list).get(0);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static A first(Pair p) {
return p == null ? null : p.a;
}
static A second(List l) {
return get(l, 1);
}
static A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static B second(Pair p) {
return p == null ? null : p.b;
}
static Map newDangerousWeakHashMap() {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()));
}
// initFunction: voidfunc(Map) - is called initially, and after clearing the map
static Map newDangerousWeakHashMap(Object initFunction) {
return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction);
}
static HashMap> callMC_cache = new HashMap();
static String callMC_key;
static Method callMC_value;
// varargs assignment fixer for a single string array argument
static Object callMC(String method, String[] arg) {
return callMC(method, new Object[] {arg});
}
static Object callMC(String method, Object... args) { try {
Method me;
if (callMC_cache == null) callMC_cache = new HashMap(); // initializer time workaround
synchronized(callMC_cache) {
me = method == callMC_key ? callMC_value : null;
}
if (me != null) try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
List m;
synchronized(callMC_cache) {
m = callMC_cache.get(method);
}
if (m == null) {
if (callMC_cache.isEmpty()) {
callMC_makeCache();
m = callMC_cache.get(method);
}
if (m == null) throw fail("Method named " + method + " not found in main");
}
int n = m.size();
if (n == 1) {
me = m.get(0);
synchronized(callMC_cache) {
callMC_key = method;
callMC_value = me;
}
try {
return invokeMethod(me, null, args);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e);
}
}
for (int i = 0; i < n; i++) {
me = m.get(i);
if (call_checkArgs(me, args, false))
return invokeMethod(me, null, args);
}
throw fail("No method called " + method + " with matching arguments found in main");
} catch (Exception __e) { throw rethrow(__e); } }
static void callMC_makeCache() {
synchronized(callMC_cache) {
callMC_cache.clear();
Class _c = (Class) mc(), c = _c;
while (c != null) {
for (Method m : c.getDeclaredMethods())
if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
m.setAccessible(true);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
}
static RuntimeException fail() { throw new RuntimeException("fail"); }
static RuntimeException fail(Throwable e) { throw asRuntimeException(e); }
static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); }
static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); }
static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); }
static String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static Object invokeMethod(Method m, Object o, Object... args) { try {
try {
return m.invoke(o, args);
} catch (InvocationTargetException e) {
throw rethrow(getExceptionCause(e));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
}
} catch (Exception __e) { throw rethrow(__e); } }
static boolean call_checkArgs(Method m, Object[] args, boolean debug) {
Class>[] types = m.getParameterTypes();
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++)
if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static MechMode mechMode_value = new MechMode();
static MechMode mechMode() {
return mechMode_value;
}
static File loadLibrary(String snippetID) {
return loadBinarySnippet(snippetID);
}
static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1));
}
//sbool ping_actions_shareable = true;
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map ping_actions = newWeakHashMap();
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions ) ping_impl();
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl() { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
Object action = null;
synchronized(ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static boolean isFalse(Object o) {
return eq(false, o);
}
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();
}
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); } }
static List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null) for (Object o : l)
out.add(o == null ? null : getClassName(o));
return out;
}
// An "Android" is a program that accepts text questions (on console or TCP) and outputs one response text per question
//please include function myJavaSource. // for getting my known commands
static boolean makeAndroid3_disable; // disable all android making
static class Android3 {
String greeting;
boolean publicOverride; // optionally set this in client
int startPort = 5000; // optionally set this in client
Responder responder;
boolean console = true;
boolean quiet; // no messages on console
boolean daemon = false;
boolean incomingSilent = false;
int incomingPrintLimit = 200;
boolean useMultiPort = true;
boolean recordHistory;
boolean verbose;
int answerPrintLimit = 500;
boolean newLineAboveAnswer, newLineBelowAnswer;
// set by system
int port;
long vport;
DialogHandler handler;
ServerSocket server;
Android3(String greeting) {
this.greeting = greeting;}
Android3() {}
synchronized void dispose() {
if (server != null) {
try {
server.close();
} catch (IOException e) {
print("[internal] " + e);
}
server = null;
}
if (vport != 0) try {
print("Disposing " + this);
removeFromMultiPort(vport);
vport = 0;
} catch (Throwable __e) { _handleException(__e); }
}
public String toString() { return "Bot: " + greeting + " [vport " + vport + "]"; }
}
static abstract class Responder {
abstract String answer(String s, List history);
}
static Android3 makeAndroid3(final String greeting) {
return makeAndroid3(new Android3(greeting));
}
static Android3 makeAndroid3(final String greeting, Responder responder) {
Android3 android = new Android3(greeting);
android.responder = responder;
return makeAndroid3(android);
}
static Android3 makeAndroid3(final Android3 a) {
if (makeAndroid3_disable) return a;
if (a.responder == null)
a.responder = new Responder() {
String answer(String s, List history) {
return callStaticAnswerMethod(s, history);
}
};
if (!a.quiet)
print("[bot] " + a.greeting);
if (a.console && (readLine_noReadLine || makeAndroid3_consoleInUse()))
a.console = false;
record(a);
if (a.useMultiPort)
a.vport = addToMultiPort(a.greeting,
makeAndroid3_verboseResponder(a));
if (a.console)
makeAndroid3_handleConsole(a);
if (a.useMultiPort) return a;
a.handler = makeAndroid3_makeDialogHandler(a);
if (a.quiet) startDialogServer_quiet.set(true);
try {
a.port = a.daemon
? startDialogServerOnPortAboveDaemon(a.startPort, a.handler)
: startDialogServerOnPortAbove(a.startPort, a.handler);
} finally {
startDialogServer_quiet.set(null);
}
a.server = startDialogServer_serverSocket;
return a;
}
static void makeAndroid3_handleConsole(final Android3 a) {
// Console handling stuff
if (!a.quiet)
print("You may also type on this console.");
{ Thread _t_0 = new Thread() {
public void run() { try {
List history = new ArrayList();
while (licensed()) {
String line;
try {
line = readLine();
} catch (Throwable e) {
print(getInnerMessage(e));
break;
}
if (line == null) break;
/*if (eq(line, "bye")) {
print("> bye stranger");
history = new ArrayList();
} else*/ {
history.add(line);
history.add(makeAndroid3_getAnswer(line, history, a)); // prints answer on console too
}
}
} catch (Throwable __e) { _handleException(__e); } }
};
startThread(_t_0); }
}
static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) {
return new DialogHandler() {
public void run(final DialogIO io) {
if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) {
io.sendLine("Sorry, not allowed");
return;
}
String dialogID = randomID(8);
io.sendLine(a.greeting + " / Your ID: " + dialogID);
List history = new ArrayList();
while (io.isStillConnected()) {
if (io.waitForLine()) {
final String line = io.readLineNoBlock();
String s = dialogID + " at " + now() + ": " + quote(line);
if (!a.incomingSilent)
print(shorten(s, a.incomingPrintLimit));
if (eq(line, "bye")) {
io.sendLine("bye stranger");
return;
}
Matches m = new Matches();
if (a.recordHistory)
history.add(line);
String answer;
if (match3("this is a continuation of talk *", s, m)
|| match3("hello bot! this is a continuation of talk *", s, m)) {
dialogID = unquote(m.m[0]);
answer = "ok";
} else try {
makeAndroid3_io.set(io);
answer = makeAndroid3_getAnswer(line, history, a);
} finally {
makeAndroid3_io.set(null);
}
if (a.recordHistory)
history.add(answer);
io.sendLine(answer);
//appendToLog(logFile, s);
}
}
}};
}
static String makeAndroid3_getAnswer(String line, List history, Android3 a) {
String answer, originalAnswer;
try {
originalAnswer = a.responder.answer(line, history);
answer = makeAndroid3_fallback(line, history, originalAnswer);
} catch (Throwable e) {
e = getInnerException(e);
printStackTrace(e);
originalAnswer = answer = e.toString();
}
if (!a.incomingSilent) {
if (originalAnswer == null) originalAnswer = "?";
if (a.newLineAboveAnswer) print();
print(">" + dropFirst(indentx(2, shorten(rtrim(originalAnswer), a.answerPrintLimit))));
if (a.newLineBelowAnswer) print();
}
return answer;
}
static String makeAndroid3_fallback(String s, List history, String answer) {
// Now we only do the safe thing instead of VM inspection - give out our process ID
if (answer == null && match3("what is your pid", s))
return getPID();
if (answer == null && match3("what is your program id", s)) // should be fairly safe, right?
return getProgramID();
if (match3("get injection id", s))
return getInjectionID();
if (answer == null) answer = "?";
if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0)
answer = quote(answer);
return answer;
}
static boolean makeAndroid3_consoleInUse() {
if (isTrue(vm_generalMap_get("consoleInUse"))) return true;
for (Object o : record_list)
if (o instanceof Android3 && ((Android3) o).console)
return true;
return false;
}
static Responder makeAndroid3_verboseResponder(final Android3 a) {
return new Responder() {
String answer(String s, List history) {
if (a.verbose)
print("> " + shorten(s, a.incomingPrintLimit));
String answer = a.responder.answer(s, history);
if (a.verbose)
print("< " + shorten(answer, a.incomingPrintLimit));
return answer;
}
};
}
static ThreadLocal makeAndroid3_io = new ThreadLocal();
static Android3 makeAndroid3() {
return makeAndroid3(getProgramTitle() + ".");
}
static int makeBot(String greeting) {
return makeAndroid3(greeting).port;
}
static Android3 makeBot(Android3 a) {
makeAndroid3(a);
return a;
}
static Android3 makeBot(String greeting, Object responder) {
Android3 a = new Android3(greeting);
a.responder = makeResponder(responder);
makeBot(a);
return a;
}
static Android3 makeBot() {
return makeAndroid3(defaultBotName());
}
static List myInnerClasses_list=litlist(
"VF1", "PairComparedByA", "VF2", "ChooseCategory", "NLLogicChecker_v2", "Var", "StringMatcher", "TokCondition", "Literal", "ExpNot", "Sentence", "ChoosePart", "Sentence2", "F0", "F1", "IterableIterator", "Snippet", "betterCIComparator_C", "IfThen", "Flag", "VirtualMechLists", "CloseableIterableIterator", "ExpiringMap2", "getOpt_Map", "NLStringMatcher_noVars", "And", "WeightedProduction", "structure_Data", "PTElement", "IVar", "MechMode", "Cache", "Matches", "Func", "TimedCache", "TelegramInitiativeBot", "Eq", "TelegramFactsBot", "DerivedMap", "MultiMap", "QuickException", "CriticalAction", "NLStringMatcher_dollarVars", "DialogHandler", "Lowest", "Either", "AbstractThinkBot", "ai_Reconstructed", "CompilerBot", "Pair", "AI_BottomUpParser1", "JavaXClassLoader", "DialogIO", "TelegramThinkBot", "NLStringMatcher_singleDollarVar", "JavaXClassLoaderWithParent", "IntRange", "NLStringMatcher_dollarVars_underscores", "BetterLabel", "MRUCache", "componentPopupMenu_Adapter", "HaveCategory", "DynamicObject", "PersistableThrowable", "Android3", "Exp", "Responder");
static List myInnerClasses() {
return myInnerClasses_list;
}
static Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null; // could optimize this
}
}
static Class _getClass(Object o) {
return o == null ? null
: o instanceof Class ? (Class) o : o.getClass();
}
static Class _getClass(Object realm, String name) { try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (Exception __e) { throw rethrow(__e); } }
static boolean isAbstract(Class c) {
return (c.getModifiers() & Modifier.ABSTRACT) != 0;
}
static boolean isSubtypeOf(Class a, Class b) {
return b.isAssignableFrom(a); // << always hated that method, let's replace it!
}
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static List emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
// Try to match capacity
static List emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static ArrayList asList(int[] a) {
ArrayList l = new ArrayList();
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(Iterable s) {
if (s instanceof ArrayList) return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
static A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null) return null;
A old = tl.get();
tl.set(value);
return old;
}
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); }
return null;
}
static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
static PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static ArrayList cloneList(Collection l) {
if (l == null) return new ArrayList();
synchronized(collectionMutex(l)) {
return new ArrayList (l);
}
}
// usually L
static String fromLines(Collection lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines)
buf.append(str(line)).append('\n');
return buf.toString();
}
static String fromLines(String... lines) {
return fromLines(asList(lines));
}
static IterableIterator toLines(File f) {
return linesFromFile(f);
}
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;
}
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;
}
static A lookupByNLMatch(Map map, String s) {
return lookupByNLMatch(map, s, null);
}
static A lookupByNLMatch(Map map, String s, Matches m) {
for (String key : keys(map))
if (match(key, s, m))
return map.get(key);
return null;
}
static List lookupByNLMatch(MultiMap map, String s) {
for (String key : keys(map))
if (match(key, s))
return map.get(key);
return emptyList();
}
// name -> (name, parsed map)
static Map>> mechMapCI_cache = synchroMap();
static Map mechMapCI(String listName) {
Pair> p = mechMapCI_cache.get(listName);
String text = mechList_raw(listName);
if (p != null && eq(p.a, text)) return p.b;
String parsing = first(mechList_opt(listName + " | Parsing"));
Map map;
if (parsing == null)
map = parseDoubleArrowMapCI(tlft(text));
else
map = asCIMap((Map) callAndMake(parsing, text));
p = pair(text, map);
mechMapCI_cache.put(listName, p);
return p.b;
}
static int parseIntAtEnd(String s) {
int i = l(s);
while (i > 0 && isDigit(charAt(s, i-1))) --i;
return parseInt(substring(s, i));
}
static String quote(Object o) {
if (o == null) return "null";
return quote(str(o));
}
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();
}
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('"');
}
static boolean canQuickEval(String t) {
return isQuoted(t) || isIdentifier(t) || isInteger(t) || isSnippetID(t);
}
static Object quickEval(String t) {
if (isQuoted(t)) return unquote(t);
if (isInteger(t)) return parseInt(t);
if (eq(t, "null")) return null;
if (eq(t, "false")) return false;
if (eq(t, "true")) return true;
if (isIdentifier(t)) return getMC(t);
if (isSnippetID(t)) return t;
throw quickFail("Can't quick eval: " + t);
}
// returns pair(functionName, args)
static Pair> tok_parseFunctionCall(String s) {
return tok_parseFunctionCall(javaTok(s));
}
static Pair> tok_parseFunctionCall(List tok) {
if (!(isIdentifier(get(tok, 1)) && eqGet(tok, 3, "("))) return null;
Map bracketMap = getBracketMap(tok);
Integer iClosing = bracketMap.get(3);
if (!(eq(iClosing, l(tok)-4) && eqGet(tok, l(tok)-2, ";"))
&& neq(iClosing, l(tok)-2)) return null;
int i = 5, argStart = 5;
List args = new ArrayList();
while (i < iClosing) {
Integer j = bracketMap.get(i);
if (j != null) { i = j+2; continue; }
if (eqGetOneOf(tok, i, ",")) {
if (i > argStart) args.add(trimJoinSubList(tok, argStart, i));
argStart = i+2;
}
i += 2;
}
if (i > argStart) args.add(trimJoinSubList(tok, argStart, i));
return pair(tok.get(1), args);
}
static Object callAndMake(String functionName, Object... args) {
return callAndMake_orDirect(functionName, args);
}
static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static Object javaEval(String code) {
return evalJava(code);
}
static void _threadInfo_addMakerAndRetriever(VF1 maker, VF1 retriever) {
_threadInfo_makers.add(maker);
_threadInheritInfo_retrievers.add(retriever);
}
static void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null) map.put(key, value);
}
static Random random_random = new Random();
static int random(int n) {
return n <= 0 ? 0 : random_random.nextInt(n);
}
static double random(double max) {
return random()*max;
}
static double random() {
return random_random.nextInt(100001)/100000.0;
}
static double random(double min, double max) {
return min+random()*(max-min);
}
// min <= value < max
static int random(int min, int max) {
return min+random(max-min);
}
static A random(List l) {
return oneOf(l);
}
static A random(Collection c) {
if (c instanceof List) return random((List ) c);
int i = random(l(c));
return collectionGet(c, i);
}
static Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static Set keys(Object map) {
return keys((Map) map);
}
static Set keys(MultiMap mm) {
return mm.keySet();
}
static boolean gac3k_verbose;
static Cache> gac36k_cache = new Cache("gac36k_load");
static TreeMap gac36k() { return gac36k_cache.get(); }
static TreeMap gac36k_load() {
TreeMap map = new TreeMap();
for (String s : tlft(loadSnippet("#2000592"))) try {
int i = indexOfAny(s, 0, " \t");
float f = parseFloat(takeFirst(i, s));
Float previous = mapPutIfChange2(map, trim(substring(s, i)), f);
if (gac3k_verbose && previous != null)
print("Gac-36K: Duplicate question: " + s + " (was: " + previous + ")");
} catch (Throwable __e) { _handleException(__e); }
print("GAC-36K: Have " + n(map, "question"));
return map;
}
static PTElement ai_cullParseTree(PTElement e) {
if (e == null) return e;
if (!(e instanceof ChoosePart))
removeAllButFirst(e.children);
for (PTElement child : unnull(e.children))
ai_cullParseTree(child);
return e;
}
static String ai_renderParseTree(final PTElement e) {
return hijackPrint(new Runnable() { public void run() { try { ai_printParseTree(e) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ai_printParseTree(e)"; }});
}
static List ai_uncategorizedWordsInSentence(String s) {
return filter(uniquify(words(s)) , new F1() { Object get(String word) { try { return empty(ai_wordToCategories(word)) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "empty(ai_wordToCategories(word))"; }});
}
static TimedCache>>> ai_wordToCategories_cache = new TimedCache("ciMap", 10.0); // language -> word -> categories
static Map> ai_wordToCategories() {
Map>> languages = ai_wordToCategories_cache.get();
Map> map = languages.get(ai_language());
if (map == null)
languages.put(ai_language(), map = ai_wordToCategories_make());
return map;
}
static Map> ai_wordToCategories_make() {
Map> catMap = ai_wordCategoriesWithElements();
final Map> map = ciMap();
for (String cat : keys(catMap))
for (String word : catMap.get(cat)) {
Set set = map.get(word);
if (set == null) map.put(word, set = new LinkedHashSet());
set.add(cat);
}
return map;
}
static Set ai_wordToCategories(String word) {
return ai_wordToCategories().get(word);
}
static Map ai_guessCategoriesForUnknownWord_weighted(String word) {
Map map = lithashmap("" , 0.3, "" , 0.3, "" , 0.2);
if (ewic(word, "ing")) map.put("" , 0.6);
if (ewic(word, "ly")) map.put("" , 0.6);
if (eqic(word, "ed")) map.put("" , 0.5);
return map;
}
static PTElement ai_parseBottomUpToTree(String input) {
return ai_parseBottomUpToTree(new AI_BottomUpParser1(), input);
}
static PTElement ai_parseBottomUpToTree(AI_BottomUpParser1 parser, String input) {
parser.parse(input);
return ai_parseBottomUpToTree(parser);
}
static PTElement ai_parseBottomUpToTree(AI_BottomUpParser1 parser, List tok) {
parser.parse(tok);
return ai_parseBottomUpToTree(parser);
}
static PTElement ai_parseBottomUpToTree(AI_BottomUpParser1 parser) {
AI_BottomUpParser1.Word w = parser.fullGroup();
if (w == null) return null;
List classes = withoutQuoted(w.classes);
if (empty(classes)) return null;
return ai_completeParseTree(parser, new ChooseCategory(w, classes));
}
static PTElement ai_parseTree_descendToComposite(PTElement e) {
/*while (e instanceof ChooseCategory
|| e instanceof HaveCategory
&& (e/HaveCategory.reconstruction == null || e/HaveCategory.reconstruction.b == null)) {*/
while (e != null && !(e instanceof ChoosePart)) {
PTElement e2 = e;
e = first(e.children); // Choose most likely reconstruction
//print("Went from " + className(e2) + "(" + e + ") to " + className(e) + " (" + n2(e2.children, "child", "children") + ")");
}
return e;
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static void insertFirst(List l, A a) {
if (l != null) l.add(0, a);
}
static List> combineZigZag(List l1, List l2) {
int lA = l(l1), lB = l(l2), maxSum = max(lA, lB);
List> out = new ArrayList();
int ndiags = lA + lB - 1;
for (int diag = 0; diag < ndiags; diag++) {
int row_stop = max(0, diag - lA + 1);
int row_start = min(diag, lB - 1);
for (int row = row_start; row >= row_stop; row--) {
// on a given diagonal row + col = constant "diag"
// diag labels the diagonal number
int col = diag - row;
out.add(pair(l1.get(col), l2.get(row)));
}
}
return out;
}
// TODO: remove
static Object call(Object o) {
return callF(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Method m = call_findStaticMethod((Class) o, method, args, false);
m.setAccessible(true);
return invokeMethod(m, null, args);
/*} else if (o instanceof DynamicMethods) {
ret ((DynamicMethods) o)._dynCall(method, args);*/
} else {
Method m = call_findMethod(o, method, args, false);
m.setAccessible(true);
return invokeMethod(m, o, args);
}
} catch (Exception __e) { throw rethrow(__e); } }
static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (!m.getName().equals(method)) {
if (debug) System.out.println("Method name mismatch: " + method);
continue;
}
if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + _c.getName());
}
static Method call_findMethod(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && call_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName());
}
static Object dm_moduleOfType(String type) {
return first(dm_modulesOfType(type));
}
static String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
static String botAppendToMechList(String name, String text) {
return botAppendToMechList_now(name, text);
}
static String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
static String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
static String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
static String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
static String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
static List mechList_opt(String name) {
return mechList_opt_tlft(name);
}
// o is either a map already (string->object) or an arbitrary object,
// in which case its fields are converted into a map.
static Map objectToMap(Object o) { try {
if (o instanceof Map) return (Map) o;
TreeMap map = new TreeMap();
Class c = o.getClass();
while (c != Object.class) {
Field[] fields = c.getDeclaredFields();
for (final Field field : fields) {
if ((field.getModifiers() & Modifier.STATIC) != 0)
continue;
field.setAccessible(true);
final Object value = field.get(o);
if (value != null)
map.put(field.getName(), value);
}
c = c.getSuperclass();
}
// XXX NEW - hopefully this doesn't break anything
if (o instanceof DynamicObject)
map.putAll(((DynamicObject) o).fieldValues);
return map;
} catch (Exception __e) { throw rethrow(__e); } }
// same for a collection (convert each element)
static List> objectToMap(Collection l) {
List x = new ArrayList();
for (Object o : l)
x.add(objectToMap(o));
return x;
}
static Field setOpt_findField(Class c, String field) {
HashMap map;
synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map.get(field);
}
static void setOpt(Object o, String field, Object value) { try {
if (o == null) return;
Class c = o.getClass();
HashMap map;
if (getOpt_cache == null)
map = getOpt_makeCache(c); // in class init
else synchronized(getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
// It's probably a subclass of Map. Use raw method
setOpt_raw(o, field, value);
return;
}
Field f = map.get(field);
if (f != null)
smartSet(f, o, value); // possible improvement: skip setAccessible
} catch (Exception __e) { throw rethrow(__e); } }
static void setOpt(Class c, String field, Object value) {
if (c == null) return;
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field setOpt_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) {
f.setAccessible(true);
return f;
}
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null) return null;
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// access of static fields is not yet optimized
static Object getOpt(Class c, String field) {
try {
if (c == null) return null;
Field f = getOpt_findStaticField(c, field);
if (f == null) return null;
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field getOpt_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);
return null;
}
static String[] asStringArray(Collection c) {
return toStringArray(c);
}
static String[] asStringArray(Object o) {
return toStringArray(o);
}
static Pair, Object> prepareEvalWithDollarVars(String code) {
List tok = javaTok(code);
LinkedHashSet