Warning : session_start(): open(/var/lib/php/sessions/sess_ccruv2vlrs7ujplq09furu9575, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBotOpt;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.rethrow;
import static loadableUtils.utils.hasBot;
import static loadableUtils.utils.concepts_setUnlistedByDefault;
import static loadableUtils.utils.realMC_tl;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF0;
import loadableUtils.utils.IF1;
import loadableUtils.utils.IVF1;
import loadableUtils.utils.IVF2;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.RC;
import loadableUtils.utils.IConceptIndex;
import loadableUtils.utils.IConceptCounter;
import loadableUtils.utils.IterableIterator;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import loadableUtils.utils.SecretValue;
import loadableUtils.utils.HCRUD;
import loadableUtils.utils.HCRUD_Data;
import loadableUtils.utils.HCRUD_Concepts;
import loadableUtils.utils.DefaultValueConverterForField;
import loadableUtils.utils.OrError;
import loadableUtils.utils.HTML;
import java.text.*;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import javax.swing.undo.UndoManager;
import java.awt.datatransfer.StringSelection;
import java.util.TimeZone;
import java.awt.geom.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import javax.swing.border.*;
class main {
static public class MemberCompany extends Concept {
static final public String _fieldOrder = "productName description funding raised payZonesSubscribed ends";
public String productName;
public String description;
public String funding;
public String raised;
public int payZonesSubscribed;
public String ends;
}
static public class Pays5 extends GazelleExamples {
public void init() {
super.init();
botName = heading = adminName = "PAYS5";
templateID = "#1030430";
cssID = "396";
enableVars = true;
enableAvatars = true;
showTalkToBotLink = true;
enableRadioButtons = true;
quickRadioButtons = true;
newDialogAfterWindowClosed = true;
showJoiningConversation = true;
timeZone = nyTimeZone_string();
phoneNumberSpecialInputField = false;
}
public List crudClasses(Req req) {
return listPlus(super.crudClasses(req), MemberCompany.class);
}
public Set hiddenCrudClasses() {
return litset();
}
public List botCmdClasses() {
return dynNewBot2_botCmdClasses();
}
public String authFormHeading() {
return h3("pays5.com");
}
public void makeFramer(Req req) {
super.makeFramer(req);
req.framer.renderTitle = () -> h1(ahref(baseLink + "/", "Pays5.com") + " " + htmlEncode2(req.framer.title));
}
public String calcVar(Conversation conv, String var) {
if (eqic(var, "hasUserName"))
return str(nempty(calcVar(conv, "userName")));
return super.calcVar(conv, var);
}
public String cssURL() {
return "https://pays5.com/text/" + cssID;
}
public Object serveOtherPage(Req req) {
if (eqOptSlash(req.uri, "/companies")) {
req.markNoSpam();
String template = getText(eq(req.params.get("dev"), "1") ? 2961 : 2559);
SmoothHTMLTemplater templater = new SmoothHTMLTemplater(template);
templater.entriesByType.put("company", map(list(MemberCompany.class), x -> templater.mapToEntry(litcimap("Wash pebbles", x.productName, "spherical hydrogel sanitiser", x.description, "$ 435,000", x.funding, "% 1.245", x.raised, "6,432", x.payZonesSubscribed, "34 days", x.ends))));
return templater.render();
}
return super.serveOtherPage(req);
}
public boolean allowedTemplateID(String id) {
return sameSnippetID(id, "#1030498");
}
}
static public boolean _moduleClass_Pays5 = true;
static public class GazelleExamples extends DynGazelleRocks {
public void init() {
super.init();
useBotNameAsModuleName = false;
}
public List navLinks(Object... __) {
return itemPlusList(ahref("https://bea.gazelle.rocks", "Switch to BEA", "title", "Latest iteration of Gazelle"), super.navLinks(__));
}
}
static public boolean _moduleClass_GazelleExamples = true;
static public String programID;
static public void _onLoad_initUtils() {
utils.__javax = javax();
}
static public void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
public Class get(String name) {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (name.startsWith("main$"))
return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
return null;
}
});
}
static public ThreadLocal dynamicObjectIsLoading_threadLocal() {
return DynamicObject_loading;
}
static volatile public Concepts mainConcepts;
static public Concepts db_mainConcepts() {
if (mainConcepts == null)
mainConcepts = newConceptsWithClassFinder(getDBProgramID());
return mainConcepts;
}
static public void cleanMeUp_concepts() {
if (db_mainConcepts() != null)
db_mainConcepts().cleanMeUp();
}
static public String nyTimeZone_string() {
return "US/Eastern";
}
static public List listPlus(Collection l, A... more) {
return concatLists(l, asList(more));
}
static public HashSet litset(A... items) {
return lithashset(items);
}
static public String h3(String s, Object... params) {
return tag("h3", s, params) + "\n";
}
static public String h1(String s, Object... params) {
return hfulltag("h1", s, params);
}
static public String ahref(String link, Object contents, Object... params) {
return link == null ? str(contents) : href(link, contents, params);
}
static public String htmlEncode2(String s) {
return htmlencode_noQuotes(s);
}
static public String htmlEncode2(Object o) {
return htmlEncode2(strOrEmpty(o));
}
static public boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(Symbol a, Symbol b) {
return eq(a, b);
}
static public boolean eqic(Symbol a, String b) {
return eqic(asString(a), b);
}
static public 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);
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public boolean nempty(Collection c) {
return !empty(c);
}
static public boolean nempty(CharSequence s) {
return !empty(s);
}
static public boolean nempty(Object[] o) {
return !empty(o);
}
static public boolean nempty(byte[] o) {
return !empty(o);
}
static public boolean nempty(int[] o) {
return !empty(o);
}
static public boolean nempty(Map m) {
return !empty(m);
}
static public boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static public boolean nempty(Object o) {
return !empty(o);
}
static public boolean nempty(IntRange r) {
return !empty(r);
}
static public boolean nempty(Rect r) {
return r != null && r.w != 0 && r.h != 0;
}
static public boolean eqOptSlash(String a, String b) {
int n = lCommonPrefix(a, b);
int la = l(a), lb = l(b);
if (n == la && n == lb)
return true;
if (n == lb && n == la - 1 && lastChar(a) == '/')
return true;
if (n == la && n == lb - 1 && lastChar(b) == '/')
return true;
return false;
}
static public String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
static public String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
static public String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return l.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret l.getText();";
}
});
}
static public 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 public boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public boolean eq(Symbol a, String b) {
return eq(str(a), b);
}
static public List map(Iterable l, Object f) {
return map(f, l);
}
static public List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) {
ping();
x.add(callF(f, o));
}
return x;
}
static public List map(Iterable l, F1 f) {
return map(f, l);
}
static public List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) {
ping();
x.add(callF(f, o));
}
return x;
}
static public List map(IF1 f, Iterable l) {
return map(l, f);
}
static public List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) {
ping();
x.add(f.get(o));
}
return x;
}
static public List map(IF1 f, A[] l) {
return map(l, f);
}
static public List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) {
ping();
x.add(f.get(o));
}
return x;
}
static public List map(Object f, Object[] l) {
return map(f, asList(l));
}
static public List map(Object[] l, Object f) {
return map(f, l);
}
static public List map(Object f, Map map) {
return map(map, f);
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
ping();
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static public List map(IF1 f, A data1, A... moreData) {
List x = emptyList(l(moreData) + 1);
x.add(f.get(data1));
if (moreData != null)
for (A o : moreData) {
ping();
x.add(f.get(o));
}
return x;
}
static public List list(Class type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, Class type) {
return concepts.list(type);
}
static public List list(String type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, String type) {
return concepts.list(type);
}
static public TreeMap litcimap(Object... x) {
return litCIMap(x);
}
static public boolean sameSnippetID(String a, String b) {
if (!isSnippetID(a) || !isSnippetID(b))
return false;
return parseSnippetID(a) == parseSnippetID(b);
}
static public List itemPlusList(A a, Collection l) {
return concatLists(ll(a), l);
}
static public Class javax() {
return getJavaX();
}
static public void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
static public HashMap findClass_fullName_cache = new HashMap();
static public Class findClass_fullName(String name) {
synchronized (findClass_fullName_cache) {
if (findClass_fullName_cache.containsKey(name))
return findClass_fullName_cache.get(name);
Class c;
try {
c = Class.forName(name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_fullName_cache.put(name, c);
return c;
}
}
static public Object _defaultClassFinder_value = defaultDefaultClassFinder();
static public Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
static public Concepts newConceptsWithClassFinder(String progID) {
Concepts cc = new Concepts(progID);
cc.classFinder = _defaultClassFinder();
return cc;
}
static public String getDBProgramID_id;
static public String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
static public List concatLists(Iterable ... lists) {
List l = new ArrayList();
if (lists != null)
for (Iterable list : lists) addAll(l, list);
return l;
}
static public List concatLists(Collection extends Iterable > lists) {
List l = new ArrayList();
if (lists != null)
for (Iterable list : lists) addAll(l, list);
return l;
}
static public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(long[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static public ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static public ArrayList asList(double[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static public ArrayList asList(Iterator it) {
ArrayList l = new ArrayList();
if (it != null)
while (it.hasNext()) l.add(it.next());
return l;
}
static public ArrayList asList(IterableIterator s) {
return asList((Iterator) s);
}
static public 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 public ArrayList asList(Producer p) {
ArrayList l = new ArrayList();
A a;
if (p != null)
while ((a = p.next()) != null) l.add(a);
return l;
}
static public ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
static public HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
static public String tag(String tag) {
return htag(tag);
}
static public String tag(String tag, Object contents, Object... params) {
return htag(tag, str(contents), params);
}
static public String tag(String tag, StringBuilder contents, Object... params) {
return htag(tag, contents, params);
}
static public String tag(String tag, StringBuffer contents, Object... params) {
return htag(tag, contents, params);
}
static public String hfulltag(String tag) {
return hfulltag(tag, "");
}
static public String hfulltag(String tag, Object contents, Object... params) {
return hopeningTag(tag, params) + str(contents) + "" + tag + ">";
}
static public String href(String link, Object contents, Object... params) {
if (link == null)
return str(contents);
return hfulltag("a", contents, arrayPlus(params, "href", link));
}
static public String htmlencode_noQuotes(String s) {
if (s == null)
return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '<')
out.append("<");
else if (c == '>')
out.append(">");
else if (c > 127 || c == '&') {
int cp = s.codePointAt(i);
out.append("");
out.append(intToHex_flexLength(cp));
out.append(';');
i += Character.charCount(cp) - 1;
} else
out.append(c);
}
return out.toString();
}
static public String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static public String asString(Object o) {
return o == null ? null : o.toString();
}
static public boolean empty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean empty(Iterable c) {
return c == null || !c.iterator().hasNext();
}
static public boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean empty(Map map) {
return map == null || map.isEmpty();
}
static public boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static public 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 public boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
static public boolean empty(double[] a) {
return a == null || a.length == 0;
}
static public boolean empty(float[] a) {
return a == null || a.length == 0;
}
static public boolean empty(int[] a) {
return a == null || a.length == 0;
}
static public boolean empty(long[] a) {
return a == null || a.length == 0;
}
static public boolean empty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean empty(short[] a) {
return a == null || a.length == 0;
}
static public boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
static public boolean empty(MultiMap mm) {
return mm == null || mm.isEmpty();
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public boolean empty(IntRange r) {
return r == null || r.empty();
}
static public boolean empty(Rect r) {
return !(r != null && r.w != 0 && r.h != 0);
}
static public int lCommonPrefix(String a, String b) {
int i = 0, n = Math.min(l(a), l(b));
while (i < n && a.charAt(i) == b.charAt(i)) ++i;
return i;
}
static public char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s) - 1);
}
static public void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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 public boolean isEditableComboBox(final JComboBox cb) {
return cb != null && swing(new F0() {
public Boolean get() {
try {
return cb.isEditable();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret cb.isEditable();";
}
});
}
static public String unnull(String s) {
return s == null ? "" : s;
}
static public Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static public List unnull(List l) {
return l == null ? emptyList() : l;
}
static public int[] unnull(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnull(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnull(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static public Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static public A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnull(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public int unnull(Integer i) {
return i == null ? 0 : i;
}
static public long unnull(Long l) {
return l == null ? 0L : l;
}
static public double unnull(Double l) {
return l == null ? 0.0 : l;
}
static public ArrayList emptyList() {
return new ArrayList();
}
static public ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
static public ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static public ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
static public ArrayList emptyList(Class c) {
return new ArrayList();
}
static volatile public boolean ping_pauseAll = false;
static public int ping_sleep = 100;
static volatile public boolean ping_anyActions = false;
static public Map ping_actions = newWeakHashMap();
static public ThreadLocal ping_isCleanUpThread = new ThreadLocal();
static public boolean ping() {
newPing();
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty())
ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
return x30_util.callF(f, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A callF(F0 f) {
return f == null ? null : f.get();
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
static public Object callMC(String method, Object... args) {
return call(mc(), method, args);
}
static public Object call(Object o) {
return callF(o);
}
static public Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
static public TreeMap litCIMap(Object... x) {
TreeMap map = caseInsensitiveMap();
litmap_impl(map, x);
return map;
}
public static boolean isSnippetID(String s) {
try {
parseSnippetID(s);
return true;
} catch (RuntimeException e) {
return false;
}
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
static public List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
static public Class __javax;
static public Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object defaultDefaultClassFinder() {
return new F1() {
public Class get(String name) {
Class c = get2(name);
return c;
}
public Class get2(String name) {
if (eq(name, ""))
return mc();
{
Class c = findClass_fullName(name);
if (c != null)
return c;
}
if (startsWithAny(name, "loadableUtils.utils$", "main$", mcDollar()))
for (String pkg : ll("loadableUtils.utils$", mcDollar())) {
String newName = pkg + afterDollar(name);
{
Class c = findClass_fullName(newName);
if (c != null)
return c;
}
}
return null;
}
};
}
static public String programIDWithCase() {
return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID();
}
static public void addAll(Collection c, Iterable b) {
if (c != null && b != null)
for (A a : b) c.add(a);
}
static public boolean addAll(Collection c, Collection b) {
return c != null && b != null && c.addAll(b);
}
static public boolean addAll(Collection c, B... b) {
return c != null && b != null && c.addAll(Arrays.asList(b));
}
static public Map addAll(Map a, Map extends A, ? extends B> b) {
if (a != null && b != null)
a.putAll(b);
return a;
}
static public String htag(String tag) {
return htag(tag, "");
}
static public String htag(String tag, Object contents, Object... params) {
String openingTag = hopeningTag(tag, params);
String s = str(contents);
if (empty(s) && neqic(tag, "script"))
return dropLast(openingTag) + "/>";
return openingTag + s + "" + tag + ">";
}
static public String hopeningTag(String tag, Map params) {
return hopeningTag(tag, mapToParams(params));
}
static public String hopeningTag(String tag, Object... params) {
StringBuilder buf = new StringBuilder();
buf.append("<" + tag);
params = unrollParams(params);
for (int i = 0; i < l(params); i += 2) {
String name = (String) get(params, i);
Object val = get(params, i + 1);
if (nempty(name) && val != null) {
if (eqOneOf(val, html_valueLessParam(), true))
buf.append(" " + name);
else {
String s = str(val);
if (!empty(s))
buf.append(" " + name + "=" + htmlQuote(s));
}
}
}
buf.append(">");
return str(buf);
}
static public String a(String noun) {
if (eq(noun, ""))
return "?";
return ("aeiou".indexOf(noun.charAt(0)) >= 0 ? "an " : "a ") + noun;
}
static public String a(String contents, Object... params) {
return hfulltag("a", contents, params);
}
static public Object[] arrayPlus(Object[] a1, Object... a2) {
return concatArrays(a1, a2);
}
static public String intToHex_flexLength(int i) {
return Integer.toHexString(i);
}
static public RuntimeException fail() {
throw new RuntimeException("fail");
}
static public RuntimeException fail(Throwable e) {
throw asRuntimeException(e);
}
static public RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static public RuntimeException fail(Object... objects) {
throw new Fail(objects);
}
static public RuntimeException fail(String msg) {
throw new RuntimeException(msg == null ? "" : msg);
}
static public RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
static public String getType(Object o) {
return getClassName(o);
}
static public long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static public long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static public boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
static public boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static public 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 public Object swing(Object f) {
return swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public int[] emptyIntArray_a = new int[0];
static public int[] emptyIntArray() {
return emptyIntArray_a;
}
static public char[] emptyCharArray = new char[0];
static public char[] emptyCharArray() {
return emptyCharArray;
}
static public double[] emptyDoubleArray = new double[0];
static public double[] emptyDoubleArray() {
return emptyDoubleArray;
}
static public Map emptyMap() {
return new HashMap();
}
static public Object[] emptyObjectArray_a = new Object[0];
static public Object[] emptyObjectArray() {
return emptyObjectArray_a;
}
static public Symbol emptySymbol_value;
static public Symbol emptySymbol() {
if (emptySymbol_value == null)
emptySymbol_value = symbol("");
return emptySymbol_value;
}
static public int max(int a, int b) {
return Math.max(a, b);
}
static public int max(int a, int b, int c) {
return max(max(a, b), c);
}
static public long max(int a, long b) {
return Math.max((long) a, b);
}
static public long max(long a, long b) {
return Math.max(a, b);
}
static public double max(int a, double b) {
return Math.max((double) a, b);
}
static public float max(float a, float b) {
return Math.max(a, b);
}
static public double max(double a, double b) {
return Math.max(a, b);
}
static public int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static public 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 public 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 public byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
static public short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
static public int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
static public void newPing() {
var tl = newPing_actionTL();
Runnable action = tl == null ? null : tl.get();
{
if (action != null)
action.run();
}
}
static public void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static public Thread currentThread() {
return Thread.currentThread();
}
static public Class mc() {
return main.class;
}
static public Object call_withVarargs(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);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
{
if (!(isStaticMethod(m)))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public TreeMap caseInsensitiveMap() {
return new TreeMap(caseInsensitiveComparator());
}
static public HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static public void litmap_impl(Map map, Object... x) {
if (x != null)
for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
map.put(x[i], x[i + 1]);
}
static public String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
static public Object get2(Object o, String field1, String field2) {
return get(get(o, field1), field2);
}
static public boolean startsWithAny(String a, Collection b) {
for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix))
return true;
return false;
}
static public boolean startsWithAny(String a, String... b) {
if (b != null)
for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix))
return true;
return false;
}
static public boolean startsWithAny(String a, Collection b, Matches m) {
for (String prefix : unnullForIteration(b)) if (startsWith(a, prefix, m))
return true;
return false;
}
static public String mcDollar() {
return mcName() + "$";
}
static public String afterDollar(String s) {
return substring(s, smartIndexOf(s, '$') + 1);
}
static volatile public String caseID_caseID;
static public String caseID() {
return caseID_caseID;
}
static public void caseID(String id) {
caseID_caseID = id;
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static public String quoteUnlessIdentifierOrInteger(String s) {
return quoteIfNotIdentifierOrInteger(s);
}
static public boolean neqic(String a, String b) {
return !eqic(a, b);
}
static public boolean neqic(char a, char b) {
return !eqic(a, b);
}
static public A[] dropLast(A[] a) {
return dropLast(a, 1);
}
static public A[] dropLast(A[] a, int n) {
if (a == null)
return null;
n = Math.min(n, a.length);
A[] b = arrayOfSameType(a, a.length - n);
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static public List dropLast(List l) {
return subList(l, 0, l(l) - 1);
}
static public List dropLast(int n, List l) {
return subList(l, 0, l(l) - n);
}
static public List dropLast(Iterable l) {
return dropLast(asList(l));
}
static public String dropLast(String s) {
return substring(s, 0, l(s) - 1);
}
static public String dropLast(String s, int n) {
return substring(s, 0, l(s) - n);
}
static public String dropLast(int n, String s) {
return dropLast(s, n);
}
static public Object[] mapToParams(Map map) {
return mapToObjectArray(map);
}
static public Object[] unrollParams(Object[] params) {
if (l(params) == 1 && params[0] instanceof Map)
return mapToParams((Map) params[0]);
return params;
}
static public boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
static public Object html_valueLessParam_cache;
static public Object html_valueLessParam() {
if (html_valueLessParam_cache == null)
html_valueLessParam_cache = html_valueLessParam_load();
return html_valueLessParam_cache;
}
static public Object html_valueLessParam_load() {
return new Object();
}
static public String htmlQuote(String s) {
return "\"" + htmlencode_forParams(s) + "\"";
}
static public Object[] concatArrays(Object[]... arrays) {
int l = 0;
for (Object[] a : arrays) l += l(a);
Object[] x = new Object[l];
int i = 0;
for (Object[] a : arrays) if (a != null) {
System.arraycopy(a, 0, x, i, l(a));
i += l(a);
}
return x;
}
static public RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static public Runnable asRunnable(Object o) {
return toRunnable(o);
}
static public void _inheritThreadInfo(Object info) {
_threadInheritInfo(info);
}
static public WeakHasherMap symbol_map = new WeakHasherMap(new Hasher() {
public int hashCode(Symbol symbol) {
return symbol.text.hashCode();
}
public boolean equals(Symbol a, Symbol b) {
if (a == null)
return b == null;
return b != null && eq(a.text, b.text);
}
});
static public Symbol symbol(String s) {
if (s == null)
return null;
synchronized (symbol_map) {
Symbol symbol = new Symbol(s, true);
Symbol existingSymbol = symbol_map.findKey(symbol);
if (existingSymbol == null)
symbol_map.put(existingSymbol = symbol, true);
return existingSymbol;
}
}
static public Symbol symbol(CharSequence s) {
if (s == null)
return null;
if (s instanceof Symbol)
return (Symbol) s;
if (s instanceof String)
return symbol((String) s);
return symbol(str(s));
}
static public Symbol symbol(Object o) {
return symbol((CharSequence) o);
}
static public x30_pkg.x30_util.BetterThreadLocal newPing_actionTL;
static public x30_pkg.x30_util.BetterThreadLocal newPing_actionTL() {
if (newPing_actionTL == null)
newPing_actionTL = vm_generalMap_getOrCreate("newPing_actionTL", () -> new x30_pkg.x30_util.BetterThreadLocal());
return newPing_actionTL;
}
static volatile public boolean licensed_yes = true;
static public boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
static public void licensed_off() {
licensed_yes = false;
}
static final public Map callOpt_cache = newDangerousWeakHashMap();
static public 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);
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 public _MethodCache callOpt_getCache(Class c) {
_MethodCache cache = callOpt_cache.get(c);
if (cache == null)
callOpt_cache.put(c, cache = new _MethodCache(c));
return cache;
}
static public 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 public boolean isStaticMethod(Method m) {
return methodIsStatic(m);
}
static public Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
Class>[] types = m.getParameterTypes();
int n = types.length - 1, nArgs = args.length;
if (nArgs < n)
return null;
for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
return null;
Class varArgType = types[n].getComponentType();
for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
return null;
Object[] newArgs = new Object[n + 1];
arraycopy(args, 0, newArgs, 0, n);
Object[] varArgs = arrayOfType(varArgType, nArgs - n);
arraycopy(args, n, varArgs, 0, nArgs - n);
newArgs[n] = varArgs;
return newArgs;
}
static public String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static public List classNames(Collection l) {
return getClassNames(l);
}
static public List classNames(Object[] l) {
return getClassNames(Arrays.asList(l));
}
static public Comparator caseInsensitiveComparator() {
return betterCIComparator();
}
static public long parseLong(String s) {
if (empty(s))
return 0;
return Long.parseLong(dropSuffix("L", s));
}
static public long parseLong(Object s) {
return Long.parseLong((String) s);
}
static public String unnullForIteration(String s) {
return s == null ? "" : s;
}
static public Collection unnullForIteration(Collection l) {
return l == null ? immutableEmptyList() : l;
}
static public List unnullForIteration(List l) {
return l == null ? immutableEmptyList() : l;
}
static public int[] unnullForIteration(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnullForIteration(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnullForIteration(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public short[] unnullForIteration(short[] l) {
return l == null ? emptyShortArray() : l;
}
static public Map unnullForIteration(Map l) {
return l == null ? immutableEmptyMap() : l;
}
static public Iterable unnullForIteration(Iterable i) {
return i == null ? immutableEmptyList() : i;
}
static public A[] unnullForIteration(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnullForIteration(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnullForIteration(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnullForIteration(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnullForIteration(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public long unnullForIteration(Long l) {
return l == null ? 0L : l;
}
static public boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static public boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static public boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
if (m != null)
m.m = new String[] { substring(a, strL(b)) };
return true;
}
static public boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static public String mcName() {
return mc().getName();
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
int n = s.length();
if (y < x)
y = x;
if (y > n)
y = n;
if (x >= y)
return "";
return s.substring(x, y);
}
static public String substring(String s, IntRange r) {
return r == null ? null : substring(s, r.start, r.end);
}
static public String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
static public int smartIndexOf(String s, String sub, int i) {
if (s == null)
return 0;
i = s.indexOf(sub, min(i, l(s)));
return i >= 0 ? i : l(s);
}
static public int smartIndexOf(String s, int i, char c) {
return smartIndexOf(s, c, i);
}
static public int smartIndexOf(String s, char c, int i) {
if (s == null)
return 0;
i = s.indexOf(c, min(i, l(s)));
return i >= 0 ? i : l(s);
}
static public int smartIndexOf(String s, String sub) {
return smartIndexOf(s, sub, 0);
}
static public int smartIndexOf(String s, char c) {
return smartIndexOf(s, c, 0);
}
static public int smartIndexOf(List l, A sub) {
return smartIndexOf(l, sub, 0);
}
static public int smartIndexOf(List l, int start, A sub) {
return smartIndexOf(l, sub, start);
}
static public int smartIndexOf(List l, A sub, int start) {
int i = indexOf(l, sub, start);
return i < 0 ? l(l) : i;
}
static public String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
static public String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static public String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static public String quoteIfNotIdentifierOrInteger(String s) {
if (s == null)
return null;
return isJavaIdentifier(s) || isInteger(s) ? s : quote(s);
}
static public A[] arrayOfSameType(A[] a, int n) {
return newObjectArrayOfSameType(a, n);
}
static public List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static public List subList(int startIndex, List l) {
return subList(l, startIndex);
}
static public List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static public List subList(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex > endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return l.subList(startIndex, endIndex);
}
static public List subList(List l, IntRange r) {
return subList(l, r.start, r.end);
}
static public Object[] mapToObjectArray(Map map) {
List l = new ArrayList();
for (Object o : keys(map)) {
l.add(o);
l.add(map.get(o));
}
return toObjectArray(l);
}
static public Object[] mapToObjectArray(Object f, Collection l) {
int n = l(l);
Object[] array = new Object[n];
if (n != 0) {
Iterator it = iterator(l);
for (int i = 0; i < n; i++) array[i] = callF(f, it.next());
}
return array;
}
static public Object[] mapToObjectArray(Object f, Object[] l) {
int n = l(l);
Object[] array = new Object[n];
for (int i = 0; i < n; i++) array[i] = callF(f, l[i]);
return array;
}
static public Object[] mapToObjectArray(Collection l, IF1 f) {
return mapToObjectArray(f, l);
}
static public Object[] mapToObjectArray(A[] l, IF1 f) {
return mapToObjectArray(f, l);
}
static public Object[] mapToObjectArray(IF1 f, A[] l) {
int n = l(l);
Object[] array = new Object[n];
for (int i = 0; i < n; i++) array[i] = f.get(l[i]);
return array;
}
static public ThreadLocal htmlencode_forParams_useV2 = new ThreadLocal();
static public String htmlencode_forParams(String s) {
if (s == null)
return "";
if (isTrue(htmlencode_forParams_useV2.get()))
return htmlencode_forParams_v2(s);
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>') {
out.append("");
out.append((int) c);
out.append(';');
} else
out.append(c);
}
return out.toString();
}
static public void _handleError(Error e) {
call(javax(), "_handleError", e);
}
static public 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 public A vm_generalMap_getOrCreate(Object key, F0 create) {
return vm_generalMap_getOrCreate(key, f0ToIF0(create));
}
static public A vm_generalMap_getOrCreate(Object key, IF0 create) {
Map generalMap = vm_generalMap();
if (generalMap == null)
return null;
synchronized (generalMap) {
A a = (A) (vm_generalMap_get(key));
if (a == null)
vm_generalMap_put(key, a = create == null ? null : create.get());
return a;
}
}
static public void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
static public Throwable getExceptionCause(Throwable e) {
Throwable c = e.getCause();
return c != null ? c : e;
}
static public String joinWithSpace(Iterable c) {
return join(" ", c);
}
static public String joinWithSpace(String... c) {
return join(" ", c);
}
static public boolean methodIsStatic(Method m) {
return (m.getModifiers() & Modifier.STATIC) != 0;
}
static public boolean argumentCompatibleWithType(Object arg, Class type) {
return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
}
static public void arraycopy(Object[] a, Object[] b) {
if (a != null && b != null)
arraycopy(a, 0, b, 0, Math.min(a.length, b.length));
}
static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
if (n != 0)
System.arraycopy(src, srcPos, dest, destPos, n);
}
static public A[] arrayOfType(Class type, int n) {
return makeArray(type, n);
}
static public A[] arrayOfType(int n, Class type) {
return arrayOfType(type, n);
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return str(first((Collection) strings));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static public String join(Iterable strings) {
return join("", strings);
}
static public String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static public String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static public List getClassNames(Collection l) {
List out = new ArrayList();
if (l != null)
for (Object o : l) out.add(o == null ? null : getClassName(o));
return out;
}
static public betterCIComparator_C betterCIComparator_instance;
static public betterCIComparator_C betterCIComparator() {
if (betterCIComparator_instance == null)
betterCIComparator_instance = new betterCIComparator_C();
return betterCIComparator_instance;
}
final static public class betterCIComparator_C implements Comparator {
public int compare(String s1, String s2) {
if (s1 == null)
return s2 == null ? 0 : -1;
if (s2 == null)
return 1;
int n1 = s1.length();
int n2 = s2.length();
int min = Math.min(n1, n2);
for (int i = 0; i < min; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2) {
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
if (c1 != c2) {
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);
if (c1 != c2) {
return c1 - c2;
}
}
}
}
return n1 - n2;
}
}
static public String dropSuffix(String suffix, String s) {
return nempty(suffix) && endsWith(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
static public List immutableEmptyList() {
return Collections.emptyList();
}
static public short[] emptyShortArray = new short[0];
static public short[] emptyShortArray() {
return emptyShortArray;
}
static public Map immutableEmptyMap() {
return Collections.emptyMap();
}
static public boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static public int strL(String s) {
return s == null ? 0 : s.length();
}
static public int listL(Collection l) {
return l == null ? 0 : l.size();
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static public int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
static public int min(int a, int b) {
return Math.min(a, b);
}
static public long min(long a, long b) {
return Math.min(a, b);
}
static public float min(float a, float b) {
return Math.min(a, b);
}
static public float min(float a, float b, float c) {
return min(min(a, b), c);
}
static public double min(double a, double b) {
return Math.min(a, b);
}
static public double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static public float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static public byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
static public short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
static public int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
static public String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static public String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static public String formatSnippetID(long id) {
return "#" + id;
}
static public Class getMainClass() {
return mc();
}
static public Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
ClassLoader cl = (o instanceof Class ? (Class) o : o.getClass()).getClassLoader();
if (cl == null)
return null;
String name = mainClassNameForClassLoader(cl);
return loadClassFromClassLoader_orNull(cl, name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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 public boolean isInteger(String s) {
int n = l(s);
if (n == 0)
return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n)
return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9')
return false;
++i;
}
return true;
}
static public String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
static public String quote(String s) {
if (s == null)
return "null";
StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
quote_impl(s, out);
return out.toString();
}
static public void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\t')
out.append("\\t");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static public A[] newObjectArrayOfSameType(A[] a) {
return newObjectArrayOfSameType(a, a.length);
}
static public A[] newObjectArrayOfSameType(A[] a, int n) {
return (A[]) Array.newInstance(a.getClass().getComponentType(), n);
}
static public Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keys(Object map) {
return keys((Map) map);
}
static public Set keys(MultiSet ms) {
return ms.keySet();
}
static public Set keys(MultiMap mm) {
return mm.keySet();
}
static public Set keys(MultiSetMap mm) {
return mm.keySet();
}
static public Object[] toObjectArray(Collection c) {
return toObjectArray((Iterable) c);
}
static public Object[] toObjectArray(Iterable c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static public Iterator iterator(Iterable c) {
return c == null ? emptyIterator() : c.iterator();
}
static public String htmlencode_forParams_v2(String s) {
if (s == null)
return "";
StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
out.append("");
out.append((int) c);
out.append(';');
} else
out.append(c);
}
return out.toString();
}
static public IF0 f0ToIF0(F0 f) {
return f == null ? null : () -> f.get();
}
static public Map vm_generalMap_map;
static public Map vm_generalMap() {
if (vm_generalMap_map == null)
vm_generalMap_map = (Map) get(javax(), "generalMap");
return vm_generalMap_map;
}
static public Object vm_generalMap_get(Object key) {
return vm_generalMap().get(key);
}
static public Object vm_generalMap_put(Object key, Object value) {
return mapPutOrRemove(vm_generalMap(), key, value);
}
static public 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 public A[] makeArray(Class type, int n) {
return (A[]) Array.newInstance(type, n);
}
static public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public A first(IterableIterator i) {
return first((Iterator ) i);
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public Character first(CharSequence s) {
return empty(s) ? null : s.charAt(0);
}
static public A first(Pair p) {
return p == null ? null : p.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public A first(A[] l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(Iterable l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(IF1 pred, Iterable l) {
return firstThat(pred, l);
}
static public boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static public boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
static public boolean endsWith(String a, String b, Matches m) {
if (!endsWith(a, b))
return false;
m.m = new String[] { dropLast(l(b), a) };
return true;
}
static public String mainClassNameForClassLoader(ClassLoader cl) {
return or((String) callOpt(cl, "mainClassName"), "main");
}
static public Class loadClassFromClassLoader_orNull(ClassLoader cl, String name) {
try {
return cl == null ? null : cl.loadClass(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Iterator emptyIterator() {
return Collections.emptyIterator();
}
static public B mapPutOrRemove(Map map, A key, B value) {
if (map != null && key != null)
if (value != null)
return map.put(key, value);
else
return map.remove(key);
return null;
}
static public A firstThat(Iterable l, Object pred) {
if (l != null)
for (A a : l) if (checkCondition(pred, a))
return a;
return null;
}
static public A firstThat(A[] l, IF1 pred) {
if (l != null)
for (A a : l) if (pred.get(a))
return a;
return null;
}
static public A firstThat(Iterable l, IF1 pred) {
return firstThat(l, (Object) pred);
}
static public A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static public A or(A a, A b) {
return a != null ? a : b;
}
static public boolean checkCondition(Object condition, Object... args) {
return isTrue(callF(condition, args));
}
static public boolean checkCondition(IF1 condition, A arg) {
return isTrue(callF(condition, arg));
}
final static public class _MethodCache {
final public Class c;
final public HashMap> cache = new HashMap();
public _MethodCache(Class c) {
this.c = c;
_init();
}
public void _init() {
Class _c = c;
while (_c != null) {
for (Method m : _c.getDeclaredMethods()) if (!isAbstract(m) && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
_c = _c.getSuperclass();
}
for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m))
multiMapPut(cache, m.getName(), makeAccessible(m));
}
public Method findMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public Method findStaticMethod(String method, Object[] args) {
try {
List m = cache.get(method);
if (m == null)
return null;
int n = m.size();
for (int i = 0; i < n; i++) {
Method me = m.get(i);
if (isStaticMethod(me) && call_checkArgs(me, args, false))
return me;
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
static public String passwordSalt() {
File f = programSecretFile("password-salt");
if (fileExists(f))
return loadTextFile(f);
File global = javaxSecretDir("password-salt");
if (fileExists(global))
return loadTextFile(global);
return loadTextFileOrCreateWithRandomID(f);
}
static public class PostReferenceable extends Concept {
}
static public class User extends PostReferenceable {
static final public String _fieldOrder = "name passwordMD5 contact isMaster botToken lastSeen";
public String name;
public SecretValue passwordMD5;
public String contact;
public boolean isMaster = false;
public SecretValue botToken = aSecretGlobalID();
public long lastSeen;
public String name() {
return name;
}
public String toString() {
return nempty(name) ? "User " + name : super.toString();
}
}
static public class UserCreatedObject extends PostReferenceable {
static final public String _fieldOrder = "creator botInfo";
public Ref creator = new Ref();
public String botInfo;
}
static public class UserPost extends UserCreatedObject {
public String type, title, text;
public boolean isPublic = true, hidden;
public boolean creating = false;
public long xmodified;
public long bumped;
static public List fieldsToSaveOnDelete = ll("id", "text", "title", "type", "creatorID", "postRefs", "postRefTags", "hidden", "isPublic", "created", "_modified", "xmodified", "botInfo", "creating");
public String text() {
return text;
}
public RefL postRefs = new RefL();
public List postRefTags = new ArrayList();
static public String _fieldOrder = "title text type postRefs isPublic";
public String toString() {
String content = nempty(title) ? shorten(title) : escapeNewLines(shorten(text));
return content + " [by " + author() + "]";
}
public boolean isReply() {
return nempty(postRefs);
}
public boolean isBotPost() {
return nempty(botInfo);
}
public boolean isMasterMade() {
return creator.has() && creator.get().isMaster;
}
public String author() {
String author = userName(creator.get());
if (isBotPost())
author += "'s bot " + quote(botInfo);
return author;
}
public void change() {
super.change();
((DynGazelleRocks) botMod()).distributePostChanges(this);
}
public List> postRefsWithTags() {
return zipTwoListsToPairs_lengthOfFirst(postRefs, postRefTags);
}
public List postRefsWithTag(String tag) {
return pairsAWhereB(postRefsWithTags(), t -> eqic_unnull(t, tag));
}
public UserPost primaryRefPost() {
return optCast(UserPost.class, first(postRefsWithTag("")));
}
public void _setModified(long modified) {
super._setModified(modified);
setXModified(modified);
}
public void bump() {
bumped = now();
_change_withoutUpdatingModifiedField();
for (UserPost p : syncInstancesOf(UserPost.class, postRefs)) p.setXModified();
}
public long modifiedOrBumped() {
return max(_modified, bumped);
}
public void setXModified() {
setXModified(now());
}
public void setXModified(long modified) {
boolean changed = modified > xmodified;
xmodified = modified;
_change_withoutUpdatingModifiedField();
if (changed)
((DynGazelleRocks) botMod()).distributePostChanges(this);
}
public void _backRefsModified() {
super._backRefsModified();
setXModified(now());
}
public int distanceToUserPost() {
int n = 0;
UserPost post = this;
while (post != null && n < 100) {
if (!post.isBotPost())
return n;
post = post.primaryRefPost();
}
return -1;
}
public boolean isJavaXCode() {
return eqicOrSwicPlusSpace(type, "JavaX Code");
}
}
abstract static public class DynGazelleRocks extends DynNewBot2 {
transient public boolean inlineSearch = false;
static public boolean _switchableField_webPushEnabled = true;
public boolean webPushEnabled = true;
static public boolean _switchableField_showPostStats = true;
public boolean showPostStats = false;
static public boolean _switchableField_showSuggestorBot = true;
public boolean showSuggestorBot = true;
static public boolean _switchableField_showMetaBotOnEveryPage = true;
public boolean showMetaBotOnEveryPage = true;
static public boolean _switchableField_delayAfterSuggestion = true;
public int delayAfterSuggestion = 1000;
static public boolean _switchableField_defaultBotPost = true;
public int defaultBotPost = 238410;
static public boolean _switchableField_teamPostID = true;
public long teamPostID;
static public boolean _switchableField_favIconID = true;
public long favIconID;
static public boolean _switchableField_defaultFavIconSnippet = true;
public String defaultFavIconSnippet = gazelleFavIconSnippet();
static public boolean _switchableField_gazelleBotURL = true;
public String gazelleBotURL = null;
static public boolean _switchableField_salterService = true;
public String salterService;
transient public double systemLoad;
transient public long processSize;
public void init() {
dm_require("#1017856/SystemLoad");
dm_vmBus_onMessage("systemLoad", new VF1() {
public void get(Double load) {
try {
if (setField("systemLoad", load))
distributeDivChanges("serverLoadRightHemi");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (setField(systemLoad := load))\r\n distributeDivChanges(\"serverLoadRi...";
}
});
dm_vmBus_onMessage("processSize", new VF1() {
public void get(Long processSize) {
try {
if (setField("processSize", processSize))
distributeDivChanges("memRightHemi");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (setField(+processSize))\r\n distributeDivChanges(\"memRightHemi\");";
}
});
botName = heading = adminName = "gazelle.rocks";
templateID = "#1030086";
cssID = "237267";
enableUsers = true;
useWebSockets = true;
showRegisterLink = true;
showTalkToBotLink = false;
alwaysRedirectToHttps = true;
redirectOnLogout = true;
showFullErrors = true;
inlineSearch = true;
lockWhileDoingBotActions = false;
showMailSenderInfo = false;
if (empty(salterService))
passwordSalt();
}
public void makeIndices() {
super.makeIndices();
indexConceptFieldCI(User.class, "name");
indexConceptFieldDesc(UserPost.class, "xmodified");
indexConceptFieldDesc(UserPost.class, "_modified");
indexConceptFieldCI(UserPost.class, "botInfo");
}
public void start() {
init();
super.start();
db_mainConcepts().modifyOnCreate = true;
printConceptIndices();
onConceptsChange(new Runnable() {
public int postCount = countConcepts(UserPost.class);
public void run() {
AutoCloseable __7 = enter();
try {
int count = countConcepts(UserPost.class);
if (count != postCount) {
postCount = count;
distributeDivChanges("postCount");
}
} finally {
_close(__7);
}
}
});
internalUser();
}
public void requestServed() {
distributeDivChanges("webRequestsRightHemi");
}
public class WebSocketInfo extends Meta implements AutoCloseable {
public boolean _isTransient() {
return true;
}
public String uri;
public Map params;
public Req req;
public WeakReference webSocket;
public Set> messageHandlers = syncLinkedHashSet();
public Set closeHandlers = syncLinkedHashSet();
public Map misc = syncMap();
public WebSocketInfo(Object webSocket) {
this.webSocket = weakRef(webSocket);
setFieldToIVF1Proxy(webSocket, "onMessage", msg -> {
AutoCloseable __8 = enter();
try {
try {
String data = rcall_string("getTextPayload", msg);
pcallFAll(messageHandlers, data);
} catch (Throwable __e) {
_handleException(__e);
}
} finally {
_close(__8);
}
});
}
public String uri() {
return uri;
}
public Map params() {
return params;
}
public String get(String param) {
return mapGet(params, param);
}
public void setParams(Map params) {
this.params = params;
req.params = params;
}
public Object dbRepresentation;
public Set> liveDivs = new HashSet();
public void eval(String jsCode) {
eval(jsCode, null);
}
public void eval(String jsCode, Object... __) {
jsCode = jsDollarVars(jsCode, __);
if (empty(jsCode))
return;
dm_call(webSocket.get(), "send", jsonEncode(litmap("eval", jsCode)));
}
public void send(String jsonData) {
if (empty(jsonData))
return;
dm_call(webSocket.get(), "send", jsonData);
}
public AutoCloseable onStringMessage(IVF1 onMsg) {
return tempAdd(messageHandlers, onMsg);
}
public AutoCloseable onClose(Runnable r) {
return tempAdd(closeHandlers, r);
}
public void callCloseHandlers() {
pcallFAll(closeHandlers);
}
public void close() {
cleanUp(webSocket.get());
}
}
transient public Map webSockets = syncWeakHashMap();
public void cleanMeUp_webSockets() {
closeAllKeysAndClear((Map) webSockets);
}
public void handleWebSocket(Object ws) {
set(ws, "onClose", new Runnable() {
public void run() {
try {
var info = webSockets.get(ws);
if (info != null) {
try {
onWebSocketClose(info);
} catch (Throwable __e) {
_handleException(__e);
}
}
webSockets.remove(ws);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "var info = webSockets.get(ws);\r\n if (info != null) pcall { onWebSocketCl...";
}
});
set(ws, "onOpen", new Runnable() {
public void run() {
try {
AutoCloseable __9 = enter();
try {
String uri = (String) (rcall("getUri", ws));
Map params = (Map) (rcall("getParms", ws));
print("WebSocket opened! uri: " + uri + ", params: " + params);
WebSocketInfo info = new WebSocketInfo(ws);
IWebRequest webRequest = proxy(IWebRequest.class, call(ws, "webRequest"));
info.req = webRequestToReq(webRequest);
String cookie = cookieFromWebRequest(webRequest);
AuthedDialogID auth = authObject(cookie);
fillReqAuthFromCookie(info.req, cookie, auth);
AutoCloseable __10 = tempSetTL(currentReq, info.req);
try {
info.uri = uri;
info.params = params;
webSockets.put(ws, info);
try {
onNewWebSocket(info);
} catch (Throwable __e) {
_handleException(__e);
}
long objectID = toLong(params.get("objectID"));
long modified = toLong(params.get("modified"));
if (objectID != 0) {
UserPost c = getConceptOpt(UserPost.class, objectID);
print("Modification: " + c.xmodified + " / " + c._modified + " / " + modified);
if (c != null && c.xmodified > modified)
reloadBody(ws);
}
} finally {
_close(__10);
}
} finally {
_close(__9);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); \r\n String uri = (String) (rcall getUri(ws));\r\n Map...";
}
});
setFieldToIVF1Proxy(ws, "onMessage", msg -> {
AutoCloseable __11 = enter();
try {
try {
WebSocketInfo info = webSockets.get(ws);
if (info == null)
return;
String data = rcall_string("getTextPayload", msg);
Map map = jsonDecodeMap(data);
Object div = map.get("liveDiv");
if (div instanceof String) {
String contentDesc = (String) div;
syncAdd(info.liveDivs, pair(((String) div), (Object) contentDesc));
reloadDiv(ws, ((String) div), calcDivContent(contentDesc));
}
} catch (Throwable __e) {
_handleException(__e);
}
} finally {
_close(__11);
}
});
}
public String serveRegisterForm(Map params) {
String user = trim(params.get("user"));
String pw = trim(params.get("f_pw"));
String pw2 = trim(params.get("pw2"));
String redirect = params.get("redirect");
String contact = trim(params.get("contact"));
redirect = dropParamFromURL(redirect, "logout");
if (empty(redirect))
redirect = baseLink + "/";
List msgs = new ArrayList();
if (nempty(user) || nempty(pw)) {
Lock __1 = dbLock();
lock(__1);
try {
if (empty(user))
msgs.add("Please enter a user name");
else if (l(user) < 4)
msgs.add("Minimum user name length: 4 characters");
else if (l(user) > 30)
msgs.add("Maximum user name length: 30 characters");
else if (hasConceptIC(User.class, "name", user))
msgs.add("This user exists, please choose a different name");
if (regexpContainsIC("[^a-z0-9\\-\\.]", user))
msgs.add("Bad characters in user name (please use only a-z, 0-9, - and .)");
if (empty(pw))
msgs.add("Please enter a password. Don't use one of your regular (important) passwords! Just make one up and let the browser save it.");
else if (l(pw) < 6)
msgs.add("Minimum password length: 6 characters");
if (neq(pw, pw2))
msgs.add("Passwords don't match");
if (empty(msgs)) {
User userObj = cnew(User.class, "name", user, "passwordMD5", new SecretValue(hashPW(pw)), "contact", contact);
vmBus_send("userCreated", userObj);
return hrefresh(5.0, redirect) + "User " + user + " created! Redirecting...";
}
} finally {
unlock(__1);
}
}
return hhtml(hhead(htitle("Register new user") + hsansserif() + hmobilefix() + hresponstable()) + hbody(hfullcenter(h3_htmlEncode(adminName + " | Register new user") + hpostform(hhidden("redirect", redirect) + tag("table", (empty(msgs) ? "" : tr(td() + td() + td(htmlEncode2_nlToBr(lines_rtrim(msgs))))) + tr(td_valignTop("Choose a user name:") + td_valignTop(hinputfield("user", user) + " " + "(Minimum length 4. Characters allowed: a-z, 0-9, - and .)")) + tr(td_valignTop("Choose a password:") + td_valignTop(hpassword("f_pw", pw) + " " + "(Minimum length 6 characters)")) + tr(td_valignTop("Repeat the password please:") + td(hpassword("pw2", pw2))) + tr(td_valignTop("Way to contact you (e.g. e-mail) - optional:") + td(hinputfield("contact", contact))) + tr(td() + td(hsubmit("Register"))), "class", "responstable"), "action", baseLink + "/register"))));
}
public boolean calcMasterAuthed(Req req) {
return super.calcMasterAuthed(req) || req.auth != null && req.auth.user.has() && req.auth.user.get().isMaster;
}
public Object serveOtherPage(Req req) {
String uri = req.uri;
Matches m = new Matches();
if (eq(uri, "/register"))
return serveRegisterForm(req.params);
if (eq(uri, "/becomeMaster") && req.auth != null && req.auth.user != null) {
String pw = trim(req.params.get("masterPW"));
if (eq(pw, realPW())) {
cset(req.auth.user, "isMaster", true);
return "You are master, " + req.auth.user + "!";
}
if (nempty(pw))
return "Bad master PW";
return hhtml(hhead(htitle("Become master") + hsansserif() + hmobilefix() + hresponstable()) + hbody(hfullcenter(h3_htmlEncode(adminName + " | Become master") + hpostform(tag("table", tr(td_valignTop("You are:") + td_valignTop(htmlEncode2(req.auth.user.get().name))) + tr(td_valignTop("Enter the master password:") + td_valignTop(hpassword("masterPW", pw))) + tr(td() + td(hsubmit("Become master user"))), "class", "responstable"), "action", baseLink + "/becomeMaster"))));
}
if (swic(uri, "/text/", m)) {
long id = parseLong(m.rest());
UserPost post = getConceptOpt(UserPost.class, id);
if (post == null)
return serve404("Post with ID " + id + " not found");
if (!post.isPublic)
return serve404("Post is not public");
String ct = req.params.get("ct");
Object response = nempty(ct) ? serveWithContentType(post.text(), ct) : serveText(post.text());
if (eq(ct, "text/javascript"))
addHeader("Service-Worker-Allowed", "/", response);
return response;
}
if (swic(uri, "/postRefs/", m)) {
long id = parseLong(m.rest());
UserPost post = getConceptOpt(UserPost.class, id);
if (post == null)
return serve404("Post with ID " + id + " not found");
if (!post.isPublic)
return serve404("Post is not public");
return serveJSON(lmap(__60 -> conceptID(__60), post.postRefs));
}
if (swic(uri, "/postRefsWithTags/", m)) {
long id = parseLong(m.rest());
UserPost post = getConceptOpt(UserPost.class, id);
if (post == null)
return serve404("Post with ID " + id + " not found");
if (!post.isPublic)
return serve404("Post is not public");
return serveJSON(map(post.postRefsWithTags(), p -> litorderedmap("id", conceptID(p.a), "as", p.b)));
}
String uri2 = dropSlashPrefix(uri);
if (isInteger(uri2)) {
long id = parseLong(uri2);
{
Object __5 = serveIntegerLink(req, id);
if (__5 != null)
return __5;
}
}
{
Object __6 = serveOtherPage2(req);
if (__6 != null)
return __6;
}
return super.serveOtherPage(req);
}
static public boolean _switchableField_bot_maxPollSeconds = true;
public double bot_maxPollSeconds = 600;
static public boolean _switchableField_bot_pollInterval = true;
public int bot_pollInterval = 500;
public Class extends Concept> defaultCRUDClass() {
return Sequence.class;
}
public Object serveOtherPage2(Req req) {
Matches m = new Matches();
String uri = dropTrailingSlashIfNemptyAfterwards(req.uri);
if (eq(uri, "/admin"))
return hrefresh(baseLink + "/crud/" + shortClassName(defaultCRUDClass()));
if (eq(uri, "/latestPost")) {
UserPost post = highestConceptByField(UserPost.class, "created");
if (post == null)
return serve404("No posts in database");
return servePost(post, req);
}
if (eq(uri, "/latestModifiedPost")) {
UserPost post = highestConceptByField(UserPost.class, "_modified");
if (post == null)
return serve404("No posts in database");
return servePost(post, req);
}
if (eq(uri, "/rootPosts")) {
Collection posts = sortedByConceptIDDesc(filter(list(UserPost.class), post -> empty(post.postRefs)));
framer().navBeforeTitle = true;
framer().title = "Root Posts";
framer().add(ul(lmap(__61 -> postToHTMLWithDate(__61), posts)));
return framer().render();
}
if (eq(uri, "/allPosts")) {
Collection posts = sortedByConceptIDDesc(list(UserPost.class));
framer().navBeforeTitle = true;
framer().title = "All Posts";
framer().add(ul(lmap(__62 -> postToHTMLWithDate(__62), posts)));
return framer().render();
}
if (eq(uri, "/latestPosts")) {
Collection posts = takeFirst(50, sortedByConceptIDDesc(list(UserPost.class)));
framer().navBeforeTitle = true;
framer().title = "Latest Posts & Replies";
framer().add(ul(lmap(__63 -> postToHTMLWithDate(__63), posts)));
return framer().render();
}
if (eq(uri, "/latestModifiedPosts")) {
Collection posts = takeFirst(50, sortedByFieldDesc("_modified", list(UserPost.class)));
framer().navBeforeTitle = true;
framer().title = "Latest Modified Posts & Replies";
framer().add(ul(lmap(__64 -> postToHTMLWithDate(__64), posts)));
return framer().render();
}
if (eq(uri, "/mainPosts")) {
Collection posts = takeFirst(50, sortedByConceptID(conceptsWhereCI(UserPost.class, "type", "Main")));
framer().navBeforeTitle = true;
framer().title = "Main Posts";
framer().add(ul(lmap(__65 -> postToHTMLWithDate(__65), posts)));
return framer().render();
}
if (swic(uri, "/html/", m) && isInteger(m.rest())) {
long id = parseLong(m.rest());
return serveHTMLPost(id);
}
if (swic(uri, "/htmlEmbedded/", m) && isInteger(m.rest())) {
long id = parseLong(m.rest());
UserPost post = getConcept(UserPost.class, id);
if (post == null)
return serve404("Post not found");
HTMLFramer1 framer = framer();
framer.title = "[" + post.id + "] " + or2(post.title, shorten(post.text));
framer.add(hcomment("Post begins here") + "\n" + post.text + "\n" + hcomment("Post ends here"));
return framer.render();
}
if (swic(uri, "/css/", m) && isInteger(m.rest())) {
long id = parseLong(m.rest());
UserPost post = getConcept(UserPost.class, id);
if (post == null)
return serve404("Post not found");
return serveWithContentType(post.text, "text/css");
}
if (eq(uri, "/search")) {
framer().navBeforeTitle = true;
String q = trim(req.params.get("q"));
framer().title = joinNemptiesWithColon("Search", q);
framer().add(hcomment("cookie: " + req.webRequest.cookie()));
framer().add(hform(hinputfield("q", q, "autofocus", true) + " " + hsubmit("Search")));
framer().add(p(small("Search help: If you search for multiple words, they can appear in any order in the text. An underscore matches any character. Plus means space. Post titles, texts and types are searched.")));
if (nempty(q)) {
ScoredSearcher searcher = new ScoredSearcher<>(q);
long id = parseLongOpt_pcall(q);
for (UserPost post : list(UserPost.class)) searcher.add(post, (post.id == id ? 4 : 0) + searcher.score(post.title) * 3 + searcher.score(post.text) * 2 + searcher.score(post.type) + searcher.score(joinWithSpace(post.postRefTags)) * 0.5);
List posts = searcher.get();
framer().add(p(b(addPlusToCount(searcher.maxResults, l(posts), nPosts(posts)) + " found for " + htmlEncode2(q))));
framer().add(ul(lmap(__66 -> postToHTMLWithDate(__66), posts)));
}
return framer().render();
}
if (eq(uri, "/jstree/replies")) {
UserPost post = getConcept(UserPost.class, parseLong(req.params.get("post")));
if (post == null)
return serveJSON(ll());
Collection refs = referencingPosts(post);
return serveJSON(map(refs, p -> litorderedmap("id", p.id, "text", postToHTMLWithDate(post), "children", nempty(referencingPosts(p)) ? true : null, "type", "root")));
}
if (startsWith(uri, "/touchPost/", m)) {
long id = parseLong(m.rest());
UserPost post = getConcept(UserPost.class, id);
if (post == null)
return serve404("Post not found");
if (!canEditPost(post))
return "You are not authorized to do this";
touchConcept(post);
return hscript("setTimeout('history.go(-1)', 1000);") + "Post " + post.id + " touched";
}
if (startsWith(uri, "/hidePost/", m)) {
long id = parseLong(m.rest());
UserPost post = getConcept(UserPost.class, id);
if (post == null)
return serve404("Post not found");
if (!canEditPost(post))
return "You are not authorized to do this";
cset(post, "hidden", true);
return hrefresh(postLink(post));
}
if (startsWith(uri, "/unhidePost/", m)) {
long id = parseLong(m.rest());
UserPost post = getConcept(UserPost.class, id);
if (post == null)
return serve404("Post not found");
if (!canEditPost(post))
return "You are not authorized to do this";
cset(post, "hidden", false);
return hrefresh(postLink(post));
}
if (startsWith(uri, "/markSafe/", m)) {
long id = parseLong(m.rest());
UserPost post = getConcept(UserPost.class, id);
if (post == null)
return serve404("Post not found");
UserPost codePost = optCast(UserPost.class, first(post.postRefs));
if (codePost == null)
return "Code post not found";
if (!canEditPost(codePost))
return "You are not authorized to do this";
uniqCI(UserPost.class, "creator", currentUser(), "text", "Mark safe", "postRefs", ll(post));
sleepSeconds(6);
touchConcept(codePost);
return hrefresh(postLink(codePost));
}
if (eq(uri, "/mirrorAllConversations")) {
if (!req.masterAuthed)
return serveAuthForm(rawLink(uri));
for (Conversation c : list(Conversation.class)) rstUpdateMirrorPosts.add(c);
return "OK";
}
if (startsWith(uri, "/mirrorConversation/", m)) {
if (!req.masterAuthed)
return serveAuthForm(rawLink(uri));
long id = parseLong(m.rest());
Conversation conv = getConcept(Conversation.class, id);
if (conv == null)
return "Conversation not found";
conv.updateMirrorPost();
return "Mirror post updated (" + htmlEncode2(str(conv.mirrorPost.get())) + ")";
}
if (eqic(uri, "/favicon.ico"))
return serveFavIcon();
if (startsWith(uri, "/bot/", m)) {
req.subURI = m.rest();
String json = req.params.get("json");
Map data = new HashMap();
if (nempty(json))
data = jsonDecodeMap(json);
data.putAll(withoutKey("json", req.params));
User user;
String userName = (String) (data.get("_user"));
if (nempty(userName)) {
String botToken = (String) (data.get("_botToken"));
if (botToken == null)
return serveJSON("error", "Need _botToken");
user = conceptWhereIC(User.class, "name", userName);
if (user == null)
return serveJSON("error", "User not found");
if (!eq(botToken, getVar(user.botToken)))
return serveJSON("error", "Wrong bot token");
} else
user = user(req);
String function = beforeSlashOrAll(req.subURI);
req.subURI = substring(req.subURI, l(function) + 1);
req.webRequest.noSpam();
{
Object __41 = servePossiblyUserlessBotFunction(req, function, data, user);
if (__41 != null)
return __41;
}
if (user == null)
return serveJSON("error", "Need _user");
if (eq(function, "authTest"))
return serveJSON("status", "You are authorized as " + user.name);
if (eq(function, "postCount"))
return serveJSON("result", countConcepts(UserPost.class));
if (eq(function, "listPosts")) {
List fields = unnull(stringToStringListOpt(__105 -> tok_identifiersInOrder(__105), data.get("fields")));
if (!fields.contains("id"))
fields.add(0, "id");
long changedAfter = toLong(data.get("changedAfter"));
long repliesTo = toLong(data.get("repliesTo"));
double pollFor = min(bot_maxPollSeconds, toLong(data.get("pollFor")));
long startTime = sysNow();
if (changedAfter > 0 && changedAfter == now())
sleep(1);
Collection posts;
while (true) {
if (repliesTo != 0) {
posts = referencingPosts(getConcept(UserPost.class, repliesTo));
if (changedAfter != 0)
posts = objectsWhereFieldGreaterThan(posts, "_modified", changedAfter);
} else {
posts = changedAfter == 0 ? list(UserPost.class) : conceptsWithFieldGreaterThan_sorted(UserPost.class, "_modified", changedAfter);
}
if (nempty(posts) || pollFor == 0 || elapsedSeconds_sysNow(startTime) >= pollFor)
return serveJSON_breakAtLevels(2, "result", map(posts, post -> mapToValues(fields, field -> getPostFieldForBot(post, field))));
sleep(bot_pollInterval);
}
}
if (eq(function, "createPost")) {
Either e = createPostArgs(user, data);
if (e.isB())
return serveJSON("error", e.b());
Pair post = uniq2(UserPost.class, e.a());
if (!post.b)
post.a.bump();
return serveJSON("status", post.b ? "Post created" : "Post existed already, bumped", "postID", post.a.id);
}
if (eq(function, "editPost")) {
long postID = toLong(data.get("postID"));
UserPost post = getConcept(UserPost.class, postID);
if (post == null)
return serveJSON("error", "Post " + postID + " not found");
Either e = createPostArgs(user, data);
if (e.isB())
return serveJSON("error", e.b());
int changes = cset(post, e.a());
return serveJSON(changes > 0 ? "Post updated" : "Post updated, no changes", "postID", postID);
}
if (eq(function, "deletePosts")) {
List ids = allToLong(tok_integersInOrder((String) data.get("ids")));
List results = new ArrayList();
List errors = new ArrayList();
for (long id : unnullForIteration(ids)) {
UserPost post = getConceptOpt(UserPost.class, id);
if (post == null)
errors.add("Post " + id + " not found");
else {
if (!user.isMaster && neq(post.creator.get(), user))
errors.add("Can't delete post " + id + " from other user");
else {
deletePost(post);
results.add("Post " + id + " deleted");
}
}
}
return serveJSON(litorderedmap("results", results, "errors", errors));
}
return serveBotFunction(req, function, data, user);
}
if (teamPostID != 0 && eq(uri, "/team"))
return serveHTMLPost(teamPostID);
if (startsWith(uri, "/history/", m)) {
long id = parseLong(m.rest());
UserPost post = getConcept(UserPost.class, id);
if (post == null)
return serve404("Post not found");
return servePostHistory(post);
}
if (startsWith(uri, "/htmlBot/", m)) {
long id = parseLong(beforeSlashOrAll(m.rest()));
UserPost post = getConcept(UserPost.class, id);
if (post == null)
return serve404("Post not found");
return doPost(htmlBotURLOnBotServer(id), req.params());
}
if (eq(uri, "/deletedPosts")) {
CloseableIterableIterator lines = linesFromFile(deletedPostsFile());
try {
List posts = new ArrayList();
while (lines.hasNext()) {
String line = lines.next();
if (isProperlyQuoted(line)) {
Map map = safeUnstructureMap(unquote(line));
posts.add(onlyKeys(map, "id", "title", "type"));
}
}
return serveText("Deleted posts:\n" + lines(lmap(__67 -> struct(__67), posts)));
} finally {
_close(lines);
}
}
if (eq(uri, "/formToPost")) {
User user = currentUser();
if (user == null)
serve500("Please log in first");
Map params = cloneMap(req.params);
String type = or2(getAndRemove(params, "_type"), "Form Input");
String title = getAndRemove(params, "_title");
List postRefs = map(id -> getConceptOpt(UserPost.class, parseLong(id)), tok_integersInOrder(getAndRemove(params, "_postRefs")));
List postRefTags = lines(getAndRemove(params, "_postRefTags"));
String text = sortLinesAlphaNumIC(mapToLines(params, (k, v) -> urlencode(k) + "=" + urlencode(v)));
Pair p = uniq2(UserPost.class, "creator", user, "text", text, "type", type, "title", title, "postRefs", postRefs, "postRefTags", postRefTags);
return (p.b ? "Post " + p.a.id + " created" : "Post " + p.a.id + " exists") + hrefresh(2.0, "/" + p.a.id);
}
if (eq(uri, "/webPushSubscribe")) {
Map data = jsonDecodeMap(mapGet(req.webRequest.files(), "postData"));
printVars_str("webPushSubscribe", "data", data);
cnew(WebPushSubscription.class, "data", data, "clientIP", req.webRequest.clientIP());
return serveJSON(litmap("message", "success"));
}
if (eq(uri, "/changePassword")) {
if (!req.masterAuthed)
return serveAuthForm(rawLink(uri));
String name = assertNempty(req.get("user"));
String newPW = assertNempty(req.get("newPW"));
User user = conceptWhereCI(User.class, "name", name);
if (user == null)
return "User not found";
cset(user, "passwordMD5", new SecretValue(hashPW(newPW)));
return "PW updated";
}
if (eq(uri, "/webPushNotify")) {
if (!req.masterAuthed)
return serveAuthForm(rawLink(uri));
String msg = or2(req.params.get("msg"), "Hello user. It is " + localTimeWithSeconds() + " on the server");
WebPushSubscription sub = getConcept(WebPushSubscription.class, toLong(req.params.get("webPushSubID")));
if (sub == null)
return serve404("webPushSubID not found");
String mod = dm_require("#1030463/WebPushKeyManager");
dm_call(mod, "sendNotification", sub.data, msg);
return "Push message sent";
}
if (eq(uri, "/hashPW") && req.masterAuthed)
return hashPW(req.params.get("pw"));
return null;
}
public Object servePostHistory(UserPost post) {
return serveText(unquoteAllLines(loadTextFile(postHistoryFile(post))));
}
public Either createPostArgs(User user, Map data) {
String text = (String) (data.get("text"));
String type = (String) (data.get("type"));
String title = (String) (data.get("title"));
String botInfo = or2((String) data.get("botInfo"), "Made by bot");
List postRefTags = unnull(lines((String) data.get("refTags")));
List postRefs = new ArrayList();
Object _refs = data.get("refs");
if (_refs instanceof String)
for (String s : tok_integersInOrder((String) _refs)) {
UserPost ref = getConcept(UserPost.class, parseLong(s));
if (ref == null)
return eitherB("Post " + s + " not found");
postRefs.add(ref);
}
if (empty(text) && empty(title))
return eitherB("Need either a text or a title");
boolean isPublic = eqOneOf(data.get("isPublic"), null, true, "1", "t", "true");
return eitherA(litparams("creator", user, "text", text, "type", type, "title", title, "isPublic", isPublic, "botInfo", botInfo, "postRefs", postRefs, "postRefTags", postRefTags));
}
public Object serveBotFunction(Req req, String function, Map data, User user) {
return serveJSON("error", "You are logged in correctly but function is unknown: " + function);
}
public Object servePossiblyUserlessBotFunction(Req req, String function, Map data, User user) {
return null;
}
public Object servePost(UserPost post, Req req) {
if (!post.isPublic)
return serve404("Post is not public");
HTMLFramer1 framer = framer();
framer.add(hjs("webSocketQuery = " + jsQuote("?objectID=" + post.id + "&modified=" + post.xmodified) + ";\n" + "if (ws != null) ws.url = ws.url.split(\"?\")[0] + webSocketQuery;"));
framer.title = "[" + post.id + "] " + or2(post.title, shorten(post.text));
framer.add(p("By " + htmlEncode2(post.author()) + ". " + renderConceptDate(post)));
if (nempty(post.type))
framer.add(p("Post type: " + htmlEncode2(post.type)));
List actions = new ArrayList();
if (eqic(post.type, "HTML"))
actions.add(targetBlank("/html/" + post.id, "Show as HTML page"));
if (eqic(post.type, "HTML (embedded)"))
actions.add(targetBlank("/htmlEmbedded/" + post.id, "Show as HTML page"));
if (eqicOneOf(post.type, "JavaX Code (HTML Bot)", "JavaX Code (Live Home Page)"))
actions.add(targetBlank(htmlBotURL(post.id), "Show as HTML page"));
if (eqic(post.type, "Conversation HTML"))
actions.add(targetBlank("/demo?cookie=htmlDemo&_autoOpenBot=1&chatContentsPost=" + post.id, "Show in chat box"));
if (canEditPost(post)) {
actions.add(ahref(conceptEditLink(post), "Edit post"));
actions.add(ahref(touchLink(post), "Touch post"));
actions.add(post.hidden ? ahref(unhideLink(post), "Unhide post") : ahref(hideLink(post), "Hide post"));
}
actions.add(ahref(replyLink(post), "Reply"));
actions.add(ahref(conceptDuplicateLink(post), "Duplicate"));
actions.add(ahref(conceptEditLink(post, "onlyFields", "title"), "Rename"));
if (postHasHistory(post))
actions.add(ahref("/history/" + post.id, "History"));
actions.add(ahref(baseLink + "/text/" + post.id, "Raw Text"));
if (post.isJavaXCode()) {
actions.add(targetBlank(simulateBotLink(post), "Talk to this bot"));
actions.add(ahref(gazelleBotURL + "/transpilation/" + post.id, "Show Java transpilation"));
}
framer.add(p_vbar(actions));
List postRefs = cloneList(post.postRefs);
if (nempty(postRefs)) {
framer.add(p("In reference to:"));
List> l = post.postRefsWithTags();
framer.add(ul(mapPairsToList(l, (ref, as) -> htmlEncode2(as) + " " + objectToHTML(ref))));
}
String text = post.text;
String html = null;
if (post.isJavaXCode()) {
try {
JavaXHyperlinker hl = new JavaXHyperlinker();
hl.targetBlank = true;
html = hl.codeToHTML(text);
} catch (Throwable __e) {
_handleException(__e);
}
}
if (html == null)
html = htmlEncodeWithLinking(post.text);
if (eq(req.params.get("showLineFeeds"), "1"))
html = html_showLineFeedsForPRE(html);
framer.add(div(sourceCodeToHTML_noEncode(html), "style", hstyle_sourceCodeLikeInRepo()));
Collection refs = referencingPosts(post);
refs = reversed(refs);
Pair, List> p = filterAntiFilter(refs, post2 -> !post2.hidden);
if (nempty(p.a)) {
framer.add(p("Referenced by posts (latest first):"));
UserPost latestCodeSafetyPost = highestBy(p2 -> p2.modifiedOrBumped(), filter(p.a, p2 -> eqic(p2.botInfo, "Code Safety Checker")));
framer.add(ul(map(p.a, p2 -> {
String html2 = htmlEncode2(squareBracketIfNempty(getPostRefTag(p2, post))) + " " + objectToHTML(p2);
if (p2 == latestCodeSafetyPost && cic(p2.text, "Unknown identifiers:"))
html2 += " " + hbuttonLink("/markSafe/" + p2.id, htmlEncode2("Mark safe"));
return html2;
})));
}
if (nempty(p.b)) {
framer.add(p("Referenced by hidden posts:"));
framer.add(ul(map(p.b, p2 -> htmlEncode2(squareBracketIfNempty(getPostRefTag(p2, post))) + " " + objectToHTML(p2))));
}
if (showPostStats) {
String stats = nLines(countLines(post.text)) + ", distance to user post: " + post.distanceToUserPost();
framer.add(p_alignRight(small(span_title(stats, "Post stats"))));
}
return framer.render();
}
public String getPostRefTag(UserPost a, UserPost b) {
return get(a.postRefTags, indexOf(a.postRefs, b));
}
public String htmlEncodeWithLinking(String text) {
String html = htmlEncode2(text);
return regexpReplace(html, gazelle_postMentionRegexp(), matcher -> {
UserPost post = getConceptOpt(UserPost.class, parseLong(matcher.group(1)));
return post == null ? matcher.group() : ahref(postLink(post), matcher.group());
});
}
public List referencingPosts(UserPost post) {
return sortedByCalculatedField(p -> p.modifiedOrBumped(), instancesOf(UserPost.class, allBackRefs(post)));
}
public List referencingPostsWithTag(UserPost post, String tag) {
return filter(referencingPosts(post), p -> eqic_unnull(getPostRefTag(p, post), tag));
}
public String serveAuthForm(String redirect) {
return hAddToHead(super.serveAuthForm(redirect), hInitWebSocket());
}
public String authFormMoreContent() {
return navDiv();
}
public String navDiv() {
return div_vbar(navLinks(), "style", "margin-bottom: 0.5em");
}
public Object handleAuth(Req req, String cookie) {
String name = trim(req.params.get("user")), pw = trim(req.params.get("pw"));
if (nempty(name) && nempty(pw) && nempty(cookie)) {
Domain authDomain;
User user = findOrCreateUserForLogin(name, pw);
if (user == null)
return errorMsg("User " + htmlEncode2(name) + " not found");
if (!eq(getVar(user.passwordMD5), hashPW(pw)))
return errorMsg("Bad password, please try again");
cset(uniq(AuthedDialogID.class, "cookie", cookie), "restrictedToDomain", null, "master", user.isMaster, "user", user);
String redirect = req.params.get("redirect");
if (nempty(redirect))
return hrefresh(redirect);
}
return null;
}
public User findOrCreateUserForLogin(String name, String pw) {
return conceptWhereCI(User.class, "name", name);
}
public Object serve2(Req req) {
if (req.auth != null) {
cset(req.auth, "userMode", false);
if (req.auth.user.get() != null)
cset(req.auth.user.get(), "lastSeen", now());
}
return super.serve2(req);
}
public String hashPW(String pw) {
if (nempty(salterService))
return assertMD5(postPage(salterService, "pw", pw));
else
return md5(pw + passwordSalt());
}
public Req currentReq() {
return currentReq.get();
}
final public boolean isMasterAuthed() {
return inMasterMode();
}
final public boolean masterAuthed() {
return inMasterMode();
}
public boolean inMasterMode() {
return inMasterMode(currentReq());
}
final public boolean isMasterAuthed(Req req) {
return inMasterMode(req);
}
final public boolean masterAuthed(Req req) {
return inMasterMode(req);
}
public boolean inMasterMode(Req req) {
return req.masterAuthed && !(req.auth != null && req.auth.userMode);
}
public Map filtersForClass(Class c, Req req) {
if (c == UserPost.class) {
if (req.auth != null && !inMasterMode(req))
return litmap("creator", req.auth.user.get());
}
return super.filtersForClass(c, req);
}
public String loggedInUserDesc_html(Req req) {
if (req.auth == null)
return ahref(loginLink(), "not logged in");
if (req.auth.user.get() == null)
return req.masterAuthed ? "master user" : "anonymous user " + req.auth.id;
return "user " + req.auth.user.get().name;
}
public String loginLink() {
return baseLink + "/";
}
public HCRUD_Concepts crudData(Class c, Req req) {
HCRUD_Concepts cc = super.crudData(c, req);
if (c == UserPost.class) {
cc.useDynamicComboBoxes = true;
cc.lsMagic = true;
cc.itemName = () -> "Post";
cc.dropEmptyListValues = false;
if (eq(req.params.get("noace"), "1"))
cc.addRenderer("text", new HCRUD_Data.TextArea(80, 20));
else
cc.addRenderer("text", new HCRUD_Data.AceEditor(80, 20));
cc.addRenderer("postRefTags", new HCRUD_Data.FlexibleLengthList(new HCRUD_Data.TextField(20)));
cc.addRenderer("type", new HCRUD_Data.ComboBox(true, itemPlus("", userPostTypesByPopularity())));
cc.fieldHelp("type", "Type of post (any format, optional)", "title", "Title for this post (any format, optional)", "text", "Text contents of this post (any format)", "nameInRepo", "Name in repository (not really used yet)", "botInfo", "Info on which bot made this post (if any)");
cc.massageItemMapForList = (item, map) -> {
applyFunctionToValue(__68 -> shorten(__68), map, "text", "title", "type", "nameInRepo");
List refs = ((UserPost) item).postRefs;
map.put("postRefs", new HTML(joinWithBR(lmap(__69 -> objectToHTML(__69), refs))));
};
cc.getObject = id -> {
Map map = cc.getObject_base(id);
List refs = (List) (map.get("postRefs"));
List tags = (List) (map.get("postRefTags"));
print("counts:" + l(refs) + "/" + l(tags));
map.put("postRefTags", padList(tags, l(refs), ""));
return map;
};
cc.emptyObject = () -> {
Map item = cc.emptyObject_base();
item.put("creator", req.auth.user.get());
return item;
};
cc.getObjectForDuplication = id -> {
Map item = cc.getObjectForDuplication_base(id);
item.put("creator", req.auth.user.get());
UserPost post = getConcept(UserPost.class, toLong(id));
List postRefs = cloneList((List) item.get("postRefs"));
List tags = cloneList((List) item.get("postRefTags"));
for (int i = 0; i < l(tags); i++) if (eqic(tags.get(i), "created from")) {
remove(postRefs, i);
tags.remove(i--);
}
int idx = l(postRefs);
postRefs.add(post);
listSet(tags, idx, "created from");
item.put("postRefs", postRefs);
item.put("postRefTags", tags);
print("tags", tags);
return item;
};
cc.fieldsToHideInCreationForm = litset("hidden", "creating");
cc.lockDB = true;
cc.afterUpdate = (post, oldValues) -> {
Map newValues = cgetAll_cloneLists(post, keys(oldValues));
for (Map.Entry extends String, ? extends Object> __0 : _entrySet(newValues)) {
String field = __0.getKey();
Object newVal = __0.getValue();
Object oldVal = oldValues.get(field);
if (eq(oldVal, newVal)) {
printVars_str("field", field, "oldVal", oldVal);
continue;
}
IF1 f = o -> o instanceof Concept ? ((Concept) o).id : null;
Object oldValForLog = defaultMetaTransformer().transform(f, oldVal);
Object newValForLog = defaultMetaTransformer().transform(f, newVal);
Map logEntry = litorderedmap("date", now(), "field", field, "oldVal", oldValForLog, "newVal", newValForLog);
printStruct("logEntry", logEntry);
logStructure(postHistoryFile(((UserPost) post)), logEntry);
}
};
cc.actuallyDeleteConcept = post -> deletePost(((UserPost) post));
}
return cc;
}
public HCRUD makeCRUD(Class c, Req req) {
HCRUD crud = super.makeCRUD(c, req);
if (c == UserPost.class) {
crud.refreshAfterCommand = (params, msgs) -> {
UserPost post = getConcept(UserPost.class, toLong(crud.objectIDToHighlight));
return post != null ? hrefresh(postLink(post)) : crud.refreshAfterCommand_base(params, msgs);
};
crud.renderCmds = map -> {
UserPost post = getConcept(UserPost.class, toLong(crud.itemID(map)));
return joinNemptiesWithVBar(crud.renderCmds_base(map), ahref(postLink(post), "Show post"), ahref(touchLink(post), "Touch", "title", "Mark post as modified so it is looked at by bots again"));
};
crud.uneditableFields = litset("xmodified", "creating", "bumped");
if (showSuggestorBot)
crud.moreSelectizeOptions = name -> ", onChange: function() { console.log(\"selectize onChange\"); sugTrigger(); }";
crud.showQuickSaveButton = true;
crud.massageFormMatrix = (map, matrix) -> {
if (showSuggestorBot) {
List entries = ((HCRUD_Concepts) crud.data).comboBoxItems(conceptsWhereIC(UserPost.class, "type", "JavaX Code (Post Edit Suggestor)"));
String js = hscript(replaceVars("\r\n const suggestorSelector = $(\"[name=suggestorID]\");\r\n var sugLoading = false, sugTriggerAgain = false;\r\n\r\n function sugTrigger() {\r\n //console.log(\"sugTrigger\");\r\n if (sugLoading) { sugTriggerAgain = true; return; }\r\n\r\n const sugText = suggestorSelector.text();\r\n //console.log(\"sugText=\" + sugText);\r\n const sugMatch = sugText.match(/\\d+/);\r\n if (!sugMatch) {\r\n //$(\"#suggestorResult\").html(\"\");\r\n $(\"#suggestorResult\").hide();\r\n return;\r\n }\r\n const suggestorID = sugMatch[0];\r\n\r\n // get form data as JSON\r\n \r\n var data = {};\r\n $(suggestorSelector).closest(\"form\").serializeArray().map(function(x){data[x.name] = x.value;});\r\n const json = JSON.stringify(data);\r\n console.log(\"JSON: \" + json);\r\n \r\n const url = \"" + gazelleBotURL + "/chatBotReply/\" + suggestorID;\r\n console.log(\"Loading \" + url);\r\n sugLoading = true;\r\n $.post(url, {q : json},\r\n function(result) {\r\n console.log(\"Suggestor result: \" + result);\r\n const answer = !result ? \"\" : JSON.parse(result).answer;\r\n if (answer) {\r\n $(\"#suggestorResult .sectionContents\").html(answer);\r\n $(\"#suggestorResult\").show();\r\n } else\r\n $(\"#suggestorResult\").hide();\r\n //$(\"#suggestorResult\").html(answer ? \"Suggestor says: \" + answer : \"\");\r\n }\r\n ).always(function() {\r\n console.log(\"sug loading done\");\r\n setTimeout(function() {\r\n sugLoading = false;\r\n if (sugTriggerAgain) { sugTriggerAgain = false; sugTrigger(); }\r\n }, delayAfterSuggestion);\r\n });\r\n }\r\n\r\n $(document).ready(function() {\r\n $(\"input[type=text], input[type=hidden], textarea, select\").on('input propertychange change', sugTrigger);\r\n sugTrigger();\r\n });\r\n suggestorSelector.change(sugTrigger);\r\n ", "delayAfterSuggestion", delayAfterSuggestion));
long defaultSuggestor = parseFirstLong(userDefaults(req.auth.user.get()).get("Default Suggestor Bot"));
String selectedSuggestor = firstWhereFirstLongIs(entries, defaultSuggestor);
matrix.add(0, ll("Suggestor Bot", crud.addHelpText("Choose a bot to assist you in editing this post [feature in development]", p_alignRight(crud.renderComboBox("suggestorID", selectedSuggestor, entries, false))) + htitledSectionWithDiv("Suggestion", "", "id", "suggestorResult", "style", "display: none", "innerDivStyle", "max-height: 150px; overflow: auto") + js));
}
};
crud.flexibleLengthListLeeway = 3;
}
if (c == User.class) {
crud.allowCreate = false;
}
return crud;
}
public String authFormHeading() {
return h3_htmlEncode("Welcome to the Gazelle AI System") + p(hsnippetimg_scaleToWidth(200, "#1101482", 425, 257, "title", "Gazelle"));
}
public void makeFramer(Req req) {
super.makeFramer(req);
req.framer.renderTitle = () -> h1(ahref(baseLink + "/", himgsnippet("#1102967", "style", "height: 1em; vertical-align: bottom", "title", "Gazelle.rocks Logo")) + " " + req.framer.encodedTitle());
req.framer.add(() -> navDiv());
if (showMetaBotOnEveryPage && !eq(req.params.get("_reloading"), "1"))
req.framer.willRender.add(new Runnable() {
public void run() {
try {
req.framer.add(hscript("var botConfig = \"codePost=" + defaultBotPost + "\"; ") + hjssrc(baseLink + "/script"));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "req.framer.add(hscript(\"var botConfig = \\\"codePost=\" + defaultBotPost + \"\\\"; ...";
}
});
}
public HTMLFramer1 framer() {
return framer(currentReq.get());
}
public HTMLFramer1 framer(Req req) {
if (req.framer == null)
makeFramer(req);
return req.framer;
}
public String postLink(UserPost post) {
return objectLink(post);
}
public String postLink(long postID) {
return objectLink(getConcept(UserPost.class, postID));
}
public String touchLink(UserPost post) {
return baseLink + "/touchPost/" + post.id;
}
public String hideLink(UserPost post) {
return baseLink + "/hidePost/" + post.id;
}
public String unhideLink(UserPost post) {
return baseLink + "/unhidePost/" + post.id;
}
public String objectLink(Concept c) {
return baseLink + "/" + c.id;
}
public String objectToHTML(Concept c) {
return c == null ? "-" : ahref(objectLink(c), htmlEncode2(str(c)));
}
public String postToHTMLWithDate(UserPost post) {
return post == null ? "" : objectToHTML(post) + " " + span(htmlEncode2(renderHowLongAgoPlusModified(post.created, post._modified)), "style", "color: #888");
}
public boolean canEditPost(UserPost post) {
User user = currentUser();
return user != null && (user.isMaster || user == post.creator.get());
}
public User currentUser() {
Req req = currentReq.get();
return req != null && req.auth != null ? req.auth.user.get() : null;
}
public String replyLink(UserPost post) {
return appendQueryToURL(crudLink(UserPost.class), "cmd", "new", "fList_postRefs_0", post == null ? null : post.id);
}
public String newPostLink() {
return replyLink(null);
}
public List navLinks(Object... __) {
return gazelle_navLinks(baseLink, inlineSearch && !eq(currentReq.get().uri, "/search") ? "" : null, paramsPlus(__, "withTeam", teamPostID != 0));
}
public List botCmdClasses() {
return ll();
}
public List crudClasses(Req req) {
List l = super.crudClasses(req);
l = listMinusSet(l, hiddenCrudClasses());
l.add(UserPost.class);
l.add(UploadedImage.class);
if (req.masterAuthed) {
l.add(User.class);
}
return l;
}
@Override
public Collection cruddableClasses(Req req) {
return addAllAndReturnCollection(super.cruddableClasses(req), WebPushSubscription.class);
}
public Set hiddenCrudClasses() {
return litset(Lead.class, ConversationFeedback.class, Domain.class, UserKeyword.class, UploadedSound.class, Settings.class);
}
public Object getPostFieldForBot(UserPost post, String field) {
if (eq(field, "creatorID"))
return post.creator.get().id;
if (eq(field, "creatorName"))
return post.creator.get().name;
if (eq(field, "creatorIsMaster"))
return post.creator.get().isMaster;
if (eq(field, "postRefs"))
return lmap(__70 -> conceptID(__70), post.postRefs);
return cget(post, field);
}
public void deletePost(UserPost post) {
if (post == null)
return;
print("Deleting post " + post);
Lock __2 = dbLock();
lock(__2);
try {
long filePos = l(deletedPostsFile());
logStructure(deletedPostsFile(), mapToValues(UserPost.fieldsToSaveOnDelete, field -> getPostFieldForBot(post, field)));
for (Pair p : post.postRefsWithTags()) if (p.a instanceof UserPost)
logStructure(deletedRepliesFile((UserPost) p.a), litorderedmap("tag", p.b, "id", post.id, "filePos", filePos, "type", post.type));
cdelete(post);
} finally {
unlock(__2);
}
}
public File deletedPostsFile() {
return programFile("deleted-posts.log");
}
public Object serveHTMLPost(long id) {
UserPost post = getConcept(UserPost.class, id);
if (post == null)
return serve404("Post " + id + " not found");
return post.text;
}
transient public ReliableSingleThread_Multi rstDistributePostChanges = new ReliableSingleThread_Multi<>(1000, __14 -> distributePostChanges_impl(__14));
public void distributePostChanges(UserPost post) {
rstDistributePostChanges.add(post);
}
public void distributePostChanges_impl(UserPost post) {
AutoCloseable __12 = enter();
try {
String uri = "/" + post.id;
for (Pair p : syncMapToPairs(webSockets)) {
if (eq(p.b.uri, uri))
reloadBody(p.a);
}
if (eqic(post.type, "Line Labels")) {
UserPost parent = post.primaryRefPost();
print("Line labels post " + post.id + ", parent=" + parent);
updateLineLabels(parent);
}
} finally {
_close(__12);
}
}
public void updateLineLabels(UserPost post) {
try {
if (post == null || !eqic(post.type, "Detailed Conversation Mirror"))
return;
print("Looking at conversation mirror " + post.id + " - " + post.title);
long convID = toLong(regexpFirstGroupIC("Conversation (\\d+) with details", post.title));
Conversation conv = getConcept(Conversation.class, convID);
if (conv == null)
return;
print("updateLineLabels " + convID + " / " + post.id);
MultiMap, String> labels = new MultiMap();
for (UserPost p : referencingPostsWithTag(post, "")) if (eqic(p.type, "Line Labels")) {
try {
Map map = safeUnstructMapAllowingClasses(p.text(), Pair.class);
print("Got labels map: " + map);
putAll(labels, map);
} catch (Throwable __e) {
_handleException(__e);
}
}
boolean change = false;
for (Msg msg : cloneList(conv.msgs)) {
List lbls = uniquifyAndSortAlphaNum(allToUpper(labels.get(pair(msg.time, msg.text))));
if (nempty(lbls))
print("Got labels: " + lbls);
if (!eq(msg.labels, lbls)) {
msg.labels = lbls;
change = true;
}
}
if (change)
conv.incReloadCounter();
} catch (Throwable __e) {
_handleException(__e);
}
}
public void reloadBody(Object ws) {
print("Reloading body through WebSocket");
String jsCode = " {\r\n const loc = new URL(document.location);\r\n const params = new URLSearchParams(loc.search);\r\n params.set('_reloading', '1');\r\n loc.search = params;\r\n console.log(\"Getting: \" + loc);\r\n $.get(loc, function(html) {\r\n var bodyHtml = /([\\s\\S]*)<\\/body>/.exec(html)[1];\r\n if (bodyHtml) {\r\n //$(\"body\").html(bodyHtml);\r\n $('body > *:not(.chatbot)').remove();\r\n $(\"body\").prepend(bodyHtml);\r\n }\r\n });\r\n } ";
dm_call(ws, "send", jsonEncode(litmap("eval", jsCode)));
}
transient public ReliableSingleThread_Multi rstDistributeDivChanges = new ReliableSingleThread_Multi<>(1000, __15 -> distributeDivChanges_impl(__15), new F0() {
public AutoCloseable get() {
try {
return enter();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret enter();";
}
});
public void distributeDivChanges(String contentDesc) {
rstDistributeDivChanges.add(contentDesc);
}
public void distributeDivChanges_impl(String contentDesc) {
AutoCloseable __13 = enter();
try {
String content = null;
for (Pair p : syncMapToPairs(webSockets)) {
for (String div : asForPairsWithB(p.b.liveDivs, contentDesc)) {
if (content == null)
content = calcDivContent(contentDesc);
if (content == null) {
print("No content for " + contentDesc);
return;
}
reloadDiv(p.a, div, content);
}
}
} finally {
_close(__13);
}
}
public void reloadDiv(Object ws, String div, String content) {
String jsCode = replaceDollarVars(" $(\"#\" + $div).html($content);", "div", jsQuote(div), "content", jsQuote(content));
dm_call(ws, "send", jsonEncode(litmap("eval", jsCode)));
}
public String calcDivContent(String contentDesc) {
if (eq(contentDesc, "postCount"))
return nPosts(countConcepts(UserPost.class));
if (eq(contentDesc, "webRequestsRightHemi"))
return n2(requestsServed);
if (eq(contentDesc, "serverLoadRightHemi"))
return formatDoubleX(systemLoad, 1);
if (eq(contentDesc, "memRightHemi"))
return str_toM(processSize);
return null;
}
public int countUserPosts() {
return countConcepts(UserPost.class, "botInfo", null) + countConcepts(UserPost.class, "botInfo", "");
}
public int countBotPosts() {
return countConcepts(UserPost.class) - countUserPosts();
}
public Collection allUserPosts() {
return filter(list(UserPost.class), p -> !p.isBotPost());
}
public List userPostTypesByPopularity() {
return listToTopTenCI(map(allUserPosts(), p -> p.type));
}
public void startMainScript(Conversation conv) {
UserPost post = getConceptOpt(UserPost.class, parseLong(mapGet(conv.botConfig, "codePost")));
if (post != null) {
CustomBotStep step = uniq(CustomBotStep.class, "codePostID", post.id);
if (executeStep(step, conv))
nextStep(conv);
} else
super.startMainScript(conv);
}
public String simulateBotLink(UserPost post) {
return appendQueryToURL(baseLink + "/demo", "_botConfig", makePostData("codePost", post.id), "_newConvCookie", 1, "_autoOpenBot", 1);
}
@Override
public boolean isRequestFromBot(Req req) {
return startsWith(req.uri, "/bot/");
}
public User internalUser() {
return uniqCI(User.class, "name", "internal");
}
transient public ReliableSingleThread_Multi rstUpdateMirrorPosts = new ReliableSingleThread_Multi<>(100, c -> c.updateMirrorPost());
public File postHistoryFile(UserPost post) {
return programFile("Post Histories/" + post.id + ".log");
}
public boolean postHasHistory(UserPost post) {
return fileNempty(postHistoryFile(post));
}
public File deletedRepliesFile(UserPost post) {
return programFile("Deleted Replies/" + post.id + ".log");
}
public String makeClassNavItem(Class c, Req req) {
String html = super.makeClassNavItem(c, req);
if (c == UserPost.class) {
int count1 = countUserPosts(), count2 = countBotPosts();
if (count1 != 0 || count2 != 0)
html += " " + roundBracket(n2(count1) + " from users, " + n2(count2) + " from bots");
}
return html;
}
@Override
public String modifyTemplateBeforeDelivery(String html, Req req) {
String contentsPostID = req.params.get("chatContentsPost");
if (nempty(contentsPostID)) {
html = html.replace("#N#", "99999");
html = html.replace("chatBot_interval = 1000", "chatBot_interval = 3600*1000");
html = html.replace("#INCREMENTALURL#", baseLink + "/text/" + contentsPostID + "?");
}
return html;
}
public String headingForReq(Req req) {
String codePost = decodeHQuery(req.params.get("_botConfig")).get("codePost");
if (nempty(codePost)) {
UserPost post = getConcept(UserPost.class, parseLong(codePost));
return post == null ? null : post.title;
}
return null;
}
public UserPost homePagePost() {
return firstThat(p -> p.isMasterMade(), conceptsWhereIC(UserPost.class, "type", "JavaX Code (Live Home Page)"));
}
public Object serveHomePage() {
try {
UserPost post = homePagePost();
if (post != null)
return loadPage(htmlBotURLOnBotServer(post.id));
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
public String callHtmlBot(long id, Map params) {
return id == 0 ? "" : doPost(htmlBotURLOnBotServer(id), params);
}
public String callHtmlBot_dropMadeByComment(long id, Map params) {
return regexpReplace_direct(callHtmlBot(id, params), "^\n", "");
}
public String htmlBotURL(long postID) {
return baseLink + "/htmlBot/" + postID;
}
public String htmlBotURLOnBotServer(long postID) {
return gazelleBotURL + "/htmlBot/" + postID;
}
public UserPost userDefaultsPost(User user) {
return conceptWhereIC(UserPost.class, "creator", user, "type", "My Defaults");
}
public Map userDefaults(User user) {
UserPost post = userDefaultsPost(user);
return post == null ? emptyMap() : parseColonPropertyCIMap(post.text);
}
public double favIconCacheHours() {
return 24;
}
public Object favIconHeaders(Object response) {
call(response, "addHeader", "Cache-Control", "public, max-age=" + iround(hoursToSeconds(favIconCacheHours())));
return response;
}
public Object serveFavIcon() {
if (favIconID != 0) {
UploadedFile f = getConcept(UploadedFile.class, favIconID);
if (f != null)
return favIconHeaders(subBot_serveFile(f.theFile(), faviconMimeType()));
}
return favIconHeaders(subBot_serveFile(loadLibrary(defaultFavIconSnippet), faviconMimeType()));
}
public String cssURL() {
return gazelle_textURL(parseLong(cssID));
}
public String getText(long postID) {
UserPost post = getConcept(UserPost.class, postID);
return post == null ? null : post.text();
}
@Override
public void addThingsAboveCRUDTable(Req req, Class c, List aboveTable) {
if (c == User.class)
aboveTable.add(p(ahref(baseLink + "/register", "Register new user")));
}
public User user(Req req) {
if (req == null)
return null;
AuthedDialogID auth = req.auth;
return auth == null ? null : auth.user();
}
public Object serveIntegerLink(Req req, long id) {
UserPost post = getConceptOpt(UserPost.class, id);
if (post == null)
return null;
return servePost(post, req);
}
public void onNewWebSocket(WebSocketInfo ws) {
}
public void onWebSocketClose(WebSocketInfo ws) {
ws.callCloseHandlers();
}
public String cookieFromWebRequest(IWebRequest req) {
if (req == null)
return null;
{
String __4 = req.cookie();
if (!empty(__4))
return __4;
}
return afterLastEquals(req.headers().get("cookie"));
}
public void makeMaster() {
var users = listMinus(list(User.class), internalUser());
if (empty(users)) {
infoMessage("Please first register a user in the web interface!");
return;
}
ShowComboBoxForm cb = new ShowComboBoxForm();
cb.desc = "Select user to upgrade";
cb.itemDesc = "User to make master";
cb.items = map(users, user -> user.id + " " + user.name);
cb.action = user -> {
startThread(new Runnable() {
public void run() {
try {
enter();
long userID = parseFirstLong(user);
User userObj = getConcept(User.class, userID);
printVars("user", user, "userID", userID, "userObj", userObj);
makeMaster(userObj);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "enter();\r\n long userID = parseFirstLong(user);\r\n User userObj = get...";
}
});
};
cb.show();
}
public void makeMaster(User user) {
if (user == null)
return;
if (!swingConfirm("Turn " + user + " into a master user?"))
return;
cset(user, "isMaster", true);
infoMessage(user + " is now my master!!");
}
public Object[] popDownButtonEntries() {
return objectArrayPlus(super.popDownButtonEntries(), "Make master user...", runnableThread(new Runnable() {
public void run() {
try {
AutoCloseable __17 = enter();
try {
makeMaster();
} finally {
_close(__17);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); makeMaster();";
}
}));
}
}
static public class CustomBotStep extends BotStep implements IInputHandler {
public long codePostID;
public String toString() {
return "CustomBotStep " + codePostID;
}
public boolean run(Conversation conv) {
String answer;
try {
Map result = (Map) (postJSONPage(replyURL(), "initial", 1, "cookie", conv.cookie));
answer = (String) result.get("answer");
} catch (Throwable e) {
_handleException(e);
answer = "Error: " + e.getMessage();
}
conv.add(new Msg(false, answer));
cset(conv, "inputHandler", this);
return false;
}
public String replyURL() {
return ((DynGazelleRocks) botMod()).gazelleBotURL + "/chatBotReply/" + codePostID;
}
public boolean handleInput(String s, Conversation conv) {
String answer;
try {
Map result = (Map) (postJSONPage(replyURL(), "q", s, "cookie", conv.cookie));
answer = (String) result.get("answer");
} catch (Throwable e) {
_handleException(e);
answer = "Error: " + e.getMessage();
}
conv.add(new Msg(false, answer));
return true;
}
}
static public String userName(User user) {
return user != null ? user.name : "?";
}
static public class WebPushSubscription extends Concept {
public String clientIP;
public Map data;
}
static public interface Hasher {
public int hashCode(A a);
public boolean equals(A a, A b);
}
static public interface IF2 {
public C get(A a, B b);
}
static public class Symbol implements CharSequence {
public String text;
public Symbol() {
}
public Symbol(String text, boolean dummy) {
this.text = text;
}
public int hashCode() {
return _hashCode(text);
}
public String toString() {
return text;
}
public boolean equals(Object o) {
return this == o;
}
public int length() {
return text.length();
}
public char charAt(int index) {
return text.charAt(index);
}
public CharSequence subSequence(int start, int end) {
return text.substring(start, end);
}
}
static public class Var implements IVar , ISetter {
public Var() {
}
public Var(A v) {
this.v = v;
}
public A v;
public synchronized void set(A a) {
if (v != a) {
v = a;
notifyAll();
}
}
public synchronized A get() {
return v;
}
public synchronized boolean has() {
return v != null;
}
public synchronized void clear() {
v = null;
}
public String toString() {
return str(this.get());
}
}
static final public class WeakHasherMap extends AbstractMap implements Map {
public Hasher hasher = null;
final public boolean keyEquals(Object k1, Object k2) {
return (hasher == null ? k1.equals(k2) : hasher.equals(k1, k2));
}
final public int keyHashCode(Object k1) {
return (hasher == null ? k1.hashCode() : hasher.hashCode(k1));
}
final public WeakKey WeakKeyCreate(K k) {
if (k == null)
return null;
else
return new WeakKey(k);
}
final public WeakKey WeakKeyCreate(K k, ReferenceQueue super K> q) {
if (k == null)
return null;
else
return new WeakKey(k, q);
}
final public class WeakKey extends WeakReference {
public int hash;
public WeakKey(K k) {
super(k);
hash = keyHashCode(k);
}
final public WeakKey create(K k) {
if (k == null)
return null;
else
return new WeakKey(k);
}
public WeakKey(K k, ReferenceQueue super K> q) {
super(k, q);
hash = keyHashCode(k);
}
final public WeakKey create(K k, ReferenceQueue super K> q) {
if (k == null)
return null;
else
return new WeakKey(k, q);
}
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o.getClass().equals(WeakKey.class)))
return false;
Object t = this.get();
@SuppressWarnings("unchecked")
Object u = ((WeakKey) o).get();
if ((t == null) || (u == null))
return false;
if (t == u)
return true;
return keyEquals(t, u);
}
@Override
public int hashCode() {
return hash;
}
}
public HashMap hash;
public ReferenceQueue super K> queue = new ReferenceQueue();
@SuppressWarnings("unchecked")
final public void processQueue() {
WeakKey wk;
while ((wk = (WeakKey) queue.poll()) != null) {
hash.remove(wk);
}
}
public WeakHasherMap(int initialCapacity, float loadFactor) {
hash = new HashMap(initialCapacity, loadFactor);
}
public WeakHasherMap(int initialCapacity) {
hash = new HashMap(initialCapacity);
}
public WeakHasherMap() {
hash = new HashMap();
}
public WeakHasherMap(Hasher h) {
hash = new HashMap();
hasher = h;
}
@Override
public int size() {
return entrySet().size();
}
@Override
public boolean isEmpty() {
return entrySet().isEmpty();
}
@Override
public boolean containsKey(Object key) {
@SuppressWarnings("unchecked")
K kkey = (K) key;
return hash.containsKey(WeakKeyCreate(kkey));
}
@Override
public V get(Object key) {
@SuppressWarnings("unchecked")
K kkey = (K) key;
return hash.get(WeakKeyCreate(kkey));
}
@Override
public V put(K key, V value) {
processQueue();
return hash.put(WeakKeyCreate(key, queue), value);
}
@Override
public V remove(Object key) {
processQueue();
@SuppressWarnings("unchecked")
K kkey = (K) key;
return hash.remove(WeakKeyCreate(kkey));
}
@Override
public void clear() {
processQueue();
hash.clear();
}
@SuppressWarnings("TypeParameterShadowing")
final public class Entry implements Map.Entry {
public Map.Entry ent;
public K key;
public Entry(Map.Entry ent, K key) {
this.ent = ent;
this.key = key;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return ent.getValue();
}
@Override
public V setValue(V value) {
return ent.setValue(value);
}
final public boolean keyvalEquals(K o1, K o2) {
return (o1 == null) ? (o2 == null) : keyEquals(o1, o2);
}
final public boolean valEquals(V o1, V o2) {
return (o1 == null) ? (o2 == null) : o1.equals(o2);
}
@SuppressWarnings("NonOverridingEquals")
public boolean equals(Map.Entry e) {
return (keyvalEquals(key, e.getKey()) && valEquals(getValue(), e.getValue()));
}
@Override
public int hashCode() {
V v;
return (((key == null) ? 0 : keyHashCode(key)) ^ (((v = getValue()) == null) ? 0 : v.hashCode()));
}
}
final public class EntrySet extends AbstractSet> {
public Set> hashEntrySet = hash.entrySet();
@Override
public Iterator> iterator() {
return new Iterator>() {
public Iterator> hashIterator = hashEntrySet.iterator();
public Map.Entry next = null;
@Override
public boolean hasNext() {
while (hashIterator.hasNext()) {
Map.Entry ent = hashIterator.next();
WeakKey wk = ent.getKey();
K k = null;
if ((wk != null) && ((k = wk.get()) == null)) {
continue;
}
next = new Entry(ent, k);
return true;
}
return false;
}
@Override
public Map.Entry next() {
if ((next == null) && !hasNext())
throw new NoSuchElementException();
Map.Entry e = next;
next = null;
return e;
}
@Override
public void remove() {
hashIterator.remove();
}
};
}
@Override
public boolean isEmpty() {
return !(iterator().hasNext());
}
@Override
public int size() {
int j = 0;
for (Iterator> i = iterator(); i.hasNext(); i.next()) j++;
return j;
}
@Override
public boolean remove(Object o) {
processQueue();
if (!(o instanceof Map.Entry, ?>))
return false;
@SuppressWarnings("unchecked")
Map.Entry e = (Map.Entry) o;
Object ev = e.getValue();
WeakKey wk = WeakKeyCreate(e.getKey());
Object hv = hash.get(wk);
if ((hv == null) ? ((ev == null) && hash.containsKey(wk)) : hv.equals(ev)) {
hash.remove(wk);
return true;
}
return false;
}
@Override
public int hashCode() {
int h = 0;
for (Iterator> i = hashEntrySet.iterator(); i.hasNext(); ) {
Map.Entry ent = i.next();
WeakKey wk = ent.getKey();
Object v;
if (wk == null)
continue;
h += (wk.hashCode() ^ (((v = ent.getValue()) == null) ? 0 : v.hashCode()));
}
return h;
}
}
public Set> entrySet = null;
@Override
public Set> entrySet() {
if (entrySet == null)
entrySet = new EntrySet();
return entrySet;
}
public K findKey(Object key) {
processQueue();
K kkey = (K) key;
WeakKey wkey = WeakKeyCreate(kkey);
WeakKey found = hashMap_findKey(hash, wkey);
return found == null ? null : found.get();
}
}
static public class SmoothHTMLTemplater {
public String template;
public boolean verbose = false;
public Map>> entriesByType = ciMap();
public List tok;
public List commentRanges;
public List comments;
public SmoothHTMLTemplater() {
}
public SmoothHTMLTemplater(String template) {
this.template = template;
}
static public class Replacement implements IFieldsToList {
static final public String _fieldOrder = "exampleValue actualValue";
public String exampleValue;
public String actualValue;
public Replacement() {
}
public Replacement(String exampleValue, String actualValue) {
this.actualValue = actualValue;
this.exampleValue = exampleValue;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + exampleValue + ", " + actualValue + ")";
}
public boolean equals(Object o) {
if (!(o instanceof Replacement))
return false;
Replacement __1 = (Replacement) o;
return eq(exampleValue, __1.exampleValue) && eq(actualValue, __1.actualValue);
}
public int hashCode() {
int h = 2098787826;
h = boostHashCombine(h, _hashCode(exampleValue));
h = boostHashCombine(h, _hashCode(actualValue));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { exampleValue, actualValue };
}
public String replaceIn(String text) {
return replaceIC(text, exampleValue, actualValue);
}
}
public List mapToEntry(Map map) {
return map(map, (key, value) -> new Replacement(key, str(value)));
}
public String render() {
tok = htmlTok(template);
commentRanges = charRangesOfHTMLComments(template);
comments = map(commentRanges, r -> htmlCommentContents(substring(template, r)));
Matches m = new Matches();
List> replacements = new ArrayList();
for (int i = 0; i < l(comments); i++) {
String comment = comments.get(i);
if (match("start * block", comment, m)) {
String type = m.unq(0);
String endPat = format3("end * block", type);
if (verbose)
print("Start of block found: " + i + " / " + comment);
int j = indexOfMatches(endPat, comments, i + 1);
int jEndOfList = indexOfMatches(format3("end * list", type), comments, i + 1);
if (j < 0) {
warn("End of block comment not found: " + endPat);
continue;
}
if (verbose)
print("End of block found: " + j + " / " + comments.get(j));
if (!isEntity(type)) {
print("Not an entity: " + type);
continue;
}
List> entries = getEntries(type);
if (verbose)
print(nEntries(entries));
IntRange r1 = commentRanges.get(i), r2 = commentRanges.get(j);
IntRange rEndOfList = commentRanges.get(jEndOfList >= 0 ? jEndOfList : j);
String contents = substring(template, r1.end, r2.start);
addPair(replacements, intRange(r1.end, rEndOfList.start), lines(map(entries, entry -> rewriteEntry(contents, entry))));
i = j;
}
}
if (verbose)
pnlStruct("Replacement", replacements);
return replaceCharRanges(template, replacements);
}
public boolean isEntity(String type) {
return true;
}
public String rewriteEntry(String text, List entry) {
for (Replacement r : unnullForIteration(entry)) text = r.replaceIn(text);
return text;
}
public List> getEntries(String type) {
return entriesByType.get(type);
}
}
static public class Fail extends RuntimeException implements IFieldsToList {
public Object[] objects;
public Fail() {
}
public Fail(Object... objects) {
this.objects = objects;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + objects + ")";
}
public Object[] _fieldsToList() {
return new Object[] { objects };
}
}
static public class Meta implements IMeta {
volatile public Object meta;
public void _setMeta(Object meta) {
this.meta = meta;
}
public Object _getMeta() {
return meta;
}
}
static public class HTMLFramer1 {
public String title;
public boolean titleIsHTML = false;
public List navItems = new ArrayList();
public List contents = new ArrayList();
public LinkedHashSet headElements = new LinkedHashSet();
public boolean navBeforeTitle = false;
public List willRender = new ArrayList();
static public class NavItem implements IFieldsToList {
static final public String _fieldOrder = "link html targetBlank";
public String link;
public String html;
public NavItem() {
}
public NavItem(String link, String html) {
this.html = html;
this.link = link;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + link + ", " + html + ")";
}
public boolean equals(Object o) {
if (!(o instanceof NavItem))
return false;
NavItem __1 = (NavItem) o;
return eq(link, __1.link) && eq(html, __1.html);
}
public int hashCode() {
int h = -900864330;
h = boostHashCombine(h, _hashCode(link));
h = boostHashCombine(h, _hashCode(html));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { link, html };
}
public boolean targetBlank = false;
}
public String get() {
return render();
}
transient public IF0 render;
public String render() {
return render != null ? render.get() : render_base();
}
final public String render_fallback(IF0 _f) {
return _f != null ? _f.get() : render_base();
}
public String render_base() {
callFAll(willRender);
return hhtml(hhead(htitle(titleIsHTML ? hTitleClean(title) : title) + lines(headElements)) + hbody((navBeforeTitle ? renderNav() + renderTitle() : renderTitle() + renderNav()) + nemptyLines(contents)));
}
transient public IF0 renderTitle;
public String renderTitle() {
return renderTitle != null ? renderTitle.get() : renderTitle_base();
}
final public String renderTitle_fallback(IF0 _f) {
return _f != null ? _f.get() : renderTitle_base();
}
public String renderTitle_base() {
return h1(encodedTitle());
}
public String encodedTitle() {
return titleIsHTML ? title : htmlEncode2(title);
}
transient public IF0 renderNav;
public String renderNav() {
return renderNav != null ? renderNav.get() : renderNav_base();
}
final public String renderNav_fallback(IF0 _f) {
return _f != null ? _f.get() : renderNav_base();
}
public String renderNav_base() {
if (empty(navItems))
return "";
return div_vbar(map(__25 -> renderNavItem(__25), navItems), "style", "margin-bottom: 0.5em");
}
public String renderNavItem(NavItem ni) {
return ahref_possiblyTargetBlank(ni.link, ni.html, ni.targetBlank);
}
public void addNavItem(String html) {
navItems.add(new NavItem(null, html));
}
public void addNavItems(Iterable htmls) {
forEach(__71 -> addNavItem(__71), htmls);
}
public void addNavItem(String link, String html, Object... __) {
navItems.add(setAll(new NavItem(link, html), filterParams(__, "targetBlank")));
}
final public void addInHEAD(Object html) {
addInHead(html);
}
public void addInHead(Object html) {
headElements.add(str(html));
}
public void add(String html) {
add((Object) html);
}
public void add(IF0 html) {
add(lambdaToToString(html));
}
public void add(Object html) {
if (notNullOrEmptyString(html))
contents.add(html);
}
public void addAll(Collection l) {
forEach(__72 -> add(__72), l);
}
public void clearNavItems() {
navItems.clear();
}
public HTMLFramer1 setTitle(String title) {
this.title = title;
return this;
}
public String htmlTitle(String title) {
this.title = title;
titleIsHTML = true;
return title;
}
public Collection headElements() {
return headElements;
}
}
static public interface IWebRequest {
public String uri();
public Map params();
public Map headers();
public Map files();
default public String clientIP() {
return unnull(getClientIPFromHeaders(headers()));
}
default public String getHeader(String name) {
return mapGet(headers(), name);
}
default public String domain() {
return getHeader("host");
}
public String cookie();
public boolean isHttps();
public boolean isPost();
default public String protocol() {
return isHttps() ? "https://" : "http://";
}
default public void noSpam() {
}
default public String get(String param) {
return mapGet(params(), param);
}
default public String userAgent() {
return getHeader("user-agent");
}
default public Object proxy(String url, boolean rewriteHost, boolean rewritePort) {
throw unimplemented();
}
}
static public interface ISetter {
public void set(A a);
}
static public class JavaXHyperlinker {
public boolean targetBlank = false;
public Map shortFor = litmap("BigInt", "BigInteger", "$1", "m.unq(0)", "$2", "m.unq(1)", "$3", "m.unq(2)", "LS", "List", "sclass", "static class", "asclass", "abstract static class", "svoid", "static void", "SS", "Map", "S", "String", "ret", "return", "L", "List", "Cl", "Collection", "O", "Object", "sO", "static Object", "sS", "static String", "fO", "final Object", "fS", "final String", "sS", "static String", "sbool", "static boolean", "fbool", "final boolean", "bool", "boolean", "Int", "Integer", "cast", "casting to the type required on the left-hand side", "°", "()", "ItIt", "IterableIterator", "ES", "Ext (string plus extended information)", "CloseableItIt", "CloseableIterableIterator", "LPairS", "List>", "ISegmenter", "IF1>");
public String explFunc = "anonymous function declaration (similar to Java 8 lambdas)";
public String explPNoconsole = "Main program including Substance L&F, started in non-AWT thread, hiding the console";
public Map tokenExplanations = litmap("cm", "cm summons the last version of a module in Stefan's OS (cm originally stood for 'compact module')", "~.", "short for accessing a field or calling a method by reflection", "beaConcept", "a BEA concept is just a concept (database-enabled Java class) derived from BEAObject (the AGI base class)", "== null ?:", "short for: == null ? null :", "p-exp {", "main program with automatic upgrade", "mapLike", "a function that takes a global function name as first argument and can be called like this: (...)", "mapMethodLike", "a function that takes a method or field name as first argument and can be called like this: (...)", "func(", explFunc, "func{", explFunc, "voidfunc", "anonymous function declaration without return value (similar to Java 8 lambdas)", "ctex", "ctex rethrows exceptions as RuntimeExceptions so you don't have to declare them", "p {", "short for: public static void main(String[] args)", "p-experiment {", "Main program with a nice big console & auto-restart", "p-substance {", "Main program including Substance L&F, started in AWT thread", "p-subst {", "Main program including Substance L&F, started in non-AWT thread", "p-noconsole {", explPNoconsole, "pn {", explPNoconsole, "answer {", "Answer function - static S answer(S s) { new Matches m; ...; null; }", "time {", "Run the code block and print how long it took", "cprint {", "A module with default class name derived from DynPrintLog", "semiauto {", "In a semiauto block, JavaX automatically adds a ; to (almost) every line", "autosemi {", "In an autosemi block, JavaX automatically adds a ; to (almost) every line", "Clusters", "Clusters is short for Map >", "temp", "temp is like try (...) extending to the end of the current block", "pcall {", "protected call - try { ... } catch { print exception }", "r {", "r { ... } is short for: new Runnable() { public void run() { ... } }", "runnable {", "runnable { ... } is short for: new Runnable() { public void run() { ... } }", "pcall-short {", "protected call, shorter output - try { ... } catch { printShortException }", "LPair<", "LPair<...> is short for: L>", "visualize {", "Visualisation method for an OS module; returns a Swing component", "visualize as", "define a visualization for the module", "enhanceFrame {", "Method that changes properties of an OS module's frame", "run {", "short for: public void run()", "start {", "Method that is run when an OS module is loaded", "enter {", "Methods in a module should be marked 'enter' for bookkeeping", "vf<", "reference to function as voidfunc", "compact module", "try to save memory by reusing code between modules", "cmodule", "cmodule = compact module for Stefan's OS. compact = try to save memory by reusing code between modules", "cmodule2", "cmodule2 = compact module for Stefan's OS (newer version). compact = try to save memory by reusing code between modules", "rThread {", "Runnable in a new thread", "shit(", "short for: return with print", "shit:", "short for: return with print", ":=", "the := operator translates to a simple comma, but converts an identifier on its left-hand side into a string", "noeq", "don't auto-generate equals+hashCode methods", "for single (", "for single is for ping + singletonUnlessNull", "selfType", "selfType is replaced with the enclosing class's name", "runnable class", "short for: class X implementing Runnable { run { ... }}", "aka", "In JavaX, methods can have multiple names");
public Map sc, sf;
public StringTree2 tokenExplanationsTree;
public JavaXHyperlinker() {
clearCaches();
tokenExplanationsTree = stringTree2_javaTok(tokenExplanations);
}
public String codeToHTML(String code) {
return codeToHTML(code, true);
}
public String codeToHTML(String code, boolean real) {
List tok = javaTok(code);
Map links = new HashMap();
Map explanations = new HashMap();
putMultipleKeys(explanations, allPlus(4, jfindAll(tok, "void q {")), "Function will execute in module's queue");
Map styles = new HashMap();
tokensToColors(tok, styles);
Matches m = new Matches();
for (int i = 1; i < l(tok); i += 2) {
String t = tok.get(i);
String prev = get(tok, i - 2), prevPrev = get(tok, i - 4);
String next = get(tok, i + 2);
String sfID = sf.get(t);
if (startsWith(t, "lambda", m) && isInteger(m.rest()) && isIdentifier(next))
explanations.put(i, ("lambda reference to a " + (m.rest()) + "-argument function"));
if (eq(t, "is") && isIdentifier(next))
explanations.put(i, "synonym of 'implements'");
if (eq(t, "methodLambda0") && isIdentifier(next))
explanations.put(i, ("short for: x -> x." + next + "() (with a fresh variable instead of x)"));
if (eq(t, "swappable") && isIdentifier(next))
explanations.put(i, "swappable functions can be exchanged per object instance");
if (eq(t, "main") && isIdentifier(next))
explanations.put(i, "reference to the current 'main' class (where all the standard functions are held, not always called 'main')");
if (eq(t, "autoDispose") && isIdentifier(next))
explanations.put(i, "autoDispose adds a cleanMeUp method that properly disposes of this variable");
if (eq(t, "macro") && isIdentifier(next))
explanations.put(i, "define a macro called '" + next + "', visible until the end of the enclosing block (or until redefined)");
if (eq(t, "virtual") && isIdentifier(next))
explanations.put(i, "\"virtual\" represents a type that is not visible in this realm, so it is transpiled to just Object");
if (eq(t, "concept") && isIdentifier(next))
explanations.put(i, "A concept is like a Java class, but persistable");
if (eq(t, "flexeq") && isIdentifier(next))
explanations.put(i, "flexeq is a fix for records inside parameterized classes");
if (eq(t, "switchable") && isIdentifier(next))
explanations.put(i, "A field that can be changed through the module's popup menu");
if (eq(t, "embedded") && isIdentifier(next))
explanations.put(i, "\"embedded\" allows you to put a function where they would not normally be allowed");
if (eq(t, "visual") && isIdentifier(next))
explanations.put(i, "short definition of the visualize() function");
if (eq(t, "dm_q") && isIdentifier(next))
explanations.put(i, "Function reference delegating to module queue");
if (eq(t, "!") && isIdentifier(prev) && neq(next, "="))
explanations.put(i, "! is short for .get()");
if (eq(t, "#") && isIdentifier(next))
explanations.put(i, "# makes an identifier local to the scope");
if (eq(t, "f") && isIdentifier(next))
explanations.put(i, "f references a static function in the main class");
if (eq(t, "r") && isIdentifier(next))
explanations.put(i, "short for: r { " + next + "() }");
if (eqOneOf(t, "rThread", "rThreadEnter") && isIdentifier(next))
explanations.put(i, "short for: " + t + " { " + next + "() }");
if (eq(t, "dispose") && isIdentifier(next))
explanations.put(i, "short for: cleanUp(" + next + "); " + next + " = null;");
if (eq(t, "*") && eq(next, "("))
explanations.put(i, "Short syntax for a constructor declaration");
if (eq(t, "thread") && eq(next, "{"))
explanations.put(i, "Start a new thread with the following code");
if (eq(t, "module") && isIdentifier(next))
explanations.put(i, "A module is a class that can be loaded in Stefan's OS");
if (eq(t, "record") && isIdentifier(next))
explanations.put(i, "A record is a value-based class");
if (eq(t, "srecord") && isIdentifier(next))
explanations.put(i, "An srecord is a static value-based class");
if (eqOneOf(t, "cached", "simplyCached") && isIdentifier(next))
explanations.put(i, "A function that caches its return value");
if (eq(t, "thread") && isQuoted(next))
explanations.put(i, "Start a new thread with the following name & code");
if (eq(t, "if") && isQuoted(next)) {
try {
List tok2 = tok_subListWithoutBorderNTokens(tok, i, i + 3);
tok_expandIfQuoted(tok2);
explanations.put(i, "short for: " + join(tok2));
} catch (Throwable __e) {
_handleException(__e);
}
}
if (eq(t, "html") && eq(next, "{"))
explanations.put(i, "short for: static Object html(String uri, final Map params) ctex {");
if (eq(t, "try") && eq(next, "answer"))
doublePut(explanations, i, i + 2, "\"try answer\" returns the expression if it isn't null or empty");
if (isSingleQuoteIdentifier(t))
explanations.put(i, "string constant, " + quote(fromSingleQuoteIdentifier(t)));
if (eq(t, "event") && isIdentifier(next))
explanations.put(i, "declare a function called " + next + "() plus helpers for adding listeners");
if (eqOneOf(t, "null", "false", "true", "this") && eq(next, ";") && tok_tokenBeforeLonelyReturnValue(tok, i - 2))
doublePut(explanations, i, i + 2, "short for: return " + t + ";");
String e = shortFor.get(t);
if (e != null)
mapPut(explanations, i, "short for: " + e);
if (!explanations.containsKey(i) && sfID != null) {
if (eqOneOf(prev, "f", "r", "rThread") || startsWith(prev, "lambda") || isIdentifier(next) && eqGet(tok, i + 4, "(") || eqOneOf(next, "(", "°") && (neq(prev, ".") || eq(prevPrev, "main") && neq(get(tok, i - 6), ".")) || eq(prev, "{") && eq(next, "}") && eq(prevPrev, "postProcess") || eq(prev, ":") && eq(prevPrev, ":"))
links.put(i, sfID);
}
List