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.awt.datatransfer.StringSelection;
public class main {
static class MyTruth extends Concept {
static String _fieldOrder = "globalID term madeByRule globalID term";
String globalID;
Lisp term;
String madeByRule;
MyTruth() {}
MyTruth(String globalID, Lisp term, String madeByRule) {
this.madeByRule = madeByRule;
this.term = term;
this.globalID = globalID; change(); }
}
static void loadMyTruth() {
db();
for (MyTruth t : list(MyTruth.class))
lispAddLocalTruth(t.globalID, t.term);
}
static void fromUser(String head, Object... args) { fromUser(lisp(head, args)); }
static void fromUser(Lisp l) { emit(l, "user"); }
static void emit(Lisp l, String madeByRule) {
LispStatement s = lispAddLocalTruth(l);
if (s != null)
new MyTruth(s.globalID, l, madeByRule);
}
static void unemit(Lisp l) {
LispStatement s = findLispStatement(l);
if (s == null) return;
removeLispStatement(s);
deleteConcepts(MyTruth.class, "globalID" , s.globalID);
}
static String concepts = "\n mbyttdugcxbjayki - X is a sentence.\n kdcwxggxvwljzqcd - X is a verb.\n lwsqdttlqfrtghme - X is a noun.\n";
public static void main(final String[] args) throws Exception {
useConceptsAndStatements(concepts, "");
loadMyTruth();
printLispStatements();
showControlButtons(
jbutton("Add sentence...", "addSentence"),
jbutton("Add verb...", "addVerb"),
jbutton("Add noun...", "addNoun"));
}
static void addSentence() {
showTextFieldForm("Add sentence", "Sentence", new Object() { void get(String text) { try {
fromUser("mbyttdugcxbjayki", text);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "fromUser(\"mbyttdugcxbjayki\", text);"; }});
}
static void addVerb() {
showTextFieldForm("Add verb", "Verb", new Object() { void get(String text) { try {
fromUser("kdcwxggxvwljzqcd", text);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "fromUser(\"kdcwxggxvwljzqcd\", text);"; }});
}
static void addNoun() {
showTextFieldForm("Add noun", "Noun", new Object() { void get(String text) { try {
fromUser("lwsqdttlqfrtghme", text);
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "fromUser(\"lwsqdttlqfrtghme\", text);"; }});
}
static void useConceptsAndStatements(String concepts, String statements) {
useConcepts(concepts);
useFacts(statements);
}
static void showControlButtons(final List extends Component> components) {
{ swingAndWait(new Runnable() { public void run() { try {
showControls(jcenteredline(components));
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "showControls(jcenteredline(components));"; }}); }
}
static void showControlButtons(Component... components) {
showControlButtons(asList(components));
}
// action: voidfunc(S)
static void showTextFieldForm(final String title, final String name, final Object action) {
swingLater(new Runnable() { public void run() { try {
final JTextField tf = jtextfield();
showFormTitled(title, name, tf, new Runnable() { public void run() { try {
pcallF(action, getTextTrim(tf))
;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcallF(action, getTextTrim(tf))"; }});
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "final JTextField tf = jtextfield();\r\n showFormTitled(title, name, tf, r {\r\n ..."; }});
}
// return new statement or null if it existed
static LispStatement lispAddLocalTruth(Lisp l) {
if (lispTrue(l)) return null;
return lispAddLocalTruth_noCheck(aGlobalID(), l);
}
static LispStatement lispAddLocalTruth(String id, Lisp l) {
if (lispTrue(l)) return null;
return lispAddLocalTruth_noCheck(id, l);
}
static LispStatement lispAddLocalTruth_noCheck(String id, Lisp l) {
LispStatement s = new LispStatement(id, l);
lispStatements_cached().put(id, s);
lispChange();
return s;
}
static void deleteConcepts(List conceptsOrIDs) {
mainConcepts.deleteConcepts(conceptsOrIDs);
}
static List deleteConcepts(Class c, Object... params) {
List l = findConceptsWhere(c, params);
deleteConcepts(l);
return l;
}
// make a lisp form
static Lisp lisp(String head, Object... args) {
Lisp l = new Lisp(head);
for (Object o : args)
l.add(o);
return l;
}
static Lisp lisp(String head, Collection args) {
return new Lisp(head, args);
}
static LispStatement findLispStatement(Lisp l) {
for (LispStatement s : lispStatementsByHead(l.head))
if (eq(s.term, l)) return s;
return null;
}
static JButton jbutton(String text, Object action) {
return newButton(text, action);
}
// button without action
static JButton jbutton(String text) {
return newButton(text, null);
}
static JButton jbutton(BufferedImage img, Object action) {
return setButtonImage(img, jbutton("", action));
}
static void removeLispStatement(LispStatement s) {
if (s == null) return;
lispStatements_cached().remove(s.globalID);
lispChange();
}
static void printLispStatements() {
printNumberedLines(map(new Object() { Object get(LispStatement s) { try { return
"[" + s.globalID + "] " + s.term
; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "\"[\" + s.globalID + \"] \" + s.term"; }}, values(lispStatements_cached())));
print();
}
static void db() {
conceptsAndBot();
}
static String aGlobalID() {
return randomID(16);
}
static AtomicLong lispChange_count = new AtomicLong();
static void lispChange() {
lispChange_count.incrementAndGet();
}
static List printNumberedLines(List l) {
int i = 0;
for (A a : l) print((++i) + ". " + str(a));
return l;
}
static void printNumberedLines(Object[] l) {
printNumberedLines(asList(l));
}
static void printNumberedLines(Object o) {
printNumberedLines(lines(str(o)));
}
static Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static List lispStatementsByHead(final String... heads) {
return aiUsing(filter(values(lispStatements_cached()) , new Object() { Object get(LispStatement s) { try { return s.term.is(heads) ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "s.term.is(heads)"; }}));
}
static ArrayList asList(A[] a) {
return new ArrayList(Arrays.asList(a));
}
static ArrayList asList(int[] a) {
ArrayList l = new ArrayList();
for (int i : a) l.add(i);
return l;
}
static ArrayList asList(Iterable s) {
if (s instanceof ArrayList) return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s)
l.add(a);
return l;
}
static ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}
//please include function withMargin.
static int showForm_defaultGap = 4;
static JPanel showFormTitled(String title, Object... _parts) {
final Var frame = new Var();
JPanel panel = showForm_makePanel(frame, _parts);
frame.set(minFrameWidth(showPackedFrame(title, withMargin(panel)), 400));
return panel;
}
static JPanel showForm_makePanel(final Var frame, Object... _parts) {
List l = new ArrayList();
List parts = asList(_parts);
Runnable submit = null;
for (int i = 0; i < l(parts); i++) {
final Object o = parts.get(i), next = get(parts, i+1);
if (o instanceof Component || o instanceof String || next instanceof Component) { // smartAdd accepts strings
l.add(ll(o == null ? new JPanel() : o, next));
if (next instanceof JButton && submit == null)
submit = new Runnable() { public void run() { try { ((JButton) next).doClick() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "((JButton) next).doClick()"; }};
i++;
} else if (isRunnable(o))
l.add(ll(null, jbutton(showFormSubmitButtonName(), submit = new Runnable() { public void run() { try {
Object result = call(o);
if (neq(Boolean.FALSE, result))
disposeFrame(frame.get());
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Object result = call(o);\r\n if (neq(Boolean.FALSE, result))\r\n dis..."; }})));
else print("showForm: Unknown element type: " + getClassName(o));
}
JPanel panel = hvgrid((List) l, showForm_defaultGap);
if (submit != null)
for (JTextField textField : childrenOfType(panel, JTextField.class))
onEnter(textField, submit);
return panel;
}
static List findConceptsWhere(Class c, Object... params) {
return filterConcepts(list(c), expandParams(c, params));
}
static List findConceptsWhere(String c, Object... params) {
return filterConcepts(list(c), params);
}
static List findConceptsWhere(Concepts concepts, Class c, Object... params) {
return filterConcepts(concepts.list(c), expandParams(c, params));
}
static List findConceptsWhere(Concepts concepts, String c, Object... params) {
return filterConcepts(concepts.list(c), params);
}
static List map(Iterable l, Object f) {
return map(f, l);
}
static List map(Object f, Iterable l) {
List x = new ArrayList();
Object mc = mc();
for (Object o : unnull(l))
x.add(callF(f, o));
return x;
}
static List map(Object f, Object[] l) {
return map(f, asList(l));
}
static List map(Object f, Map map) {
return map(map, f);
}
static List map(Map map, Object f) {
List x = new ArrayList();
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static WeakAssoc, Map> lispStatements_cache = new WeakAssoc("statementsToLisp");
static Map lispStatements_global;
static Map lispStatements_cached() {
if (lispStatements_global != null) return lispStatements_global;
return lispStatements_cache.get(loadTruth_cached());
}
static JButton setButtonImage(BufferedImage img, JButton btn) {
btn.setIcon(imageIcon(img));
return btn;
}
static boolean eq(Object a, Object b) {
return a == null ? b == null : a == b || a.equals(b);
}
static JTextField jtextfield() {
return jTextField();
}
static JTextField jtextfield(String text) {
return jTextField(text);
}
static JTextField jtextfield(Object o) {
return jTextField(o);
}
static String getTextTrim(JTextComponent c) {
return trim(getText(c));
}
static void useConcepts(String concepts) {
useConceptsDump(concepts);
}
static volatile StringBuffer local_log = new StringBuffer(); // not redirected
static volatile StringBuffer 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 volatile ThreadLocal> print_byThread; // special handling by thread
static void print() {
print("");
}
// slightly overblown signature to return original object...
static A print(A o) {
ping();
if (print_silent) return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static void print_noNewLine(String s) {
if (print_byThread != null) {
F1 f = print_byThread.get();
if (f != null)
if (isFalse(f.get(s))) return;
}
print_raw(s);
}
static void print_raw(String s) {
s = fixNewLines(s);
// TODO if (print_maxLineLength != 0)
StringBuffer loc = local_log;
StringBuffer 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 void print(long l) {
print(String.valueOf(l));
}
static void print(char c) {
print(String.valueOf(c));
}
static void print_append(StringBuffer buf, String s, int max) {
synchronized(buf) {
buf.append(s);
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);
}
}
}
static boolean lispTrue(String head, Object... args) {
return lispTrue(lisp(head, args));
}
static boolean lispTrue(Lisp l) {
for (Lisp x : lispTruthByHead(l.head))
if (eq(x, l)) return true;
return false;
}
static void useFacts(String facts) {
List statements = linesToCL(facts);
useFacts_cl(statements);
}
// use facts in CL
static void useFacts_cl(List statements) {
ai();
// trueStatements_cached_autoClearInterval = 0;
trueStatements_cached_cache.set(new LinkedHashSet(statements));
loadTruth_cached_cache.set(aiMakeStatements(statements));
}
static void useFacts_cl(String statements) {
useFacts_cl(toLinesFullTrim(statements));
}
// action can be Runnable or a function name
static JButton newButton(final String text, final Object action) {
return swing(new F0() { JButton get() { try {
JButton btn = new JButton(text);
if (action != null)
btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) {
callFunction(action);
}});
return btn;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JButton btn = new JButton(text);\r\n if (action != null)\r\n btn.addActionLi..."; }});
}
volatile static boolean conceptsAndBot_running;
static void conceptsAndBot() {
conceptsAndBot(null);
}
static void conceptsAndBot(Integer autoSaveInterval) {
if (conceptsAndBot_running) return;
conceptsAndBot_running = true;
ensureBotIsNotAlreadyRunning(dbBotStandardName());
if (autoSaveInterval != null)
loadAndAutoSaveConcepts(autoSaveInterval);
else
loadAndAutoSaveConcepts();
dbBot();
}
static JPanel jcenteredline(Component... components) {
//ret new CenteredLine(components);
return jFullCenter(hstackWithSpacing(components));
}
static JPanel jcenteredline(List extends Component> components) {
return jcenteredline(asArray(Component.class, components));
}
static JComponent showControls_controls;
static void showControls(final JComponent controls) {
{ swingAndWait(new Runnable() { public void run() { try {
hideControls();
JComponent _controls = withMargin(controls);
showControls_controls = _controls;
addToConsole2(showControls_controls);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "hideControls();\r\n JComponent _controls = withMargin(controls);\r\n showContr..."; }}); }
}
static List ll(A... a) {
return litlist(a);
}
static Cache> loadTruth_cached_cache = new Cache("loadTruth");
static List loadTruth_cached() {
return loadTruth_cached_cache.get();
}
static void loadTruth_clearCache() {
loadTruth_cached_cache.clear();
}
static void loadTruth_clearCache(double seconds) {
loadTruth_cached_cache.clear(seconds);
}
static void ensureBotIsNotAlreadyRunning(String name) {
if (hasBot(name))
throw fail("Bot already running [" + name + "]");
}
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 useConceptsDump(String concepts) {
List usedConcepts = conceptsFromDump(concepts);
//dumpConcepts2(findAIConcepts(conceptsUsed));
//printAIConcepts(usedConcepts);
setOpt(mc(), "englishToConceptLanguage_concepts_global", usedConcepts);
aiConceptsMap_cached_autoClearInterval = 0;
aiConceptsMap_cached_cache.set(indexByField(usedConcepts, "globalID"));
ai();
}
static WeakHashMap> callF_cache = new WeakHashMap();
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 methods.get(0).invoke(f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return m.invoke(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 Object callFunction(Object f, Object... args) {
return callF(f, args);
}
static JPanel jFullCenter(Component c) {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(c);
return panel;
}
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 disposeFrame(final Component c) {
swingNowOrLater(new Runnable() { public void run() { try {
Frame f = getFrame(c);
if (f != null)
f.dispose();
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Frame f = getFrame(c);\n if (f != null)\n f.dispose();"; }});
}
static Object mc() {
return getMainClass();
}
static boolean neq(Object a, Object b) {
return !eq(a, b);
}
static JTextField jTextField() {
return jTextField("");
}
static JTextField jTextField(String text) {
JTextField tf = new JTextField(unnull(text));
jenableUndoRedo(tf);
tf.selectAll();
return tf;
}
static JTextField jTextField(Object o) {
return jTextField(strOrEmpty(o));
}
static List filterConcepts(List list, Object... params) {
List l = new ArrayList();
for (A x : list)
if (checkConceptFields(x, params))
l.add(x);
return l;
}
static void hideControls() {
{ swingAndWait(new Runnable() { public void run() { try {
removeFromConsole2(showControls_controls);
showControls_controls = null;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "removeFromConsole2(showControls_controls);\r\n showControls_controls = null;"; }}); }
}
static int withMargin_defaultWidth = 6;
static JPanel withMargin(Component c) {
JPanel p = new JPanel(new BorderLayout());
int w = withMargin_defaultWidth;
p.setBorder(BorderFactory.createEmptyBorder(w, w, w, w));
p.add(c);
return p;
}
static List aiMakeStatements(List statements) {
return map(new Object() { Object get(String s) { try {
Statement st = unlisted(Statement.class);
String id = getGlobalIDPrefix(s);
if (id == null) {
st.globalID = aGlobalID();
st.text = s;
} else {
st.globalID = id;
st.text = dropGlobalIDPrefix(s);
}
return st;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "Statement st = unlisted(Statement);\r\n S id = getGlobalIDPrefix(s);\r\n if (i..."; }}, statements);
}
static String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new Object() { Object get() { try { return c.getText() ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "c.getText()"; }});
}
static String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new Object() { Object get() { try { return l.getText() ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "l.getText()"; }});
}
// TODO: WeakAssoc from loadTruth_cached()
static Cache> trueStatements_cached_cache = new Cache(new Object() { Object get() { try { return collectTreeSet(loadTruth_cached(), "text") ; } catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "collectTreeSet(loadTruth_cached(), \"text\")"; }});
static Set trueStatements_cached() {
return trueStatements_cached_cache.get();
}
static void trueStatements_clearCache() {
trueStatements_cached_cache.clear();
}
// clear cache if older than x seconds
static void trueStatements_clearCache(double seconds) {
trueStatements_cached_cache.clear(seconds);
}
static void ai() {
aiEnhancements();
}
static boolean isFalse(Object o) {
return eq(false, o);
}
static ArrayList list(A[] a) {
return asList(a);
}
static ArrayList list(int[] a) {
return asList(a);
}
static ArrayList list(Set s) {
return asList(s);
}
static String str(Object o) {
return o == null ? "null" : o.toString();
}
static String str(char[] c) {
return new String(c);
}
static JTextField onEnter(JTextField tf, final Object action) {
if (action == null || tf == null) return tf;
tf.addActionListener(actionListener(action));
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, final Object action) {
list.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER)
pcallF(action);
}
});
return list;
}
static List toLinesFullTrim(String s) {
List l = toLines(s);
for (ListIterator i = l.listIterator(); i.hasNext(); ) {
String line = i.next().trim();
if (line.length() == 0)
i.remove();
else
i.set(line);
}
return l;
}
static List toLinesFullTrim(File f) {
return toLinesFullTrim(loadTextFile(f));
}
static List lispTruthByHead(String... heads) {
return collect(lispStatementsByHead(heads), "term");
}
static String getClassName(Object o) {
return o == null ? "null" : o.getClass().getName();
}
static List linesToCL(String text) {
return listToCL(linesToCL_prepare(text));
}
static List linesToCL_prepare(String text) {
return toLinesFullTrim(joinLines(map("javaDropComments", toLinesFullTrim(text))));
}
static boolean isRunnable(Object o) {
return o instanceof Runnable || hasMethod(o, "get");
}
static String fixNewLines(String s) {
return s.replace("\r\n", "\n").replace("\r", "\n");
}
static volatile boolean ping_pauseAll;
static int ping_sleep = 100; // poll pauseAll flag every 100
static volatile boolean ping_anyActions;
static Map ping_actions = synchroMap(new WeakHashMap());
// always returns true
static boolean ping() {
if (ping_pauseAll || ping_anyActions) ping_impl();
return true;
}
// returns true when it slept
static boolean ping_impl() { try {
if (ping_pauseAll && !isAWTThread()) {
do
Thread.sleep(ping_sleep);
while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
Object action;
synchronized(mc()) {
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 Android3 dbBot() {
return dbBot(dbBotStandardName());
}
static Android3 dbBot(String name) {
ensureBotIsNotAlreadyRunning(name);
assertNotNull(mainConcepts);
return methodsBot2(name, mainConcepts, exposedDBMethods, mainConcepts.lock);
}
static String unnull(String s) {
return s == null ? "" : s;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static Object[] unnull(Object[] a) {
return a == null ? new Object[0] : a;
}
static BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static List childrenOfType(Component c, Class theClass) {
List l = new ArrayList();
scanForComponents(c, theClass, l);
return l;
}
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
static String dbBotStandardName() {
return dbBotName(getDBProgramID()) + ".";
}
static int hstackWithSpacing_spacing = 10;
// first part can be spacing value
static JPanel hstackWithSpacing(Object... parts) {
int spacing = hstackWithSpacing_spacing;
int i = 0;
if (first(parts) instanceof Integer) {
spacing = toInt(first(parts));
++i;
}
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.gridheight = GridBagConstraints.REMAINDER;
for (; i < l(parts); i++) {
if (i != 0)
panel.add(Box.createRigidArea(new Dimension(spacing, 0)), gbc);
panel.add(wrapForSmartAdd(parts[i]), gbc);
}
gbc.weightx = 1;
panel.add(Box.createRigidArea(new Dimension(0, 0)), gbc);
return panel;
}
// get purpose 1: access a list/array (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;
}
static A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
// default to false
static boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
// get purpose 2: access a field by reflection or a map
static Object get(Object o, String field) {
try {
if (o instanceof Class) return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
f.setAccessible(true);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static Object get_raw(Object o, String field) {
try {
Field f = get_findField(o.getClass(), field);
f.setAccessible(true);
return f.get(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
f.setAccessible(true);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields())
if (f.getName().equals(field) && (f.getModifiers() & 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 ImageIcon imageIcon(String imageID) { try {
return new ImageIcon(loadBinarySnippet(imageID).toURI().toURL());
} catch (Exception __e) { throw rethrow(__e); } }
static ImageIcon imageIcon(BufferedImage img) {
return new ImageIcon(img);
}
static ImageIcon imageIcon(RGBImage img) {
return imageIcon(img.getBufferedImage());
}
static Object[] expandParams(Class c, Object[] params) {
if (l(params) == 1)
params = new Object[] { singleFieldName(c), params[0] };
else
warnIfOddCount(params);
return params;
}
static String lines(List lines) { return fromLines(lines); }
static List lines(String s) { return toLines(s); }
static String showFormSubmitButtonName() {
return "Submit";
}
static JFrame showPackedFrame(String title, Component contents) {
return packFrame(showFrame(title, contents));
}
static JFrame showPackedFrame(Component contents) {
return packFrame(showFrame(contents));
}
static JFrame minFrameWidth(JFrame frame, int w) {
if (frame != null && frame.getWidth() < w)
frame.setSize(w, frame.getHeight());
return frame;
}
static JFrame minFrameWidth(int w, JFrame frame) {
return minFrameWidth(frame, w);
}
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(int[] a) { return a == null ? 0 : a.length; }
static int l(float[] 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 instanceof String ? l((String) o)
: o instanceof Map ? l((Map) o)
: l((Collection) o); // incomplete
}
static int l(Lisp l) { return l == null ? 0 : l.size(); }
static Set aiUsing_set = synchroTreeSet();
static String aiUsing(String s) {
aiUsing_set.addAll(aggressivelyCollectPossibleGlobalIDs(s));
return s;
}
static void aiUsing(Object o) {
// TODO
}
static List aiUsing(List l) {
for (Object li : unnull(l)) aiUsing(li);
return l;
}
static Lisp aiUsing(Lisp l) {
if (l != null) {
aiUsing(l.head);
for (Lisp sub : l) aiUsing(sub);
}
return l;
}
static void aiUsing_print() {
aiUsing_print(null);
}
static void aiUsing_print(List priorityConcepts) {
//print("\nAI concepts used: " + aiUsing_set);
print("\nAI concepts used: ");
dumpConcepts2(findAIConcepts(prioritizeList(aiUsing_set, priorityConcepts)));
}
static Object call(Object o) {
return callFunction(o);
}
// varargs assignment fixer for a single string array argument
static Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] {arg});
}
static Object call(Object o, String method, Object... args) {
try {
if (o instanceof Class) {
Method m = call_findStaticMethod((Class) o, method, args, false);
m.setAccessible(true);
return m.invoke(null, args);
} else {
Method m = call_findMethod(o, method, args, false);
m.setAccessible(true);
return m.invoke(o, args);
}
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
}
static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) {
Class _c = c;
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (!m.getName().equals(method)) {
if (debug) System.out.println("Method name mismatch: " + method);
continue;
}
if ((m.getModifiers() & Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug))
continue;
return m;
}
c = c.getSuperclass();
}
throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + _c.getName());
}
static Method call_findMethod(Object o, String method, Object[] args, boolean debug) {
Class c = o.getClass();
while (c != null) {
for (Method m : c.getDeclaredMethods()) {
if (debug)
System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");;
if (m.getName().equals(method) && call_checkArgs(m, args, debug))
return m;
}
c = c.getSuperclass();
}
throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName());
}
private 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 int randomID_defaultLength = 12;
static String randomID(int length) {
return makeRandomID(length);
}
static String randomID() {
return randomID(randomID_defaultLength);
}
static Object swing(Object f) {
return swingAndWait(f);
}
static A swing(F0 f) {
return (A) swingAndWait(f);
}
static void addToConsole2(Component toAdd) {
JFrame frame = consoleFrame();
if (frame == null) return;
Container cp = frame.getContentPane();
Container cp2 = (Container) getCenterComponent(cp);
replaceCenterComponent(cp, centerAndSouth(cp2, toAdd));
validateFrame(frame);
}
// TODO: all the fringe cases (?)
static JPanel hvgrid(List> components) {
if (empty(components)) return new JPanel();
int h = l(components), w = l(first(components));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(h, w));
for (List row : components)
smartAdd(panel, row);
return panel;
}
static JPanel hvgrid(List> components, int gap) {
JPanel panel = hvgrid(components);
GridLayout g = (GridLayout) ( panel.getLayout());
g.setHgap(gap);
g.setVgap(gap);
return panel;
}
static Object pcallFunction(Object f, Object... args) {
try { return callFunction(f, args); } catch (Throwable __e) { printStackTrace2(__e); }
return null;
}
static JFrame consoleFrame() {
return (JFrame) getOpt(get(getJavaX(), "console"), "frame");
}
static final 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;
synchronized(callMC_cache) {
me = method == callMC_key ? callMC_value : null;
}
if (me != null) return callMC_value.invoke(null, args);
List 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;
}
return me.invoke(null, args);
}
for (int i = 0; i < n; i++) {
me = m.get(i);
if (call_checkArgs(me, args, false))
return me.invoke(null, args);
}
throw fail("No method called " + method + " with matching arguments found in main");
} catch (Exception __e) { throw rethrow(__e); } }
static synchronized void callMC_makeCache() {
callMC_cache.clear();
Class _c = (Class) mc(), c = _c;
while (c != null) {
for (Method m : c.getDeclaredMethods())
if ((m.getModifiers() & Modifier.STATIC) != 0) {
m.setAccessible(true);
multiMapPut(callMC_cache, m.getName(), m);
}
c = c.getSuperclass();
}
}
static A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static void replaceCenterComponent(Container container, Component c) {
Component old = getCenterComponent(container);
if (old != null)
container.remove(old);
container.add(c, BorderLayout.CENTER);
}
static TreeSet collectTreeSet(Collection c, String field) {
TreeSet set = new TreeSet();
for (Object a : c) {
Object val = getOpt(a, field);
if (val != null)
set.add(val);
}
return set;
}
// 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 void swingAndWait(Runnable r) { try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(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 Thread currentThread() {
return Thread.currentThread();
}
static int packFrame_minw = 150, packFrame_minh = 50;
static JFrame packFrame(final Component c) {
return (JFrame) swing(new Object() { Object get() { try {
JFrame frame = getFrame(c);
if (frame == null) return null;
frame.pack();
int maxW = getScreenWidth()-50, maxH = getScreenHeight()-50;
frame.setSize(
min(maxW, max(frame.getWidth(), packFrame_minw)),
min(maxH, max(frame.getHeight(), packFrame_minh)));
return frame;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "JFrame frame = getFrame(c);\r\n if (frame == null) null;\r\n frame.pack();\r\n ..."; }});
}
static JFrame packFrame(ButtonGroup g) {
return packFrame(getFrame(g));
}
static JPanel smartAdd(JPanel panel, List parts) {
for (Object o : parts)
panel.add(wrapForSmartAdd(o));
return panel;
}
static JPanel smartAdd(JPanel panel, Object... parts) {
return smartAdd(panel, asList(parts));
}
static void aiEnhancements() {
conceptLanguageToolTips();
}
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(unnull(msg));
}
static RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
static boolean aiConceptsMap_fastLoad, aiConceptsMap_silent;
static List aiConceptsMap_list;
static Map aiConceptsMap() {
long time = sysNow();
List concepts = aiConceptsMap_fastLoad ? fastLoadAIConcepts() : loadAIConcepts();
aiConceptsMap_list = concepts;
Map map = indexByField(concepts, "globalID");
if (!aiConceptsMap_silent)
sysDone(time, "load ai concepts");
return map;
}
static File loadBinarySnippet(String snippetID) { try {
long id = parseSnippetID(snippetID);
File f = DiskSnippetCache_getLibrary(id);
if (f == null)
f = loadDataSnippetToFile(snippetID);
return f;
} catch (Exception __e) { throw rethrow(__e); } }
static Set synchroTreeSet() {
return Collections.synchronizedSet(new TreeSet());
}
static ActionListener actionListener(final Object runnable) {
return new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { pcallF(runnable); }};
}
static Component wrapForSmartAdd(Object o) {
if (o == null) return new JPanel();
if (o instanceof String) return jlabel((String) o);
return wrap(o);
}
static ArrayList litlist(A... a) {
return new ArrayList(Arrays.asList(a));
}
static List toLines(File f) {
return toLines(loadTextFile(f));
}
public static List toLines(String s) {
List lines = new ArrayList();
if (s == null) return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start) lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
private 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 JFrame showFrame() {
return makeFrame();
}
static JFrame showFrame(Object content) {
return makeFrame(content);
}
static JFrame showFrame(String title) {
return makeFrame(title);
}
static JFrame showFrame(String title, Object content) {
return makeFrame(title, content);
}
static JFrame showFrame(final JFrame frame) {
if (frame != null) { swingAndWait(new Runnable() { public void run() { try {
if (frameTooSmall(frame)) frameStandardSize(frame);
frame.setVisible(true);
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (frameTooSmall(frame)) frameStandardSize(frame);\r\n frame.setVisible(true);"; }}); }
return frame;
}
// make or update frame
static JFrame showFrame(String title, Object content, JFrame frame) {
if (frame == null)
return showFrame(title, content);
else {
frame.setTitle(title);
setFrameContents(frame, content);
return frame;
}
}
static Class getMainClass() {
return main.class;
}
static Class getMainClass(Object o) { try {
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) { throw rethrow(__e); } }
static String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static String getDBProgramID_id;
static String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programID();
}
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 List prioritizeList(Collection c, List prioritizer) {
List l = new ArrayList();
Set set = asSet(c);
for (A a : prioritizer) {
if (set.contains(a)) {
set.remove(a);
l.add(a);
}
}
l.addAll(set);
return l;
}
static Object first(Object list) {
return empty((List) list) ? null : ((List) list).get(0);
}
static A first(List list) {
return empty(list) ? null : list.get(0);
}
static A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static A first(Iterable i) {
if (i == null) return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static Character first(String s) { return empty(s) ? null : s.charAt(0); }
static String joinLines(List lines) {
return fromLines(lines);
}
static String joinLines(String glue, String text) {
return join(glue, toLines(text));
}
static Component getCenterComponent(Container container) {
return ((BorderLayout) container.getLayout()).getLayoutComponent(BorderLayout.CENTER);
}
static boolean empty(Collection c) {
return isEmpty(c);
}
static boolean empty(String s) {
return isEmpty(s);
}
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);
throw fail("unknown type for 'empty': " + getType(o));
}
static boolean empty(float[] a) { return a == null || a.length == 0; }
static String getGlobalIDPrefix(String s) {
List tok = javaTok(s);
if (eq(get(tok, 1), "[") && eq(get(tok, 5), "]") && possibleGlobalID(get(tok, 3)))
return get(tok, 3);
return null;
}
static RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static A jenableUndoRedo(A textcomp) {
final UndoManager undo = new UndoManager();
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");
return textcomp;
}
// extended over Class.isInstance() to handle primitive types
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 String singleFieldName(Class c) {
Set l = listFields(c);
if (l(l) != 1)
throw fail("No single field found in " + c + " (have " + n(l(l), "fields") + ")");
return first(l);
}
static void removeFromConsole2(Component c) {
JFrame frame = getFrame(c);
if (frame == null) return;
Container cp = frame.getContentPane(); // This is our BorderLayout
cp = (Container) getCenterComponent(cp);
if (cp != c.getParent()) { print("removeFromWindow fail"); return; }
cp.remove(c);
Container mainC = (Container) cp.getComponents()[0];
cp.remove(mainC);
replaceCenterComponent(frame.getContentPane(), mainC);
validateFrame(frame);
}
static Set aggressivelyCollectPossibleGlobalIDs(String s) {
LinkedHashSet ids = new LinkedHashSet();
if (s == null) return ids;
for (int i = 0; i < l(s); i++) {
int j = i;
while (j < l(s) && Character.isLowerCase(s.charAt(j))) ++j;
if (j-i == 16)
ids.add(substring(s, i, j));
i = j;
}
return ids;
}
static boolean hasMethod(Object o, String method, Object... args) {
return findMethod(o, method, args) != null;
}
static String dbBotName(String progID) {
return fsI(progID) + " Concepts";
}
// make concept instance that is not connected to DB
static A unlisted(Class c, Object... args) {
concepts_unlisted.set(true);
try {
return nuObject(c, args);
} finally {
concepts_unlisted.set(null);
}
}
static List conceptsFromDump(String s) {
List < List < String > > l = new ArrayList();
if (neq(first(javaTokC(s)), "[")) {
for (String line : toLinesFullTrim(s)) {
int i = line.indexOf(" - ");
if (i > 0) {
String id = trim(substring(line, 0, i));
if (!possibleGlobalID(id)) warn("no id: " + id);
else
l.add(ll(id, trim(substring(line, i+3))));
}
}
} else
l = (List) safeUnstructure("[" + s + "]");
List out = new ArrayList();
for (List x : l) {
AIConcept c = unlisted(AIConcept.class);
String id = makeNewID(get(x, 0));
cset(c, "globalID" , id, "name" , unnull(get(x, 1)), "comment" , unnull(get(x, 2)));
out.add(c);
}
return out;
}
static String dropGlobalIDPrefix(String s) {
List tok = javaTok(s);
if (eq(get(tok, 1), "[") && eq(get(tok, 5), "]") && possibleGlobalID(get(tok, 3)))
return join(subList(tok, 7));
return s;
}
static List collect(Collection c, String field) {
return collectField(c, field);
}
static void scanForComponents(Component c, Class theClass, List l) {
if (theClass.isInstance(c))
l.add((A) c);
if (c instanceof Container)
for (Component comp : ((Container) c).getComponents())
scanForComponents(comp, theClass, l);
}
static Map synchroMap() {
return synchroHashMap();
}
static Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static List findAIConcepts(String ids) {
return findAIConcepts(javaTokC(ids));
}
static List findAIConcepts(Iterable ids) {
List l = new ArrayList();
for (Object id : ids)
if (id instanceof String)
addIfNotNull(l, aiConceptsMap_cached().get((String) id));
else if (id instanceof AIConcept)
l.add((AIConcept) id);
return l;
}
static JFrame getFrame(Object o) {
if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component)) return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JFrame) return (JFrame) c;
c = c.getParent();
}
return null;
}
static JPanel centerAndSouth(Component c, Component s) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
if (s != null) panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
}
static boolean hasBot(String searchPattern) {
DialogIO io = findBot(searchPattern);
if (io != null) {
io.close();
return true;
} else
return false;
}
static void warnIfOddCount(Object... list) {
if (odd(l(list)))
printStackTrace("Odd list size: " + list);
}
// usually L
static String fromLines(List 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 listToCL(List l) {
return map("englishToConceptLanguage_keepPrefix", l);
}
static Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static boolean checkConceptFields(Concept x, Object... data) {
for (int i = 0; i < l(data); i += 2)
if (neq(cget(x, (String) data[i]), deref(data[i+1])))
return false;
return true;
}
static Android3 methodsBot2(String name, final Object receiver, final List exposedMethods) {
return methodsBot2(name, receiver, exposedMethods, null);
}
static Android3 methodsBot2(String name, final Object receiver, final List exposedMethods, final Lock lock) {
Android3 android = new Android3();
android.greeting = name;
android.console = false;
android.responder = new Responder() {
String answer(String s, List history) {
return exposeMethods2(receiver, s, exposedMethods, lock);
}
};
return makeBot(android);
}
static int toInt(Object o) {
if (o == null) return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt((String) o);
throw fail("woot not int: " + getClassName(o));
}
static int toInt(long l) {
if (l != (int) l) throw fail("Too large for int: " + l);
return (int) l;
}
public static String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(String fileName, String defaultContents) {
try {
if (!new File(fileName).exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
public static String loadTextFile(File fileName, String defaultContents) {
return loadTextFile(fileName.getPath(), defaultContents);
}
public static String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer)))
builder.append(buffer, 0, n);
} finally {
reader.close();
}
return builder.toString();
}
static String makeRandomID(int length) {
Random random = new Random();
char[] id = new char[length];
for (int i = 0; i < id.length; i++)
id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
static void validateFrame(Component c) {
revalidateFrame(c);
}
// does not store null values
static Map indexByField(Collection c, String field) {
HashMap map = new HashMap();
for (Object a : c) {
Object val = getOpt(a, field);
if (val != null)
map.put(val, a);
}
return map;
}
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;
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;
}
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() & Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static String dumpConcepts2(List concepts) {
List l = new ArrayList();
for (AIConcept c : concepts) {
List x = ll(c.globalID, c.name);
addIfNempty(x, c.comment);
l.add(" " + struct(x));
}
return print("[[\n" + join(",\n", l) + "\n]]");
}
static WeakHashMap makeFrame_myFrames = new WeakHashMap();
static JFrame makeFrame() {
return makeFrame((Component) null);
}
static JFrame makeFrame(Object content) {
return makeFrame(programTitle(), content);
}
static JFrame makeFrame(String title) {
return makeFrame(title, null);
}
static JFrame makeFrame(String title, Object content) {
return makeFrame(title, content, true);
}
static JFrame makeFrame(final String title, final Object content, final boolean showIt) {
return (JFrame) swing(new Object() { Object get() { try {
if (getFrame(content) != null)
return setFrameTitle((Component) content, title);
final JFrame frame = new JFrame(title);
makeFrame_myFrames.put(frame, Boolean.TRUE);
JComponent wrapped = wrap(content);
if (wrapped != null)
frame.getContentPane().add(wrapped);
frame.setBounds(300, 100, 500, 400);
if (showIt)
frame.setVisible(true);
//callOpt(content, "requestFocus");
//exitOnFrameClose(frame);
standardTitlePopupMenu(frame);
return frame;
} catch (Exception __e) { throw rethrow(__e); } }
public String toString() { return "if (getFrame(content) != null)\r\n ret setFrameTitle((Component) content, tit..."; }});
}
// This is for main classes that are all static.
// (We don't go to base classes.)
static Set listFields(Object c) {
TreeSet fields = new TreeSet();
for (Field f : _getClass(c).getDeclaredFields())
fields.add(f.getName());
return fields;
}
static Cache