Warning : session_start(): open(/var/lib/php/sessions/sess_auslq3ado04i415m2n7goe7mlp, 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 javax.swing.undo.UndoManager;
import java.text.NumberFormat;
import java.awt.datatransfer.StringSelection;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.awt.datatransfer.Transferable;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.text.*;
class main {
static class TestBot extends DynObjectTable {
InputChooser inputChooser = new InputChooser(this);
String source;
String inputAs = "Input:"; // "Input:" or "Fact:"
boolean unsafeEvals;
void start() { super.start();
dm_useLocalMechListCopies();
inputChooser.delay = 1000;
itemToMap = itemToMap_ExecutedRule();
}
JComponent visualize() {
return withMargin(northAndCenter(vstackWithSpacing(
westAndCenter(dm_fieldComboBox("inputAs",
ll("Input:", "Fact:")),
wrap(inputChooser)),
withLabel("Rules mech list (empty for default rules&facts):",
onEnter(dm_fieldTextField("source"), runnableThread(new Runnable() { public void run() { try { doIt();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "doIt();"; }}))),
jrightalignedline(main.onChange(dm_fieldCheckBox("Allow unsafe evals", "unsafeEvals"), runnableThread(new Runnable() { public void run() { try { doIt();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "doIt();"; }})))),
super.visualize()));
}
void doIt() { update(inputChooser.input()); }
void update() { if (inputChooser.update()) update(inputChooser.input()); }
void update(String input) {
AutoCloseable __0 = enter(); try {
boolean inputAsFact = cic(inputAs, "fact");
NLLogicChecker_v2.staticVerbose = true;
AutoCloseable __1 = tempSetTL(nlLogic_processInputOrFact_allowUnsafeEvals, unsafeEvals); try {
setData(printLength("l=", nlLogic_processInputOrFact(input, inputAsFact,
or2(trim(source), ""))));
} finally { _close(__1); }} finally { _close(__0); }}
}
static void dm_useLocalMechListCopies() {
dm_useLocallyCopiedMechLists();
}
static F1 itemToMap_ExecutedRule() {
return new F1() { Map get(ExecutedRule r) { try {
Map map = litorderedmap(
"Output" , nullIfEmpty(join("|", r.output)),
"Facts" , nullIfEmpty(join("|", r.facts)),
"New Input" , nullIfEmpty(join("|", r.newInput)));
RuleWithParams rule = r.rule;
if (rule instanceof FailedRule) {
mapPut(map, "Failure Level" , nlLogic_failureLevelString(r));
mapPut(map, "Satisfied Conditions" , empty(((FailedRule) rule).satisfiedConditions) ? null : join(" && ", allToString(((FailedRule) rule).satisfiedConditions)));
mapPut(map, "Remaining Conditions" , simpleSpaces3(strOrNull(((FailedRule) rule).remainingCondition)));
}
mapPut(map, "Rule ID" , r.ruleID());
mapPut(map, "Details" , rule);
return map;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Map map = litorderedmap(\r\n Output := nullIfEmpty(join(\"|\", r.output)),\r\n..."; }};
}
static int withMargin_defaultWidth = 6;
static JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
static JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
static JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
static JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
return swing(new F0() { JPanel get() { try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
p.add(c);
return p;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat..."; }});
}
static JPanel northAndCenter(Component n, Component c) {
return centerAndNorth(c, n);
}
static int vstackWithSpacing_default = 10;
static JPanel vstackWithSpacing(final List parts) {
return vstackWithSpacing(parts, vstackWithSpacing_default);
}
static JPanel vstackWithSpacing(final List parts, final int spacing) {
return swing(new F0() { JPanel get() { try {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(spacing/2, 0, spacing/2, 0); // well...
smartAddWithLayout(panel, gbc, toObjectArray(parts));
//gbc = (GridBagConstraints) gbc.clone();
//gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
gbc.insets = new Insets(0, 0, 0, 0);
panel.add(jrigid(), gbc);
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new GridBagLayout);\r\n new GridBagConstraints gbc..."; }});
}
static JPanel vstackWithSpacing(Component... parts) {
return vstackWithSpacing(asList(parts), vstackWithSpacing_default);
}
static JPanel westAndCenter(final Component w, final Component c) {
return swing(new F0() { JPanel get() { try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.WEST, wrap(w));
panel.add(BorderLayout.CENTER, wrap(c));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.WEST..."; }});
}
static JComboBox dm_fieldComboBox(String field, Collection values) {
return jLiveValueComboBox(values, dm_fieldLiveValue(field));
}
static List ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
// c = Component or something implementing swing()
static Component wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
static Component wrap_2(Object swingable) {
if (swingable == null) return null;
Component c;
if (swingable instanceof Component) c = (Component) swingable;
else if (swingable instanceof Swingable) c = ((Swingable) swingable).visualize();
else c = (Component) callOpt(swingable, "swing");
if (c instanceof JTable || c instanceof JList
|| c instanceof JTextArea || c instanceof JEditorPane
|| c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
public static JComponent withLabel(String label, JComponent component) {
return westAndCenter(jlabel(label + " "), component);
}
static JTextField onEnter(final JTextField tf, final Object action) {
if (action == null || tf == null) return tf;
tf.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
tf.selectAll();
callF(action);
} catch (Throwable __e) { messageBox(__e); }}});
return tf;
}
static JButton onEnter(JButton btn, final Object action) {
if (action == null || btn == null) return btn;
btn.addActionListener(actionListener(action));
return btn;
}
static JList onEnter(JList list, Object action) {
list.addKeyListener(enterKeyListener(rCallOnSelectedListItem(list, action)));
return list;
}
static JComboBox onEnter(final JComboBox cb, final Object action) {
{ swing(new Runnable() { public void run() { try {
if (cb.isEditable()) {
JTextField text = (JTextField) cb.getEditor().getEditorComponent();
onEnter(text, action);
} else {
cb.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
cb.getActionMap().put("enter", abstractAction("", new Runnable() { public void run() { try { cb.hidePopup(); callF(action);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.hidePopup(); callF(action);"; }}));
}
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (cb.isEditable()) {\r\n JTextField text = (JTextField) cb.getEditor().g..."; }}); }
return cb;
}
static JTable onEnter(final JTable table, final Object action) {
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
table.getActionMap().put("Enter", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
callF(action, table.getSelectedRow());
}
});
return table;
}
/*static JTextArea onEnter(final JTextArea ta, fO action) {
addKeyListener(ta, enterKeyListener(action));
ret ta;
}*/
static JTextField onEnter(Object action, JTextField tf) {
return onEnter(tf, action);
}
static JTextField dm_fieldTextField(String field) {
return jLiveValueTextField_bothWays(dm_fieldLiveValue(field));
}
static Runnable runnableThread(final Runnable r) {
return new Runnable() { public void run() { try { startThread(r) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "startThread(r)"; }};
}
static RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static JPanel jrightalignedline(Component... components) {
return jrightAlignedLine(components);
}
static JPanel jrightalignedline(List components) {
return jrightAlignedLine(components);
}
static void onChange(JSpinner spinner, Object r) {
spinner.addChangeListener(changeListener(r));
}
static A onChange(A b, Object r) {
b.addItemListener(itemListener(r));
return b;
}
static void onChange(JTextComponent tc, Object r) {
onUpdate(tc, r);
}
static void onChange(final JSlider slider, final Object r) {
{ swing(new Runnable() { public void run() { try {
slider.addChangeListener(changeListener(r));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "slider.addChangeListener(changeListener(r));"; }}); }
}
static void onChange(JComboBox cb, final Object r) {
if (isEditableComboBox(cb))
onChange(textFieldFromComboBox(cb), r);
else
onSelectedItem(cb, new VF1() { public void get(String s) { try { callF(r) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callF(r)"; }});
}
static JCheckBox dm_fieldCheckBox(String field) {
return dm_fieldCheckBox(humanizeFormLabel(field), field);
}
static JCheckBox dm_fieldCheckBox(String text, String field) {
// magic parameter swap :)
if (isIdentifier(text) && !isIdentifier(field)) { String temp = field; field = text; text = temp; }
return jLiveValueCheckBox(text, dm_fieldLiveValue(field));
}
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 AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
static A printLength(String s, A a) {
print(s, l(a));
return a;
}
static A printLength(A a) {
return printLength("", a);
}
// rulesMechListName = "" => default rules & facts
static List nlLogic_processInputOrFact(String input, boolean inputAsFact, String rulesMechListName) {
return nlLogic_processInputOrFact(input, inputAsFact,
eq(rulesMechListName, "")
? ai_activeRulesAndFacts()
: pair(ai_rulesFromMechList(trim(rulesMechListName)), emptyList(String.class)));
}
static ThreadLocal nlLogic_processInputOrFact_allowUnsafeEvals = new ThreadLocal();
static List nlLogic_processInputOrFact(String input, boolean inputAsFact, Pair, List> rulesAndFacts) {
NLLogicChecker_v3 c = new NLLogicChecker_v3();
if (!inputAsFact) c.input = input;
c.facts = reversed(rulesAndFacts.b);
if (inputAsFact) c.facts = concatLists(ll(input), c.facts);
c.rules = reversed(rulesAndFacts.a); // latest rules first!
if (!inputAsFact)
c.rules = filter(c.rules , new F1() { Boolean get(IfThen r) { try { return ai_ruleAccessesInput(r); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ai_ruleAccessesInput(r)"; }});
if (!isTrue(nlLogic_processInputOrFact_allowUnsafeEvals.get()))
c.rules = nlLogic_safeLHSEvalsOnly/*_verbose*/(c.rules);
print("Have " + n2(rulesAndFacts.a, "rule"));
c.useIterate = true;
//c.staticVerbose = true;
List battleSpace = new ArrayList();
nlLogic_fillBattleSpace(c, battleSpace, false);
//print("l=" + l(battleSpace));
return map("nlLogic_executedRuleFromRuleWithParams",battleSpace);
}
static String or2(String a, String b) {
return nempty(a) ? a : b;
}
static String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
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 void _close(AutoCloseable c) {
if (c != null) try {
c.close();
} catch (Throwable e) {
// Some classes stupidly throw an exception on double-closing
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else throw rethrow(e);
}
}
static void dm_useLocallyCopiedMechLists() {
dm_requireModule("#1016073/MechLists");
useLocalMechListCopies(true);
setOptMC("serverMechList_raw_fresh_verbose" , true);
setOptMC("mechList_goToCreator_dont" , true);
}
// get purpose 1: access a list/array/map (safer version of x.get(y))
static A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
// seems to conflict with other signatures
/*static B get(Map map, A key) {
ret map != null ? map.get(key) : null;
}*/
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o == null) return null;
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
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 LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
static Map nullIfEmpty(Map map) {
return isEmpty(map) ? null : map;
}
static List nullIfEmpty(List l) {
return isEmpty(l) ? null : l;
}
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 void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null) map.put(key, value);
}
static String nlLogic_failureLevelString(ExecutedRule r) {
int n = r.failureLevel();
return n == 0 ? null : n < 0 ? "?" : str(n);
}
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 boolean empty(File f) { return getFileSize(f) == 0; }
static List allToString(Collection c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
static List allToString(Object[] c) {
List l = new ArrayList();
for (Object o : unnull(c)) l.add(str(o));
return l;
}
static List simpleSpaces3(List tok) {
tok = cloneList(tok);
for (int i = 0; i < l(tok); i += 2)
if (nempty(tok.get(i))) tok.set(i, " ");
return tok;
}
static String simpleSpaces3(String s) {
return empty(s) ? s : join(simpleSpaces3(javaTok(s)));
}
static String strOrNull(Object o) {
return o == null ? null : str(o);
}
static Object swing(Object f) {
return swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
static JPanel centerAndNorth(final Component c, final Component n) {
return swing(new F0() { JPanel get() { try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.NORTH, wrap(n));
return panel;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT..."; }});
}
static JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) {
for (Object o : parts)
panel.add(wrapForSmartAdd(o), layout);
return panel;
}
static JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) {
return smartAddWithLayout(panel, layout, asList(flattenArray2(parts)));
}
static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static Component jrigid() {
return javax.swing.Box.createRigidArea(new Dimension(0, 0));
}
static ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static ArrayList asList(int[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(float[] a) {
if (a == null) return null;
ArrayList l = emptyList(a.length);
for (float 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(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null) while ((a = p.next()) != null)
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 JComboBox jLiveValueComboBox(Collection values, final SimpleLiveValue lv) {
final JComboBox cb = jComboBox(values);
bindComboBoxToLiveValue(cb, lv);
return cb;
}
static SimpleLiveValue dm_fieldLiveValue(String fieldName) {
return dm_fieldLiveValue(dm_current_mandatory(), fieldName);
}
static SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) {
Lock __36 = module.lock; lock(__36); try {
Class type = getFieldType(module, fieldName);
final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName));
module.onChange(new Runnable() { public void run() { try {
Object o = get(module, fieldName);
value.set(o);
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting \" + fi..."; }});
value.onChange(new Runnable() { public void run() { try {
module.setField(fieldName, value.get());
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting 2 \" + ..."; }});
return value;
} finally { unlock(__36); } }
static A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), c);
return c;
}
static Object callOpt(Object o) {
return callF(o);
}
static A callOpt(Object o, String method, Object... args) {
return (A) callOpt_cached(o, method, args);
}
static JScrollPane jscroll(final Component c) {
return swing(new F0() { JScrollPane get() { try { return new JScrollPane(c); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret new JScrollPane(c);"; }});
}
static JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
static JLabel jlabel() {
return jlabel(" ");
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
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 C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static void callF(VF1 f, A a) {
if (f != null) f.get(a);
}
static Object callF(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 messageBox(final String msg) {
if (headless()) print(msg);
else { swing(new Runnable() { public void run() { try {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES..."; }}); }
}
static void messageBox(Throwable e) {
//showConsole();
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
static ActionListener actionListener(final Object runnable) {
return actionListener(runnable, null);
}
static ActionListener actionListener(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener) return (ActionListener) runnable;
final Object info = _threadInfo();
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { try {
_threadInheritInfo(info);
AutoCloseable __71 = holdInstance(instanceToHold); try {
callF(runnable);
} finally { _close(__71); }} catch (Throwable __e) { messageBox(__e); }}};
}
static KeyListener enterKeyListener(final Object action) {
return new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER)
pcallF(action);
}
};
}
static Runnable rCallOnSelectedListItem(final JList list, final Object action) {
return new Runnable() { public void run() { try { pcallF(action, getSelectedItem(list)) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, getSelectedItem(list))"; }};
}
static AbstractAction abstractAction(String name, final Object runnable) {
return new AbstractAction(name) {
public void actionPerformed(ActionEvent evt) {
pcallF(runnable);
}
};
}
static JTextField jLiveValueTextField_bothWays(final SimpleLiveValue lv) {
final JTextField ta = jTextField();
bindTextComponentToLiveValue_bothWays(ta, lv);
return ta;
}
static Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
static Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static void _handleError(Error e) {
call(javax(), "_handleError", e);
}
static JPanel jrightAlignedLine(final Component... components) {
return swing(new F0() { RightAlignedLine get() { try { return new RightAlignedLine(components); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret RightAlignedLine(components);"; }});
}
static JPanel jrightAlignedLine(List extends Component> components) {
return jrightAlignedLine(asArray(Component.class, components));
}
static ChangeListener changeListener(final Object r) {
return new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(r);
}
};
}
static ItemListener itemListener(final Object r) {
return new ItemListener() {
public void itemStateChanged(ItemEvent e) {
pcallF(r);
}
};
}
// action = runnable or method name
static void onUpdate(JComponent c, final Object r) {
if (c instanceof JTextComponent)
((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
call(r);
}
public void removeUpdate(DocumentEvent e) {
call(r);
}
public void changedUpdate(DocumentEvent e) {
call(r);
}
});
else if (c instanceof ItemSelectable) // JCheckBox and others
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
call(r);
}
});
else
print("Warning: onUpdate doesn't know " + getClassName(c));
}
static void onUpdate(List extends JComponent> l, Object r) {
for (JComponent c : l)
onUpdate(c, r);
}
static boolean isEditableComboBox(final JComboBox cb) {
return cb != null && swing(new F0() { Boolean get() { try { return cb.isEditable(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret cb.isEditable();"; }});
}
static JTextField textFieldFromComboBox(JComboBox cb) {
return (JTextField) cb.getEditor().getEditorComponent();
}
static JComboBox onSelectedItem(final JComboBox cb, final VF1 f) {
addActionListener(cb, new Runnable() { public void run() { try {
pcallF(f, selectedItem(cb))
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(f, selectedItem(cb))"; }});
return cb;
}
static Map humanizeFormLabel_replacements = litmap("id" , "ID", "md5" , "MD5");
static String humanizeFormLabel(String s) {
if (containsSpace(s)) return s;
return firstToUpper(
joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID")
);
}
static boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static JCheckBox jLiveValueCheckBox(String text, final SimpleLiveValue lv) {
final JCheckBox cb = jCheckBox(text);
bindCheckBoxToLiveValue(cb, lv);
return cb;
}
static boolean containsIgnoreCase(Collection l, String s) {
if (l != null) for (String x : l)
if (eqic(x, s))
return true;
return false;
}
static boolean containsIgnoreCase(String[] l, String s) {
if (l != null) for (String x : l)
if (eqic(x, s))
return true;
return false;
}
static boolean containsIgnoreCase(String s, char c) {
return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}
static boolean containsIgnoreCase(String a, String b) {
return indexOfIgnoreCase(a, b) >= 0;
}
static boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x)
if (eq(a, o))
return true;
return false;
}
static boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null) return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); }};
}
static 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_okInCleanUp();
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)
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static 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)
: o instanceof boolean[] ? l((boolean[]) o)
: o instanceof byte[] ? l((byte[]) o)
: o instanceof char[] ? l((char[]) o)
: o instanceof short[] ? l((short[]) o)
: o instanceof int[] ? l((int[]) o)
: o instanceof float[] ? l((float[]) o)
: o instanceof double[] ? l((double[]) o)
: o instanceof long[] ? l((long[]) o)
: (Integer) call(o, "size");
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || b != null && a.equals(b);
}
static Pair, List> ai_activeRulesAndFacts() {
return ai_activeRulesAndFacts(null);
}
static Pair, List> ai_activeRulesAndFacts(List extraFacts) {
long _startTime_28 = sysNow();
List facts = concatLists_conservative(extraFacts, 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
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 (String listName : mL("Default active scripts"))
addAll(rules, nlLogic_loadMechScript(listName));
nlLogic_expandMacros(rules);
done2_always("ai_activeRulesAndFacts", _startTime_28);
return pair(rules, facts);
}
static Pair pair(A a, B b) {
return new Pair(a, b);
}
static Pair pair(A a) {
return new Pair(a, a);
}
static List ai_rulesFromMechList(String listName) {
return ai_parseRulesWithMacros(mL_raw(listName));
}
static ArrayList emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
// Try to match capacity
static ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
// get correct type at once
static ArrayList emptyList(Class c) {
return new ArrayList();
}
static List reversed(Collection l) {
return reversedList(l);
}
static List reversed(A[] l) {
return reversedList(asList(l));
}
static String reversed(String s) {
return reversedString(s);
}
static List concatLists(Collection ... lists) {
List l = new ArrayList();
for (Collection list : lists)
if (list != null)
l.addAll(list);
return l;
}
static List concatLists(Collection extends Collection > lists) {
List l = new ArrayList();
for (Collection list : lists)
if (list != null)
l.addAll(list);
return l;
}
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;
}
static List filter(Object pred, Iterable c) {
return filter(c, pred);
}
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;
}
static List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
// OLD version
static boolean ai_ruleAccessesInput(String rule) {
List tok = javaTokC(rule);
String t;
if (contains(tok, "ai_input")) return true;
for (int i = 0; i < l(tok); i++)
if (eqGet(tok, i+1, "(") && isIdentifier(t = tok.get(i)))
if (eq(t, "i") || swic(t, "input") || ewic(t, "input")) return true;
return false;
}
// NEW version
static boolean ai_ruleAccessesInput(IfThen rule) {
final Flag flag = new Flag();
nlLogic_visit(rule.in, new VF1() { public void get(Object o) { try {
if (o instanceof Func) {
String t = ((Func) o).name;
if (eqOneOf(t, "i", "phrase") || swic(t, "input") || ewic(t, "input"))
flag.raise();
}
if (o instanceof Exp)
if (jcontains(((Exp) o).text(), "ai_input()")) flag.raise();
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (o cast Func) {\r\n S t = o.name;\r\n if (eqOneOf(t, \"i\", \"phrase\") ..."; }});
return flag.isUp();
}
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
if (o instanceof ThreadLocal)
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static List nlLogic_safeLHSEvalsOnly(List rules) {
return filter("nlLogic_allLHSEvalsSafe",rules);
}
static String n2(long l) { return formatWithThousands(l); }
static String n2(Collection l) { return n2(l(l)); }
static String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
static String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
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 void nlLogic_fillBattleSpace(NLLogicChecker_v2 c, final List battleSpace, boolean debug) {
VF2 onRuleFired = new VF2() { public void get(IfThen rule, NLLogicChecker_v2.Matching m) { try {
battleSpace.add(new RuleWithParams(rule, m.matches));
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "battleSpace.add(new RuleWithParams(rule, m.matches));"; }};
if (c.useIterate) {
print("Iterating over " + n2(c.rules, "rule"));
applyNLLogicFacts_v4_iterate_verbose.set(debug);
applyNLLogicFacts_v4_iterate(c, onRuleFired, c.rules);
} else {
applyNLLogicFacts_v4_verbose.set(debug);
applyNLLogicFacts_v4(c, onRuleFired, c.rules);
}
}
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(Iterable l, F1 f) { return map(f, l); }
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 ExecutedRule nlLogic_executedRuleFromRuleWithParams(RuleWithParams r) {
return nlLogic_executedRuleFromRuleWithParams(r, null);
}
static ExecutedRule nlLogic_executedRuleFromRuleWithParams(RuleWithParams r, NLLogicChecker_v2 logicChecker) {
List l = nlLogic_unrollAndApplyRuleWithParams(r);
if (r instanceof FailedRule) {
ExecutedRule e = new ExecutedRule();
e.logicChecker = logicChecker;
e.rule = ((FailedRule) r);
assertNotNull(((FailedRule) r).remainingCondition);
return e;
}
ExecutedRule e = new ExecutedRule(r,
nlLogic_certainOperatorArgs(l, "output", "say"),
nlLogic_certainOperatorArgs(l, "fact"),
nlLogic_certainOperatorArgs(l, "input"));
e.logicChecker = logicChecker;
return e;
}
static boolean nempty(Collection c) {
return !empty(c);
}
static boolean nempty(CharSequence s) {
return !empty(s);
}
static boolean nempty(Object[] o) { return !empty(o); }
static boolean nempty(byte[] o) { return !empty(o); }
static boolean nempty(int[] o) { return !empty(o); }
static boolean nempty(Map m) {
return !empty(m);
}
static boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static boolean nempty(Object o) { return !empty(o); }
// makes dynamic & static modules
static String dm_requireModule(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
static boolean useLocalMechListCopies_flag;
static boolean useLocalMechListCopies() {
return useLocalMechListCopies_flag;
}
static void useLocalMechListCopies(boolean flag) {
useLocalMechListCopies_flag = flag;
if (flag) mechMode().readMode = "localCopies";
}
static void setOptMC(String field, Object value) {
setOpt(mc(), field, value);
}
static Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
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 boolean isEmpty(Collection c) {
return c == null || c.isEmpty();
}
static boolean isEmpty(CharSequence s) {
return s == null || s.length() == 0;
}
static boolean isEmpty(Object[] a) { return a == null || a.length == 0; }
static boolean isEmpty(byte[] a) { return a == null || a.length == 0; }
static boolean isEmpty(Map map) {
return map == null || map.isEmpty();
}
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 getType(Object o) {
return getClassName(o);
}
static long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static String unnull(String s) {
return s == null ? "" : s;
}
static Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
//ifclass Symbol
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);
}
}
// 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 void swingAndWait(Runnable r) { try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) { throw rethrow(__e); } }
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();
}
}
static Component wrapForSmartAdd(Object o) {
if (o == null) return jpanel();
if (o instanceof String) return jlabel((String) o);
return wrap(o);
}
static Object[] flattenArray2(Object... a) {
List l = new ArrayList();
if (a != null) for (Object x : a)
if (x instanceof Object[])
l.addAll(asList((Object[]) x));
else if (x instanceof Collection)
l.addAll((Collection) x);
else
l.add(x);
return asObjectArray(l);
}
static JComboBox jComboBox(final String... items) {
return jcombobox(items);
}
static JComboBox jComboBox(Collection items) {
return jcombobox(items);
}
static ThreadLocal bindComboBoxToLiveValue_debug = new ThreadLocal();
static A bindComboBoxToLiveValue(final A cb, final SimpleLiveValue lv) {
final boolean debug = isTrue(bindComboBoxToLiveValue_debug.get());
bindLiveValueListenerToComponent(cb, lv, new Runnable() { public void run() { try { selectItem(cb, lv.get()) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "selectItem(cb, lv.get())"; }});
onChange(cb, new Runnable() { public void run() { try {
String s = getText(cb); // also works on editable combo boxes
if (debug)
print("ComboBox: " + s);
lv.set(s);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "String s = getText(cb); // also works on editable combo boxes\r\n if (debug)..."; }});
return cb;
}
static DynModule dm_current_mandatory() {
return assertNotNull("No module set!", dm_currentModule());
}
static void lock(Lock lock) { try {
ping();
if (lock == null) return;
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
print("Locking interrupted! I probably deadlocked, oops.");
printStackTrace(e);
rethrow(e);
}
ping();
} catch (Exception __e) { throw rethrow(__e); } }
static void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static ReentrantLock lock() {
return fairLock();
}
static Class getFieldType(Object o, String field) {
return fieldType(o, field);
}
static void unlock(Lock lock, String msg) {
if (lock == null) return;
print("Unlocking: " + msg);
lock.unlock();
}
static void unlock(Lock lock) {
if (lock == null) return;
lock.unlock();
}
static A vm_generalMap_get(Object key) {
return (A) vm_generalMap().get(key);
}
static final Map callOpt_cache = newDangerousWeakHashMap();
static Object callOpt_cached(Object o, String methodName, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
// TODO: (super-rare) case where method exists static and non-static
// with different args
Method me = cache.findMethod(methodName, args);
if (me == null || (me.getModifiers() & Modifier.STATIC) == 0) return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(methodName, args);
if (me == null) return null;
return invokeMethod(me, o, args);
}
} catch (Exception __e) { throw rethrow(__e); } }
static _MethodCache callOpt_getCache(Class c) {
synchronized(callOpt_cache) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
}
static A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () { A get() { try { return nuObject(c, args); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret nuObject(c, args);"; }});
}
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 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 boolean headless() {
return isHeadless();
}
static Throwable printStackTrace(Throwable e) {
// we go to system.out now - system.err is nonsense
print(getStackTrace(e));
return e;
}
static void printStackTrace() {
printStackTrace(new Throwable());
}
static void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); }
static String hideCredentials(String url) {
return url.replaceAll("([&?])(_pass|key)=[^&\\s\"]*", "$1$2=");
}
static String hideCredentials(Object o) {
return hideCredentials(str(o));
}
static Throwable innerException2(Throwable e) {
if (e == null) return null;
while (empty(e.getMessage()) && e.getCause() != null)
e = e.getCause();
return e;
}
static List> _threadInfo_makers = synchroList();
static Object _threadInfo() {
if (empty(_threadInfo_makers)) return null;
HashMap map = new HashMap();
pcallFAll(_threadInfo_makers, map);
return map;
}
static List> _threadInheritInfo_retrievers = synchroList();
static void _threadInheritInfo(Object info) {
if (info == null) return;
pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
static ThreadLocal < List < Object > > holdInstance_l = new ThreadLocal();
static AutoCloseable holdInstance(Object o) {
if (o == null) return null;
listThreadLocalAdd(holdInstance_l, o);
return new AutoCloseable() {
public void close() {
listThreadLocalPopLast(holdInstance_l);
}
};
}
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 String getSelectedItem(JList l) {
return (String) l.getSelectedValue();
}
static String getSelectedItem(JComboBox cb) {
return strOrNull(cb.getSelectedItem());
}
static JTextField jTextField() {
return jTextField("");
}
static JTextField jTextField(final String text) {
return swing(new F0() { JTextField get() { try {
JTextField tf = new JTextField(unnull(text));
standardTextFieldPopupMenu(tf);
jenableUndoRedo(tf);
tf.selectAll();
return tf;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JTextField tf = new JTextField(unnull(text));\r\n standardTextFieldPopupMenu..."; }});
}
static JTextField jTextField(Object o) {
return jTextField(strOrEmpty(o));
}
static A bindTextComponentToLiveValue_bothWays(final A tc, final SimpleLiveValue lv) {
bindLiveValueListenerToComponent(tc, lv, new Runnable() { public void run() { try { setTextKeepCaret(tc, lv.get()) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "setTextKeepCaret(tc, lv.get())"; }});
onChange(tc, new Runnable() { public void run() { try { lv.set(getText(tc)) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lv.set(getText(tc))"; }});
return tc;
}
static String defaultThreadName_name;
static String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
// runnable = Runnable or String (method name)
static Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
static Thread newThread(Object runnable, String name) {
if (name == null) name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
static Runnable toRunnable(final Object o) {
if (o instanceof Runnable) return (Runnable) o;
return new Runnable() { public void run() { try { callF(o) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; }};
}
static Map _registerThread_threads;
static Object _onRegisterThread; // voidfunc(Thread)
static Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static void _registerThread() { _registerThread(Thread.currentThread()); }
static A call(Object o) {
return (A) callF(o);
}
// varargs assignment fixer for a single string array argument
static A call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static A call(Object o, String method, Object... args) {
return (A) call_cached(o, method, args);
}
static Class javax() {
return getJavaX();
}
static Object[] asArray(List l) {
return toObjectArray(l);
}
static A[] asArray(Class type, List l) {
return (A[]) l.toArray((Object[]) Array.newInstance(type, l.size()));
}
static void addActionListener(JTextField tf, final Runnable action) {
onEnter(tf, action);
}
static void addActionListener(final JComboBox cb, final Runnable action) {
if (cb != null) { swing(new Runnable() { public void run() { try {
cb.addActionListener(actionListener(action));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.addActionListener(actionListener(action));"; }}); }
}
static void addActionListener(final AbstractButton b, final Runnable action) {
if (b != null) { swing(new Runnable() { public void run() { try {
b.addActionListener(actionListener(action));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "b.addActionListener(actionListener(action));"; }}); }
}
static String selectedItem(JList l) {
return getSelectedItem(l);
}
static String selectedItem(JComboBox cb) {
return getSelectedItem(cb);
}
static boolean containsSpace(String s) {
return containsSpaces(s);
}
static String firstToUpper(String s) {
if (empty(s)) return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
static String joinWithSpace(Collection c) {
return join(" ", c);
}
static String joinWithSpace(String... c) {
return join(" ", c);
}
static List replaceElementsUsingMap(Iterable l, final Map map) {
return map(l, new F1 () { A get(A a) { try { return getOrKeep(map, a); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "getOrKeep(map, a)"; }});
}
static List splitCamelCase(String s) {
return ai_splitCamelCase(s);
}
static boolean isJavaIdentifier(String s) {
if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < s.length(); i++)
if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
static JCheckBox jCheckBox() {
return swingNu(JCheckBox.class);
}
static JCheckBox jCheckBox(boolean checked) {
return swingNu(JCheckBox.class, "", checked);
}
static JCheckBox jCheckBox(String text, boolean checked) {
return swingNu(JCheckBox.class, text, checked);
}
static JCheckBox jCheckBox(String text) {
return swingNu(JCheckBox.class, text);
}
static JCheckBox jCheckBox(String text, boolean checked, final Object onChange) {
JCheckBox cb = jCheckBox(checked, onChange);
cb.setText(text);
return cb;
}
// onChange can be a Runnable or a voidfunc(bool)
static JCheckBox jCheckBox(boolean checked, final Object onChange) {
final JCheckBox cb = jCheckBox(checked);
cb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
pcallF(onChange, cb.isSelected());
}
});
return cb;
}
static A bindCheckBoxToLiveValue(final A cb, final SimpleLiveValue lv) {
bindLiveValueListenerToComponent(cb, lv, new Runnable() { public void run() { try {
setChecked(cb, isTrue(lv.get()));
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: se..."; }});
onChange(cb, new Runnable() { public void run() { try {
lv.set(isChecked(cb));
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef bindCheckBoxToLiveValue_debug\r\n print(\"bindCheckBoxToLiveValue: se..."; }});
return cb;
}
static boolean eqic(String a, String b) {
if ((a == null) != (b == null)) return false;
if (a == null) return true;
return a.equalsIgnoreCase(b);
}
static boolean eqic(char a, char b) {
if (a == b) return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2) return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
// works on lists and strings and null
static int indexOfIgnoreCase(List a, String b) {
return indexOfIgnoreCase(a, b, 0);
}
static int indexOfIgnoreCase(List a, String b, int i) {
int n = l(a);
for (; i < n; i++)
if (eqic(a.get(i), b)) return i;
return -1;
}
static int indexOfIgnoreCase(String a, String b) {
return indexOfIgnoreCase_manual(a, b);
/*Matcher m = Pattern.compile(b, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(a);
if (m.find()) return m.start(); else ret -1;*/
}
static A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null) return null;
A old = tl.get();
tl.set(value);
return old;
}
static boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1));
}
static void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions )
ping_impl(true);
}
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 long sysNow() {
ping();
return System.nanoTime()/1000000;
}
static List concatLists_conservative(List a, List b) {
if (empty(a)) return b;
if (empty(b)) return a;
return concatLists(a, b);
}
static List mL_facts() {
return concatLists(mL("Random facts"), mL("Derived facts"));
}
static List ai_unparsedTalkRules() {
return splitAtEmptyLines(mL_raw("NL Logic Examples"));
}
static List mL(String name) {
return mechList_opt(name);
}
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);
}
static IfThen nlLogic_parseRule(String s) {
IfThen rule = new IfThen();
rule.originalText = s;
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 || l(l) == 0) return null;
rule.out = nlLogic_parseExpression(last(l));
rule.in = nlLogic_parseExpression(nextToLast(l));
if (rule.globalID == null)
//rule.globalID = aGlobalID();
rule.globalID = textMD5ToGlobalID(str(rule));
return rule;
}
// f: A -> Comparable
static List sortedByCalculatedField(Iterable c, Object f) {
return sortByCalculatedField(c, f);
}
static List sortedByCalculatedField(Object f, Iterable c) {
return sortedByCalculatedField(c, f);
}
static boolean jcontains(String s, String pat) {
return jfind(s, pat) >= 0;
}
static boolean jcontains(List tok, String pat) {
return jfind(tok, pat) >= 0;
}
static 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 void addAll(Collection c, Iterable b) {
if (c != null && b != null) for (A a : b) c.add(a);
}
static boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static boolean addAll(Collection c, B... b) {
return c != null && c.addAll(Arrays.asList(b));
}
static List nlLogic_loadMechScript(String listName) {
List out = new ArrayList();
Matches m = new Matches();
String scriptID = "";
for (String s : splitAtEmptyLines(mL_raw(listName))) { try {
if (match("this is script *", s, m))
{ scriptID = m.unq(0) + "-"; continue; }
IfThen rule = nlLogic_parseRule(s);
if (rule != null)
out.add(rule);
else
print("Couldn't parse: " + s);
} catch (Throwable __e) { _handleException(__e); }}
nlLogic_setScriptID(out, scriptID);
return out;
}
static Map nlLogic_expandMacros_funcShortNames = litmap(
"o", "output",
"i", "input");
// changes original rules
static void nlLogic_expandMacros(List rules) {
for (IfThen rule : unnull(rules)) { try {
nlLogic_expandMacros(rule);
} catch (Throwable __e) { _handleException(__e); }}
}
static IfThen nlLogic_expandMacros(IfThen r) {
if (r == null) return r;
int varCount = 0;
String rendered;
do {
ping();
rendered = str(r);
nlLogic_visit(r, new VF1() { public void get(Object o) { try {
if (o instanceof Func) {
String name = nlLogic_expandMacros_funcShortNames.get(((Func) o).name);
if (name != null) ((Func) o).name = name;
}
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (o cast Func) {\r\n S name = nlLogic_expandMacros_funcShortNames.get(..."; }});
Exp out = r.out;
if (out instanceof Func) {
String name = ((Func) out).name;
if (eq(name, "sayIfTrue")) {
r.out = new Func("output", ((Func) out).arg);
r.in = new And(r.in, new Func("fact", ((Func) out).arg));
} else if (eq(name, "inputToFact")) {
r.out = new Func("fact", ((Func) out).arg);
r.in = nlLogic_and(new Func("input", restructure(((Func) out).arg)), r.in);
} else if (eqOneOf(name, "outputEval", "evalOutput")) {
String var = "$_" + ++varCount;
r.out = new Func("output", new Sentence2(var));
r.in = new And(r.in, new Eq(new Sentence2(var), new Func("eval", ((Func) out).arg)));
//print("Rewritten rule => " + sfu(r));
} else if (eq(name, "output")) {
do {
// in: output(... $x1, $x2 [...] and $x_n ...)
String pat = "*, * [...] * *";
T3 t = jextractWithRests(pat, ((Func) out).argText());
if (t == null) break;
Matches m = new Matches();
List tok = javaTok(t.b);
if (!jmatch(pat, tok, m)) break;
String x1 = m.get(0);
if (!isDollarVar(x1) || !endsWith(x1, "1")) { print("x1"); break; }
String x = dropSuffix("1", x1);
if (!eq(m.get(1), x + "2")) { print("x2"); break; }
//S lastSep = m.get(2);
if (!eq(m.get(3), x + "_n")) { print("x_n"); break; }
// out: outputEval(joinWithComma_specialLast((LS) call(ai_context(), 'getList, "x"), " and "))
((Func) out).name = "outputEval";
((Func) out).arg = new Sentence2(quote(t.a) + " + joinWithComma_specialLast((LS) call(ai_context(), 'getList, " + quote(x) + "), "
+ quote(joinSubList(tok, l(tok)-5, l(tok)-2)) + ")"
+ " + " + quote(t.c));
} while (false);
}
}
// LHS only
nlLogic_visit(r.in, new VF1() { public void get(Object o) { try {
// english a/an magic
if (o instanceof Func)
if (eqOneOf(((Func) o).name, "input", "fact")) {
if (contains(((Func) o).options, "re"))
((Func) o).arg = new Sentence2(ctxREToJavaRE(ctxExpandMacros(((Func) o).arg.text(), ctxMacros())));
else {
String s = ai_expandPatternForAAndAn(((Func) o).arg.text());
if (s != null)
((Func) o).arg = new Sentence2(s);
}
} else if (eq(((Func) o).name, "unresolvedFact")) {
((Func) o).name = "fact";
((Func) o).arg = new Sentence2("Unresolved fact: " + ((Func) o).arg.text());
} else if (eq(((Func) o).name, "evalTrue")) {
((Func) o).name = "eval";
((Func) o).arg = new Sentence2(tok_addSemicolon(((Func) o).arg.text()) + " ret true;");
}
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "// english a/an magic\r\n if (o cast Func)\r\n if (eqOneOf(o.name, 'i..."; }});
} while (neq(rendered, str(r)));
return r;
}
static long done2_always(long startTime, String desc) {
long time = sysNow()-startTime;
print(desc + " [" + time + " ms]");
return time;
}
static long done2_always(String desc, long startTime) {
return done2_always(startTime, desc);
}
static long done2_always(long startTime) {
return done2_always(startTime, "");
}
static List ai_parseRulesWithMacros(String s) {
return map("nlLogic_expandMacros",ai_parseRules(s));
}
static int max(int a, int b) { return Math.max(a, b); }
static int max(int a, int b, int c) { return max(max(a, b), c); }
static long max(int a, long b) { return Math.max((long) a, b); }
static long max(long a, long b) { return Math.max(a, b); }
static double max(int a, double b) { return Math.max((double) a, b); }
static float max(float a, float b) { return Math.max(a, b); }
static double max(double a, double b) { return Math.max(a, b); }
static int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static double max(double[] c) {
if (c.length == 0) return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static float max(float[] c) {
if (c.length == 0) return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x) x = d;
return x;
}
static short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x) x = d;
return x;
}
static int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x) x = d;
return x;
}
static List reversedList(Collection l) {
List x = cloneList(l);
Collections.reverse(x);
return x;
}
static String reversedString(String s) {
return reverseString(s);
}
static List javaTokC(String s) {
if (s == null) return null;
int l = s.length();
ArrayList tok = new ArrayList();
int i = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !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) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
i = j;
}
return tok;
}
static boolean eqGet(List l, int i, Object o) {
return eq(get(l, i), o);
}
static boolean eqGet(Map map, A key, Object o) {
return eq(mapGet(map, key), o);
}
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 ewic(String a, String b) {
return endsWithIgnoreCase(a, b);
}
static boolean ewic(String a, String b, Matches m) {
return endsWithIgnoreCase(a, b, m);
}
static void nlLogic_visit(IfThen rule, VF1 visitor) {
if (rule == null) return;
callF(visitor, rule);
nlLogic_visit(rule.in, visitor);
nlLogic_visit(rule.out, visitor);
}
static void nlLogic_visit(Exp e, VF1 visitor) {
if (e == null) return;
callF(visitor, e);
if (e instanceof And) {
nlLogic_visit(((And) e).a, visitor);
nlLogic_visit(((And) e).b, visitor);
} else if (e instanceof ExpNot)
nlLogic_visit(((ExpNot) e).a, visitor);
else if (e instanceof Func)
nlLogic_visit(((Func) e).arg, visitor);
}
static void nlLogic_visit(Collection l, VF1 visitor) {
for (Object o : unnull(l)) nlLogic_visit(o, visitor);
}
static void nlLogic_visit(Object o, VF1 visitor) {
if (o instanceof Exp) nlLogic_visit(((Exp) o), visitor);
if (o instanceof IfThen) nlLogic_visit(((IfThen) o), visitor);
if (o instanceof Collection) nlLogic_visit(((Collection) o), visitor);
}
static boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x)) return true; return false;
}
static boolean nlLogic_allLHSEvalsSafe(IfThen rule) {
for (String code : nlLogic_allLHSEvalFragments(rule))
if (!isSafeCodeFragment(code)) return false;
return true;
}
static String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
static double fraction(double d) {
return d % 1;
}
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 ThreadLocal applyNLLogicFacts_v4_iterate_verbose = new ThreadLocal();
static void applyNLLogicFacts_v4_iterate(String input, VF2 onRuleFired) {
applyNLLogicFacts_v4_iterate(input, onRuleFired, mL_facts());
}
static void applyNLLogicFacts_v4_iterate(String input, VF2 onRuleFired, List facts) {
applyNLLogicFacts_v4_iterate(input, onRuleFired, facts, ai_mL_parsedLogicExamples2());
}
static void applyNLLogicFacts_v4_iterate(String input, VF2 onRuleFired, List facts, List rules) {
NLLogicChecker_v2 c = new NLLogicChecker_v2();
c.matcher = new NLStringMatcher_dollarVars();
addAll(c.facts, facts);
c.input = input;
applyNLLogicFacts_v4_iterate(c, onRuleFired, rules);
}
static void applyNLLogicFacts_v4_iterate(final NLLogicChecker_v2 c, final VF2 onRuleFired, List rules) {
c.rules = rules;
for (final IfThen rule : rules) { try {
final NLLogicChecker_v2.Matching m = new NLLogicChecker_v2.Matching();
m.verbose = isTrue(applyNLLogicFacts_v4_iterate_verbose.get());
if (m.verbose)
print("Checking rule (iterating): " + rule);
c.iterate(rule.in, m, new Runnable() { public void run() { try {
if (m.verbose) {
print("Matched " + quote(c.input) + " with rule " + quote(rule));
printStruct(" ", m.matches);
}
callF(onRuleFired, rule, m);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (m.verbose) {\r\n print(\"Matched \" + quote(c.input) + \" with rule \" +..."; }});
} catch (Throwable __e) { _handleException(__e); }}
}
static ThreadLocal applyNLLogicFacts_v4_verbose = new ThreadLocal();
static void applyNLLogicFacts_v4(String input, VF2 onRuleFired) {
applyNLLogicFacts_v4(input, onRuleFired, mL_facts());
}
static void applyNLLogicFacts_v4(String input, VF2 onRuleFired, List facts) {
applyNLLogicFacts_v4(input, onRuleFired, facts, ai_mL_parsedLogicExamples2());
}
static void applyNLLogicFacts_v4(String input, VF2 onRuleFired, List facts, List rules) {
NLLogicChecker_v2 c = new NLLogicChecker_v2();
c.matcher = new NLStringMatcher_dollarVars();
addAll(c.facts, facts);
c.input = input;
applyNLLogicFacts_v4(c, onRuleFired, rules);
}
static void applyNLLogicFacts_v4(NLLogicChecker_v2 c, VF2 onRuleFired, List rules) {
c.rules = rules;
for (IfThen rule : rules) { try {
NLLogicChecker_v2.Matching m = new NLLogicChecker_v2.Matching();
m.verbose = isTrue(applyNLLogicFacts_v4_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);
}
} catch (Throwable __e) { _handleException(__e); }}
}
static List nlLogic_unrollAndApplyRuleWithParams(RuleWithParams r) {
List out = new ArrayList();
for (Exp e : nlLogic_unrollAnd(r.rule.out)) {
e = nlLogic_applyMatches(e, r.matches);
if (!nlLogic_checkHelper(e, r.matches)) // changes matches e.g. for newID()
out.add(e);
}
return out;
}
static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static Collection nlLogic_certainOperatorArgs(List l, String... operators) {
HashSet set = lithashset(operators);
LinkedHashSet out = new LinkedHashSet();
for (Exp e : unnull(l)) {
if (e instanceof Func)
if (set.contains(((Func) e).name))
out.add(nlLogic_text(((Func) e).arg));
}
return out;
}
// makes dynamic & static modules - returns module ID
static String dm_makeModule(String moduleLibID) {
return (String) callCreator("makeModule", moduleLibID);
}
static MechMode mechMode_value = new MechMode();
static MechMode mechMode() {
return mechMode_value;
}
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 Class mc() {
return main.class;
}
static Map emptyMap() {
return new HashMap();
}
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;
}
static String javaTok_substringN(String s, int i, int j) {
if (i == j) return "";
if (j == i+1 && s.charAt(i) == ' ') return " ";
return s.substring(i, j);
}
static String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
static List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 0;
while (i < l) {
int j = i;
char c, d;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
d = j+1 >= l ? '\0' : s.charAt(j+1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
i = j;
if (i >= l) break;
c = s.charAt(i);
d = i+1 >= l ? '\0' : s.charAt(i+1);
// scan for non-whitespace
// Special JavaX syntax: 'identifier
if (c == '\'' && Character.isJavaIdentifierStart(d) && i+2 < l && "'\\".indexOf(s.charAt(i+2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j)))
++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't"
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L
} else if (c == '[' && d == '[') {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') {
do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]"));
j = Math.min(j+3, l);
} else
++j;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
javaTok_elements += tok.size();
return tok;
}
static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j-i
&& s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave
}
// TODO: test if android complains about this
static boolean isAWTThread() {
if (isAndroid()) return false;
if (isHeadless()) return false;
return isAWTThread_awt();
}
static boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static Runnable addThreadInfoToRunnable(final Object r) {
final Object info = _threadInfo();
return info == null ? asRunnable(r) : new Runnable() { public void run() { try { _inheritThreadInfo(info); callF(r);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_inheritThreadInfo(info); callF(r);"; }};
}
static JPanel jpanel(LayoutManager layout) {
return swingNu(JPanel.class, layout);
}
static JPanel jpanel() {
return swingNu(JPanel.class);
}
static Object[] asObjectArray(List l) {
return toObjectArray(l);
}
static JComboBox jcombobox(final String... items) {
return swing(new F0() { JComboBox get() { try { return new JComboBox(items); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret new JComboBox(items);"; }});
}
static JComboBox jcombobox(Collection items) {
return jcombobox(toStringArray(items));
}
static A bindLiveValueListenerToComponent(A component, final LiveValue lv, final Runnable listener) {
if (lv != null)
bindToComponent(component,
new Runnable() { public void run() { try {
lv.onChangeAndNow(listener);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ifdef bindLiveValueListenerToComponent_debug\r\n print(\"bindLiveValueL..."; }},
new Runnable() { public void run() { try { lv.removeOnChangeListener(listener) ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "lv.removeOnChangeListener(listener)"; }});
return component;
}
static JComboBox selectItem(final String item, final JComboBox cb) {
if (cb != null) { swing(new Runnable() { public void run() { try { cb.setSelectedItem(item);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cb.setSelectedItem(item);"; }}); }
return cb;
}
static JComboBox selectItem(final JComboBox cb, final String item) {
return selectItem(item, cb);
}
static String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() { Object get() { try { return c.getText(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret c.getText();"; }});
}
static String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new F0() { Object get() { try { return c.getText(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret c.getText();"; }});
}
static String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new F0() { Object get() { try { return l.getText(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret l.getText();"; }});
}
// returns the contents of text field for editable combo box
static String getText(final JComboBox cb) {
if (cb == null) return null;
if (isEditableComboBox(cb))
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
static InheritableThreadLocal < WeakReference < DynModule > > dm_currentModule_value = new InheritableThreadLocal();
static DynModule dm_currentModule() {
return getWeakRef(dm_currentModule_value.get());
}
static void _onLoad_dm_currentModule() {
setOptMC("dm_currentModule_generic", dm_currentModule_value);
}
// prevent memory leak
static void cleanMeUp_dm_currentModule() {
dm_currentModule_value = new InheritableThreadLocal();
}
//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();
static ThreadLocal ping_isCleanUpThread = new ThreadLocal();
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions ) ping_impl(true /* XXX */);
//ifndef LeanMode ping_impl(); endifndef
return true;
}
// returns true when it slept
static boolean ping_impl(boolean okInCleanUp) { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) { // don't allow sharing ping_actions
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized(ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty()) ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) { throw rethrow(__e); } }
static void lockOrFail(Lock lock, long timeout) { try {
ping();
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) ( lock);
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
ping();
} catch (Exception __e) { throw rethrow(__e); } }
static ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static Class fieldType(Object o, String field) {
Field f = getField(o, field);
return f == null ? null : f.getType();
}
static Map vm_generalMap_map;
static Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
static Object nuObject(String className, Object... args) { try {
return nuObject(classForName(className), args);
} catch (Exception __e) { throw rethrow(__e); } }
// too ambiguous - maybe need to fix some callers
/*static O nuObject(O realm, S className, O... args) {
ret nuObject(_getClass(realm, className), args);
}*/
static A nuObject(Class c, Object... args) { try {
if (args.length == 0) return nuObjectWithoutArguments(c); // cached!
Constructor m = nuObject_findConstructor(c, args);
m.setAccessible(true);
return (A) m.newInstance(args);
} catch (Exception __e) { throw rethrow(__e); } }
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!" : ""));
}
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;
}
static List _registerDangerousWeakMap_preList;
static A _registerDangerousWeakMap(A map) {
return _registerDangerousWeakMap(map, null);
}
static A _registerDangerousWeakMap(A map, Object init) {
callF(init, map);
if (init instanceof String) {
final String f = (String) ( init);
init = new VF1() { public void get(Map map) { try { callMC(f, map) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "callMC(f, map)"; }};
}
if (javax() == null) {
// We're in class init
if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList();
_registerDangerousWeakMap_preList.add(pair(map, init));
return map;
}
call(javax(), "_registerDangerousWeakMap", map, init);
return map;
}
static void _onLoad_registerDangerousWeakMap() {
assertNotNull(javax());
if (_registerDangerousWeakMap_preList == null) return;
for (Pair p : _registerDangerousWeakMap_preList)
_registerDangerousWeakMap(p.a, p.b);
_registerDangerousWeakMap_preList = null;
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static List classNames(Collection l) {
return getClassNames(l);
}
static List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static void multiMapPut(Map > map, A a, B b) {
List l = map.get(a);
if (l == null)
map.put(a, l = new ArrayList());
l.add(b);
}
static void multiMapPut(MultiMap mm, A key, B value) {
if (mm != null && key != null && value != null) mm.put(key, value);
}
static Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
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);
}
static Boolean isHeadless_cache;
static boolean isHeadless() {
if (isHeadless_cache != null) return isHeadless_cache;
if (isAndroid()) return isHeadless_cache = true;
if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true;
// Also check if AWT actually works.
// If DISPLAY variable is set but no X server up, this will notice.
try {
SwingUtilities.isEventDispatchThread();
return isHeadless_cache = false;
} catch (Throwable e) { return isHeadless_cache = true; }
}
static String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static List synchroList(List l) {
return Collections.synchronizedList(l);
}
static void pcallFAll(Collection l, Object... args) {
if (l != null) for (Object f : cloneList(l)) pcallF(f, args);
}
static void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static void listThreadLocalAdd(ThreadLocal> tl, A a) {
List l = tl.get();
if (l == null) tl.set(l = new ArrayList());
l.add(a);
}
static A listThreadLocalPopLast(ThreadLocal> tl) {
List l = tl.get();
if (l == null) return null;
A a = popLast(l);
if (empty(l)) tl.set(null);
return a;
}
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); }
return null;
}
static JTextField standardTextFieldPopupMenu(final JTextField tf) {
final WeakReference ref = weakRef(tf);
componentPopupMenuItem(tf, "Copy text to clipboard", new Runnable() { public void run() { try {
copyTextToClipboard(ref.get().getText())
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "copyTextToClipboard(ref.get().getText())"; }});
componentPopupMenuItem(tf, "Paste", new Runnable() { public void run() { try { ref.get().paste() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ref.get().paste()"; }});
return tf;
}
static A jenableUndoRedo(final A textcomp) {
{ swing(new Runnable() { public void run() { try {
final UndoManager undo = new UndoManager();
vm_generalWeakSet("Undo Managers").add(undo);
textcomp.getDocument().addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
textcomp.getActionMap().put("Undo", abstractAction("Undo", new Runnable() { public void run() { try {
if (undo.canUndo()) undo.undo()
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canUndo()) undo.undo()"; }}));
textcomp.getActionMap().put("Redo", abstractAction("Redo", new Runnable() { public void run() { try {
if (undo.canRedo()) undo.redo()
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (undo.canRedo()) undo.redo()"; }}));
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
textcomp.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final new UndoManager undo;\r\n vm_generalWeakSet(\"Undo Managers\").add(undo)..."; }}); }
return textcomp;
}
static String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static A setTextKeepCaret(final String text, final A c) {
if (c != null) { swing(new Runnable() { public void run() { try {
int caret = c.getCaretPosition();
setText(c, text);
setCaretPosition(c, caret);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "int caret = c.getCaretPosition();\r\n setText(c, text);\r\n setCaretPositio..."; }}); }
return c;
}
static A setTextKeepCaret(A c, String text) {
return setTextKeepCaret(text, c);
}
static String programID() {
return getProgramID();
}
static String programID(Object o) {
return getProgramID(o);
}
static Runnable _topLevelErrorHandling(final Runnable runnable) {
final Object info = _threadInfo();
return new Runnable() { public void run() { try {
try {
_threadInheritInfo(info);
runnable.run();
} catch (Throwable __e) { _handleException(__e); }
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }"; }};
}
static Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static Map vm_generalWeakSubMap(Object name) {
synchronized(get(javax(), "generalMap")) {
Map map = (Map) ( vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = newWeakMap());
return map;
}
}
static WeakReference weakRef(A a) {
return newWeakReference(a);
}
static Object call_cached(Object o, String method, Object... args) { try {
if (o == null) return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
// TODO: (super-rare) case where method exists static and non-static
// with different args
Method me = cache.findMethod(method, args);
if (me == null)
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
if ((me.getModifiers() & Modifier.STATIC) == 0)
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not static");
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me == null)
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
return invokeMethod(me, o, args);
}
} catch (Exception __e) { throw rethrow(__e); } }
static Class __javax;
static Class getJavaX() { try {
return __javax;
} catch (Exception __e) { throw rethrow(__e); } }
static boolean containsSpaces(String s) {
return indexOf(s, ' ') >= 0;
}
static A getOrKeep(Map map, A a) {
A v = map.get(a);
return v != null ? v : a;
}
static List ai_splitCamelCase(String s) {
int j = 0;
List l = new ArrayList();
for (int i = 0; i < l(s); i++)
if (isUpperCaseLetter(s.charAt(i)) && i > j) {
l.add(substring(s, j, i));
j = i;
}
if (j < l(s))
l.add(substring(s, j));
return l;
}
static A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static void setChecked(final JCheckBox checkBox, final boolean b) {
if (checkBox != null) { swing(new Runnable() { public void run() { try {
if (isChecked(checkBox) != b)
checkBox.setSelected(b);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (isChecked(checkBox) != b)\r\n checkBox.setSelected(b);"; }}); }
}
static boolean isChecked(final JCheckBox checkBox) {
return checkBox != null && (boolean) swing(new F0() { Boolean get() { try { return checkBox.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret checkBox.isSelected();"; }});
}
static boolean isChecked(final JCheckBoxMenuItem mi) {
return mi != null && (boolean) swing(new F0() { Boolean get() { try { return mi.isSelected(); } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "ret mi.isSelected();"; }});
}
static String asString(Object o) {
return o == null ? null : o.toString();
}
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;
}
static int indexOf(List l, A a, int startIndex) {
if (l == null) return -1;
for (int i = startIndex; i < l(l); i++)
if (eq(l.get(i), a))
return i;
return -1;
}
static int indexOf(List l, int startIndex, A a) {
return indexOf(l, a, startIndex);
}
static int indexOf(List l, A a) {
if (l == null) return -1;
return l.indexOf(a);
}
static int indexOf(String a, String b) {
return a == null || b == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, String b, int i) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, char b) {
return a == null ? -1 : a.indexOf(b);
}
static int indexOf(String a, int i, char b) {
return indexOf(a, b, i);
}
static int indexOf(String a, char b, int i) {
return a == null ? -1 : a.indexOf(b, i);
}
static int indexOf(String a, int i, String b) {
return a == null || b == null ? -1 : a.indexOf(b, i);
}
static int indexOf(A[] x, A a) {
if (x == null) return -1;
for (int i = 0; i < l(x); i++)
if (eq(x[i], a))
return i;
return -1;
}
static List mechList_opt(String name) {
return mechList_opt_tlft(name);
}
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 boolean emptyAfterTrim(String s) {
return empty(trim(s));
}
// 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 List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
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);
}
static List subList(List l, IntRange r) {
return subList(l, r.start, r.end);
}
static ExpiringMap2 mechList_raw_cache = new ExpiringMap2(10000).setMap(ciMap());
static Lock mechList_raw_lock = lock();
// timeout for loading
static int mechList_raw_timeout = 60000;
static String mechList_raw(String name) { try {
Lock __305 = mechList_raw_lock; lock(__305); try {
if (empty(name)) return "";
// get from cache
String src = mechList_raw_cache.get(name);
if (src != null) return src;
// load & put in cache - TODO: make postPage honor this
AutoCloseable __306 = tempSetThreadLocal(loadPage_forcedTimeout_byThread, mechList_raw_timeout); try {
src = mechList_raw_fresh(name);
if (src != null)
mechList_raw_cache.put(name, src);
return src;
} finally { _close(__306); }} finally { unlock(__305); } } catch (Exception __e) { throw rethrow(__e); } }
static VF2 mechList_raw_listener = new VF2() { public void get(String msg, Object arg) { try {
if (eq(msg, "mechChange") && arg instanceof String) {
//print("Got change notification: " + arg);
mechList_raw_cache.remove((String) arg);
}
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (eq(msg, 'mechChange) && arg instanceof S) {\r\n //print(\"Got change noti..."; }};
static void _onLoad_mechList_raw() { add(vm_busListeners_live(), mechList_raw_listener); }
static void cleanMeUp_mechList_raw() { remove(vm_busListeners_live(), mechList_raw_listener); }
static boolean noJavaTokens(String s) {
return numberOfJavaTokens(s) == 0;
}
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) {
if (s == null) return null;
List tok = javaTokPlusAllThreeBrackets(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 with options - a[bla, blubb](...)
if (l(tok) == 7 && isIdentifier(tok.get(1))
&& isSquareBracketed(tok.get(3))
&& isRoundBracketed(tok.get(5)))
return new Func(tok.get(1),
tok_splitAtComma(deSquareBracket(tok.get(3))),
nlLogic_parseExpression(deRoundBracket(tok.get(5))));
// function - a(...)
if (l(tok) == 5 && isIdentifier(tok.get(1)) && isRoundBracketed(tok.get(3))) {
String name = tok.get(1), arg = deRoundBracket(tok.get(3));
boolean parseInnerPart = false;
return new Func(name, parseInnerPart ? nlLogic_parseExpression(arg)
: new Sentence2(unquoteIfNormalQuoted(arg)));
}
// 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 A last(List l) {
return empty(l) ? null : l.get(l.size()-1);
}
static char last(String s) {
return empty(s) ? '#' : s.charAt(l(s)-1);
}
static int last(int[] a) {
return l(a) != 0 ? a[l(a)-1] : 0;
}
static A last(A[] a) {
return l(a) != 0 ? a[l(a)-1] : null;
}
static A last(Iterator it) {
A a = null;
while (it.hasNext()) { ping(); a = it.next(); }
return a;
}
static A nextToLast(List l) {
return get(l, l(l)-2);
}
static String textMD5ToGlobalID(String s) {
return md5ToGlobalID(md5(s));
}
// f: A -> Comparable
static List sortByCalculatedField(Iterable c, final Object f) {
List l = cloneList(c);
sort(l, new Comparator () {
public int compare(A a, A b) {
return stdcompare(callF(f, a), callF(f, b));
}
});
return l;
}
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 volatile PersistableThrowable _handleException_lastException;
static List _handleException_onException = synchroList(ll("printStackTrace2"));
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); // not using pcall here - it could lead to endless loops
}
}
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 void nlLogic_setScriptID(List rules, final String scriptID) {
final Set ids = collectAsHashSet(rules, "globalID");
for (IfThen rule : rules) {
rule.globalID = scriptID + rule.globalID;
mapIntoSameCollection(rule.options, new F1() { String get(String s) { try {
Matches m = new Matches();
for (String pat : splitAtVerticalBar("trumps *|conflicts with"))
if (match(pat, s, m))
return format(pat, scriptID + m.unq(0));
return s;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "new Matches m;\r\n for (S pat : splitAtVerticalBar(\"trumps *|conflicts wit..."; }});
nlLogic_visit(rule, new VF1() { public void get(Object o) { try {
String name;
if (o instanceof Func) {
if (eq(((Func) o).name, "followingUpOn")) {
List tok = javaTok(nlLogic_text(((Func) o).arg));
if (ids.contains(_get(tok, 1))) {
tok.set(1, scriptID + tok.get(1));
((Func) o).arg = new Sentence2(join(tok));
}
}
}
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "S name;\r\n if (o cast Func) {\r\n if (eq(o.name, 'followingUpOn)) {\r..."; }});
}
}
static Exp nlLogic_and(Exp a, Exp b) {
return a == null ? b : b == null ? a : new And(a, b);
}
static Exp nlLogic_and(List l) {
if (empty(l)) return null;
Exp e = last(l);
for (int i = l(l)-2; i >= 0; i--)
e = new And(l.get(i), e);
return e;
}
static