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.*;
public class main {
// hzkawzgzyruhuawt - The correct answer to X is Y
static class HowMany1 extends Agent_abs_NameToGenerator {
boolean check(String name) {
return find3("how many", name);
}
void gen(AIConcept c) {
emit("hzkawzgzyruhuawt " + c.globalID + " " + random(100));
}
}
public static void main(final String[] args) throws Exception {
new HowMany1().runLive(args);
}
static Random random_random = new Random();
static int random(int n) {
return n <= 0 ? 0 : random_random.nextInt(n);
}
static double random(double max) {
return random()*max;
}
static double random() {
return random_random.nextInt(100001)/100000.0;
}
static double random(double min, double max) {
return min+random()*(max-min);
}
// min <= value < max
static int random(int min, int max) {
return min+random(max-min);
}
static A random(List l) {
return oneOf(l);
}
static A random(Collection c) {
return oneOf(asList(c));
}
static boolean find3(String pat, String s) {
return find3(pat, s, null);
}
static boolean find3(String pat, String s, Matches matches) {
List tokpat = parse3(pat), toks = parse3(s);
String[] m = find2(tokpat, toks);
//print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m));
if (m == null)
return false;
else {
if (matches != null) matches.m = m;
return true;
}
}
static A oneOf(List l) {
return l.isEmpty() ? null : l.get(new Random().nextInt(l.size()));
}
static char oneOf(String s) {
return empty(s) ? '?' : s.charAt(random(l(s)));
}
// We dropped the "***" support here (use match3 for that)
static String[] find2(List pat, List tok) {
for (int idx = 0; idx < tok.size(); idx += 2) {
String[] result = find2(pat, tok, idx);
if (result != null) return result;
}
return null;
}
static String[] find2(List pat, List tok, int idx) {
if (idx+pat.size() > tok.size())
return null;
List result = new ArrayList();
for (int i = 1; i < pat.size(); i += 2) {
String p = pat.get(i), t = tok.get(idx+i);
if (eq(p, "*"))
result.add(t);
else if (!p.equalsIgnoreCase(t))
return null;
}
return toStringArray(result);
}
static List parse3(String s) {
return dropPunctuation(javaTokPlusPeriod(s));
}
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;
}
static List dropPunctuation_keep = litlist("*", "<", ">");
static List dropPunctuation(List tok) {
tok = new ArrayList(tok);
for (int i = 1; i < tok.size(); i += 2) {
String t = tok.get(i);
if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) {
tok.set(i-1, tok.get(i-1) + tok.get(i+1));
tok.remove(i);
tok.remove(i);
i -= 2;
}
}
return tok;
}
static String dropPunctuation(String s) {
return join(dropPunctuation(nlTok(s)));
}
// This is made for NL parsing.
// It's javaTok extended with "..." token, "$n" and "#n" and
// special quotes (which are converted to normal ones).
static List javaTokPlusPeriod(String s) {
List tok = new ArrayList();
int l = s.length();
int i = 0;
while (i < l) {
int j = i;
char c; String cc;
// scan for whitespace
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j+2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/"));
j = Math.min(j+2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l) break;
c = s.charAt(i);
cc = s.substring(i, Math.min(i+2, l));
// scan for non-whitespace
if (c == '\u201C' || c == '\u201D') c = '"'; // normalize quotes
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
char _c = s.charAt(j);
if (_c == '\u201C' || _c == '\u201D') _c = '"'; // normalize quotes
if (_c == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j+1 < l)
j += 2;
else
++j;
}
if (j-1 >= i+1) {
tok.add(opener + s.substring(i+1, j-1) + opener);
i = j;
continue;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // for things like "this one's"
else if (Character.isDigit(c))
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else if (cc.equals("[[")) {
do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]"));
j = Math.min(j+2, l);
} else if (cc.equals("[=") && 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 if (s.substring(j, Math.min(j+3, l)).equals("..."))
j += 3;
else if (c == '$' || c == '#')
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0) tok.add("");
return tok;
}
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)
: l((Collection) o); // incomplete
}
static boolean eq(Object a, Object b) {
if (a == null) return b == null;
if (a.equals(b)) return true;
if (a instanceof BigInteger) {
if (b instanceof Integer) return a.equals(BigInteger.valueOf((Integer) b));
if (b instanceof Long) return a.equals(BigInteger.valueOf((Long) b));
}
return false;
}
static String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++)
a[i] = it.next();
return a;
}
static String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
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 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(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(unnull(msg));
}
static RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
// disabled for now to shorten some programs
/*static RuntimeException fail(S msg, O... args) {
throw new RuntimeException(format(msg, args));
}*/
static List nlTok(String s) {
return javaTokPlusPeriod(s);
}
static String getType(Object o) {
return getClassName(o);
}
static ArrayList litlist(A... a) {
return new ArrayList(Arrays.asList(a));
}
public static String join(String glue, Iterable strings) {
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String[] strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(Iterable strings) {
return join("", strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static String getClassName(Object o) {
return o == null ? "null" : o.getClass().getName();
}
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 RuntimeException asRuntimeException(Throwable t) {
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static List emptyList() {
return new ArrayList();
//ret Collections.emptyList();
}
abstract static class Agent_abs_NameToGenerator extends Agent {
void impl() {
for (AIConcept c : aiConcepts())
if (check(c.name))
gen(c);
}
abstract boolean check(String name);
abstract void gen(AIConcept c);
}
static class Node extends Concept {
String globalID = isTrue(DynamicObject_loading.get()) ? null : aGlobalID();
String importedFrom; // computer or snippet ID
String originatingUniverse; // global ID of "universe" concept was created in
boolean exportable = true;
Ref pngFile = new Ref();
String imageMD5, suggestedImageMD5;
Ref suggestedImage = new Ref();
boolean searchedForSuggestedImage;
long imported, touched; // timestamps
}
static class AIConcept extends Node {
String name;
String comment;
}
static class Matches {
String[] m;
String get(int i) { return i < m.length ? m[i] : null; }
String unq(int i) { return unquote(get(i)); }
String fsi(int i) { return formatSnippetID(unq(i)); }
String fsi() { return fsi(0); }
String tlc(int i) { return unq(i).toLowerCase(); }
boolean bool(int i) { return "true".equals(unq(i)); }
String rest() { return m[m.length-1]; } // for matchStart
int psi(int i) { return Integer.parseInt(unq(i)); }
}
// A concept should be an object, not just a string.
static int concepts_internStringsLongerThan = 10;
static ThreadLocal concepts_unlisted = new ThreadLocal();
static interface Derefable {
Concept get();
}
static class Concepts {
Map concepts = synchroTreeMap();
HashMap perClassData = new HashMap();
String programID; // set to "-" for non-persistent (possibly not implemented)
long idCounter;
volatile long changes = 1, changesWritten;
volatile java.util.Timer autoSaver;
volatile boolean savingConcepts;
int autoSaveInterval = -1000; // 1 second + wait logic
boolean useGZIP = true, quietSave;
ReentrantLock lock = new ReentrantLock(true);
ReentrantLock saverLock = new ReentrantLock(true);
long lastSaveTook, lastSaveWas;
float maxAutoSavePercentage = 10;
Concepts() {}
Concepts(String programID) {
this.programID = programID;}
synchronized long internalID() {
do {
++idCounter;
} while (hasConcept(idCounter));
return idCounter;
}
void initProgramID() {
if (programID == null)
programID = getDBProgramID();
}
// Now tries to load from bot first, then go to disk.
Concepts load() {
return load(false);
}
Concepts safeLoad() {
return load(true);
}
Concepts load(boolean allDynamic) {
initProgramID();
if (tryToGrab(allDynamic)) return this;
return loadFromDisk(allDynamic);
}
Concepts loadFromDisk() { return loadFromDisk(false); }
Concepts loadFromDisk(boolean allDynamic) {
clearConcepts();
DynamicObject_loading.set(true);
try {
long time = now();
Map _concepts = concepts; // empty map
readLocally2_allDynamic.set(allDynamic);
readLocally2(this, programID, "concepts");
Map __concepts = concepts;
concepts = _concepts;
concepts.putAll(__concepts);
int l = readLocally_stringLength;
int tokrefs = unstructure_tokrefs;
assignConceptsToUs();
done("Loaded " + n(l(concepts), "concepts"), time);
readLocally2(this, programID, "idCounter");
} finally {
DynamicObject_loading.set(null);
}
allChanged();
return this;
}
Concepts loadConcepts() { return load(); }
boolean tryToGrab(boolean allDynamic) {
if (sameSnippetID(programID, getDBProgramID())) return false;
RemoteDB db = connectToDBOpt(programID);
try {
if (db != null) {
loadGrab(db.fullgrab(), allDynamic);
return true;
}
} finally {
if (db != null) db.close();
}
return false;
}
Concepts load(String grab) {
return loadGrab(grab, false);
}
Concepts safeLoad(String grab) {
return loadGrab(grab, true);
}
Concepts loadGrab(String grab, boolean allDynamic) {
clearConcepts();
DynamicObject_loading.set(true);
try {
Map map = (Map)
(allDynamic ? safeUnstructure(grab) : unstructure(grab));
concepts.putAll(map);
assignConceptsToUs();
for (long l : map.keySet())
idCounter = max(idCounter, l);
} finally {
DynamicObject_loading.set(null);
}
allChanged();
return this;
}
void assignConceptsToUs() {
for (Concept c : values(concepts)) {
c._concepts = this;
callOpt_noArgs(c, "_doneLoading2");
}
}
String progID() {
return programID == null ? getDBProgramID() : programID;
}
Concept getConcept(String id) {
return empty(id) ? null : getConcept(parseLong(id));
}
Concept getConcept(long id) {
return (Concept) concepts.get((long) id);
}
Concept getConcept(RC ref) {
return ref == null ? null : getConcept(ref.longID());
}
boolean hasConcept(long id) {
return concepts.containsKey((long) id);
}
void deleteConcept(long id) {
Concept c = getConcept(id);
if (c == null)
print("Concept " + id + " not found");
else
c.delete();
}
void saveConceptsIfDirty() { saveConcepts(); }
void save() { saveConcepts(); }
void saveConcepts() {
initProgramID();
saverLock.lock();
savingConcepts = true;
long start = now(), time;
try {
String s = null;
//synchronized(main.class) {
File f = getProgramFile(programID, useGZIP ? "concepts.structure.gz" : "concepts.structure");
long _changes = changes;
if (_changes == changesWritten) return;
lock.lock();
long fullTime = now();
try {
saveLocally2(this, programID, "idCounter");
if (useGZIP) {
saveGZStructureToFile(f, cloneMap(concepts));
getProgramFile(programID, "concepts.structure").delete();
} else
s = structure(cloneMap(concepts));
} finally {
lock.unlock();
}
changesWritten = _changes; // only update when structure didn't fail
if (!useGZIP) {
time = now()-start;
if (!quietSave)
print("Saving " + toM(l(s)) + "M chars (" /*+ changesWritten + ", "*/ + time + " ms)");
start = now();
saveTextFile(f, javaTokWordWrap(s));
getProgramFile(programID, "concepts.structure.gz").delete();
}
copyFile(f, getProgramFile(programID, "concepts.structure" + (useGZIP ? ".gz" : "") + ".backup" + ymd() + "-" + formatInt(hours(), 2)));
time = now()-start;
if (!quietSave)
print(programID + ": Saved " + toK(f.length()) + " K, " + n(concepts, "concepts") + " (" + time + " ms)");
lastSaveWas = fullTime;
lastSaveTook = now()-fullTime;
} finally {
savingConcepts = false;
saverLock.unlock();
}
}
void _autoSaveConcepts() {
if (autoSaveInterval < 0 && maxAutoSavePercentage != 0) {
long pivotTime = Math.round(lastSaveWas+lastSaveTook*100.0/maxAutoSavePercentage);
if (now() < pivotTime) {
//print("Skipping auto-save (last save took " + lastSaveTook + ")");
return;
}
}
saveConcepts();
}
void clearConcepts() {
concepts.clear();
allChanged();
}
synchronized void allChanged() {
++changes;
}
// auto-save every second if dirty
synchronized void autoSaveConcepts() {
if (autoSaver == null) {
if (isTransient()) throw fail("Can't persist transient database");
autoSaver = doEvery_daemon(abs(autoSaveInterval), new Runnable() { public void run() { try { _autoSaveConcepts() ;
} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_autoSaveConcepts()"; }});
// print("Installed auto-saver (" + autoSaveInterval + " ms, " + progID() + ")");
}
}
void cleanMeUp() {
if (autoSaver != null) {
autoSaver.cancel();
autoSaver = null;
while (savingConcepts) sleepInCleanUp(10);
saveConceptsIfDirty();
}
}
Map getIDsAndNames() {
Map map = new HashMap();
Map cloned = cloneMap(concepts);
for (long id : keys(cloned))
map.put(id, cloned.get(id).className);
return map;
}
void deleteConcepts(List l) {
for (Object o : l)
if (o instanceof Long)
concepts.remove((Long) o);
else if (o instanceof Concept)
((Concept) o).delete();
else
warn("Can't delete " + getClassName(o));
}
A conceptOfType(Class type) {
return firstOfType(allConcepts(), type);
}
List conceptsOfType(Class type) {
return filterByType(allConcepts(), type);
}
List listConcepts(Class type) {
return conceptsOfType(type);
}
List list(Class type) {
return conceptsOfType(type);
}
List list(String type) {
return conceptsOfType(type);
}
List conceptsOfType(String type) {
return filterByDynamicType(allConcepts(), "main$" + type);
}
boolean hasConceptOfType(Class extends Concept> type) {
return hasType(allConcepts(), type);
}
void persistConcepts() {
loadConcepts();
autoSaveConcepts();
}
// We love synonyms
void conceptPersistence() {
persistConcepts();
}
void persist() { persistConcepts(); }
void persist(int interval) { autoSaveInterval = interval; persist(); }
// Runs r if there is no concept of that type
A ensureHas(Class c, Runnable r) {
A a = conceptOfType(c);
if (a == null) {
r.run();
a = conceptOfType(c);
if (a == null)
throw fail("Concept not made by " + r + ": " + shortClassName(c));
}
return a;
}
// Ensures that every concept of type c1 is ref'd by a concept of
// type c2.
// Type of func: voidfunc(concept)
void ensureHas(Class extends Concept> c1, Class extends Concept> c2, Object func) {
for (Concept a : conceptsOfType(c1)) {
Concept b = findBackRef(a, c2);
if (b == null) {
callF(func, a);
b = findBackRef(a, c2);
if (b == null)
throw fail("Concept not made by " + func + ": " + shortClassName(c2));
}
}
}
// Type of func: voidfunc(concept)
void forEvery(Class extends Concept> type, Object func) {
for (Concept c : conceptsOfType(type))
callF(func, c);
}
int deleteAll(Class extends Concept> type) {
List l = (List) conceptsOfType(type);
for (Concept c : l) c.delete();
return l(l);
}
Collection allConcepts() {
synchronized(concepts) {
return new ArrayList(values(concepts));
}
}
int countConcepts(Class c, Object... params) {
int n = 0;
for (A x : list(c)) if (checkConceptFields(x, params)) ++n;
return n;
}
int countConcepts(String c, Object... params) {
int n = 0;
for (Concept x : list(c)) if (checkConceptFields(x, params)) ++n;
return n;
}
int countConcepts() {
return l(concepts);
}
// inter-process methods
RC xnew(String name, Object... values) {
return new RC(cnew(name, values));
}
void xset(long id, String field, Object value) {
xset(new RC(id), field, value);
}
void xset(RC c, String field, Object value) {
if (value instanceof RC)
value = getConcept((RC) value);
cset(getConcept(c), field, value);
}
Object xget(long id, String field) {
return xget(new RC(id), field);
}
Object xget(RC c, String field) {
return xgetPost(cget(getConcept(c), field));
}
Object xgetPost(Object o) {
o = deref(o);
if (o instanceof Concept)
return new RC((Concept) o);
return o;
}
void xdelete(long id) {
xdelete(new RC(id));
}
void xdelete(RC c) {
getConcept(c).delete();
}
void xdelete(List l) {
for (RC c : l)
xdelete(c);
}
List xlist() {
return map("toPassRef", allConcepts());
}
List xlist(String className) {
return map("toPassRef", conceptsOfType(className));
}
boolean isTransient() { return eq(programID, "-"); }
String xfullgrab() {
lock.lock();
try {
if (changes == changesWritten && !isTransient())
return loadConceptsStructure(programID);
return structure(cloneMap(concepts));
} finally {
lock.unlock();
}
}
void xshutdown() {
// Killing whole VM if someone wants this DB to shut down
cleanKillVM();
}
long xchangeCount() { return changes; }
int xcount() { return countConcepts(); }
void register(Concept c) {
if (c._concepts == this) return;
if (c._concepts != null) throw fail("Can't re-register");
c._concepts = this;
c.id = internalID();
c.created = now();
concepts.put((long) c.id, c);
c.change();
}
} // class Concepts
static volatile Concepts mainConcepts = new Concepts(); // Where we create new concepts
static class Concept extends DynamicObject {
transient Concepts _concepts; // Where we belong
long id;
//O madeBy;
//double energy;
//bool defunct;
long created;
// used only internally (cnew)
Concept(String className) {
super(className);
_created();
}
Concept() {
if (!isTrue(DynamicObject_loading.get())) {
//className = shortClassName(this); // XXX - necessary?
//print("New concept of type " + className);
_created();
}
}
List[ refs;
List][ backRefs;
static boolean loading() { return _loading(); }
static boolean _loading() { return isTrue(DynamicObject_loading.get()); }
void _created() {
if (!isTrue(concepts_unlisted.get())) mainConcepts.register(this);
}
void put(String field, Object value) {
fieldValues.put(field, value);
change();
}
Object get(String field) {
return fieldValues.get(field);
}
class Ref {
A value;
Ref() {
if (!isTrue(DynamicObject_loading.get())) refs = addDyn(refs, this);
}
Ref(A value) {
this.value = value;
refs = addDyn(refs, this);
index();
}
// get owning concept (source)
Concept concept() {
return Concept.this;
}
// get target
A get() { return value; }
boolean has() { return value != null; }
void set(A a) {
if (a == value) return;
unindex();
value = a;
index();
}
void set(Ref ref) { set(ref.get()); }
void clear() { set((A) null); }
void index() {
if (value != null)
value.backRefs = addDyn(value.backRefs, this);
change();
}
void unindex() {
if (value != null)
value.backRefs = removeDyn(value.backRefs, this);
}
void change() {
Concept.this.change();
}
}
class RefL extends AbstractList {
List < Ref < A > > l = new ArrayList();
public A set(int i, A o) {
A prev = l.get(i).get();
l.get(i).set(o);
return prev;
}
public void add(int i, A o) {
l.add(i, new Ref(o));
}
public A get(int i) {
return l.get(i).get();
}
public A remove(int i) {
return l.remove(i).get();
}
public int size() {
return l.size();
}
public boolean contains(Object o) {
if (o instanceof Concept)
for (Ref r : l) if (eq(r.get(), o)) return true;
return super.contains(o);
}
}
void delete() {
//name = "[defunct " + name + "]";
//defunct = true;
//energy = 0;
for (Ref r : refs)
r.unindex();
refs = null;
for (Ref r : cloneList(backRefs))
r.set((Concept) null);
backRefs = null;
if (_concepts != null) {
_concepts.concepts.remove((long) id);
change();
_concepts = null;
}
id = 0;
}
BaseXRef export() {
return new BaseXRef(_concepts.progID(), id);
}
// notice system of a change in this object
void change() {
if (_concepts != null) _concepts.allChanged();
}
String _programID() {
return _concepts == null ? getDBProgramID() : _concepts.progID();
}
} // class Concept
// remote reference (for inter-process communication or
// external databases). Formerly "PassRef".
// prepared for string ids if we do them later
static class RC {
transient Object owner;
String id;
RC() {} // make serialisation happy
RC(long id) { this.id = str(id); }
RC(Object owner, long id) { this.id = str(id); this.owner = owner; }
RC(Concept c) { this(c.id); }
long longID() { return parseLong(id); }
public String toString() {
return id;
}
transient RemoteDB db;
String getString(String field) { return db.xS(this, field); }
Object get(String field) { return db.xget(this, field); }
void set(String field, Object value) { db.xset(this, field, value); }
}
// Reference to a concept in another program
static class BaseXRef {
String programID;
long id;
BaseXRef() {}
BaseXRef(String programID, long id) {
this.id = id;
this.programID = programID;}
public boolean equals(Object o) {
if (!(o instanceof BaseXRef)) return false;
BaseXRef r = (BaseXRef) ( o);
return eq(programID, r.programID) && eq(id, r.id);
}
public int hashCode() {
return programID.hashCode() + (int) id;
}
}
// BaseXRef as a concept
static class XRef extends Concept {
BaseXRef ref;
XRef() {}
XRef(BaseXRef ref) {
this.ref = ref; _doneLoading2(); }
// after we have been added to concepts
void _doneLoading2() {
getIndex().put(ref, this);
}
HashMap getIndex() {
return getXRefIndex(_concepts);
}
}
static synchronized HashMap getXRefIndex(Concepts concepts) {
HashMap cache = (HashMap) concepts.perClassData.get(XRef.class);
if (cache == null)
concepts.perClassData.put(XRef.class, cache = new HashMap());
return cache;
}
// uses mainConcepts
static XRef lookupOrCreateXRef(BaseXRef ref) {
XRef xref = getXRefIndex(mainConcepts).get(ref);
if (xref == null)
xref = new XRef(ref);
return xref;
}
// define standard concept functions to use main concepts
static List list(Class type) {
return mainConcepts.list(type);
}
static List list(Concepts concepts, Class type) {
return concepts.list(type);
}
static List list(String type) {
return mainConcepts.list(type);
}
static List list(Concepts concepts, String type) {
return concepts.list(type);
}
static int csetAll(Concept c, Object... values) {
return cset(c, values);
}
// returns number of changes
static int cset(Concept c, Object... values) { try {
int changes = 0;
values = expandParams(c.getClass(), values);
warnIfOddCount(values);
for (int i = 0; i+1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i+1];
Field f = setOpt_findField(c.getClass(), field);
//print("cset: " + c.id + " " + field + " " + struct(value) + " " + f);
if (value instanceof RC) value = c._concepts.getConcept((RC) value);
value = deref(value);
if (value instanceof String && l((String) value) >= concepts_internStringsLongerThan) value = ((String) value).intern();
if (f == null) {
// TODO: keep ref if it exists
c.fieldValues.put(field, value instanceof Concept ? c.new Ref((Concept) value) : value);
c.change();
} else if (isSubtypeOf(f.getType(), Concept.Ref.class)) {
((Concept.Ref) f.get(c)).set((Concept) derefRef(value));
c.change(); ++changes;
} else {
Object old = f.get(c);
if (neq(value, old)) {
f.set(c, value);
c.change(); ++changes;
}
}
}
return changes;
} catch (Exception __e) { throw rethrow(__e); } }
static void cleanMeUp_concepts() {
mainConcepts.cleanMeUp();
}
static void loadAndAutoSaveConcepts() {
mainConcepts.persist();
}
static void loadAndAutoSaveConcepts(int interval) {
mainConcepts.persist(interval);
}
static void loadConceptsFrom(String progID) {
mainConcepts.programID = progID;
mainConcepts.load();
}
static List conceptsOfType(String type) {
return mainConcepts.conceptsOfType(type);
}
static Collection allConcepts() {
return mainConcepts.allConcepts();
}
static long changeCount() {
return mainConcepts.changes;
}
static List exposedDBMethods = ll("xlist", "xnew", "xset", "xdelete", "xget", "xclass", "xfullgrab", "xshutdown", "xchangeCount", "xcount");
static RC toPassRef(Concept c) {
return new RC(c);
}
// so we can instantiate the program to run as a bare DB bot
public static String unquote(String s) {
if (s == null) return null;
if (s.startsWith("[")) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i+1, s.length()-i-1);
}
}
if ((s.startsWith("\"") || s.startsWith("\'")) && s.length() > 1) {
int l = s.endsWith(substring(s, 0, 1)) ? s.length()-1 : s.length();
StringBuilder sb = new StringBuilder(l-1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
// Octal escape?
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0'
&& s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch (nextChar) {
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\"':
ch = '\"';
break;
case '\'':
ch = '\'';
break;
// Hex Unicode: u????
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt(
"" + s.charAt(i + 2) + s.charAt(i + 3)
+ s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar; // added by Stefan
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
return s; // not quoted - return original
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
static String aGlobalID() {
return randomID(16);
}
static String substring(String s, int x) {
return substring(s, x, l(s));
}
static String substring(String s, int x, int y) {
if (s == null) return null;
if (x < 0) x = 0;
if (x > s.length()) return "";
if (y < x) y = x;
if (y > s.length()) y = s.length();
return s.substring(x, y);
}
// assumes the function returns toString()
static void gen(List l, Object func) {
l.add(new Gen(str(func), func));
}
static void gen(List l, String name, Object func) {
l.add(new Gen(name, func));
}
static void gen(List l, int line, Object func) {
gen(l, str(line), func);
}
static void gen(List l, Quine q) {
gen(l, q.text, q.value);
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0) throw fail("0 is not a snippet ID");
return id;
}
// 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;
}
static Class get_dynamicObject = DynamicObject.class;
// 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 (get_dynamicObject != null && get_dynamicObject.isInstance(o))
return call(get_raw(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 Collection aiConcepts() {
return values(aiConceptsMap_cached());
}
// hmm, this shouldn't call functions really. That was just
// for coroutines.
static boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null) return false;
return ((Boolean) callF(o)).booleanValue();
}
static boolean isTrue(Object pred, Object arg) {
return booleanValue(callF(pred, arg));
}
static String fsi(String id) {
return formatSnippetID(id);
}
static Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static Object callF(Object f, Object... args) {
return callFunction(f, args);
}
static Cache]