Warning : session_start(): open(/var/lib/php/sessions/sess_p90l4ditnchkmtt23hhnnkgmaf, 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 org.python.core.*;
import org.python.util.*;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.EnumDeclaration;
import com.github.javaparser.ast.stmt.LocalClassDeclarationStmt;
import com.github.javaparser.printer.*;
import com.github.javaparser.*;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.body.*;
import com.github.javaparser.ast.visitor.*;
import com.github.javaparser.Problem;
import java.text.NumberFormat;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import static x30_pkg.x30_util.DynamicObject;
import java.nio.file.Path;
import javax.swing.border.*;
import java.awt.datatransfer.StringSelection;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import javax.swing.undo.UndoManager;
import java.text.*;
import java.nio.file.Files;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.util.TimeZone;
import java.awt.geom.*;
public class main {
static public class Conversation extends Concept {
public String cookie;
public String dataStruct;
}
abstract static public class DynGazelleMultiBot extends DynGazelleBot {
static public boolean _switchableField_maxEvalResultLength = true;
public int maxEvalResultLength = oneMegabyte_int();
static public boolean _switchableField_evalTimeout = true;
public double evalTimeout = 30.0;
static public boolean _switchableField_botProcessed = true;
public long botProcessed;
static public boolean _switchableField_maxBotAnswerLength = true;
public int maxBotAnswerLength = 100000;
static public boolean _switchableField_runAutoBots = true;
public boolean runAutoBots = true;
static public boolean _switchableField_doPython = true;
public boolean doPython = true;
static public boolean _switchableField_maxRuntimeMinutes = true;
public int maxRuntimeMinutes = 60;
transient public List bots = new ArrayList();
public Map allPosts = syncTreeMap();
transient public Map loadedCodePosts = syncTreeMap();
transient public boolean considerMasterPostsSafe = false;
static public class CouldntLoadCode {
}
transient public Lock codeLoadLock = lock();
volatile public long requestsServed;
transient public double systemLoad;
transient public long processSize;
transient public Lock statsLock = lock();
transient public ReliableSingleThread rstPersistRarely = dm_rstWithPreDelay(this, 60.0, new Runnable() {
public void run() {
try {
change();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "change();";
}
});
public void setEleu(Object eleu) {
mainBot = eleu;
}
public class Bot {
public String name;
public Bot() {
}
public Bot(String name) {
this.name = name;
}
public Bot(String name, IVF1 handlePost) {
this.handlePost = handlePost;
this.name = name;
}
transient public IVF1 handlePost;
public void handlePost(GazellePost post) {
if (handlePost != null)
handlePost.get(post);
else
handlePost_base(post);
}
final public void handlePost_fallback(IVF1 _f, GazellePost post) {
if (_f != null)
_f.get(post);
else
handlePost_base(post);
}
public void handlePost_base(GazellePost post) {
}
public GazelleBotCred cred() {
return new GazelleBotCred(_user, _botToken, name).server(gazelleServer);
}
public void postReply(GazellePost post, String text, String type) {
postReply(post, text, type, null);
}
public void postReply(GazellePost post, String text, String type, String title) {
if (empty(text) && empty(title))
text = "";
gazelle_createPost(cred(), text, type, "refs", post.id, "title", title);
}
public void createPostFromBotResult(GazellePost post, IF0 f) {
createPostFromBotResult(post, f, null);
}
public void createPostFromBotResult(GazellePost post, IF0 f, IF1 modifyBotInfo) {
String text, type = "Code Result", title = "", botInfo = "";
boolean overrideLastPost = false;
try {
Object result = f.get();
if (result == null)
return;
print("Result type: " + className(result));
if (result instanceof CreatePost) {
print("Is CreatePost");
Object[] params = toObjectArray(((CreatePost) result).params);
text = (String) optPar("text", params);
type = (String) optPar("type", params, type);
title = (String) optPar("title", params);
botInfo = (String) optPar("botInfo", params);
overrideLastPost = boolPar("overrideLastPost", params);
} else
text = str_shortenSyntheticAndStandardToString(result);
} catch (Throwable e) {
_handleException(e);
text = getStackTrace(e);
}
if (empty(text) && empty(title))
text = "";
botInfo = callFOrKeep(modifyBotInfo, botInfo);
GazelleBotCred cred = cred();
if (nempty(botInfo))
cred.botInfo = botInfo;
if (overrideLastPost) {
String _botInfo = botInfo;
GazellePost lastPost = firstThat(repliesTo(post), p -> eqic(p.botInfo, _botInfo));
print("Last post with bot info " + botInfo + ": " + lastPost);
if (lastPost != null) {
gazelle_editPost(cred, lastPost.id, text, type, "title", title, "refs", post.id);
return;
}
}
gazelle_createPost(cred, text, type, "title", title, "refs", post.id);
}
}
static public class CreatePost implements IFieldsToList {
public List params;
public CreatePost() {
}
public CreatePost(List params) {
this.params = params;
}
public String toString() {
return shortClassName(this) + "(" + params + ")";
}
public boolean equals(Object o) {
if (!(o instanceof CreatePost))
return false;
CreatePost __9 = (CreatePost) o;
return eq(params, __9.params);
}
public int hashCode() {
int h = -932402212;
h = boostHashCombine(h, _hashCode(params));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { params };
}
}
public void start() {
try {
super.start();
dm_require("#1017856/SystemLoad");
dm_vmBus_onMessage("systemLoad", new VF1() {
public void get(Double load) {
try {
if (setField_noPersist("systemLoad", load))
distributeDivChanges("serverLoadLeftHemi");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (setField_noPersist(systemLoad := load))\r\n distributeDivChanges(\"se...";
}
});
dm_vmBus_onMessage("processSize", new VF1() {
public void get(Long processSize) {
try {
if (setField_noPersist("processSize", processSize))
distributeDivChanges("memLeftHemi");
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (setField_noPersist(+processSize))\r\n distributeDivChanges(\"memLeftH...";
}
});
hotwire_addSharedClasses(Pair.class);
dm_useLocalMechListCopies();
dbIndexing(Conversation.class, "cookie");
grabLoop.handlePosts = posts -> {
dm_mediumRefreshTranspiler();
grabLoop.handlePosts_base(posts);
for (GazellePost post : posts) setField("botProcessed", max(botProcessed, post.modified));
};
setField_noCheck("allPosts", asSyncTreeMap(allPosts));
bots.add(new Bot("Math Bot", post -> {
if (post.creating)
return;
gazelle_mathBot1_handlePost_2(_user, _botToken, post);
}));
bots.add(new Bot("Code Safety Checker") {
public void handlePost(GazellePost post) {
if (post.creating)
return;
if (post.isJavaXCode())
gazelle_createPost(cred(), codeSafetyCheckResult(post.text), "Code Safety", "refs", post.id);
}
});
bots.add(new Bot("Python Code Safety Checker") {
public void handlePost(GazellePost post) {
if (post.creating)
return;
if (post.isPythonCode())
gazelle_createPost(cred(), pythonCodeSafetyCheckResult(post.text), "Python Code Safety", "refs", post.id);
}
});
bots.add(new Bot("Safe Code Runner") {
public void handlePost(GazellePost post) {
if (post.creating)
return;
if (post.isJavaXCode()) {
int runtime = min(maxRuntimeMinutes, parseFirstInt(jextractIC("runtime minutes", post.type)));
String code = post.text;
if (isCodePostSafe(post)) {
String _code = prepareCode(code, post);
createPostFromBotResult(post, () -> evalCode(runtime * 60.0, _code, post));
}
}
}
});
bots.add(new Bot("Python Safe Code Runner") {
public void handlePost(GazellePost post) {
if (post.creating)
return;
if (!doPython)
return;
if (post.isPythonCode()) {
String code = post.text;
if (isPythonCodeSafe(code)) {
IF0 f = () -> {
PythonInterpreter interpreter = jython();
PyCode compiled = interpreter.compile(code);
TraceFunction traceFunction = new TraceFunction() {
@Override
public TraceFunction traceCall(PyFrame frame) {
{
ping();
return null;
}
}
@Override
public TraceFunction traceReturn(PyFrame frame, PyObject ret) {
{
ping();
return null;
}
}
@Override
public TraceFunction traceLine(PyFrame frame, int line) {
{
ping();
return null;
}
}
@Override
public TraceFunction traceException(PyFrame frame, PyException exc) {
{
ping();
return null;
}
}
};
Py.getThreadState().tracefunc = traceFunction;
return interpreter.eval(compiled);
};
createPostFromBotResult(post, () -> evalWithTimeoutOrFail(evalTimeout, f));
}
}
}
});
bots.add(new Bot("Run Code On All Posts") {
public void handlePost(GazellePost post) {
if (post.creating)
return;
if (eqic(post.type, "Instruction") && match("Please run this code on all posts", post.text)) {
long ref = gazelle_firstPostRef(post.id);
if (ref == 0)
return;
String code = gazelle_text(ref);
if (!isCodeSafe(code))
return;
String code2 = "ret func(S post) { " + code + " };";
Object function = evalCode(code2);
List lines = new ArrayList();
String out = shorten(maxEvalResultLength, runCode(code));
for (GazellePost post2 : cloneValues(allPosts)) {
lines.add("Post " + post2.id + " (" + quote(shorten(20, post2.text)) + "): " + shorten(80, runFunc(() -> callF(function, post2.text))));
}
gazelle_createPost(cred(), lines(lines), "Code Result", "refs", post.id);
}
}
});
bots.add(new Bot("Mark identifiers safe") {
public void handlePost(GazellePost post) {
if (post.creating)
return;
if (post.creator.isMaster && match("Mark safe", post.text)) {
String text = getPost(first(post.postRefs)).text;
List ids = tok_identifiersInOrder(regexpFirstGroupIC("Unknown identifiers: (.+)", text));
print("Marking safe: " + ids);
postReply(post, markSafe(ids), "Marked safe");
}
}
});
bots.add(new Bot("Post Deleter") {
public void handlePost(GazellePost post) {
if (post.creating)
return;
if (post.creator.isMaster && match("Delete posts", post.text)) {
long ref = gazelle_firstPostRef(post.id);
if (ref == 0)
return;
String text = gazelle_text(ref);
List postIDs = allToLong(regexpAllFirstGroups(gazelle_deletePostRegexp(), text));
print("Deleting posts: " + postIDs);
if (nempty(postIDs)) {
Map result = gazelle_deletePosts(cred(), postIDs);
postReply(post, str(result), "Deletion result");
} else
postReply(post, "No mentioned posts found", "Deletion result");
}
}
});
bots.add(new Bot("Detector Runner") {
public void handlePost(GazellePost post) {
if (post.creating)
return;
{
if (!(eqic(post.type, "Instruction") && match("Please run detector", post.text)))
return;
}
try {
long detectorID = post.refWithTagOrFail("detector");
long posExamplesID = post.refWithTagOrFail("positive examples");
long negExamplesID = post.refWithTagOrFail("negative examples");
String code = getPost(detectorID).text;
List posExamples = tlft(getPost(posExamplesID).text);
List negExamples = tlft(getPost(negExamplesID).text);
List> examples = trueFalseBPairs(posExamples, negExamples);
if (!isCodeSafe(code))
throw fail("Detector code not safe");
IF1 detector = proxy(IF1.class, evalCode(code));
List good = new ArrayList();
List bad = new ArrayList();
Scorer scorer = new Scorer();
long time = sysNow();
evalWithTimeoutOrFail(evalTimeout, new Runnable() {
public void run() {
try {
for (Pair example : examples) {
String result = runFunc(() -> detector.get(example.a));
boolean ok = eq(result, str(example.b));
scorer.add(ok);
String line = (ok ? "OK" : example.b ? "False negative" : "False positive") + " (" + shorten(10, result) + "): " + example.a;
(ok ? good : bad).add(line);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "for (Pair example : examples) {\r\n String result...";
}
});
time = sysNow() - time;
String text = "Detector code:\n\n" + indentx(code) + "\n\n" + n2(good, "correct answer") + ", " + n2(bad, "bad answer") + ". Runtime: " + n2(time) + " ms\n\n" + or2(trim(lines(concatLists(bad, ll(""), good))), "No errors");
String title = "Score for detector " + detectorID + ": " + scorer;
gazelle_createPost(cred(), text, "Detector Score", "title", title, "refs", joinWithSpace(ll(post.id, detectorID, posExamplesID, negExamplesID)), "refTags", linesLL_rtrim("", "detector", "positive examples", "negative examples"));
} catch (Throwable e) {
postReply(post, getStackTrace(e), "Error");
}
}
});
bots.add(new Bot("Auto Bot Runner") {
public void handlePost(GazellePost post) {
if (!runAutoBots)
return;
if (post.creating)
return;
print("Auto Bot Runner: " + post.id);
for (GazellePost botPost : values(allPosts)) {
try {
{
if (!(eqicOneOf(botPost.type, "JavaX Code (Bot run on every post)", "JavaX Code (Live Auto Bot)") && botPost.creator.isMaster))
continue;
}
print("Processing auto-bot " + botPost.id + " on " + post.id);
Object code = codeForPost(botPost);
if (shortNameIs("CouldntLoadCode", code)) {
print("Couldn't load code for auto-bot " + botPost.id);
continue;
}
print("Code type: " + className(code));
Object botInstance = evalWithTimeoutOrFail(evalTimeout, () -> callFOrNewInstance(code));
print("Bot instance type: " + className(botInstance));
setOpt(botInstance, "postID", post.id);
setOpt(botInstance, "post", post.text);
setOpt(botInstance, "postType", post.type);
if (post.isAutoBotMade()) {
if (!botPost.isMasterMade())
continue;
if (!isTrue(evalWithTimeoutOrFail(evalTimeout, () -> call(botInstance, "runOnAutoBotPost"))))
continue;
}
createPostFromBotResult(post, () -> evalWithTimeoutOrFail(evalTimeout, () -> call(botInstance, "calc")), botInfo -> joinNemptiesWithColon("Auto-Bot " + botPost.id, botInfo));
} catch (Throwable __e) {
_handleException(__e);
}
}
}
});
dm_doEvery(60.0, 3600.0, new Runnable() {
public void run() {
try {
removeDeletedPosts();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "removeDeletedPosts();";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void handlePost(GazellePost post) {
allPosts.put(post.id, post);
change();
loadedCodePosts.remove(post.id);
if (post.modified > botProcessed) {
print("modified post: " + post.id + " - " + post.modified + "/" + botProcessed);
for (Bot bot : bots) {
try {
bot.handlePost(post);
} catch (Throwable __e) {
_handleException(__e);
}
}
}
}
public Object evalCode(String code) {
return evalCode(code, null);
}
public Object evalCode(String code, GazellePost post) {
return evalCode(evalTimeout, code, post);
}
public Object evalCode(double timeout, String code) {
return evalCode(timeout, code, null);
}
public Object evalCode(double timeout, String code, GazellePost post) {
veryQuickJava_transpiled.set(post != null ? "" : null);
try {
return dm_javaEvalWithTimeout(timeout, code);
} finally {
if (post != null) {
String java = veryQuickJava_transpiled.get();
print("Transpilation for " + post.id + ": " + shorten(java));
saveTextFile(transpilationFile(post.id), nullOnEmpty(java));
}
}
}
public String runCode(String code) {
printWithIndent("CODE> ", code);
return runFunc(() -> str_shortenSyntheticAndStandardToString(dm_javaEval(code)));
}
public String runFunc(IF0 f) {
return str_shortenSyntheticAndStandardToString(evalWithTimeoutOrException(evalTimeout, new F0() {
public Object get() {
try {
try {
return str_shortenSyntheticAndStandardToString(f.get());
} catch (Throwable e) {
return getStackTrace(e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "try {\r\n ret str_shortenSyntheticAndStandardToString(f!);\r\n } catc...";
}
}));
}
public List repliesTo(GazellePost post) {
return filter(values(allPosts), p -> contains(p.postRefs, post.id));
}
public List repliesWithTag(GazellePost post, String tag) {
Pair pair = pair(post.id, upper(tag));
return filter(repliesTo(post), p -> contains(mapPairsB("toUpper", p.taggedRefs()), pair));
}
public GazellePost getPost(long id) {
return allPosts.get(id);
}
public String getPostText(long id) {
return getPost(id).text;
}
public Collection getAllPosts() {
return values(allPosts);
}
public CreatePost createPost(Object... __) {
return new CreatePost(asList(__));
}
public CodeSafetyChecker codeSafetyChecker() {
CodeSafetyChecker checker = new CodeSafetyChecker();
checker.init();
checker.markSafe("getAllPosts");
return checker;
}
public PythonCodeSafetyChecker pythonCodeSafetyChecker() {
PythonCodeSafetyChecker checker = new PythonCodeSafetyChecker();
checker.init();
checker.markSafe("getAllPosts");
return checker;
}
public String codeSafetyCheckResult(String code) {
CodeSafetyChecker checker = codeSafetyChecker();
checker.checkCode(code);
return checker.verbalCheckResult();
}
public String pythonCodeSafetyCheckResult(String code) {
PythonCodeSafetyChecker checker = pythonCodeSafetyChecker();
checker.checkCode(code);
return checker.verbalCheckResult();
}
public boolean isCodePostSafe(GazellePost post) {
return considerMasterPostsSafe && post.creator.isMaster || isCodeSafe(post.text);
}
public boolean isCodeSafe(String code) {
CodeSafetyChecker checker = codeSafetyChecker();
checker.checkCode(code);
return checker.isSafe();
}
public boolean isPythonCodeSafe(String code) {
PythonCodeSafetyChecker checker = pythonCodeSafetyChecker();
checker.checkCode(code);
return checker.isSafe();
}
public String prepareCode(String code, GazellePost post) {
if (tok_isStaticLevelCode(code))
return code;
code = tok_addReturn(code);
CodeInRewriting cir = new CodeInRewriting(javaTok(code));
augmentCode(cir, post);
return cir.get();
}
public void augmentCode(CodeInRewriting cir, GazellePost post) {
if (cir.contains("post")) {
long ref = gazelle_firstPostRef(post.id);
if (ref != 0)
cir.add("S post = " + quote(gazelle_text(ref)) + ";");
}
if (cir.contains("post2")) {
long ref = gazelle_firstPostRef(gazelle_firstPostRef(post.id));
if (ref != 0)
cir.add("S post2 = " + quote(gazelle_text(ref)) + ";");
}
if (cir.contains("postType")) {
GazellePost post2 = getPost(gazelle_firstPostRef(post.id));
if (post2 != null)
cir.add("S postType = " + quote(post2.type) + ";");
}
if (cir.contains("getAllPosts"))
cir.add("\r\n embedded Cl getAllPosts() {\r\n ret lazyMap_bitSet quickImport(asList((Cl) dm_call(dm_current_generic(), \"getAllPosts\")));\r\n }\r\n ");
if (cir.contains("createPost"))
cir.add("\r\n embedded O createPost(O... _) {\r\n ret dm_call(dm_current_generic(), \"createPost\", _);\r\n }\r\n ");
if (cir.contains("gazelle_text"))
cir.add("\r\n embedded S gazelle_text(long id) {\r\n ret (S) dm_call(dm_current_generic(), \"getPostText\", id);\r\n }\r\n ");
}
public class CodeInRewriting {
public List tok;
public List additions = new ArrayList();
public CodeInRewriting() {
}
public CodeInRewriting(List tok) {
this.tok = tok;
}
public boolean contains(String token) {
return containsToken(tok, token);
}
public String get() {
return lines(additions) + join(tok);
}
public void add(String code) {
addIfNempty(additions, code);
}
}
public Object html(IWebRequest req) {
{
Lock __2 = statsLock;
lock(__2);
try {
requestsServed++;
rstPersistRarely.trigger();
requestServed();
} finally {
unlock(__2);
}
}
Matches m = new Matches();
if (eqic(req.uri(), "/favicon.ico"))
return serveFile(loadLibrary("#1400439"), faviconMimeType());
if (startsWith(req.uri(), "/htmlBot/", m) && isInteger(m.rest())) {
req.noSpam();
long postID = parseLong(m.rest());
GazellePost post = getPost(postID);
if (post == null)
return serve404("Post " + postID + " not found");
Object code = codeForPost(post);
IF0 calc;
if (code instanceof String)
calc = () -> code;
else if (implementsInterfaceShortNamed("IF0", code))
calc = toIF0(code);
else {
Class reqType = getClassInRealm("main$IWebRequest", code);
if (reqType == null)
throw fail("IWebRequest not found in bot");
Object wrappedReq = proxy(reqType, req);
calc = () -> callF(code, wrappedReq);
}
Object result = evalWithTimeoutOrFail(evalTimeout, () -> calc.get());
return hcomment("Made by HTML bot " + postID) + "\n" + str(result);
}
if (startsWith(req.uri(), "/chatBotReply/", m) && isInteger(m.rest())) {
req.noSpam();
long postID = parseLong(m.rest());
GazellePost post = getPost(postID);
if (post == null)
return serve404("Post " + postID + " not found");
Object code = codeForPost(post);
if (shortNameIs("CouldntLoadCode", code))
return withHeader(serve500("Couldn't load code for post"));
String q = req.params().get("q");
boolean initial = eq(req.params().get("initial"), "1");
String cookie = req.params().get("cookie");
if (!initial && empty(q))
return withHeader(serveText(""));
String answer = "";
if (implementsInterfaceShortNamed("IF1", code)) {
if (!initial)
answer = evalWithTimeoutOrFail(evalTimeout, () -> strOrEmpty(callF(code, q)));
} else {
print("Stateful bot. cookie: " + cookie);
if (empty(cookie))
return withHeader(serve500("Need cookie for stateful bot"));
Conversation conv = uniq(Conversation.class, "cookie", cookie);
Object instance = code;
if (instance == null)
return withHeader(serve500("No bot instance"));
print("Stateful bot instance: " + instance);
if (nempty(conv.dataStruct)) {
Object data = unstructureInRealm(conv.dataStruct, instance);
print("Unstructured: " + data);
copyAllThisDollarFields(instance, data);
instance = data;
}
Object _instance = instance;
answer = evalWithTimeoutOrFail(evalTimeout, () -> strOrEmpty(initial ? callOpt(_instance, "initialMessage") : call(_instance, "answer", q)));
cset(conv, "dataStruct", structure(instance));
print("Structured: " + conv.dataStruct);
}
if (initial && empty(answer))
answer = "Bot " + post.id + " ready";
return withHeader(serveJSON(litorderedmap("answer", shorten(maxBotAnswerLength, answer))));
}
if (startsWith(req.uri(), "/transpilation/", m) && isInteger(m.rest())) {
long postID = parseLong(m.rest());
GazellePost post = getPost(postID);
if (post == null)
return serve404("Post " + postID + " not found");
String src = loadTextFile(transpilationFile(post.id));
if (empty(src))
src = "No transpilation found for post " + postID + "." + (!post.isJavaXCode() ? " Code is not a code post." : " Please try \"Touch post\" and wait a few seconds");
else
try {
src = javaPrettyPrint(src);
} catch (Throwable __e) {
_handleException(__e);
}
return serveText(src);
}
if (eq(req.uri(), "/")) {
return "Loaded code posts:" + ul(keys(loadedCodePosts));
}
return serve404();
}
public Object codeForPost(GazellePost post) {
Lock __3 = codeLoadLock;
lock(__3);
try {
Object code = loadedCodePosts.get(post.id);
if (code == null) {
try {
String codeText = post.text;
if (!isCodePostSafe(post))
throw fail("Code is not safe: " + codeSafetyCheckResult(codeText));
codeText = prepareCode(codeText, null);
code = evalCode(codeText, post);
} catch (Throwable e) {
_handleException(e);
code = new CouldntLoadCode();
}
loadedCodePosts.put(post.id, code);
}
dm_pointSubmoduleToMe(mainClass(code));
return code;
} finally {
unlock(__3);
}
}
public File transpilationFile(long postID) {
return programFile("Post-Transpilations/" + postID + ".java");
}
public Object withHeader(Object response) {
call(response, "addHeader", "Access-Control-Allow-Origin", "*");
return response;
}
public Object _getReloadData() {
return loadedCodePosts;
}
public void _setReloadData(Map data) {
if (data != null)
loadedCodePosts = data;
}
public void forgetLoadedCodePosts() {
clear(loadedCodePosts);
}
public void enhanceFrame(Container f) {
super.enhanceFrame(f);
internalFramePopupMenuItems(f, "Forget loaded code", new Runnable() {
public void run() {
try {
AutoCloseable __11 = enter();
try {
forgetLoadedCodePosts();
} finally {
_close(__11);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); forgetLoadedCodePosts();";
}
}, "Remove deleted posts", runnableThread(new Runnable() {
public void run() {
try {
AutoCloseable __12 = enter();
try {
removeDeletedPosts();
} finally {
_close(__12);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); removeDeletedPosts();";
}
}));
}
public void removeDeletedPosts() {
Collection posts = asSet(grabLoop.allPostIDs());
print("Keeping " + nPosts(posts));
if (syncRemoveAllExcept(allPosts, posts))
change();
print("New count: " + nPosts(allPosts));
removeAllExcept(loadedCodePosts, posts);
}
public class WebSocketInfo {
public String uri;
public Map params;
public Set> liveDivs = new HashSet();
}
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 {
webSockets.remove(ws);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "webSockets.remove(ws)";
}
});
set(ws, "onOpen", new Runnable() {
public void run() {
try {
AutoCloseable __5 = 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();
info.uri = uri;
info.params = params;
webSockets.put(ws, info);
} finally {
_close(__5);
}
} 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 __6 = 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(__6);
}
});
}
transient public ReliableSingleThread_Multi rstDistributeDivChanges = new ReliableSingleThread_Multi<>(1000, __8 -> distributeDivChanges_impl(__8));
public void distributeDivChanges(String contentDesc) {
rstDistributeDivChanges.add(contentDesc);
}
public void distributeDivChanges_impl(String contentDesc) {
AutoCloseable __7 = 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(__7);
}
}
public void reloadDiv(Object ws, String div, String content) {
print("Reloading div " + div + " through WebSocket");
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, "webRequestsLeftHemi"))
return n2(requestsServed);
if (eq(contentDesc, "serverLoadLeftHemi"))
return formatDoubleX(systemLoad, 1);
if (eq(contentDesc, "memLeftHemi"))
return str_toM(processSize);
return null;
}
public void requestServed() {
distributeDivChanges("webRequestsLeftHemi");
}
public void setFirstGrab() {
grabLoop.firstGrab = true;
change();
}
}
static public Object mainBot;
static public Object getMainBot() {
return mainBot;
}
static public int oneMegabyte_int() {
return 1024 * 1024;
}
static public NavigableMap syncTreeMap() {
return synchroTreeMap();
}
static public void lock(Lock lock) {
try {
ping();
if (lock == null)
return;
try {
vmBus_send("locking", lock, "thread", currentThread());
lock.lockInterruptibly();
vmBus_send("locked", lock, "thread", currentThread());
} catch (InterruptedException e) {
Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
printStackTrace(e);
rethrow(e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static public void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static public ReentrantLock lock() {
return fairLock();
}
static public ReliableSingleThread dm_rstWithPreDelay(int delay, Runnable r) {
return dm_rstWithDelay(delay, r);
}
static public ReliableSingleThread dm_rstWithPreDelay(double delay, Runnable r) {
return dm_rstWithDelay(delay, r);
}
static public ReliableSingleThread dm_rstWithPreDelay(DynModule m, int delay, Runnable r) {
return dm_rstWithDelay(m, delay, r);
}
static public ReliableSingleThread dm_rstWithPreDelay(DynModule m, double seconds, Runnable r) {
return dm_rstWithDelay(m, seconds, r);
}
static public ReliableSingleThread dm_rstWithPreDelay(DynModule m, Runnable r, double seconds) {
return dm_rstWithDelay(m, r, seconds);
}
static public void change() {
callOpt(getOptMC("mainConcepts"), "allChanged");
}
static public RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
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(File f) {
return getFileSize(f) == 0;
}
static public GazellePostCreated gazelle_createPost(GazelleBotCred cred, String text, String type, Object... __) {
Map result = (Map) (postJSONPage(cred.server + "bot/createPost", paramsPlus(__, "_user", cred._user, "_botToken", cred._botToken, "text", text, "type", type, "botInfo", cred.botInfo)));
String error = (String) (result.get("error"));
if (nempty(error))
throw fail(error);
return new GazellePostCreated(toLong(result.get("postID")), (String) result.get("status"));
}
static volatile public StringBuffer local_log = new StringBuffer();
static volatile public Appendable print_log = local_log;
static volatile public int print_log_max = 1024 * 1024;
static volatile public int local_log_max = 100 * 1024;
static public boolean print_silent = false;
static public Object print_byThread_lock = new Object();
static volatile public ThreadLocal print_byThread;
static volatile public Object print_allThreads;
static volatile public Object print_preprocess;
static public void print() {
print("");
}
static public A print(String s, A o) {
print(combinePrintParameters(s, o));
return o;
}
static public A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = o + "\n";
print_noNewLine(s);
return o;
}
static public void print_noNewLine(String s) {
try {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
} catch (Throwable e) {
System.out.println(getStackTrace(e));
}
print_raw(s);
}
static public void print_raw(String s) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
vmBus_send("printed", mc(), s);
}
static public void print_autoRotate() {
}
static public String className(Object o) {
return getClassName(o);
}
static public Object[] toObjectArray(Collection c) {
List l = asList(c);
return l.toArray(new Object[l.size()]);
}
static public A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
static public A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
static public Object optPar(Object[] params, String name) {
return optParam(params, name);
}
static public Object optPar(String name, Object[] params) {
return optParam(params, name);
}
static public Object optPar(String name, Map params) {
return optParam(name, params);
}
static public A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public boolean boolPar(ThreadLocal tl) {
return boolOptParam(tl);
}
static public boolean boolPar(Object[] __, String name) {
return boolOptParam(__, name);
}
static public boolean boolPar(String name, Object[] __) {
return boolOptParam(__, name);
}
static public boolean boolPar(String name, Map __) {
return boolOptParam(name, __);
}
static public boolean boolPar(String name, Object[] params, boolean defaultValue) {
return optParam(params, name, defaultValue);
}
static public String str_shortenSyntheticAndStandardToString(Object o) {
if (o == null)
return "null";
if (isInstanceOfSyntheticClass(o))
return "Synthetic instance of " + joinWithSlash(map(c -> "interface " + shortClassName(c), o.getClass().getInterfaces()));
if (o instanceof Class)
return "class " + shortName(o);
if (isArray(o))
return arrayElementType(o) + "[" + arrayLength(o) + "]";
if (!implementsCustomToString(o))
return "Instance of " + shortClassName(o);
return str(o);
}
static volatile public PersistableThrowable _handleException_lastException;
static public List _handleException_onException = synchroList(ll((IVF1) (__1 -> printStackTrace2(__1))));
static public boolean _handleException_showThreadCancellations = false;
static public void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException) {
if (_handleException_showThreadCancellations)
System.out.println(getStackTrace_noRecord(e2));
return;
}
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
try {
printStackTrace2(e3);
} catch (Throwable e4) {
System.out.println(getStackTrace(e3));
System.out.println(getStackTrace(e4));
}
}
}
static public String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static public String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static public String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static public A callFOrKeep(Object f, A arg) {
return f == null ? arg : (A) callF(f, arg);
}
static public A callFOrKeep(IF1 f, A arg) {
return callFOrKeep((Object) f, arg);
}
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 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 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(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 gazelle_editPost(GazelleBotCred cred, long postID, String text, String type, Object... __) {
Map result = (Map) (postJSONPage(cred.server + "bot/editPost", paramsPlus(__, "postID", postID, "_user", cred._user, "_botToken", cred._botToken, "text", text, "type", type, "botInfo", cred.botInfo)));
String error = (String) (result.get("error"));
if (nempty(error))
throw fail(error);
return (String) result.get("status");
}
static public String shortClassName(Object o) {
if (o == null)
return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
static public boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}
static public int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static public String dm_require(String moduleLibID) {
return dm_makeModule(moduleLibID);
}
static public AutoCloseable dm_vmBus_onMessage(final String msg, final VF1 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
static public AutoCloseable dm_vmBus_onMessage(final String msg, final IVF1 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, ivf1ToVF1(onMessage)));
}
static public AutoCloseable dm_vmBus_onMessage(final String msg, final IVF2 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, ivf2ToVF2(onMessage)));
}
static public AutoCloseable dm_vmBus_onMessage(String msg, final VF2 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
static public AutoCloseable dm_vmBus_onMessage(String msg, Runnable onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
static public double systemLoad() {
double load = osMXBean().getSystemLoadAverage();
if (load < 0)
return systemCPULoad();
return load;
}
static public void hotwire_addSharedClasses(Collection classes) {
addAll(hotwire_classesToShare, map(__41 -> className(__41), classes));
}
static public void hotwire_addSharedClasses(Class... classes) {
hotwire_addSharedClasses(asList(classes));
}
static public void dm_useLocalMechListCopies() {
dm_useLocallyCopiedMechLists();
}
static public void dbIndexing(Object... params) {
db();
indexConceptFields(params);
}
static public void dm_mediumRefreshTranspiler() {
dm_call(dm_moduleOfType("#1017065/Transpiler"), "mediumRefresh");
}
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 Map asSyncTreeMap(Map map) {
return isSyncTreeMap(map) ? map : syncMap(asTreeMap(map));
}
static public void gazelle_mathBot1_handlePost_2(String _user, String _botToken, GazellePost post) {
List groups = regexpGroupsIC("What is (\\d+)\\s*\\+\\s*(\\d+)", post.text);
if (empty(groups))
return;
print("Processing post " + sfu(post));
BigInteger result = plus(parseBigInt(first(groups)), parseBigInt(second(groups)));
print("Calculated result: " + result);
print(postJSONPage("https://gazelle.rocks/bot/createPost", "_user", _user, "_botToken", _botToken, "refs", post.id, "text", "The result is " + result, "type", "Answer", "botInfo", "Math bot"));
}
static public String codeSafetyCheckResult(String code) {
String safety = joinWithComma(getCodeFragmentSafety(code));
if (neq(safety, "safe")) {
Set unknown = codeAnalysis_getUnknownIdentifiers(code);
if (nempty(unknown))
safety += ". Unknown identifiers: " + joinWithComma(unknown);
}
return safety;
}
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 int parseFirstInt(String s) {
return parseInt(jextract("", s));
}
static public int parseFirstInt(Iterable l) {
return parseInt(firstIntegerString(l));
}
static public String jextractIC(String pat, String s) {
return jextractIC(pat, javaTok(s));
}
static public String jextractIC(String pat, List tok) {
List tokpat = javaTok(pat);
jfind_preprocess(tokpat);
int i = jfindIC(tok, tokpat);
if (i < 0)
return null;
int j = i + l(tokpat) - 2;
return joinSubList(tok, i, j);
}
static public PythonInterpreter jython() {
return jythonInterpreter();
}
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() {
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 A evalWithTimeoutOrFail(int timeoutMS, F0 f) {
return evalWithTimeoutOrException(timeoutMS, f);
}
static public A evalWithTimeoutOrFail(double timeoutSeconds, F0 f) {
return evalWithTimeoutOrException(timeoutSeconds, f);
}
static public A evalWithTimeoutOrFail(int timeoutMS, IF0 f) {
return evalWithTimeoutOrException(timeoutMS, f);
}
static public A evalWithTimeoutOrFail(double timeoutSeconds, IF0 f) {
return evalWithTimeoutOrException(timeoutSeconds, f);
}
static public void evalWithTimeoutOrFail(int timeoutMS, Runnable r) {
evalWithTimeoutOrException(timeoutMS, runnableToF0(r));
}
static public void evalWithTimeoutOrFail(double timeoutSeconds, Runnable r) {
evalWithTimeoutOrException(timeoutSeconds, runnableToF0(r));
}
static public boolean match(String pat, String s) {
return match3(pat, s);
}
static public boolean match(String pat, String s, Matches matches) {
return match3(pat, s, matches);
}
static public boolean match(String pat, List toks, Matches matches) {
return match3(pat, toks, matches);
}
static public long gazelle_firstPostRef(long postID) {
return unnull(first(gazelle_postRefs(postID)));
}
static public String gazelle_text(long postID) {
return loadPage(gazelle_textURL(postID));
}
static public boolean isCodeSafe(String code) {
return isSafeCodeFragment(code);
}
static public int shorten_default = 100;
static public String shorten(CharSequence s) {
return shorten(s, shorten_default);
}
static public String shorten(CharSequence s, int max) {
return shorten(s, max, "...");
}
static public String shorten(CharSequence s, int max, String shortener) {
if (s == null)
return "";
if (max < 0)
return str(s);
return s.length() <= max ? str(s) : subCharSequence(s, 0, min(s.length(), max - l(shortener))) + shortener;
}
static public String shorten(int max, CharSequence s) {
return shorten(s, max);
}
static public List cloneValues(Map map) {
return cloneList(values(map));
}
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 Map> callF_cache = newDangerousWeakHashMap();
static public A callF(F0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
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 C callF(IF2 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 callF(Runnable r) {
{
if (r != null)
r.run();
}
return null;
}
static public Object callF(Object f, Object... args) {
if (f instanceof String)
return callMCWithVarArgs((String) f, args);
return safeCallF(f, args);
}
static public Object safeCallF(Object f, Object... args) {
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null)
return null;
Class c = f.getClass();
ArrayList methods;
synchronized (callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1)
return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
}
static public ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods()) if (m.getName().equals("get")) {
makeAccessible(m);
l.add(m);
}
if (!l.isEmpty())
break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static public String lines(Iterable lines) {
return fromLines(lines);
}
static public String lines(Object[] lines) {
return fromLines(asList(lines));
}
static public List lines(String s) {
return toLines(s);
}
static public String lines(Iterable l, IF1 f) {
return mapToLines(l, f);
}
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 A first(T3 t) {
return t == null ? null : t.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public List tok_identifiersInOrder(String s) {
return filter(__42 -> isIdentifier(__42), javaTokC(s));
}
static public List tok_identifiersInOrder(List tok) {
return filter(__43 -> isIdentifier(__43), codeTokens(tok));
}
static public String regexpFirstGroupIC(String pat, String s) {
Matcher m = regexpIC(pat, s);
if (m.find())
return m.group(1);
else
return null;
}
static public String markSafe(Collection identifiers) {
return markIdentifiersSafe(identifiers);
}
static public String markSafe(String... identifiers) {
return markIdentifiersSafe(identifiers);
}
static public List allToLong(Collection l) {
return lmap(__44 -> toLong(__44), l);
}
static public List regexpAllFirstGroups(String pattern, String text) {
List l = new ArrayList();
Matcher matcher = regexp(pattern, text);
while (matcher.find()) l.add(matcher.group(1));
return l;
}
static public String gazelle_deletePostRegexp() {
return regexpCaseInsensitivePrefix() + "\\bdelete\\s+post\\s+(\\d+)";
}
static public Map gazelle_deletePosts(GazelleBotCred cred, Collection ids, Object... __) {
return (Map) postJSONPage(cred.server + "bot/deletePosts", paramsPlus(__, "_user", cred._user, "_botToken", cred._botToken, "ids", joinWithSpace(ids)));
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public List tlft(String s) {
return toLinesFullTrim(s);
}
static public List tlft(File f) {
return toLinesFullTrim(f);
}
static public List> trueFalseBPairs(Iterable lTrue, Iterable lFalse) {
List> out = new ArrayList();
for (A x : unnull(lTrue)) out.add(pair(x, true));
for (A x : unnull(lFalse)) out.add(pair(x, false));
return out;
}
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 A proxy(Class intrface, final Object target) {
if (target == null)
return null;
if (isInstance(intrface, target))
return (A) target;
return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, new proxy_InvocationHandler(target));
}
static public A proxy(Object target, Class intrface) {
return proxy(intrface, target);
}
static public long sysNow() {
ping();
return System.nanoTime() / 1000000;
}
static public String indentx(String s) {
return indentx(indent_default, s);
}
static public String indentx(int n, String s) {
return dropSuffix(repeat(' ', n), indent(n, s));
}
static public String indentx(String indent, String s) {
return dropSuffix(indent, indent(indent, s));
}
static public String n2(long l) {
return formatWithThousands(l);
}
static public String n2(Collection l) {
return n2(l(l));
}
static public String n2(Map map) {
return n2(l(map));
}
static public String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
static public String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static public String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
static public String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static public String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static public String n2(Map m, String singular) {
return n2(l(m), singular);
}
static public String n2(long[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
static public String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static public String or2(String a, String b) {
return nempty(a) ? a : b;
}
static public String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
static public String trim(String s) {
return s == null ? null : s.trim();
}
static public String trim(StringBuilder buf) {
return buf.toString().trim();
}
static public String trim(StringBuffer buf) {
return buf.toString().trim();
}
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 List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
static public String joinWithSpace(Iterable c) {
return join(" ", c);
}
static public String joinWithSpace(String... c) {
return join(" ", c);
}
static public String linesLL_rtrim(Object... x) {
return lines_rtrim(ll(x));
}
static public Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static public Collection values(Object map) {
return values((Map) map);
}
static public boolean eqicOneOf(String s, String... l) {
for (String x : l) if (eqic(s, x))
return true;
return false;
}
static public boolean shortNameIs(String name, Object o) {
return isShortNamed(name, o);
}
static public boolean shortNameIs(Object o, String name) {
return shortNameIs(name, o);
}
static public Object callFOrNewInstance(Object o, Object... args) {
return o instanceof Class ? newInstance((Class) o, args) : callF(o, args);
}
static public Field setOpt_findField(Class c, String field) {
HashMap map;
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
return map.get(field);
}
static public void setOpt(Object o, String field, Object value) {
try {
if (o == null)
return;
Class c = o.getClass();
HashMap map;
if (getOpt_cache == null)
map = getOpt_makeCache(c);
else
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class) {
setOpt((Class) o, field, value);
return;
}
setOpt_raw(o, field, value);
return;
}
Field f = map.get(field);
if (f != null) {
smartSet(f, o, value);
return;
}
if (o instanceof DynamicObject)
setDyn(((DynamicObject) o), field, value);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void setOpt(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = setOpt_findStaticField(c, field);
if (f != null)
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field setOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) {
makeAccessible(f);
return f;
}
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static public boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null)
return false;
if (o instanceof ThreadLocal)
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static public boolean isTrue(Boolean b) {
return b != null && b.booleanValue();
}
static public Object call(Object o) {
return callF(o);
}
static public Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] { arg });
}
static public Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
static public String joinNemptiesWithColon(String... strings) {
return joinNempties(": ", strings);
}
static public String joinNemptiesWithColon(Collection strings) {
return joinNempties(": ", strings);
}
static public FixedRateTimer dm_doEvery(long delay, Runnable r) {
return dm_ownTimer(doEvery(delay, delay, dm_rEnter(r)));
}
static public FixedRateTimer dm_doEvery(long delay, long firstDelay, Runnable r) {
return dm_ownTimer(doEvery(delay, firstDelay, dm_rEnter(r)));
}
static public FixedRateTimer dm_doEvery(double initialSeconds, double delaySeconds, Runnable r) {
return dm_ownTimer(doEvery(initialSeconds, delaySeconds, dm_rEnter(r)));
}
static public FixedRateTimer dm_doEvery(double delaySeconds, Runnable r) {
return dm_ownTimer(doEvery(delaySeconds, dm_rEnter(r)));
}
static public Object dm_javaEvalWithTimeout(double timeoutSeconds, String expression) {
String tl = veryQuickJava_transpiled.get();
Var transpilation = new Var();
try {
return evalWithTimeoutOrFail(timeoutSeconds, () -> {
veryQuickJava_transpiled.set(tl);
try {
return dm_javaEval(expression);
} finally {
transpilation.set(veryQuickJava_transpiled.get());
}
});
} finally {
veryQuickJava_transpiled.set(transpilation.get());
}
}
static public File saveTextFile(String fileName, String contents) throws IOException {
CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
try {
File file = new File(fileName);
mkdirsForFile(file);
String tempFileName = fileName + "_temp";
File tempFile = new File(tempFileName);
if (contents != null) {
if (tempFile.exists())
try {
String saveName = tempFileName + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) {
printStackTrace(e);
}
FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
vmBus_send("wroteFile", file);
return file;
} finally {
action.done();
}
}
static public File saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
return fileName;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String nullOnEmpty(String s) {
return nullIfEmpty(s);
}
static public Map nullOnEmpty(Map map) {
return nullIfEmpty(map);
}
static public List nullOnEmpty(List l) {
return nullIfEmpty(l);
}
static public A printWithIndent(A o) {
return printIndent(o);
}
static public A printWithIndent(String indent, A o) {
return printIndent(indent, o);
}
static public void printWithIndent(int indent, Object o) {
printIndent(indent, o);
}
static public Object dm_javaEval(String expression) {
return dm_evalJava_withModule(expression);
}
static public Object evalWithTimeoutOrException(final Object f, int timeoutMS) {
return evalWithTimeoutOrException(timeoutMS, f);
}
static public Object evalWithTimeoutOrException(int timeoutMS, final Object f) {
return eitherAOpt(evalWithTimeout(timeoutMS, f));
}
static public Object evalWithTimeoutOrException(double timeoutSeconds, final Object f) {
return eitherAOpt(evalWithTimeout(timeoutSeconds, f));
}
static public A evalWithTimeoutOrException(int timeoutMS, F0 f) {
Either e = evalWithTimeout(timeoutMS, f);
if (e.isA())
return (A) e.a();
throw fail(trim("Timeout after " + timeoutMS + " ms. " + unnull(stackTraceForThread(e.b()))));
}
static public A evalWithTimeoutOrException(double timeoutSeconds, F0 f) {
return evalWithTimeoutOrException(toMS_int(timeoutSeconds), f);
}
static public A evalWithTimeoutOrException(int timeoutMS, IF0 f) {
return evalWithTimeoutOrException(timeoutMS, if0ToF0(f));
}
static public A evalWithTimeoutOrException(double timeoutSeconds, IF0 f) {
return evalWithTimeoutOrException(timeoutSeconds, if0ToF0(f));
}
static public List filter(Iterable c, Object pred) {
if (pred instanceof F1)
return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null)
for (Object o : c) if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
static public List filter(Object pred, Iterable c) {
return filter(c, pred);
}
static public List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
static public List filter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(B[] c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
static public boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static public boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
static public boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static public boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static public boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static public boolean contains(Producer p, A a) {
if (p != null && a != null)
while (true) {
A x = p.next();
if (x == null)
break;
if (eq(x, a))
return true;
}
return false;
}
static public Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
static public String upper(String s) {
return s == null ? null : s.toUpperCase();
}
static public char upper(char c) {
return Character.toUpperCase(c);
}
static public List> mapPairsB(final Object f, Iterable> l) {
return mapPairB(f, l);
}
static public List> mapPairsB(F1 f, Iterable> l) {
return mapPairB(f, l);
}
static public List> mapPairsB(IF1 f, Iterable> l) {
return mapPairB(f, l);
}
static public List> mapPairsB(Iterable> l, IF1 f) {
return mapPairB(l, f);
}
static public String toUpper(String s) {
return s == null ? null : s.toUpperCase();
}
static public List toUpper(Collection s) {
return allToUpper(s);
}
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 boolean tok_isStaticLevelCode(List tok) {
return eqOneOf(firstCodeToken(tok), "static", "sclass", "sinterface", "sS", "sO");
}
static public boolean tok_isStaticLevelCode(String src) {
return tok_isStaticLevelCode(javaTok(src));
}
static public String tok_addReturn(List tok) {
if (tok_shouldAddReturn(tok)) {
tokPrepend(tok, 1, "ret ");
tokAppend(tok, l(tok) - 2, ";");
}
return join(tok);
}
static public String tok_addReturn(String s) {
return tok_addReturn(javaTok(s));
}
static public int javaTok_n, javaTok_elements;
static public boolean javaTok_opt = false;
static public List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !regionMatches(s, j, "*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') {
++j;
break;
} else if (c2 == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j < l && !regionMatches(s, j, "]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !regionMatches(s, j, "]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
static public boolean containsToken(List tok, String token) {
return tok.contains(token);
}
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 void addIfNempty(Collection l, String s) {
if (nempty(s))
l.add(s);
}
static public void addIfNempty(Collection l, Map m) {
if (nempty(m))
l.add(m);
}
static public void addIfNempty(Collection l, Collection c) {
if (nempty(c))
l.add(c);
}
static public void unlock(Lock lock, String msg) {
if (lock == null)
return;
lock.unlock();
vmBus_send("unlocked", lock, "thread", currentThread());
print("Unlocked: " + msg);
}
static public void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
vmBus_send("unlocked", lock, "thread", currentThread());
}
static public Object serveFile(File file) {
return subBot_serveFile(file);
}
static public Object serveFile(File file, String mimeType) {
return subBot_serveFile(file, mimeType);
}
static public File loadLibrary(String snippetID) {
return loadBinarySnippet(snippetID);
}
static public String faviconMimeType() {
return "image/x-icon";
}
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;
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 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 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 Object serve404() {
return subBot_serve404();
}
static public Object serve404(String msg) {
return subBot_serve404(msg);
}
static public boolean implementsInterfaceShortNamed(Object o, String name) {
return hasElementWithClassShortNamed(name, allInterfacesImplementedBy(_getClass(o)));
}
static public boolean implementsInterfaceShortNamed(String name, Object o) {
return implementsInterfaceShortNamed(o, name);
}
static public IF0 toIF0(final Object f) {
if (f == null)
return null;
if (f instanceof IF0)
return (IF0) f;
if (isString(f))
return mainFunctionToIF0((String) f);
return (IF0) () -> callF(f);
}
static public Class getClassInRealm(Object realm, String name) {
return getClass(realm, name);
}
static public Class getClassInRealm(String name, Object realm) {
return getClassInRealm(realm, name);
}
static public String hcomment(String text) {
return hcommentSafe(text);
}
static public Object serve500() {
return subBot_serve500();
}
static public Object serve500(String msg) {
return subBot_serve500(msg);
}
static public Object serveText(Object s) {
return call(getMainBot(), "serveByteArray", toUtf8(str(s)), "text/plain; charset=utf8");
}
static public String strOrEmpty(Object o) {
return o == null ? "" : str(o);
}
static public A uniq(Class c, Object... params) {
return uniqueConcept(c, params);
}
static public A uniq(Concepts cc, Class c, Object... params) {
return uniqueConcept(cc, c, params);
}
static public Object unstructureInRealm(String s, final Object realm) {
Object classFinder = new F1() {
public Object get(String name) {
try {
return getClass_noConvertName(realm, name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "getClass_noConvertName(realm, name)";
}
};
AutoCloseable __1 = tempSetTL((ThreadLocal) callOpt(mainClass(realm), "dynamicObjectIsLoading_threadLocal"), true);
try {
return unstructure(s, false, classFinder);
} finally {
_close(__1);
}
}
static public void copyAllThisDollarFields(Object src, Object dest) {
try {
for (Field f : allThisDollarFields(dest)) {
Object o = getOpt(src, f.getName());
if (o != null)
f.set(dest, o);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object callOpt(Object o) {
return callF(o);
}
static public A callOpt(Object o, String method, Object... args) {
return (A) callOpt_withVarargs(o, method, args);
}
static public int cset(Concept c, Object... values) {
try {
if (c == null)
return 0;
warnIfOddCount(values = expandParams(c.getClass(), values));
int changes = 0;
for (int i = 0; i + 1 < l(values); i += 2) if (_csetField(c, (String) values[i], values[i + 1]))
++changes;
return changes;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public int cset(Iterable extends Concept> l, Object... values) {
int changes = 0;
for (Concept c : unnullForIteration(l)) changes += cset(c, values);
return changes;
}
static public int cset(Concept.Ref c, Object... values) {
return cset(getVar(c), values);
}
static public boolean structure_showTiming, structure_checkTokenCount;
static public String structure(Object o) {
return structure(o, new structure_Data());
}
static public String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static public void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack)) popLast(d.stack).run();
}
static public void structureToPrintWriter(Object o, PrintWriter out) {
structureToPrintWriter(o, out, new structure_Data());
}
static public void structureToPrintWriter(Object o, PrintWriter out, structure_Data d) {
d.out = out;
structure_go(o, d);
}
static public boolean structure_allowShortening = false;
static public class structure_ClassInfo {
public Class c;
public List fields;
public Method customSerializer;
public IVF1 serializeObject;
public boolean special = false;
public boolean nullInstances = false;
}
static public class structure_Data {
public PrintWriter out;
public int stringSizeLimit;
public int shareStringsLongerThan = 20;
public boolean noStringSharing = false;
public boolean storeBaseClasses = false;
public String mcDollar = actualMCDollar();
public IdentityHashMap seen = new IdentityHashMap();
public HashMap strings = new HashMap();
public HashSet concepts = new HashSet();
public HashMap infoByClass = new HashMap();
public HashMap persistenceInfo = new HashMap();
public int n;
public List stack = new ArrayList();
public structure_Data append(String token) {
out.print(token);
++n;
return this;
}
public structure_Data append(int i) {
out.print(i);
++n;
return this;
}
public structure_Data append(String token, int tokCount) {
out.print(token);
n += tokCount;
return this;
}
public structure_Data app(String token) {
out.print(token);
return this;
}
public structure_Data app(int i) {
out.print(i);
return this;
}
public structure_ClassInfo infoForClass(Class c) {
structure_ClassInfo info = infoByClass.get(c);
if (info == null)
info = newClass(c);
return info;
}
public structure_ClassInfo newClass(Class c) {
structure_ClassInfo info = new structure_ClassInfo();
info.c = c;
infoByClass.put(c, info);
if (isSyntheticOrAnonymous(c)) {
info.special = info.nullInstances = true;
return info;
}
if ((info.customSerializer = findMethodNamed(c, "_serialize")) != null)
info.special = true;
if (storeBaseClasses) {
Class sup = c.getSuperclass();
if (sup != Object.class) {
append("bc ");
append(shortDynClassNameForStructure(c));
out.print(" ");
append(shortDynClassNameForStructure(sup));
out.print(" ");
infoForClass(sup);
}
}
return info;
}
public void setFields(structure_ClassInfo info, List fields) {
info.fields = fields;
}
public void writeObject(Object o, String shortName, Map fv) {
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
append(shortName);
n += countDots(shortName) * 2;
int l = n;
Iterator it = fv.entrySet().iterator();
stack.add(new Runnable() {
public void run() {
try {
if (!it.hasNext()) {
if (n != l)
append(")");
} else {
Map.Entry e = (Map.Entry) it.next();
append(n == l ? "(" : ", ");
append((String) e.getKey()).append("=");
stack.add(this);
structure_1(e.getValue(), structure_Data.this);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!it.hasNext()) {\r\n if (n != l)\r\n append(\")\");\r\n } el...";
}
});
}
}
static public void structure_1(final Object o, final structure_Data d) {
try {
if (o == null) {
d.append("null");
return;
}
Class c = o.getClass();
boolean concept = false;
concept = o instanceof Concept;
structure_ClassInfo info = d.infoForClass(c);
List lFields = info.fields;
if (lFields == null) {
if (o instanceof Number) {
PrintWriter out = d.out;
if (o instanceof Integer) {
int i = ((Integer) o).intValue();
out.print(i);
d.n += i < 0 ? 2 : 1;
return;
}
if (o instanceof Long) {
long l = ((Long) o).longValue();
out.print(l);
out.print("L");
d.n += l < 0 ? 2 : 1;
return;
}
if (o instanceof Short) {
short s = ((Short) o).shortValue();
d.append("sh ");
out.print(s);
d.n += s < 0 ? 2 : 1;
return;
}
if (o instanceof Float) {
d.append("fl ", 2);
quoteToPrintWriter(str(o), out);
return;
}
if (o instanceof Double) {
d.append("d(", 3);
quoteToPrintWriter(str(o), out);
d.append(")");
return;
}
if (o instanceof BigInteger) {
out.print("bigint(");
out.print(o);
out.print(")");
d.n += ((BigInteger) o).signum() < 0 ? 5 : 4;
return;
}
}
if (o instanceof Boolean) {
d.append(((Boolean) o).booleanValue() ? "t" : "f");
return;
}
if (o instanceof Character) {
d.append(quoteCharacter((Character) o));
return;
}
if (o instanceof File) {
d.append("File ").append(quote(((File) o).getPath()));
return;
}
Integer ref = d.seen.get(o);
if (o instanceof String && ref == null)
ref = d.strings.get((String) o);
if (ref != null) {
d.append("t").app(ref);
return;
}
if (!(o instanceof String))
d.seen.put(o, d.n);
else {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (!d.noStringSharing) {
if (d.shareStringsLongerThan == Integer.MAX_VALUE)
d.seen.put(o, d.n);
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, d.n);
}
quoteToPrintWriter(s, d.out);
d.n++;
return;
}
if (o instanceof Set) {
if (((Set) o) instanceof TreeSet) {
d.append(isCISet_gen(((Set) o)) ? "ciset" : "treeset");
structure_1(new ArrayList(((Set) o)), d);
return;
}
d.append(((Set) o) instanceof LinkedHashSet ? "lhs" : "hashset");
structure_1(new ArrayList(((Set) o)), d);
return;
}
String name = c.getName();
if (o instanceof Collection && !isJavaXClassName(name)) {
if (name.equals("java.util.Collections$SynchronizedList") || name.equals("java.util.Collections$SynchronizedRandomAccessList")) {
d.append("sync ");
{
structure_1(unwrapSynchronizedList(((List) o)), d);
return;
}
} else if (name.equals("java.util.LinkedList"))
d.append("ll");
d.append("[");
final int l = d.n;
final Iterator it = cloneList((Collection) o).iterator();
d.stack.add(new Runnable() {
public void run() {
try {
if (!it.hasNext())
d.append("]");
else {
d.stack.add(this);
if (d.n != l)
d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.sta...";
}
});
return;
}
if (o instanceof Map && !startsWith(name, d.mcDollar)) {
if (o instanceof LinkedHashMap)
d.append("lhm");
else if (o instanceof HashMap)
d.append("hm");
else if (o instanceof TreeMap)
d.append(isCIMap_gen(((TreeMap) o)) ? "cimap" : "tm");
else if (name.equals("java.util.Collections$SynchronizedMap") || name.equals("java.util.Collections$SynchronizedSortedMap") || name.equals("java.util.Collections$SynchronizedNavigableMap")) {
d.append("sync ");
{
structure_1(unwrapSynchronizedMap(((Map) o)), d);
return;
}
}
d.append("{");
final int l = d.n;
final Iterator it = cloneMap((Map) o).entrySet().iterator();
d.stack.add(new Runnable() {
public boolean v = false;
public Map.Entry e;
public void run() {
if (v) {
d.append("=");
v = false;
d.stack.add(this);
structure_1(e.getValue(), d);
} else {
if (!it.hasNext())
d.append("}");
else {
e = (Map.Entry) it.next();
v = true;
d.stack.add(this);
if (d.n != l)
d.append(", ");
structure_1(e.getKey(), d);
}
}
}
});
return;
}
if (c.isArray()) {
if (o instanceof byte[]) {
d.append("ba ").append(quote(bytesToHex((byte[]) o)));
return;
}
final int n = Array.getLength(o);
if (o instanceof boolean[]) {
String hex = boolArrayToHex((boolean[]) o);
int i = l(hex);
while (i > 0 && hex.charAt(i - 1) == '0' && hex.charAt(i - 2) == '0') i -= 2;
d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i)));
return;
}
String atype = "array";
if (o instanceof int[]) {
atype = "intarray";
} else if (o instanceof double[]) {
atype = "dblarray";
} else {
Pair p = arrayTypeAndDimensions(c);
if (p.a == int.class)
atype = "intarray";
else if (p.a == byte.class)
atype = "bytearray";
else if (p.a == boolean.class)
atype = "boolarray";
else if (p.a == double.class)
atype = "dblarray";
else if (p.a == String.class) {
atype = "array S";
d.n++;
} else
atype = "array";
if (p.b > 1) {
atype += "/" + p.b;
d.n += 2;
}
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
public int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0)
d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")");
return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")");
return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
if (d.n != l)
d.append(", ");
d.append(i);
}
d.append("}");
return;
}
if (name.startsWith("java.") || name.startsWith("javax.")) {
d.append("j ").append(quote(str(o)));
return;
}
if (info.special) {
if (info.customSerializer != null) {
Object o2 = invokeMethod(info.customSerializer, o);
d.append("cu ");
String shortName = dropPrefix(d.mcDollar, name);
d.append(shortName);
d.out.append(' ');
structure_1(o2, d);
return;
} else if (info.nullInstances) {
d.append("null");
return;
} else if (info.serializeObject != null) {
info.serializeObject.get(o);
return;
} else
throw fail("unknown special type");
}
String dynName = shortDynClassNameForStructure(o);
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
Class cc = c;
while (cc != Object.class) {
for (Field field : getDeclaredFields_cached(cc)) {
String fieldName = field.getName();
if (fieldName.equals("_persistenceInfo"))
d.persistenceInfo.put(c, field);
if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
continue;
fields.add(field);
}
cc = cc.getSuperclass();
}
lFields = asList(fields);
int n = l(lFields);
for (int i = 0; i < n; i++) {
Field f = lFields.get(i);
if (f.getName().startsWith("this$")) {
lFields.remove(i);
lFields.add(0, f);
break;
}
}
d.setFields(info, lFields);
} else {
Integer ref = d.seen.get(o);
if (ref != null) {
d.append("t").app(ref);
return;
}
d.seen.put(o, d.n);
}
Field persistenceInfoField = (Field) (d.persistenceInfo.get(c));
Map persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o);
if (persistenceInfoField == null && o instanceof DynamicObject)
persistenceInfo = (Map) getOptDynOnly(((DynamicObject) o), "_persistenceInfo");
LinkedHashMap fv = new LinkedHashMap();
for (Field f : lFields) {
Object value;
try {
value = f.get(o);
} catch (Exception e) {
value = "?";
}
if (value != null && (persistenceInfo == null || !Boolean.FALSE.equals(persistenceInfo.get(f.getName()))))
fv.put(f.getName(), value);
}
String name = c.getName();
String shortName = dropPrefix("loadableUtils.utils$", dropPrefix(d.mcDollar, name));
if (startsWithDigit(shortName))
shortName = name;
if (concept && eq(fv.get("className"), shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
putAll(fv, (Map) fv.get("fieldValues"));
fv.remove("fieldValues");
shortName = shortDynClassNameForStructure(o);
fv.remove("className");
}
d.writeObject(o, shortName, fv);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object serveJSON(Object... data) {
return serveJSON_shallowLineBreaks(jsonPrepareData(data));
}
static public LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static public String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
static public String loadTextFile(File f, String defaultContents) {
return loadTextFile(f, defaultContents, "UTF-8");
}
static public String loadTextFile(File f, String defaultContents, String encoding) {
try {
checkFileNotTooBigToRead(f);
if (f == null || !f.exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(f);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, encoding);
return loadTextFile(inputStreamReader);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
static public String loadTextFile(String fileName, String defaultContents) {
return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
}
static public String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
} finally {
reader.close();
}
return str(builder);
}
static public String javaPrettyPrint(String src) {
return javaParser_reparse_keepComments(src);
}
static public String ul(String... list) {
return ul(asList(list));
}
static public String ul(Collection list, Object... params) {
StringBuilder buf = new StringBuilder();
int i = indexOf(params, null);
if (i == -1)
i = l(params);
for (Object s : withoutNulls(list)) buf.append(tag("li", s, subArray(params, i + 1))).append("\n");
return containerTag("ul", buf, subArray(params, 0, i)) + "\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(MultiSetMap mm) {
return mm.keySet();
}
static public void dm_pointSubmoduleToMe(Object subModule) {
dm_pointSubmoduleToMe(subModule, dm_current_mandatory_generic());
}
static public void dm_pointSubmoduleToMe(Object subModule, Object me) {
setOpt(subModule, "dm_current_mandatory_generic_value", me);
}
static public Class mainClass() {
return getMainClass();
}
static public Class mainClass(Object o) {
return getMainClass(o);
}
static public File programFile(String name) {
return prepareProgramFile(name);
}
static public File programFile(String progID, String name) {
return prepareProgramFile(progID, name);
}
static public void clear(Collection c) {
if (c != null)
c.clear();
}
static public void clear(Map map) {
if (map != null)
map.clear();
}
static public void internalFramePopupMenuItems(Container f, final Object... params) {
internalFrameTitlePopupMenuItems(((JInternalFrame) f), params);
}
static public void _close(AutoCloseable c) {
if (c != null)
try {
c.close();
} catch (Throwable e) {
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else
throw rethrow(e);
}
}
static public Runnable runnableThread(final Runnable r) {
return new Runnable() {
public void run() {
try {
startThread(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startThread(r)";
}
};
}
static public Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array) if (o != null)
set.add(o);
return set;
}
static public Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array) if (o != null)
set.add(o);
return set;
}
static public Set asSet(Iterable l) {
if (l instanceof Set)
return (Set) l;
HashSet set = new HashSet();
for (A o : unnull(l)) if (o != null)
set.add(o);
return set;
}
static public Set asSet(MultiSet ms) {
return ms == null ? null : ms.asSet();
}
static public String nPosts(long n) {
return n2(n, "post");
}
static public String nPosts(Collection l) {
return nPosts(l(l));
}
static public String nPosts(Map map) {
return nPosts(l(map));
}
static public boolean syncRemoveAllExcept(Set a, Collection b) {
if (a == null)
return false;
synchronized (collectionMutex(a)) {
return removeAllBut(a, b);
}
}
static public boolean syncRemoveAllExcept(Map a, Collection b) {
if (a == null)
return false;
synchronized (collectionMutex(a)) {
return removeAllBut(a, b);
}
}
static public boolean removeAllExcept(Set a, Collection b) {
return removeAllBut(a, b);
}
static public boolean removeAllExcept(Map a, Collection b) {
return removeAllBut(a, b);
}
static public Map syncWeakHashMap() {
return newWeakHashMap();
}
static public void closeAllKeysAndClear(Map map) {
closeAllAndClear(keys(map));
}
static public A set(A o, String field, Object value) {
if (o == null)
return null;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
makeAccessible(f);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
static public void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
makeAccessible(f);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static public Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static public void set(BitSet bs, int idx) {
{
if (bs != null)
bs.set(idx);
}
}
static public Object rcall(String method, Object o, Object... args) {
return call_withVarargs(o, method, args);
}
static public void setFieldToIVF1Proxy(Object o, String field, IVF1 target) {
setFieldToSingleMethodProxy(o, field, target, "get");
}
static public String rcall_string(String method, Object o, Object... args) {
return (String) rcall(method, o, args);
}
static public Map jsonDecodeMap(String s) {
Object o = jsonDecode(s);
if (o instanceof List && empty((List) o))
return new HashMap();
if (o instanceof Map)
return (Map) o;
else
throw fail("Not a JSON map: " + s);
}
static public boolean syncAdd(Collection c, A b) {
if (c == null)
return false;
synchronized (collectionMutex(c)) {
return c.add(b);
}
}
static public void syncAdd(List l, int idx, A b) {
if (l != null)
synchronized (collectionMutex(l)) {
l.add(idx, b);
}
}
static public List> syncMapToPairs(Map map) {
if (map == null)
return new ArrayList();
synchronized (collectionMutex(map)) {
return mapToPairs(map);
}
}
static public List asForPairsWithB(B b, Iterable> l) {
List out = new ArrayList();
for (Pair p : unnullForIteration(l)) if (eq(pairB(p), b))
out.add(pairA(p));
return out;
}
static public List asForPairsWithB(Iterable> l, B b) {
return asForPairsWithB(b, l);
}
static public String replaceDollarVars(String s, Object... params) {
if (empty(params))
return s;
Map vars = mapKeys(__45 -> dropDollarPrefix(__45), (Map) litcimap(params));
return replaceDollarVars_dyn(s, var -> strOrNull(vars.get(var)));
}
static public String jsQuote(String s) {
return javascriptQuote(s);
}
static public Object dm_call(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __1 = dm_enter(mod);
try {
return call_withVarargs(mod, method, args);
} finally {
_close(__1);
}
}
static public String jsonEncode(Object o) {
StringBuilder buf = new StringBuilder();
jsonEncode(o, buf);
return str(buf);
}
static public void jsonEncode(Object o, StringBuilder buf) {
if (o == null)
buf.append("null");
else if (o instanceof String)
buf.append(quote((String) o));
else if (o instanceof Number || o instanceof Boolean)
buf.append(o);
else if (o instanceof Map) {
Map map = (Map) o;
buf.append("{");
boolean first = true;
for (Object key : keys(map)) {
if (first)
first = false;
else
buf.append(",");
buf.append(quote((String) key));
buf.append(":");
jsonEncode(map.get(key), buf);
}
buf.append("}");
} else if (o instanceof Collection) {
Collection l = (Collection) o;
buf.append("[");
boolean first = true;
for (Object element : l) {
if (first)
first = false;
else
buf.append(",");
jsonEncode(element, buf);
}
buf.append("]");
} else
throw fail("Unknown object for JSON encoding: " + className(o));
}
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 formatDoubleX(double d, int digits) {
return formatDoubleFull(d, digits);
}
static public String str_toM(long l) {
return n2(toM(l)) + " MB";
}
static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public Set hotwire_classesToShare = synchroSet();
static public Set hotwire_classesToShare() {
return hotwire_classesToShare;
}
static public class getOpt_Map extends WeakHashMap {
public getOpt_Map() {
if (getOpt_special == null)
getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final public Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
static public HashMap getOpt_special;
static public Object getOpt_cached(Object o, String field) {
try {
if (o == null)
return null;
Class c = o.getClass();
HashMap map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null)
return f.get(o);
if (o instanceof DynamicObject)
return syncMapGet2(((DynamicObject) o).fieldValues, field);
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
if (!reflection_classesNotToScan().contains(c.getName())) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
makeAccessible(f);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
}
if (getOpt_cache != null)
getOpt_cache.put(c, map);
return map;
}
static public NavigableMap synchroTreeMap() {
return Collections.synchronizedNavigableMap(new TreeMap());
}
static public void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll_minimalExceptionHandling(vm_busListeners_live(), msg, arg);
pcallFAll_minimalExceptionHandling(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static public Thread currentThread() {
return Thread.currentThread();
}
static public Map vm_threadInterruptionReasonsMap() {
return vm_generalWeakSubMap("Thread interruption reasons");
}
static public String strOr(Object o, String ifNull) {
return o == null ? ifNull : str(o);
}
static public A printStackTrace(A e) {
print(getStackTrace(e));
return e;
}
static public void printStackTrace() {
printStackTrace(new Throwable());
}
static public void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static public void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static public void lockOrFail(Lock lock, long timeout) {
try {
ping();
vmBus_send("locking", lock, "thread", currentThread());
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
vmBus_send("locked", lock, "thread", currentThread());
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ReentrantLock fairLock() {
return new ReentrantLock(true);
}
static public ReliableSingleThread dm_rstWithDelay(int delay, Runnable r) {
return dm_rst(dm_current_mandatory(), rstWithPostDelay(delay, r));
}
static public ReliableSingleThread dm_rstWithDelay(double delay, Runnable r) {
return dm_rst(dm_current_mandatory(), rstWithPostDelay(delay, r));
}
static public ReliableSingleThread dm_rstWithDelay(DynModule m, int delay, Runnable r) {
return dm_rst(m, rstWithDelay(delay, r));
}
static public ReliableSingleThread dm_rstWithDelay(DynModule m, double seconds, Runnable r) {
return dm_rst(m, rstWithDelay(seconds, r));
}
static public ReliableSingleThread dm_rstWithDelay(DynModule m, Runnable r, double seconds) {
return dm_rstWithDelay(m, seconds, r);
}
static public Object getOptMC(String field) {
return getOpt(mc(), field);
}
static public void _handleError(Error e) {
call(javax(), "_handleError", e);
}
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 Object postJSONPage(String url, Object... params) {
return jsonDecode(postPage(url, params));
}
static public Object[] paramsPlus(Object[] a1, Object... a2) {
if (a2 == null)
return a1;
if (a1 == null)
return a2;
if (l(a1) == 1 && a1[0] instanceof Map)
return new Object[] { mapPlus((Map) a1[0], a2) };
assertEvenLength(a1);
assertEvenLength(a2);
Map map = paramsToOrderedMap(a1);
int n = l(a2);
for (int i = 0; i < n; i += 2) {
Object key = a2[i];
if (key != null)
map.put(key, a2[i + 1]);
}
return mapToParams(map);
}
static public Object[] paramsPlus(Map a1, Object... a2) {
return paramsPlus(new Object[] { a1 }, a2);
}
static public long toLong(Object o) {
if (o instanceof Number)
return ((Number) o).longValue();
if (o instanceof String)
return parseLong((String) o);
return 0;
}
static public String combinePrintParameters(String s, Object o) {
return (endsWithLetterOrDigit(s) ? s + ": " : s) + o;
}
static public void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
static public Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static public A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static public A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static public ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static public boolean isFalse(Object o) {
return eq(false, o);
}
static public String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0)
return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i + 1 < l && s.charAt(i + 1) == '\n')
++i;
}
}
return out.toString();
}
static public void print_append(Appendable buf, String s, int max) {
try {
synchronized (buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Class mc() {
return main.class;
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static public A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
static public A optParam(ThreadLocal tl) {
return optPar(tl);
}
static public Object optParam(String name, Map params) {
return mapGet(params, name);
}
static public A optParam(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
if (!even(l(opt)))
throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name))
return (A) opt[i + 1];
return defaultValue;
}
static public Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
static public Object optParam(String name, Object[] params) {
return optParam(params, name);
}
static public boolean boolOptParam(ThreadLocal tl) {
return isTrue(optPar(tl));
}
static public boolean boolOptParam(Object[] __, String name) {
return isTrue(optParam(__, name));
}
static public boolean boolOptParam(String name, Object[] __) {
return boolOptParam(__, name);
}
static public boolean boolOptParam(String name, Map __) {
return isTrue(optPar(name, __));
}
static public boolean isInstanceOfSyntheticClass(Object o) {
return o != null && o.getClass().isSynthetic();
}
static public String joinWithSlash(Iterable l) {
return join("/", l);
}
static public String joinWithSlash(A... l) {
return joinWithSlash(asList(l));
}
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 String shortName(Object o) {
return shortClassName(o);
}
static public boolean isArray(Object o) {
return o != null && o.getClass().isArray();
}
static public Class arrayElementType(Object o) {
return _getClass(o).getComponentType();
}
static public int arrayLength(Object o) {
return o != null ? Array.getLength(o) : 0;
}
static public boolean implementsCustomToString(Object o) {
Method m = findMethod(o, "toString");
return m != null && m.getDeclaringClass() != Object.class;
}
static public List synchroList() {
return synchroList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(l);
}
static public Throwable printStackTrace2(Throwable e) {
print(getStackTrace2(e));
return e;
}
static public void printStackTrace2() {
printStackTrace2(new Throwable());
}
static public void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static public PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static public Throwable innerException(Throwable e) {
return getInnerException(e);
}
static public ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static public ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
static volatile public PersistableThrowable lastException_lastException;
static public PersistableThrowable lastException() {
return lastException_lastException;
}
static public void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static public String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
static public String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url)))
return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=");
}
static public String hideCredentials(Object o) {
return hideCredentials(str(o));
}
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));
}
static public String asString(Object o) {
return o == null ? null : o.toString();
}
static public String shortenClassName(String name) {
if (name == null)
return null;
int i = lastIndexOf(name, "$");
if (i < 0)
i = lastIndexOf(name, ".");
return i < 0 ? name : substring(name, i + 1);
}
static public String dm_makeModule(String moduleLibID) {
return (String) dm_callOS("makeModule", moduleLibID);
}
static public A dm_ownResource(A resource) {
dm_currentModuleMandatory().ownResource(resource);
return resource;
}
static public AutoCloseable vmBus_onMessage(String msg, IVF1 onMessage) {
return vmBus_onMessage(msg, ivf1ToVF1(onMessage));
}
static public AutoCloseable vmBus_onMessage(final String msg, final VF1 onMessage) {
Map map = vm_busListenersByMessage_live();
synchronized (map) {
Set listeners = map.get(msg);
if (listeners == null)
map.put(msg, listeners = syncIdentityHashSet());
return tempAdd(listeners, new VF2() {
public void get(String _msg, Object arg) {
try {
callF(onMessage, arg);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, arg)";
}
});
}
}
static public AutoCloseable vmBus_onMessage(String msg, final VF2 onMessage) {
return vmBus_onMessage(msg, new VF1() {
public void get(Object[] o) {
try {
callF(onMessage, first(o), second(o));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, first(o), second(o));";
}
});
}
static public AutoCloseable vmBus_onMessage(String msg, final IVF2 onMessage) {
return vmBus_onMessage(msg, new VF1() {
public void get(Object[] o) {
try {
callF(onMessage, first(o), second(o));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, first(o), second(o));";
}
});
}
static public AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) {
return vmBus_onMessage(msg, runnableToVF1(onMessage));
}
static public VF1 ivf1ToVF1(IVF1 f) {
return f == null ? null : new VF1 () {
public void get(A a) {
try {
f.get(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "f.get(a)";
}
};
}
static public VF2 ivf2ToVF2(IVF2 f) {
return f == null ? null : new VF2 () {
public void get(A a, B b) {
try {
f.get(a, b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "f.get(a, b)";
}
};
}
static public java.lang.management.OperatingSystemMXBean osMXBean() {
return ManagementFactory.getOperatingSystemMXBean();
}
static public double systemCPULoad() {
return advancedOSMXBean().getSystemCpuLoad();
}
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)
a.putAll(b);
return a;
}
static public void dm_useLocallyCopiedMechLists() {
dm_requireModule("#1016073/MechLists");
useLocalMechListCopies(true);
setOptMC("serverMechList_raw_fresh_verbose", true);
setOptMC("mechList_goToCreator_dont", true);
}
static public void db() {
conceptsAndBot();
}
static public void db(Integer autoSaveInterval) {
conceptsAndBot(autoSaveInterval);
}
static public void indexConceptFields(Object... params) {
int i = 0;
Concepts concepts;
if (first(params) instanceof Concepts) {
concepts = (Concepts) first(params);
++i;
} else
concepts = db_mainConcepts();
for (; i < l(params); i += 2) indexConceptField(concepts, (Class) params[i], (String) params[i + 1]);
}
static public Object dm_moduleOfType(String type) {
return first(dm_modulesOfType(type));
}
static public boolean isSyncTreeMap(Map map) {
return unwrapSynchronizedMapOrNull(map) instanceof TreeMap;
}
static public List syncMap(Object f, Map map) {
return syncMap(map, f);
}
static public List syncMap(Map map, Object f) {
return map(cloneLinkedHashMap(map), f);
}
static public Map syncMap() {
return synchroHashMap();
}
static public Map syncMap(Map map) {
return synchronizedMap(map);
}
static public TreeMap asTreeMap(Map map) {
return map instanceof TreeMap ? (TreeMap) map : map == null ? new TreeMap() : new TreeMap(map);
}
static public List regexpGroupsIC(String pat, String s) {
return regexpFirstGroupsIC(pat, s);
}
static public String sfu(Object o) {
return structureForUser(o);
}
static public BigInteger plus(BigInteger a, BigInteger b) {
return a.add(b);
}
static public BigInteger plus(BigInteger a, long b) {
return a.add(bigint(b));
}
static public BigInteger parseBigInt(String s) {
return new BigInteger(s);
}
static public A second(List l) {
return get(l, 1);
}
static public A second(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
if (!it.hasNext())
return null;
it.next();
return it.hasNext() ? it.next() : null;
}
static public A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static public B second(Pair p) {
return p == null ? null : p.b;
}
static public B second(T3 t) {
return t == null ? null : t.b;
}
static public A second(Producer p) {
if (p == null)
return null;
if (p.next() == null)
return null;
return p.next();
}
static public char second(String s) {
return charAt(s, 1);
}
static public B second(Either e) {
return e == null ? null : e.bOpt();
}
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 Collection getCodeFragmentSafety(String code) {
Map map = codeAnalysis_identifierSafetyMap();
Set identifiers = tok_allIdentifiers(code);
Collection tags = treeSet();
for (String id : identifiers) {
String tag;
if (codeAnalysis_isSafeIdentifier(id))
tag = "safe";
else
tag = or2(map.get(id), "?");
tags.addAll(tokSplitAtComma(tag));
}
tags = simplifySafetyTags(tags);
if (empty(tags))
tags.add("safe");
return tags;
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static public Set codeAnalysis_getUnknownIdentifiers(String code) {
Map map = codeAnalysis_identifierSafetyMap();
Set identifiers = tok_allIdentifiers(code);
TreeSet set = new TreeSet();
for (String id : identifiers) {
if (!codeAnalysis_isSafeIdentifier(id) && (!map.containsKey(id) || contains(map.get(id), "?")))
set.add(id);
}
return set;
}
static public int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static public int parseInt(char c) {
return Integer.parseInt(str(c));
}
static public String jextract(String pat, String s) {
return jextract(pat, javaTok(s));
}
static public String jextract(String pat, List tok) {
List tokpat = javaTok(pat);
jfind_preprocess(tokpat);
int i = jfind(tok, tokpat);
if (i < 0)
return null;
int j = i + l(tokpat) - 2;
return joinSubList(tok, i, j);
}
static public String firstIntegerString(Iterable c) {
Iterator it = c.iterator();
while (it.hasNext()) {
String s = it.next();
if (isInteger(s))
return s;
}
return null;
}
static public int jfind(String s, String in) {
return jfind(javaTok(s), in);
}
static public int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
static public int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, null);
}
static public int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, String in, ITokCondition condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, int startIndex, String in, ITokCondition condition) {
return jfind(tok, startIndex, in, toTokCondition(condition));
}
static public int jfind(List tok, int startIdx, String in, Object condition) {
return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
}
static public int jfind(List tok, List tokin) {
return jfind(tok, 1, tokin);
}
static public int jfind(List tok, int startIdx, List tokin) {
return jfind(tok, startIdx, tokin, null);
}
static public int jfind(List tok, int startIdx, String[] tokinC, Object condition) {
return findCodeTokens(tok, startIdx, false, tokinC, condition);
}
static public int jfind(List tok, int startIdx, List tokin, Object condition) {
return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
}
static public List jfind_preprocess(List tok) {
for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
return tok;
}
static public int jfindIC(List tok, String pat) {
return jfindIC(tok, jfind_preprocess(javaTok(pat)));
}
static public int jfindIC(List tok, List tokPat) {
String[] toks = toStringArray(codeTokensOnly(tokPat));
return findCodeTokens(tok, 0, true, toks);
}
static public int l(Object[] a) {
return a == null ? 0 : a.length;
}
static public int l(boolean[] a) {
return a == null ? 0 : a.length;
}
static public int l(byte[] a) {
return a == null ? 0 : a.length;
}
static public int l(short[] a) {
return a == null ? 0 : a.length;
}
static public int l(long[] a) {
return a == null ? 0 : a.length;
}
static public int l(int[] a) {
return a == null ? 0 : a.length;
}
static public int l(float[] a) {
return a == null ? 0 : a.length;
}
static public int l(double[] a) {
return a == null ? 0 : a.length;
}
static public int l(char[] a) {
return a == null ? 0 : a.length;
}
static public int l(Collection c) {
return c == null ? 0 : c.size();
}
static public int l(Iterator i) {
return iteratorCount_int_close(i);
}
static public int l(Map m) {
return m == null ? 0 : m.size();
}
static public int l(CharSequence s) {
return s == null ? 0 : s.length();
}
static public long l(File f) {
return f == null ? 0 : f.length();
}
static public int l(Object o) {
return o == null ? 0 : o instanceof String ? l((String) o) : o instanceof Map ? l((Map) o) : o instanceof Collection ? l((Collection) o) : o instanceof Object[] ? l((Object[]) o) : o instanceof boolean[] ? l((boolean[]) o) : o instanceof byte[] ? l((byte[]) o) : o instanceof char[] ? l((char[]) o) : o instanceof short[] ? l((short[]) o) : o instanceof int[] ? l((int[]) o) : o instanceof float[] ? l((float[]) o) : o instanceof double[] ? l((double[]) o) : o instanceof long[] ? l((long[]) o) : (Integer) call(o, "size");
}
static public int l(MultiSet ms) {
return ms == null ? 0 : ms.size();
}
static public String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
static public String joinSubList(List l, int i) {
return join(subList(l, i));
}
static public PythonInterpreter jythonInterpreter() {
return new PythonInterpreter();
}
static public Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
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 void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static public F0 runnableToF0(Runnable r) {
return r == null ? null : new F0() {
public Object get() {
try {
r.run();
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "r.run(); null;";
}
};
}
static public boolean match3(String pat, String s) {
return match3(pat, s, null);
}
static public boolean match3(String pat, String s, Matches matches) {
if (pat == null || s == null)
return false;
return match3(pat, parse3_cachedInput(s), matches);
}
static public boolean match3(String pat, List toks, Matches matches) {
List tokpat = parse3_cachedPattern(pat);
return match3(tokpat, toks, matches);
}
static public boolean match3(List