Warning : session_start(): open(/var/lib/php/sessions/sess_jeqtqdgrorciqppfuf8u02j92c, 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
1400546
1400547
1400548
1400555
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 java.util.function.*;
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 java.awt.geom.*;
import javax.imageio.*;
import java.math.*;
import java.time.Duration;
import java.lang.invoke.VarHandle;
import java.lang.invoke.MethodHandles;
import java.text.NumberFormat;
import javax.swing.border.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.geom.*;
import java.text.SimpleDateFormat;
import javax.swing.undo.UndoManager;
import java.awt.datatransfer.StringSelection;
import java.text.*;
import java.util.TimeZone;
import java.nio.charset.Charset;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import static x30_pkg.x30_util.DynamicObject;
import org.fife.ui.autocomplete.*;
import org.fife.rsta.ui.CollapsibleSectionPanel;
import org.fife.rsta.ui.GoToDialog;
import org.fife.rsta.ui.SizeGripIcon;
import org.fife.rsta.ui.search.FindDialog;
import org.fife.rsta.ui.search.ReplaceDialog;
import org.fife.rsta.ui.search.ReplaceToolBar;
import org.fife.rsta.ui.search.SearchEvent;
import org.fife.rsta.ui.search.SearchListener;
import org.fife.rsta.ui.search.FindToolBar;
import org.fife.ui.rsyntaxtextarea.ErrorStrip;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextScrollPane;
import org.fife.ui.rtextarea.SearchContext;
import org.fife.ui.rtextarea.SearchEngine;
import org.fife.ui.rtextarea.SearchResult;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.SyntaxScheme;
import javax.swing.Icon;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.Const;
import org.apache.bcel.generic.*;
import java.lang.reflect.Type;
import java.util.jar.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import javax.swing.border.TitledBorder;
import java.nio.file.Path;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import org.fife.ui.rsyntaxtextarea.*;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
public class main {
static public class G22Utils_Base {
transient public Set> onProjectFileChanged;
public G22Utils_Base onProjectFileChanged(IVF1 f) {
onProjectFileChanged = createOrAddToSyncLinkedHashSet(onProjectFileChanged, f);
return this;
}
public G22Utils_Base removeProjectFileChangedListener(IVF1 f) {
main.remove(onProjectFileChanged, f);
return this;
}
public void projectFileChanged(File file) {
if (onProjectFileChanged != null)
for (var listener : onProjectFileChanged) pcallF_typed(listener, file);
}
}
static public class G22Utils extends G22Utils_Base implements AutoCloseable, TransientObject {
final public G22Utils setBackgroundProcessesUI(IBackgroundProcesses backgroundProcessesUI) {
return backgroundProcessesUI(backgroundProcessesUI);
}
public G22Utils backgroundProcessesUI(IBackgroundProcesses backgroundProcessesUI) {
this.backgroundProcessesUI = backgroundProcessesUI;
return this;
}
final public IBackgroundProcesses getBackgroundProcessesUI() {
return backgroundProcessesUI();
}
public IBackgroundProcesses backgroundProcessesUI() {
return backgroundProcessesUI;
}
public IBackgroundProcesses backgroundProcessesUI;
final public G22Utils setModule(Enterable module) {
return module(module);
}
public G22Utils module(Enterable module) {
this.module = module;
return this;
}
final public Enterable getModule() {
return module();
}
public Enterable module() {
return module;
}
public Enterable module;
final public G22Utils setMasterStuff(G22MasterStuff masterStuff) {
return masterStuff(masterStuff);
}
public G22Utils masterStuff(G22MasterStuff masterStuff) {
this.masterStuff = masterStuff;
return this;
}
final public G22MasterStuff getMasterStuff() {
return masterStuff();
}
public G22MasterStuff masterStuff() {
return masterStuff;
}
public G22MasterStuff masterStuff;
final public G22Utils setConcepts(Concepts concepts) {
return concepts(concepts);
}
public G22Utils concepts(Concepts concepts) {
this.concepts = concepts;
return this;
}
final public Concepts getConcepts() {
return concepts();
}
public Concepts concepts() {
return concepts;
}
public Concepts concepts;
final public G22Utils setProjectActions(G22ProjectActions projectActions) {
return projectActions(projectActions);
}
public G22Utils projectActions(G22ProjectActions projectActions) {
this.projectActions = projectActions;
return this;
}
final public G22ProjectActions getProjectActions() {
return projectActions();
}
public G22ProjectActions projectActions() {
return projectActions;
}
public G22ProjectActions projectActions;
final public G22AutoStarter getAutoStarter() {
return autoStarter();
}
public G22AutoStarter autoStarter() {
return autoStarter;
}
public G22AutoStarter autoStarter = new G22AutoStarter(this);
final public G22Utils setFunctionTimings(FunctionTimings functionTimings) {
return functionTimings(functionTimings);
}
public G22Utils functionTimings(FunctionTimings functionTimings) {
this.functionTimings = functionTimings;
return this;
}
final public FunctionTimings getFunctionTimings() {
return functionTimings();
}
public FunctionTimings functionTimings() {
return functionTimings;
}
public FunctionTimings functionTimings = new FunctionTimings();
final public Map getProjectWideFunctionDefs() {
return projectWideFunctionDefs();
}
public Map projectWideFunctionDefs() {
return projectWideFunctionDefs;
}
public Map projectWideFunctionDefs = syncMap();
final public Map getProjectWideClassDefs() {
return projectWideClassDefs();
}
public Map projectWideClassDefs() {
return projectWideClassDefs;
}
public Map projectWideClassDefs = syncMap();
public Timestamp recompileDate;
final public Set getAutoClosingResources() {
return autoClosingResources();
}
public Set autoClosingResources() {
return autoClosingResources;
}
public Set autoClosingResources = syncLinkedHashSet();
public FileWatchService fileWatcher;
public boolean projectFileListenerInitiated = false;
final public CombinedStringifier getStringifier() {
return stringifier();
}
public CombinedStringifier stringifier() {
return stringifier;
}
public CombinedStringifier stringifier = new CombinedStringifier(o -> o instanceof BufferedImage ? "Image (" + ((BufferedImage) o).getWidth() + "*" + ((BufferedImage) o).getHeight() + " px)" : null);
public ILASClassLoader lasClassLoader() {
return masterStuff == null ? null : masterStuff.lasClassLoader();
}
final public G22Utils setConfirmProjectReplacements(boolean confirmProjectReplacements) {
return confirmProjectReplacements(confirmProjectReplacements);
}
public G22Utils confirmProjectReplacements(boolean confirmProjectReplacements) {
this.confirmProjectReplacements = confirmProjectReplacements;
return this;
}
final public boolean getConfirmProjectReplacements() {
return confirmProjectReplacements();
}
public boolean confirmProjectReplacements() {
return confirmProjectReplacements;
}
public boolean confirmProjectReplacements = false;
public ImageSurface stdImageSurface_noToolTip() {
return stdImageSurface_noToolTip(imageSurface());
}
public ImageSurface stdImageSurface_noToolTip(ImageSurface is) {
imageSurface_pixelated(is);
is.setAutoZoomToDisplay(true).repaintInThread(false);
is.defaultImageDir = () -> dbDir();
is.specialPurposed = true;
return is;
}
public ImageSurface stdImageSurface() {
return stdImageSurface(imageSurface());
}
public ImageSurface stdImageSurface(ImageSurface is) {
stdImageSurface_noToolTip(is);
new ImageSurface_PositionToolTip(is);
return is;
}
public List stdImageSurfaces(Collection images) {
return map(__37 -> stdImageSurface(__37), toBufferedImages(images));
}
public ImageSurface stdImageSurface(MakesBufferedImage img) {
return stdImageSurface(toBufferedImage(img));
}
public ImageSurface stdImageSurface(BufferedImage img) {
var is = stdImageSurface();
is.setImage(img);
return is;
}
public ImageSurface stdImageSurface(File file) {
var is = stdImageSurface();
is.setImage(file);
return is;
}
public ImageSurface stdImageSurface(G22GalleryImage img) {
return stdImageSurface(img == null ? null : img.path);
}
public ImageSurface stdImageSurfaceWithSelection(MakesBufferedImage img, Rect selection) {
return stdImageSurfaceWithSelection(toBufferedImage(img), selection);
}
public ImageSurface stdImageSurfaceWithSelection(BufferedImage img, Rect selection) {
var is = stdImageSurface(img);
is.setSelection(selection);
return is;
}
public String stringify(Object o) {
return stringifier.toString(o);
}
transient public Set> onBigVariableLoaded;
public G22Utils onBigVariableLoaded(IVF1 f) {
onBigVariableLoaded = createOrAddToSyncLinkedHashSet(onBigVariableLoaded, f);
return this;
}
public G22Utils removeBigVariableLoadedListener(IVF1 f) {
main.remove(onBigVariableLoaded, f);
return this;
}
public void bigVariableLoaded(G22Variable var) {
if (onBigVariableLoaded != null)
for (var listener : onBigVariableLoaded) pcallF_typed(listener, var);
}
transient public Set> onSettingUpParser;
public G22Utils onSettingUpParser(IVF1 f) {
onSettingUpParser = createOrAddToSyncLinkedHashSet(onSettingUpParser, f);
return this;
}
public G22Utils removeSettingUpParserListener(IVF1 f) {
main.remove(onSettingUpParser, f);
return this;
}
public void settingUpParser(GazelleV_LeftArrowScriptParser parser) {
if (onSettingUpParser != null)
for (var listener : onSettingUpParser) pcallF_typed(listener, parser);
}
transient public Set> onSettingUpScriptIDE;
public G22Utils onSettingUpScriptIDE(IVF1 f) {
onSettingUpScriptIDE = createOrAddToSyncLinkedHashSet(onSettingUpScriptIDE, f);
return this;
}
public G22Utils removeSettingUpScriptIDEListener(IVF1 f) {
main.remove(onSettingUpScriptIDE, f);
return this;
}
public void settingUpScriptIDE(JLeftArrowScriptIDE ide) {
if (onSettingUpScriptIDE != null)
for (var listener : onSettingUpScriptIDE) pcallF_typed(listener, ide);
}
public GazelleV_LeftArrowScriptParser leftArrowParser() {
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
parser.classNameResolver(classNameResolver());
parser.lasClassLoader(lasClassLoader());
settingUpParser(parser);
parser.addClassAlias("Bool", "Boolean");
parser.addClassAlias("BollingerBands", "LiveBollingerBands");
parser.addClassAlias("Freq", "Frequency");
parser.addClassAlias("PriceDigitizer", "PriceDigitizer2");
parser.addClassAlias("MRUAndAllTimeTop", "MRUAndAllTimeTop_optimized");
parser.findExternalObject2 = name -> {
{
var __3 = projectWideClassDefs.get(name);
if (__3 != null)
return __3;
}
return parser.findExternalObject2_base(name);
};
parser.addFunctionDefs(projectWideFunctionDefs);
return parser;
}
public Object leftArrow(String script) {
return leftArrowParse(script).get();
}
public GazelleV_LeftArrowScript.Script leftArrowParse(String script) {
return leftArrowParser().parse(script);
}
public Object leftArrowWithVars(String script, Object... vars) {
var parser = leftArrowParser();
for (int i = 0; i < l(vars); i += 2) parser.addVar((String) vars[i], or(_getClass(vars[i + 1]), Object.class), true);
var parsed = parser.parse(script);
FlexibleVarContext varContext = new FlexibleVarContext();
for (int i = 0; i < l(vars); i += 2) varContext.set((String) vars[i], vars[i + 1]);
return parsed.get(varContext);
}
public void basicParserTest() {
var parser = leftArrowParser();
print("classContainerPrefixes", parser.classContainerPrefixes());
assertEquals(pair(1, 2), parser.parse("new Pair 1 2").get());
}
final public JLeftArrowScriptIDE leftArrowScriptIDE() {
return leftArrowIDE();
}
public JLeftArrowScriptIDE leftArrowIDE() {
JLeftArrowScriptIDE ide = new JLeftArrowScriptIDE();
ide.g22utils(this);
ide.scriptTimeout(projectWideScriptTimeout());
settingUpScriptIDE(ide);
return ide;
}
public File byteCodePath() {
return assertNotNull(getBytecodePathForClass(this));
}
public ClassNameResolver classNameResolver_cache;
public ClassNameResolver classNameResolver() {
if (classNameResolver_cache == null)
classNameResolver_cache = classNameResolver_load();
return classNameResolver_cache;
}
public ClassNameResolver classNameResolver_load() {
return new ClassNameResolver().byteCodePath(byteCodePath()).init();
}
public File databasesMotherDir() {
return masterStuff.databasesMotherDir();
}
public File dirOfProjectNamed(String name) {
assertNempty(name);
return newFile(databasesMotherDir(), name);
}
public AutoCloseable enter() {
return module == null ? null : module.enter();
}
public String defaultDBName() {
return "Default";
}
public File lastOpenedDBsFile() {
return newFile(databasesMotherDir(), "Last Opened");
}
public File recentlyOpenedDBsFile() {
return newFile(databasesMotherDir(), "Recently Opened");
}
public File autoUpdateFile() {
return newFile(databasesMotherDir(), "Auto-Update");
}
public boolean autoUpdateEnabled() {
return fileExists(autoUpdateFile());
}
public void setAutoUpdate(boolean b) {
createOrRemoveFile(autoUpdateFile(), b);
}
public List dbsToOpen() {
return loadRecentProjectsFile(lastOpenedDBsFile());
}
public List dbNamesRecentlyOpened() {
return loadRecentProjectsFile(recentlyOpenedDBsFile());
}
public void addToRecentDBNames(String dbName, boolean hidden) {
List list = dbNamesRecentlyOpened();
List list2 = cloneList(list);
removeAll(list2, dbName, "*" + dbName);
list2.add(0, hidden ? "*" + dbName : dbName);
truncateList(list2, 100);
if (!eq(list, list2))
saveTextFile(recentlyOpenedDBsFile(), lines(list2));
}
public List loadRecentProjectsFile(File file) {
List dbNames = new ArrayList();
for (String name : tlft(loadTextFile(file))) {
String name2 = dropPrefix("*", name);
if (fileExists(newFile(databasesMotherDir(), name2)))
dbNames.add(name);
}
if (empty(dbNames))
dbNames.add(defaultDBName());
return dbNames;
}
public void setOpenDBs(Collection extends IG22LoadedDB> dbs) {
List dbNames = new ArrayList();
for (var db : dbs) {
var dbDir = conceptsDir(db.concepts());
if (sameFile(databasesMotherDir(), dirOfFile(dbDir)))
dbNames.add((db.hidden() ? "*" : "") + fileName(dbDir));
}
saveTextFile(lastOpenedDBsFile(), lines(dbNames));
}
public void setupScriptCRUD(SimpleCRUD_v2 crud) {
setupScriptCRUD(crud, false);
}
public void setupScriptCRUD(SimpleCRUD_v2 crud, boolean allowRunOnProjectOpen) {
crud.useNewChangeHandler(true);
crud.editableFieldsForItem = x -> llNonNulls("description", allowRunOnProjectOpen ? "runOnProjectOpen" : null, allowRunOnProjectOpen ? "runOrder" : null);
crud.multiLineField("text");
crud.multiLineField("editingText");
crud.makeTextArea = text -> jMinHeight(200, crud.makeTextArea_base(text));
crud.humanizeFieldNames = false;
crud.iconButtons(true);
crud.itemToMap_inner2 = c -> scriptToMap(c, allowRunOnProjectOpen);
crud.dontDuplicateFields = litset("runOnProjectOpen", "runCount", "lastResultByMode");
}
public Map scriptToMap(G22LeftArrowScript c) {
return scriptToMap(c, false);
}
public Map scriptToMap(G22LeftArrowScript c, boolean allowRunOnProjectOpen) {
return litorderedmap("Description", c.description(), "Status", renderScriptStatus(c), "LoC", renderScriptLoC(c), "Import note", c.importNote, "Run on project open", c.renderRunOnProjectOpenStatus());
}
public String renderScriptStatus(G22LeftArrowScript c) {
return or2_rev("Empty", joinNemptiesWithSpacedPlus(c.isClearForAutoRun() ? "Clear for auto-run" : null, c.isSavedDistinctFromAutoRunVersion() ? "Saved (not cleared)" : null, c.isEditing() ? "Editing" : null));
}
public String renderScriptLoC(G22LeftArrowScript c) {
return n2(intMax(mapLL(__38 -> linesOfCode_javaTok(__38), c.editingText, c.text, c.codeForAutoRun())));
}
public List labelsForFile(File file) {
if (file == null)
return null;
File labelsFile = appendToFileName(file, ".labels");
List labels = tlft(loadTextFile(labelsFile));
return map(__39 -> getLabel(__39), labels);
}
public File labelsFile(File file) {
if (file == null)
return null;
return appendToFileName(file, ".labels");
}
public void setLabelsForFile(File file, List labels) {
List list = map(labels, label -> label.name);
File f = labelsFile(file);
saveTextFile(f, lines(list));
print("Saved " + nLabels(list) + " (" + joinWithComma(list) + ") to " + f);
}
public G22Label getLabel(String name) {
if (empty(name))
return null;
if (containsNewLine(name))
throw fail("No newlines in label names allowed: " + name);
return uniqCI(concepts, G22Label.class, "name", name);
}
final public File projectDir() {
return dbDir();
}
public File dbDir() {
return conceptsDir(concepts);
}
final public File projectFile(String name) {
return fileInDbDir(name);
}
final public File projectDir(String name) {
return fileInDbDir(name);
}
public File fileInDbDir(String name) {
return newFile(dbDir(), name);
}
public class GazelleDB implements IFieldsToList {
public String name;
public File dir;
public GazelleDB() {
}
public GazelleDB(String name, File dir) {
this.dir = dir;
this.name = name;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + name + ", " + dir + ")";
}
public boolean equals(Object o) {
if (!(o instanceof GazelleDB))
return false;
GazelleDB __1 = (GazelleDB) o;
return eq(name, __1.name) && eq(dir, __1.dir);
}
public int hashCode() {
int h = 1669530526;
h = boostHashCombine(h, _hashCode(name));
h = boostHashCombine(h, _hashCode(dir));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { name, dir };
}
public String name() {
return name;
}
public File dir() {
return dir;
}
public boolean loaded() {
return loadedDB() != null;
}
public IG22LoadedDB loadedDB_cache;
public IG22LoadedDB loadedDB() {
if (loadedDB_cache == null)
loadedDB_cache = loadedDB_load();
return loadedDB_cache;
}
public IG22LoadedDB loadedDB_load() {
return masterStuff.getLoadedDBForConceptDir(dir);
}
public File conceptsFile() {
return conceptsFileIn(dir);
}
}
public List gazelleDBs() {
List dbs = new ArrayList();
for (File dir : listDirsContainingFileNamed(databasesMotherDir(), "concepts.structure.gz")) dbs.add(new GazelleDB(fileName(dir), dir));
return dbs;
}
public IterableIterator peekAllProjectsConcepts() {
var classFinder = masterStuff.makeClassFinder();
return mapI_pcall(gazelleDBs(), db -> {
var cc = newConceptsWithClassFinder(db.conceptsFile(), classFinder);
cc.loadFromDisk();
return cc;
});
}
public RSyntaxTextAreaWithSearch newSyntaxTextArea() {
return newSyntaxTextArea((IF1) null);
}
public RSyntaxTextAreaWithSearch newSyntaxTextArea(IF1 wrapStatusLabel) {
RSyntaxTextAreaWithSearch ta = new RSyntaxTextAreaWithSearch(wrapStatusLabel);
ta.textArea().setHighlightCurrentLine(false);
ta.menuLessOperation();
return ta;
}
public RSyntaxTextAreaWithSearch newSyntaxTextArea(String text) {
var ta = newSyntaxTextArea();
ta.setText(text);
return ta;
}
public File projectStoryTextFile() {
return newFile(dbDir(), "story.txt");
}
public String projectName() {
return fileName(dbDir());
}
public void close() {
try {
autoStarter.close();
closeAndClear(autoClosingResources);
{
cleanUp(fileWatcher);
fileWatcher = null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void close(AutoCloseable c) {
main.close(c);
}
public G22Variable findProjectVar(String name) {
return conceptWhereCI(concepts, G22Variable.class, "name", name);
}
public Collection projectVarNames() {
return collect("name", list(concepts, G22Variable.class));
}
public Object getProjectVar(String name) {
G22Variable var = findProjectVar(name);
return var == null ? null : var.value();
}
public Object getBigProjectVarOnce(String name) {
G22Variable var = findProjectVar(name);
return var == null ? null : var.getOnce();
}
public Object getMandatoryProjectVar(String name) {
return assertNotNull(name, getProjectVar(name));
}
public Object getOrSetTransientProjectVar(String name, IF0 f) {
{
var __4 = getProjectVar(name);
if (__4 != null)
return __4;
}
return setTransientProjectVarAndReturn(name, f.get());
}
public Object getProjectVarOrCallScript(String name, long scriptID) {
{
var __5 = getProjectVar(name);
if (__5 != null)
return __5;
}
return callScript(scriptID);
}
public Object getProjectVarSetByScript(String name, long scriptID) {
{
var __6 = getProjectVar(name);
if (__6 != null)
return __6;
}
callScript(scriptID);
return getProjectVar(name);
}
public Object getProjectVarFromAnyProject(String name) {
for (var project : masterStuff().openProjects()) {
var __7 = project.g22utils().getProjectVar(name);
if (__7 != null)
return __7;
}
return null;
}
final public List getVarFromAnyProject(String name) {
return getProjectVarFromAllProjects(name);
}
public List getProjectVarFromAllProjects(String name) {
return nonNulls(masterStuff().openProjects(), project -> project.g22utils().getProjectVar(name));
}
public G22Variable projectVarConcept(String name) {
return optimizedUniqCI(concepts, G22Variable.class, "name", name);
}
public Object waitForProjectVar(String name) {
return waitForProjectVar(infinity(), name);
}
public Object waitForProjectVar(double timeoutSeconds, String name) {
G22Variable var = projectVarConcept(name);
return waitForCalculatedValueUsingChangeListener(timeoutSeconds, () -> var.value(), var);
}
public void setBigProjectVar(boolean persistent, String name, Object value) {
if (persistent)
setBigProjectVar(name, value);
else
setTransientProjectVar(name, value);
}
public G22Variable setProjectVar(boolean persistent, String name, Object value) {
G22Variable var = projectVarConcept(name);
if (!persistent)
var.persistent(persistent);
var.value(value);
if (persistent)
var.persistent(persistent);
return var;
}
public void unloadProjectVar(String name) {
var var = findProjectVar(name);
{
if (var != null)
var.unload();
}
}
public A setBigProjectVar(String name, A value) {
setPersistentProjectVar(name, value);
G22Variable var = projectVarConcept(name);
var.makeBig();
return value;
}
public Object getCachedProjectVar(String name) {
var var = findProjectVar(name);
return var == null ? null : var.cachedValue();
}
public boolean isBigProjectVar(String name) {
var v = findProjectVar(name);
return v != null && v.big();
}
public A setPersistentProjectVar(String name, A value) {
setProjectVar(true, name, value);
return value;
}
public G22Variable setTransientProjectVar(String name, Object value) {
return setProjectVar(false, name, value);
}
public A setTransientProjectVarAndReturn(String name, A value) {
setProjectVar(false, name, value);
return value;
}
public void setAutoClosingProjectVar(String name, Object value) {
setTransientProjectVar(name, value).autoClose(true);
}
public void clearProjectVar(String name) {
var v = findProjectVar(name);
{
if (v != null)
v.clear();
}
}
public void deleteProjectVar(String name) {
deleteConcept(findProjectVar(name));
}
final public Object getOrCreateTransientProjectVar(String name, IF0 maker) {
return getOrCreateProjectVar(name, maker);
}
public Object getOrCreateProjectVar(String name, IF0 maker) {
return getOrCreateProjectVar(projectVarConcept(name), maker);
}
public Object getOrCreatePersistentProjectVar(String name, IF0 maker) {
var var = projectVarConcept(name);
Object value = getOrCreateProjectVar(var, maker);
var.persistent(true);
return value;
}
public Object getOrCreateBigProjectVar(String name, IF0 maker) {
var var = projectVarConcept(name);
Object value = getOrCreateProjectVar(var, maker);
var.makeBig();
return value;
}
public Object getOrCreateAutoClosingProjectVar(String name, IF0 maker) {
var var = projectVarConcept(name);
Object value = getOrCreateProjectVar(var, maker);
var.autoClose(true);
return value;
}
public G22Variable getOrCreateAutoClosingProjectVar_returnVar(String name, IF0 maker) {
var var = projectVarConcept(name);
getOrCreateProjectVar(var, maker);
return var.autoClose(true);
}
public boolean projectVarIsNotNull(String name) {
var var = findProjectVar(name);
return var != null && var.has();
}
public Object getOrCreateProjectVar(G22Variable var, IF0 maker) {
if (!var.has()) {
Object value = maker.get();
if (value != null)
var.setValueIfNull(value);
}
return var.get();
}
public IVarWithNotify liveProjectVar(String name) {
return liveProjectVar(name, null);
}
public IVarWithNotify liveProjectVar(String name, Object defaultValue) {
G22Variable var = projectVarConcept(name);
var.persistent(true);
var.setValueIfNull(defaultValue);
return var.varValue();
}
public IVarWithNotify liveTransientProjectVar(String name) {
return liveTransientProjectVar(name, null);
}
public IVarWithNotify liveTransientProjectVar(String name, Object defaultValue) {
G22Variable var = projectVarConcept(name);
var.persistent(false);
var.setValueIfNull(defaultValue);
return var.varValue();
}
public void replaceCloseableProjectVar(String name, IF0 extends AutoCloseable> calc) {
Object value = getProjectVar(name);
if (value instanceof AutoCloseable) {
main.close((AutoCloseable) value);
deleteProjectVar(name);
}
setTransientProjectVar(name, calc == null ? null : calc.get());
}
public void projectVarChanged(String name) {
var var = findProjectVar(name);
{
if (var != null)
var.changeInsideOfValue();
}
}
public Collection projectVarChanged(Object value) {
var vars = conceptsWhere(concepts, G22Variable.class, "value", value);
for (var var : vars) var.change();
return vars;
}
public double defaultScriptTimeout() {
return 10.0;
}
public double projectWideScriptTimeout() {
return or(toDoubleOrNull(getProjectVar("!Script Timeout")), defaultScriptTimeout());
}
public G22Analyzer getAnalyzer(long id) {
var a = getConcept(concepts, G22Analyzer.class, id);
if (a == null)
throw fail("Analyzer not found: " + id);
return a;
}
public G22LeftArrowScript getScript(long id) {
var a = getConcept(concepts, G22LeftArrowScript.class, id);
if (a == null)
throw fail("Script not found: " + id);
return a;
}
public Object callScript(long id) {
var script = getScript(id);
return script.evaluateWithoutTimeout();
}
public Object callAutoRunnableScript(long id) {
var script = getScript(id);
return script.evaluateAutoRunWithoutTimeout();
}
public double defaultTimeout() {
return infinity();
}
public A evalRegisteredCode(String processName, IF0 code) {
return evalRegisteredCode(defaultTimeout(), processName, code);
}
public A evalRegisteredCode(double timeoutSeconds, String processName, IF0 code) {
if (code == null)
return null;
return evalWithTimeoutOrTypedException(timeoutSeconds, () -> useThisThreadAsBackgroundProcess(processName, code));
}
public Thread startAsRegisteredThread(Runnable r) {
return startAsRegisteredThread(str_shorten(r), r);
}
public Thread startAsRegisteredThread(String processName, Runnable r) {
if (r == null)
return null;
return startThread(processName, () -> useThisThreadAsBackgroundProcess(processName, toIF0(r)));
}
public A useThisThreadAsBackgroundProcess(String processName, IF0 code) {
AutoCloseable __9 = enter();
try {
var process = backgroundProcessesUI.tempAdd(processName);
try {
Thread myThread = currentThread();
process.setInterruptAction(new Runnable() {
public void run() {
try {
cancelThread(myThread);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "cancelThread(myThread)";
}
});
return code.get();
} finally {
_close(process);
}
} finally {
_close(__9);
}
}
public Object host() {
AutoCloseable __10 = enter();
try {
return dm_os();
} finally {
_close(__10);
}
}
public A timeFunction(String name, IF0 f) {
return functionTimings.get(name, f);
}
public boolean isConceptsDir(File dir) {
return isSameFile(conceptsDir(concepts), dir);
}
synchronized public FileWatchService fileWatcher() {
{
if (fileWatcher == null)
fileWatcher = new FileWatchService();
return fileWatcher;
}
}
synchronized public G22Utils onProjectFileChanged(IVF1 listener) {
super.onProjectFileChanged(listener);
if (!projectFileListenerInitiated) {
projectFileListenerInitiated = true;
fileWatcher().addRecursiveListener(dbDir(), __11 -> projectFileChanged(__11));
}
return this;
}
public G22ProjectInfo projectInfo_cache;
public G22ProjectInfo projectInfo() {
if (projectInfo_cache == null)
projectInfo_cache = projectInfo_load();
return projectInfo_cache;
}
public G22ProjectInfo projectInfo_load() {
return optimizedUniq(concepts, G22ProjectInfo.class);
}
public RunnablesReferenceQueue runnablesReferenceQueue() {
return masterStuff.runnablesReferenceQueue();
}
public EphemeralObjectIDs ephemeralObjectIDs() {
return masterStuff.ephemeralObjectIDs();
}
public Object eph(long id) {
return ephemeralObjectIDs().get(id);
}
public void openInBrowser(String url) {
main.openPlatformBrowser(url);
}
public String compilationDate() {
return or2(compilationDateFromClassPath(this), "unknown");
}
public String projectID() {
return projectInfo().projectID();
}
public IG22LoadedDB getLoadedDB() {
return masterStuff.getLoadedDB(concepts);
}
public ConceptsComboBox galleryImagesComboBox() {
return swing(() -> new ConceptsComboBox(concepts, G22GalleryImage.class));
}
public IBackgroundProcess tempAddBackgroundProcess(String name) {
return backgroundProcessesUI == null ? null : backgroundProcessesUI.tempAdd(name);
}
public IF1 classFinder() {
var master = masterStuff.makeClassFinder();
return name -> {
{
var __8 = projectWideClassDefs().get(dropPrefix("main$", name));
if (__8 != null)
return __8;
}
return master.get(name);
};
}
public Object restructure(Object o) {
return unstructure(structure(o), false, concepts.classFinder);
}
public G22ProjectActions project() {
return projectActions();
}
public boolean openPathInProject(String path) {
return projectActions().openPathInProject(path);
}
final public void showUIURL(String url) {
openUIURL(url);
}
final public void goToURIURL(String url) {
openUIURL(url);
}
public void openUIURL(String url) {
projectActions().openUIURL(url);
}
public BufferedImage loadProjectImage(String fileName) {
return loadImage2(projectFile(fileName));
}
public IG22LoadedDB openDB(String name) {
return openDB(name, false);
}
public IG22LoadedDB openDB(String name, boolean hidden) {
return masterStuff().openDB(name, hidden);
}
public G22Utils getProject(String name) {
return openDB(name, true).g22utils();
}
public G22Utils getProjectIfExists(String name) {
return !masterStuff().projectExists(name) ? null : getProject(name);
}
public G22Utils getProjectIfOpen(String name) {
var db = first(openProjects(), p -> eqic(p.g22utils().projectName(), name));
return db == null ? null : db.g22utils();
}
final public G22JavaObjectVisualizer visualizeJavaObject(Object o) {
return visualizeObject(o);
}
public G22JavaObjectVisualizer visualizeObject(Object o) {
return new G22JavaObjectVisualizer(this, o);
}
final public G22JavaObjectVisualizer visualizeJavaObjectWithoutType(Object o) {
return visualizeObjectWithoutType(o);
}
public G22JavaObjectVisualizer visualizeObjectWithoutType(Object o) {
return visualizeObject(o).withTypeAndTime(false);
}
transient public IF0 makeVariablesPanel;
public G22VariablesPanel makeVariablesPanel() {
return makeVariablesPanel != null ? makeVariablesPanel.get() : makeVariablesPanel_base();
}
final public G22VariablesPanel makeVariablesPanel_fallback(IF0 _f) {
return _f != null ? _f.get() : makeVariablesPanel_base();
}
public G22VariablesPanel makeVariablesPanel_base() {
return new G22VariablesPanel().g22utils(this);
}
transient public IF0 jGazelleLogo;
public JComponent jGazelleLogo() {
return jGazelleLogo != null ? jGazelleLogo.get() : jGazelleLogo_base();
}
final public JComponent jGazelleLogo_fallback(IF0 _f) {
return _f != null ? _f.get() : jGazelleLogo_base();
}
public JComponent jGazelleLogo_base() {
return main.jGazelleLogo();
}
public boolean devMode() {
return masterStuff().devMode();
}
public List list(Class type) {
return list(type, concepts());
}
public List list(Class type, Concepts cc) {
return main.list(cc, type);
}
public List list(Concepts concepts, Class type) {
return main.list(type, concepts);
}
public G22GalleryImage galleryImageForMD5(String md5) {
return firstThat(list(concepts, G22GalleryImage.class), img -> cic(fileName(img.path), md5));
}
public JComponent wrapImageSurface(ImageSurface is) {
return is == null ? null : jscroll_centered_borderless(is);
}
public JComponent wrap(Object o) {
var c = main.wrap(o);
if (c instanceof ImageSurface)
return wrapImageSurface((ImageSurface) c);
return c;
}
transient public IF0 byUser;
public String byUser() {
return byUser != null ? byUser.get() : byUser_base();
}
final public String byUser_fallback(IF0 _f) {
return _f != null ? _f.get() : byUser_base();
}
public String byUser_base() {
return "";
}
final public Collection extends IG22LoadedDB> openProjects() {
return getLoadedDBs();
}
public Collection extends IG22LoadedDB> getLoadedDBs() {
return masterStuff().openProjects();
}
public List listInOpenProjects(Class type) {
return concatMap(openProjects(), db -> db.g22utils().list(type));
}
transient public PicturesByMD5 picturesByMD5_cache;
public PicturesByMD5 picturesByMD5() {
if (picturesByMD5_cache == null)
picturesByMD5_cache = picturesByMD5_load();
return picturesByMD5_cache;
}
public PicturesByMD5 picturesByMD5_load() {
return new PicturesByMD5(projectFile("Images")).extension(".qoi");
}
public JButton reloadButton(String toolTip, Runnable action) {
return jimageButton("#1101440", toolTip, action);
}
public void registerConcept(Concept c) {
main.registerConcept(concepts, c);
}
public void registerConcept(Concepts cc, Concept c) {
main.registerConcept(cc, c);
}
public void addingAdditionalAutoCompletes(LeftArrowScriptAutoCompleter autoCompleter) {
String token = autoCompleter.prevToken();
if (isIdentifier(token) && contains(token, "ProjectVar"))
autoCompleter.addToSearcher(quoteAll(projectVarNames()));
autoCompleter.addToSearcher(keys(projectWideClassDefs()));
}
public boolean addLibrary(String library) {
if (!main.addLibrary(library))
return false;
print("Loaded library: " + library);
masterStuff().newClassesDefined();
return true;
}
public boolean addLibrary(File library) {
if (!main.addLibrary(library))
return false;
print("Loaded library: " + library);
masterStuff().newClassesDefined();
return true;
}
public WrappedCloseable addResource(A resource) {
if (resource == null)
return null;
autoClosingResources.add(resource);
return new WrappedCloseable (resource) {
@Override
public void beforeClose() {
autoClosingResources.remove(resource);
}
};
}
public Object callFunctionFromScript(int scriptID, String functionName, Object... args) {
return callFunctionFromScript((long) scriptID, functionName, args);
}
public Object callLatestFunctionFromScript(int scriptID, String functionName, Object... args) {
var function = getScript(scriptID).latestCompileResult().get().getFunction(functionName);
return function.callFromOutside(args);
}
public Object callSavedFunctionFromScript(int scriptID, String functionName, Object... args) {
var function = getScript(scriptID).compileSaved().get().getFunction(functionName);
return function.callFromOutside(args);
}
public Object callFunctionFromScript(long scriptID, String functionName, Object... args) {
var function = getScript(scriptID).safestCompileResult().get().getFunction(functionName);
return function.callFromOutside(args);
}
public Object callProjectFunction(String functionName, Object... args) {
var function = projectWideFunctionDefs.get(functionName);
if (function == null)
throw fail("Function " + functionName + " not found in project " + projectName());
return function.callFromOutside(args);
}
public JComponent visualizeAutoRunnableScript(long scriptID) {
return visualizeAutoRunnableScript(getScript(scriptID));
}
public JComponent visualizeAutoRunnableScript(G22LeftArrowScript script) {
if (script == null)
return null;
if (!script.isClearForAutoRun())
return jcenteredlabel("Script not clear for auto-run");
try {
Object result = script.evaluateAutoRunWithoutTimeout();
var objVisualizer = new G22JavaObjectVisualizer(this, result).withType(false);
return objVisualizer.visualize();
} catch (Throwable e) {
printStackTrace(e);
return jErrorView(e);
}
}
public void importProjectFromZip(File zipFile, String baseDirInZip, String projectName) {
File dir = dirOfProjectNamed(projectName);
if (isConceptsDir(dir)) {
if (eqic(projectName(), "Default")) {
infoMessage("Sorry dude");
return;
}
IG22LoadedDB defaultDB = masterStuff().getLoadedDBForConceptDir(dirOfProjectNamed("Default"));
IG22LoadedDB preloadedDefaultDB = defaultDB;
if (defaultDB == null)
defaultDB = openDB("Default");
project().closeProject();
defaultDB.g22utils().importProjectFromZip(zipFile, baseDirInZip, projectName);
if (preloadedDefaultDB == null)
defaultDB.projectActions().closeProject();
return;
}
if (!directoryIsEmpty(dir)) {
if (confirmProjectReplacements && !swingConfirm("Archive and overwrite existing project " + projectName + "?"))
return;
File archiveDir = javaxBackupDir("Gazelle/" + projectName + "-" + computerID() + "-" + ymdMinusHMS());
moveFile(dir, archiveDir);
infoMessage("Archived project to: " + archiveDir);
}
zip2dir(zipFile, empty(baseDirInZip) ? dir : dir.getParentFile());
infoBox("Imported project " + projectName);
masterStuff().openDB(projectName);
}
public void importProjectFromZip(File zipFile) {
String baseDir = baseDirInZip(zipFile);
String projectName = takeFirst(baseDir, smartIndexOf(baseDir, '/'));
if (empty(projectName)) {
{
inputText("Please enter name for imported project", name -> {
if (!validFileName(name)) {
infoBox("Invalid name, use simpler characters");
importProjectFromZip(zipFile);
return;
}
importProjectFromZip(zipFile, "", name);
});
return;
}
}
assertValidFileName(projectName);
importProjectFromZip(zipFile, baseDir, projectName);
}
public Class export(Class c) {
if (c != null) {
projectWideClassDefs.put(dropHashFromClassName(shortClassName(c)), c);
newFunctionsDefined();
}
return c;
}
final public GazelleV_LeftArrowScript.FunctionDef export(GazelleV_LeftArrowScript.FunctionDef def) {
return exportFunction(def);
}
public GazelleV_LeftArrowScript.FunctionDef exportFunction(GazelleV_LeftArrowScript.FunctionDef def) {
return def == null ? null : exportFunction(def.name, def);
}
final public GazelleV_LeftArrowScript.FunctionDef export(String name, GazelleV_LeftArrowScript.FunctionDef def) {
return exportFunction(name, def);
}
public GazelleV_LeftArrowScript.FunctionDef exportFunction(String name, GazelleV_LeftArrowScript.FunctionDef def) {
projectWideFunctionDefs.put(name, def);
newFunctionsDefined();
return def;
}
final public GazelleV_LeftArrowScript.FunctionDef unexport(String name) {
return unexportFunction(name);
}
public GazelleV_LeftArrowScript.FunctionDef unexportFunction(String name) {
GazelleV_LeftArrowScript.FunctionDef f = projectWideFunctionDefs.remove(name);
if (f != null) {
print("Undefined function " + name);
newFunctionsDefined();
}
return f;
}
public void newFunctionsDefined() {
masterStuff().newClassesDefined();
recompileDate = tsNow();
}
public boolean shouldRecompile(LASCompileResult cr) {
return recompileDate != null && cr.compilationStart() != null && cr.compilationStart().compareTo(recompileDate) < 0;
}
public boolean compileResultValid(LASCompileResult cr, String code) {
return cr != null && eq(cr.script, code) && !shouldRecompile(cr);
}
public String toString() {
return "G22Utils(" + quote(projectName()) + ")";
}
public void editScript(G22LeftArrowScript script) {
projectActions().editScript(script);
}
public JButton editButton(String toolTip, Runnable action) {
return jimageButtonScaledToWidth(16, "#1103068", toolTip, action);
}
public JButton editScriptButton(G22LeftArrowScript script) {
return editButton("Edit script", () -> projectActions().editScript(script));
}
public G22ScriptView scriptView(long scriptID) {
return new G22ScriptView(getScript(scriptID));
}
public File gazelleJar() {
return getBytecodePathForClass(this);
}
public List projectErrors() {
return projectActions().projectErrors();
}
public JComponent jErrorView(Throwable e) {
var view = main.jErrorView(e);
var scriptErrors = instancesOf(GazelleV_LeftArrowScript.ScriptError.class, allCausesIncludingSelf(e));
var sources = mapNotNulls(scriptErrors, __12 -> __12.tokenRangeWithSrc());
if (empty(sources))
return view;
sources = uniquifySources(sources);
return centerAndEastWithMargin(view, jline(map(sources, src -> jThreadedButton(str_shorten(src, 40), () -> projectActions().goToSource(src)))));
}
public List uniquifySources(List sources) {
return uniquifyWith(sources, src -> pair(src.sourceInfo, src.renderRange()));
}
public structure_Data makeStructureData() {
return concepts().makeStructureData();
}
public String g22struct(Object o) {
return struct(o, makeStructureData());
}
public Object g22unstruct(String struct) {
return unstructure(struct, classFinder());
}
public Object stem() {
return dm_stem(module());
}
public void reloadProject() {
masterStuff().reopenDB(getLoadedDB());
}
public File downloadProjectFromGazAI(GazAICredentials credentials, String projectName) {
try {
var cred = credentials.asParams();
var params = cloneMap(cred);
params.put("asZip", 1);
var url = "https://gaz.ai/dl-authed/gazelle/" + spaceToPercent20(projectName) + "/";
var conn = urlConnection(url);
var file = javaxBackupDir(concat(projectName + " Downloaded ", ymdMinusHMS(), ".zip"));
doPostBinaryToFile(makePostData(params), conn, file);
if (!isZip(file))
throw fail("Download failed, not authenticated for Gaz.AI?");
fileSavedInfoBox(file);
return file;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public void waitForAutoStart() {
autoStarter().waitUntilDone();
}
}
static public Set createOrAddToSyncLinkedHashSet(Set set, A a) {
if (set == null)
set = syncLinkedHashSet();
set.add(a);
return set;
}
static public void remove(List l, int i) {
if (l != null && i >= 0 && i < l(l))
l.remove(i);
}
static public void remove(Collection l, A a) {
if (l != null)
l.remove(a);
}
static public B remove(Map map, Object a) {
return map == null ? null : map.remove(a);
}
static public void remove(BitSet bs, int i) {
bs.clear(i);
}
static public A pcallF_typed(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
pcallFail(__e);
}
return null;
}
static public B pcallF_typed(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
pcallFail(__e);
}
return null;
}
static public void pcallF_typed(VF1 f, A a) {
try {
{
if (f != null)
f.get(a);
}
} catch (Throwable __e) {
pcallFail(__e);
}
}
static public void pcallF_typed(IVF1 f, A a) {
try {
{
if (f != null)
f.get(a);
}
} catch (Throwable __e) {
pcallFail(__e);
}
}
static public void pcallF_typed(IVF2 f, A a, B b) {
try {
{
if (f != null)
f.get(a, b);
}
} catch (Throwable __e) {
pcallFail(__e);
}
}
static public Object pcallF_typed(Runnable r) {
try {
{
if (r != null)
r.run();
}
} catch (Throwable __e) {
pcallFail(__e);
}
return null;
}
static public A pcallF_typed(IF0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
pcallFail(__e);
}
return null;
}
static public B pcallF_typed(IF1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
pcallFail(__e);
}
return null;
}
static public Concepts concepts(Concept c) {
return c == null ? null : c._concepts;
}
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 Set syncLinkedHashSet() {
return synchroLinkedHashSet();
}
static public ImageSurface imageSurface(BufferedImage img) {
return swingNu(ImageSurface.class, img);
}
static public ImageSurface imageSurface(MakesBufferedImage img) {
return swingNu(ImageSurface.class, img);
}
static public ImageSurface imageSurface() {
return swingNu(ImageSurface.class);
}
static public void imageSurface_pixelated(ImageSurface imageSurface) {
if (imageSurface == null)
return;
imageSurface.setDoubleBuffered(true);
imageSurface.noAlpha = true;
imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR;
repaint(imageSurface);
}
static public void imageSurface_pixelated(ImageSurface imageSurface, boolean pixelated) {
if (pixelated)
imageSurface_pixelated(imageSurface);
else
imageSurface_unpixelated(imageSurface);
}
static public File dbDir() {
return programDir(dbProgramID());
}
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(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(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(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) {
var it = l.iterator();
if (it.hasNext()) {
var pingSource = pingSource();
do {
ping(pingSource);
x.add(f.get(it.next()));
} while (it.hasNext());
}
}
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(Map map, IF2 f) {
List x = new ArrayList();
if (map != null)
for (Map.Entry e : map.entrySet()) {
ping();
x.add(f.get(e.getKey(), e.getValue()));
}
return x;
}
static public List map(IF1 f, A data1, A... moreData) {
List x = emptyList(l(moreData) + 1);
x.add(f.get(data1));
if (moreData != null)
for (A o : moreData) {
ping();
x.add(f.get(o));
}
return x;
}
static public List toBufferedImages(Iterable l) {
return allToBufferedImage(l);
}
static public BufferedImage toBufferedImage(Object o) {
return toBufferedImageOpt(o);
}
static public GazelleV_LeftArrowScript.Script leftArrowParse(String script) {
GazelleV_LeftArrowScriptParser parser = new GazelleV_LeftArrowScriptParser();
parser.allowTheWorld();
return parser.parse(script);
}
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(IMultiSet ms) {
return ms == null ? 0 : ms.size();
}
static public int l(IMultiMap mm) {
return mm == null ? 0 : mm.size();
}
static public int l(IntRange r) {
return r == null ? 0 : r.length();
}
static public int l(IntBuffer b) {
return b == null ? 0 : b.size();
}
static public int l(IntSize o) {
return o == null ? 0 : o.size();
}
static public A or(A a, A b) {
return a != null ? a : b;
}
static public Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class _getClass(Object o) {
return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
}
static public Class _getClass(Object realm, String name) {
try {
return classLoaderForObject(realm).loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
static volatile public StringBuffer local_log = new StringBuffer();
static public boolean printAlsoToSystemOut = true;
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);
if (printAlsoToSystemOut)
System.out.print(s);
vmBus_send("printed", mc(), s);
}
static public void print_autoRotate() {
}
static public A assertEquals(Object x, A y) {
return assertEquals("", x, y);
}
static public A assertEquals(String msg, Object x, A y) {
if (assertVerbose())
return assertEqualsVerbose(msg, x, y);
if (!(x == null ? y == null : x.equals(y)))
throw fail((msg != null ? msg + ": " : "") + y + " != " + x);
return y;
}
static public void assertEquals(Scorer scorer, Object x, Object y) {
assertEquals(scorer, "", x, y);
}
static public void assertEquals(Scorer scorer, String msg, Object x, Object y) {
if (scorer == null) {
assertEquals(msg, x, y);
return;
}
scorer.add(eq(x, y), nullIfEmpty(msg));
}
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 A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static public A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static public A assertNotNull(Scorer scorer, String msg, A a) {
if (scorer == null)
return assertNotNull(msg, a);
if (a == null) {
print("BAD - " + msg + " is null: " + a);
scorer.add(false);
} else {
print("OK, " + msg + " not null: " + a);
scorer.add(true);
}
return a;
}
static public File getBytecodePathForClass(Object o) {
return getBytecodePathForClass(_getClass(o));
}
static public File getBytecodePathForClass(Class c) {
try {
return c == null ? null : new File(c.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A assertNempty(A a) {
return assertNempty("", a);
}
static public A assertNempty(String msg, A a) {
if (empty(a))
throw fail(joinNemptiesWithColon(msg, str(a)));
return a;
}
static public A assertNempty(A a) {
return assertNempty("", a);
}
static public A assertNempty(String msg, A a) {
if (empty(a))
throw fail(joinNemptiesWithColon(msg, str(a)));
return a;
}
static public A assertNempty(A a) {
return assertNempty("", a);
}
static public A assertNempty(String msg, A a) {
if (empty(a))
throw fail(joinNemptiesWithColon(msg, str(a)));
return a;
}
static public File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static public File newFile(String name) {
return name == null ? null : new File(name);
}
static public File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static public boolean fileExists(String path) {
return path != null && new File(path).exists();
}
static public boolean fileExists(File f) {
return f != null && f.exists();
}
static public void createOrRemoveFile(File f, boolean create) {
if (create) {
if (!fileExists(f))
touchFile(f);
} else if (fileExists(f))
removeFile(f);
}
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 public boolean removeAll(Collection a, Collection b) {
return a != null && b != null && a.removeAll(b);
}
static public void removeAll(Map a, Collection b) {
if (a != null && b != null)
for (A x : b) a.remove(x);
}
static public boolean removeAll(Collection c, B... b) {
return c != null && b != null && c.removeAll(Arrays.asList(b));
}
static public void removeAll(Map a, A... b) {
if (a != null && b != null)
for (A x : b) a.remove(x);
}
static public void truncateList(List l, int n) {
if (l(l) <= n)
return;
removeSubList(l, n, l(l));
}
static public boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public boolean eq(Symbol a, String b) {
return eq(str(a), b);
}
static public File saveTextFile(String fileName, String contents) throws IOException {
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());
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
} finally {
_close(fileOutputStream);
}
}
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;
}
static public File saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
return fileName;
} catch (Exception __e) {
throw rethrow(__e);
}
}
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 List tlft(String s) {
return toLinesFullTrim(s);
}
static public List tlft(File f) {
return toLinesFullTrim(f);
}
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 dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
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(BitSet bs) {
return bs == null || bs.isEmpty();
}
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(IMultiMap mm) {
return mm == null || mm.size() == 0;
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public boolean empty(IntRange r) {
return r == null || r.empty();
}
static public boolean empty(IntBuffer b) {
return b == null || b.isEmpty();
}
static public boolean empty(Rect r) {
return !(r != null && r.w != 0 && r.h != 0);
}
static public boolean empty(Chain c) {
return c == null;
}
static public boolean empty(AppendableChain c) {
return c == null;
}
static public boolean empty(IntSize l) {
return l == null || l.size() == 0;
}
static public File conceptsDir() {
return conceptsDir(db_mainConcepts());
}
static public File conceptsDir(Concepts cc) {
return cc.conceptsDir();
}
static public File conceptsDir(String subName) {
return conceptsDir(db_mainConcepts(), subName);
}
static public File conceptsDir(Concepts cc, String subName) {
return newFile(conceptsDir(cc), subName);
}
static public boolean sameFile(File a, File b) {
try {
return a == null ? b == null : b != null && eq(a.getCanonicalPath(), b.getCanonicalPath());
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public File dirOfFile(File f) {
return f == null ? null : f.getParentFile();
}
static public String fileName(File f) {
return f == null ? null : f.getName();
}
static public List llNonNulls(A... a) {
List l = new ArrayList();
if (a != null)
for (A x : a) if (x != null)
l.add(x);
return l;
}
static public Component jMinHeight(Swingable c, int h) {
return jMinHeight(wrap(c), h);
}
static public Component jMinHeight(int h, Swingable c) {
return jMinHeight(wrap(c), h);
}
static public A jMinHeight(A c, int h) {
return jMinHeight(h, c);
}
static public A jMinHeight(int h, A c) {
Dimension size = c.getMinimumSize();
c.setMinimumSize(new Dimension(size.width, max(h, size.height)));
return jPreferHeight(h, c);
}
static public HashSet litset(A... items) {
return lithashset(items);
}
static public LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static public String or2_rev(String b, String a) {
return or2(a, b);
}
static public String joinNemptiesWithSpacedPlus(Object... strings) {
return joinNempties(" + ", strings);
}
static public String joinNemptiesWithSpacedPlus(Iterable strings) {
return joinNempties(" + ", strings);
}
static public String n2(long l) {
return formatWithThousands(l);
}
static public String n2(AtomicLong l) {
return n2(l.get());
}
static public String n2(Collection l) {
return n2(l(l));
}
static public String n2(Map map) {
return n2(l(map));
}
static public String n2_getPlural(String singular) {
return plural(singular);
}
static public String n2(double l, String singular) {
return empty(singular) ? str(l) : n2(l, singular, n2_getPlural(singular));
}
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 empty(singular) ? n2(l) : n_fancy2(l, singular, n2_getPlural(singular));
}
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) {
return n2(ms, singular, n2_getPlural(singular));
}
static public String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static public String n2(IMultiMap mm, String singular) {
return n2(mm, singular, n2_getPlural(singular));
}
static public String n2(IMultiMap mm, String singular, String plural) {
return n_fancy2(l(mm), singular, plural);
}
static public int intMax(Collection c, String field) {
int max = Integer.MIN_VALUE;
for (Object o : c) max = Math.max(max, toInt(getOpt(o, field)));
return max;
}
static public int intMax(Iterable l) {
int max = Integer.MIN_VALUE;
for (int i : unnullForIteration(l)) max = Math.max(max, i);
return max;
}
static public int intMax(int... l) {
int max = Integer.MIN_VALUE;
if (l != null)
for (int i : l) max = Math.max(max, i);
return max;
}
static public List mapLL(Object f, Object... data) {
return map(f, ll(data));
}
static public List mapLL(IF1 f, A... data) {
return map(f, ll(data));
}
static public int linesOfCode_javaTok(String text) {
List tok = javaTok(text);
int lines = 0;
boolean codeInCurrentLine = false;
for (int i = 0; i < l(tok); i++) {
String t = tok.get(i);
if (odd(i)) {
int lTok = l(t);
for (int j = 0; j < lTok; j++) {
char c = t.charAt(j);
if (c == '\n')
codeInCurrentLine = false;
else if (!isSpaceEtc(c) && !codeInCurrentLine) {
codeInCurrentLine = true;
++lines;
}
}
} else {
if (codeInCurrentLine && containsNewLine(t))
codeInCurrentLine = false;
}
}
return lines;
}
static public File appendToFileName(File f, String suffix) {
return fileAppendToName(f, suffix);
}
static public File appendToFileName(String suffix, File f) {
return appendToFileName(f, suffix);
}
static public String nLabels(long n) {
return n2(n, "label");
}
static public String nLabels(Collection l) {
return nLabels(l(l));
}
static public String nLabels(Map map) {
return nLabels(l(map));
}
static public String joinWithComma(Iterable c) {
return join(", ", c);
}
static public String joinWithComma(Object... 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 boolean containsNewLine(String s) {
return contains(s, '\n');
}
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 uniqCI(Class c, Object... params) {
return uniqueConcept(db_mainConcepts(), c, params);
}
static public A uniqCI(Concepts cc, Class c, Object... params) {
AutoCloseable __1 = tempDBLock(cc);
try {
params = expandParams(c, params);
A x = findConceptWhereCI(cc, c, params);
if (x == null) {
x = unlisted(c);
csetAll(x, params);
cc.register(x);
}
return x;
} finally {
_close(__1);
}
}
static public String shortClassName_dropNumberPrefix(Object o) {
return dropNumberPrefix(shortClassName(o));
}
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 File conceptsFile(String progID) {
return getProgramFile(progID, conceptsFileName());
}
static public File conceptsFile() {
return conceptsFile(dbProgramID());
}
static public File conceptsFile(Concepts concepts) {
return concepts.conceptsFile();
}
static public File conceptsFileIn(File dir) {
return newFile(dir, conceptsFileName());
}
static public List listDirsContainingFileNamed(File dir, String fileName) {
return filter(listDirs(dir), d -> isFile(newFile(d, fileName)));
}
static public IterableIterator mapI_pcall(final Object f, final Iterator i) {
return new IterableIterator() {
public boolean hasNext() {
return i.hasNext();
}
public Object next() {
return pcallF(f, i.next());
}
};
}
static public IterableIterator mapI_pcall(IterableIterator i, Object f) {
return mapI_pcall((Iterator) i, f);
}
static public IterableIterator mapI_pcall(Object f, IterableIterator i) {
return mapI_pcall((Iterator) i, f);
}
static public IterableIterator mapI_pcall(Iterator i, Object f) {
return mapI_pcall(f, i);
}
static public IterableIterator mapI_pcall(Iterable i, IF1 f) {
return mapI_pcall(i, (Object) f);
}
static public IterableIterator mapI_pcall(Iterable i, Object f) {
return mapI_pcall(f, i.iterator());
}
static public IterableIterator mapI_pcall(Object f, Iterable i) {
return mapI_pcall(i, f);
}
static public Concepts newConceptsWithClassFinder(String progID) {
Concepts cc = new Concepts(progID);
cc.classFinder = _defaultClassFinder();
return cc;
}
static public Concepts newConceptsWithClassFinder(File conceptsFile) {
Concepts cc = new Concepts(assertNotNull(conceptsFile));
cc.classFinder = _defaultClassFinder();
return cc;
}
static public Concepts newConceptsWithClassFinder(File conceptsFile, IF1 classFinder) {
Concepts cc = new Concepts(assertNotNull(conceptsFile));
cc.classFinder = classFinder;
return cc;
}
static public void closeAndClear(Collection extends AutoCloseable> l) {
closeAllAndClear(l);
}
static public boolean cleanUp_interruptThreads = false;
static public void cleanUp(Object c) {
if (c == null)
return;
if (c instanceof AutoCloseable) {
close_pcall((AutoCloseable) c);
return;
}
if (c instanceof java.util.Timer) {
((java.util.Timer) c).cancel();
return;
}
if (c instanceof Collection) {
cleanUp((Collection) c);
return;
}
if (c instanceof Map) {
for (Object o : keysList((Map) c)) cleanUp(o);
for (Object o : valuesList((Map) c)) cleanUp(o);
syncClear((Map) c);
return;
}
try {
preCleanUp(c);
setOpt_raw(c, "ping_pauseAll", false);
innerCleanUp(c);
List androids = (List) getOpt(c, "record_list");
for (Object android : unnull(androids)) pcallOpt(android, "dispose");
List classes = (List) (getOpt(c, "hotwire_classes"));
if (classes != null)
for (WeakReference cc : classes) {
try {
cleanUp(cc.get());
} catch (Throwable __e) {
pcallFail(__e);
}
}
if (cleanUp_interruptThreads) {
List threads = registeredThreads(c);
if (nempty(threads)) {
print("cleanUp: Interrupting " + n2(threads, "thread") + ": " + joinWithComma(allToString(threads)));
interruptThreads(threads);
}
}
} catch (Throwable __e) {
pcallFail(__e);
}
setOpt_raw(c, "cleaningUp_flag", false);
if (c instanceof Class && ((Class) c).getName().equals("main"))
retireClassLoader(((Class) c).getClassLoader());
}
static public void cleanUp(Collection l) {
if (l == null)
return;
for (Object c : l) cleanUp(c);
l.clear();
}
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 void close(AutoCloseable c) {
_close(c);
}
static public A conceptWhereCI(Class c, Object... params) {
return findConceptWhereCI(c, params);
}
static public Concept conceptWhereCI(String c, Object... params) {
return findConceptWhereCI(db_mainConcepts(), c, params);
}
static public A conceptWhereCI(Concepts concepts, Class c, Object... params) {
return findConceptWhereCI(concepts, c, params);
}
static public Concept conceptWhereCI(Concepts concepts, String c, Object... params) {
return findConceptWhereCI(concepts, c, params);
}
static public List collect(Iterable c, String field) {
return collectField(c, field);
}
static public List collect(String field, Iterable c) {
return collectField(c, field);
}
static public List list(Class type) {
return list(type, db_mainConcepts());
}
static public List list(Class type, Concepts cc) {
return cc.list(type);
}
static public List list(Concepts concepts, Class type) {
return concepts.list(type);
}
static public List list(String type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, String type) {
return concepts.list(type);
}
static public List list(Concepts concepts) {
return asList(concepts.allConcepts());
}
static public List nonNulls(Iterable l) {
return withoutNulls(l);
}
static public List nonNulls(A[] l) {
return withoutNulls(l);
}
static public Map nonNulls(Map map) {
return withoutNulls(map);
}
static public List nonNulls(Iterable l, IF1 f) {
return mapNonNulls(l, f);
}
static public A optimizedUniqCI(Class c, Object... params) {
return optimizedUniqCI(db_mainConcepts(), c, params);
}
static public A optimizedUniqCI(Concepts cc, Class c, Object... params) {
{
var __1 = conceptWhereCI(cc, c, params);
if (__1 != null)
return __1;
}
return uniqCI(cc, c, params);
}
static public double infinity() {
return positiveInfinity();
}
static public A waitForCalculatedValueUsingChangeListener(IF0 f, IHasChangeListeners sender) {
return waitForCalculatedValueUsingChangeListener(infinity(), f, sender);
}
static public A waitForCalculatedValueUsingChangeListener(double timeout, IF0 f, IHasChangeListeners sender) {
BoolVar trigger = new BoolVar();
AutoCloseable __2 = tempOnChange(sender, () -> trigger.set(true));
try {
while (true) {
ping();
{
var __1 = f.get();
if (__1 != null)
return __1;
}
trigger.waitUntilTrueAndClear(timeout);
}
} finally {
_close(__2);
}
}
static public void deleteConcept(long id) {
db_mainConcepts().deleteConcept(id);
}
static public void deleteConcept(Concepts concepts, long id) {
concepts.deleteConcept(id);
}
static public void deleteConcept(Concept c) {
if (c != null)
c.delete();
}
static public void deleteConcept(Concept.Ref ref) {
if (ref != null)
deleteConcept(ref.get());
}
static public Collection conceptsWhere(Class c, Object... params) {
return findConceptsWhere(c, params);
}
static public Collection conceptsWhere(String c, Object... params) {
return findConceptsWhere(c, params);
}
static public Collection conceptsWhere(Concepts concepts, Class c, Object... params) {
return findConceptsWhere(concepts, c, params);
}
static public Double toDoubleOrNull(Object o) {
if (o == null)
return null;
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o instanceof String)
return parseDouble((String) o);
return null;
}
static public Concept getConcept(long id) {
return db_mainConcepts().getConcept(id);
}
static public Concept getConcept(Concepts concepts, long id) {
return concepts.getConcept(id);
}
static public A getConcept(Class cc, long id) {
return getConcept(db_mainConcepts(), cc, id);
}
static public A getConcept(Concepts concepts, Class cc, long id) {
Concept c = concepts.getConcept(id);
if (c == null)
return null;
if (!isInstance(cc, c))
throw fail("Can't convert concept: " + getClassName(c) + " -> " + getClassName(cc) + " (" + id + ")");
return (A) c;
}
static public A evalWithTimeoutOrTypedException(int timeoutMS, IF0 f) {
return evalWithTimeoutOrTypedException(toSeconds(timeoutMS), f);
}
static public A evalWithTimeoutOrTypedException(double timeoutSeconds, IF0 f) {
Either e = evalWithTimeout(timeoutSeconds, f);
if (e.isA())
return (A) e.a();
throw new TimeoutException_Inner(timeoutSeconds, f, e.b());
}
static public String str_shorten(Object o) {
return shorten_str(o);
}
static public String str_shorten(Object o, int max) {
return shorten_str(o, max);
}
static public String str_shorten(int max, Object o) {
return shorten_str(max, o);
}
static public Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static public Thread startThread(String name, Runnable runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(runnable, name));
}
static public Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
static public Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static public IF0 toIF0(final Object f) {
if (f == null)
return null;
if (f instanceof IF0)
return ((IF0) f);
if (f instanceof Runnable)
return () -> {
((Runnable) f).run();
return null;
};
if (isString(f))
return mainFunctionToIF0((String) f);
return (IF0) () -> callF(f);
}
static public Thread currentThread() {
return Thread.currentThread();
}
static public void cancelThread(Thread t) {
if (t == null)
return;
ping();
synchronized (ping_actions) {
ping_actions.put(t, "cancelled");
ping_anyActions = true;
}
}
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 Object dm_os() {
{
var __1 = vm_generalMap_get("stefansOS");
if (__1 != null)
return __1;
}
return creator();
}
static public boolean isSameFile(File a, File b) {
return sameFile(a, b);
}
static public A optimizedUniq(Class c, Object... params) {
return optimizedUniq(db_mainConcepts(), c, params);
}
static public A optimizedUniq(Concepts cc, Class c, Object... params) {
{
var __1 = conceptWhere(cc, c, params);
if (__1 != null)
return __1;
}
return uniq(cc, c, params);
}
static public IVF1 openPlatformBrowser;
static public void openPlatformBrowser(String url) {
if (openPlatformBrowser != null)
openPlatformBrowser.get(url);
else
openPlatformBrowser_base(url);
}
final static public void openPlatformBrowser_fallback(IVF1 _f, String url) {
if (_f != null)
_f.get(url);
else
openPlatformBrowser_base(url);
}
static public void openPlatformBrowser_base(String url) {
try {
if (isHeadless())
return;
print("Opening platform-specific browser on: " + url);
Desktop.getDesktop().browse(uri(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void openPlatformBrowser(URL url) {
if (url == null)
return;
openPlatformBrowser(str(url));
}
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 compilationDateFromClassPath(Object referenceObject) {
return loadTextFileResource(classLoader(referenceObject), "compilation-date.txt");
}
static public Object swing(Object f) {
return swingAndWait(f);
}
static public void swing(Runnable f) {
swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public Object unstructure(String text) {
return unstructure(text, false);
}
static public Object unstructure(String text, boolean allDynamic) {
return unstructure(text, allDynamic, null);
}
static public Object unstructure(String text, IF1 classFinder) {
return unstructure(text, false, classFinder);
}
static public int structure_internStringsLongerThan = 50;
static public int unstructure_unquoteBufSize = 100;
static public int unstructure_tokrefs;
abstract static public class unstructure_Receiver {
abstract public void set(Object o);
}
static public Object unstructure(String text, boolean allDynamic, Object classFinder) {
if (text == null)
return null;
return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder);
}
static public Object unstructure_reader(BufferedReader reader) {
return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null);
}
public interface unstructure_Handler {
public void parse(int refID, int tokIndex, unstructure_Receiver out);
}
static public class Unstructurer {
final public Unstructurer setTok(Producer tok) {
return tok(tok);
}
public Unstructurer tok(Producer tok) {
this.tok = tok;
return this;
}
final public Producer getTok() {
return tok();
}
public Producer tok() {
return tok;
}
public Producer tok;
final public Unstructurer setAllDynamic(boolean allDynamic) {
return allDynamic(allDynamic);
}
public Unstructurer allDynamic(boolean allDynamic) {
this.allDynamic = allDynamic;
return this;
}
final public boolean getAllDynamic() {
return allDynamic();
}
public boolean allDynamic() {
return allDynamic;
}
public boolean allDynamic = false;
public int i = -1;
public Object classFinder;
public String mcDollar = actualMCDollar();
public Unstructurer classFinder(Object _classFinder) {
classFinder = _classFinder != null ? _classFinder : _defaultClassFinder();
return this;
}
public HashMap refs = new HashMap();
public HashMap tokrefs = new HashMap();
public HashSet concepts = new HashSet();
public List stack = new ArrayList();
public Map baseClassMap = new HashMap();
public HashMap innerClassConstructors = new HashMap();
public String curT;
public char[] unquoteBuf = new char[unstructure_unquoteBufSize];
final public HashMap handlers = new HashMap();
public Unstructurer() {
try {
Class mc = (Class) (callF(classFinder, ""));
if (mc != null)
mcDollar = mc.getName() + "$";
} catch (Throwable __e) {
pcallFail(__e);
}
makeHandlers();
}
public void makeHandlers() {
unstructure_Handler h;
handlers.put("bigint", (unstructure_Handler) (refID, tokIndex, out) -> out.set(parseBigInt()));
handlers.put("d", (unstructure_Handler) (refID, tokIndex, out) -> out.set(parseDouble()));
handlers.put("fl", (unstructure_Handler) (refID, tokIndex, out) -> out.set(parseFloat()));
handlers.put("sh", (unstructure_Handler) (refID, tokIndex, out) -> {
consume();
String t = tpp();
if (t.equals("-")) {
t = tpp();
out.set((short) (-parseInt(t)));
return;
}
out.set((short) parseInt(t));
});
handlers.put("enum", (unstructure_Handler) (refID, tokIndex, out) -> {
consume();
String t = tpp();
assertTrue(isJavaIdentifier(t));
String fullClassName = mcDollar + t;
Class _c = findAClass(fullClassName);
if (_c == null)
throw fail("Enum class not found: " + fullClassName);
int ordinal = parseInt(tpp());
out.set(_c.getEnumConstants()[ordinal]);
});
handlers.put("false", h = (unstructure_Handler) (refID, tokIndex, out) -> {
consume();
out.set(false);
});
handlers.put("f", h);
handlers.put("true", h = (unstructure_Handler) (refID, tokIndex, out) -> {
consume();
out.set(true);
});
handlers.put("t", h);
handlers.put("{", (unstructure_Handler) (refID, tokIndex, out) -> parseMap(out));
handlers.put("[", (unstructure_Handler) (refID, tokIndex, out) -> {
ArrayList l = new ArrayList();
if (refID >= 0)
refs.put(refID, l);
this.parseList(l, out);
});
handlers.put("bitset", (unstructure_Handler) (refID, tokIndex, out) -> parseBitSet(out));
handlers.put("array", h = (unstructure_Handler) (refID, tokIndex, out) -> parseArray(out));
handlers.put("intarray", h);
handlers.put("dblarray", h);
handlers.put("floatarray", h);
handlers.put("shortarray", (unstructure_Handler) (refID, tokIndex, out) -> {
consume();
String hex = trivialUnquote(tpp());
out.set(shortArrayFromBytes(hexToBytes(hex)));
});
handlers.put("longarray", (unstructure_Handler) (refID, tokIndex, out) -> {
consume();
String hex = trivialUnquote(tpp());
out.set(longArrayFromBytes(hexToBytes(hex)));
});
}
public Class findAClass(String fullClassName) {
try {
return classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName);
} catch (Throwable __e) {
return null;
}
}
public String unquote(String s) {
return unquoteUsingCharArray(s, unquoteBuf);
}
public String t() {
return curT;
}
public String tpp() {
String t = curT;
consume();
return t;
}
public void parse(final unstructure_Receiver out) {
String t = t();
int refID;
if (structure_isMarker(t, 0, l(t))) {
refID = parseInt(t.substring(1));
consume();
} else
refID = -1;
final int tokIndex = i;
parse_inner(refID, tokIndex, new unstructure_Receiver() {
public void set(Object o) {
if (refID >= 0)
refs.put(refID, o);
if (o != null)
tokrefs.put(tokIndex, o);
out.set(o);
}
});
}
public void parse_inner(int refID, int tokIndex, unstructure_Receiver out) {
String t = t();
Object handler = handlers.get(t);
if (handler instanceof unstructure_Handler) {
((unstructure_Handler) handler).parse(refID, tokIndex, out);
return;
}
Class c = (Class) handler;
if (c == null) {
if (t.startsWith("\"")) {
String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan);
out.set(s);
return;
}
if (t.startsWith("'")) {
out.set(unquoteCharacter(tpp()));
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("-")) {
consume();
t = tpp();
out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)));
return;
}
if (isInteger(t) || isLongConstant(t)) {
consume();
if (isLongConstant(t)) {
out.set(parseLong(t));
return;
}
long l = parseLong(t);
boolean isInt = l == (int) l;
out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l));
return;
}
if (t.equals("File")) {
consume();
File f = new File(unquote(tpp()));
out.set(f);
return;
}
if (t.startsWith("r") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = refs.get(ref);
if (o == null)
warn("unsatisfied back reference " + ref);
out.set(o);
return;
}
if (t.startsWith("t") && isInteger(t.substring(1))) {
consume();
int ref = Integer.parseInt(t.substring(1));
Object o = tokrefs.get(ref);
if (o == null)
warn("unsatisfied token reference " + ref + " at " + tokIndex);
out.set(o);
return;
}
if (t.equals("hashset")) {
parseHashSet(out);
return;
}
if (t.equals("lhs")) {
parseLinkedHashSet(out);
return;
}
if (t.equals("treeset")) {
parseTreeSet(out);
return;
}
if (t.equals("ciset")) {
parseCISet(out);
return;
}
if (eqOneOf(t, "hashmap", "hm")) {
consume();
parseMap(new HashMap(), out);
return;
}
if (t.equals("lhm")) {
consume();
parseMap(new LinkedHashMap(), out);
return;
}
if (t.equals("tm")) {
consume();
parseMap(new TreeMap(), out);
return;
}
if (t.equals("cimap")) {
consume();
parseMap(ciMap(), out);
return;
}
if (t.equals("ll")) {
consume();
LinkedList l = new LinkedList();
if (refID >= 0)
refs.put(refID, l);
{
parseList(l, out);
return;
}
}
if (t.equals("syncLL")) {
consume();
{
parseList(synchroLinkedList(), out);
return;
}
}
if (t.equals("sync")) {
consume();
{
parse(new unstructure_Receiver() {
public void set(Object value) {
if (value instanceof Map) {
if (value instanceof NavigableMap) {
out.set(synchroNavigableMap((NavigableMap) value));
return;
}
if (value instanceof SortedMap) {
out.set(synchroSortedMap((SortedMap) value));
return;
}
{
out.set(synchroMap((Map) value));
return;
}
} else {
out.set(synchroList((List) value));
return;
}
}
});
return;
}
}
if (t.equals("ba")) {
consume();
String hex = trivialUnquote(tpp());
out.set(hexToBytes(hex));
return;
}
if (t.equals("boolarray")) {
consume();
int n = parseInt(tpp());
String hex = trivialUnquote(tpp());
out.set(boolArrayFromBytes(hexToBytes(hex), n));
return;
}
if (t.equals("class")) {
out.set(parseClass());
return;
}
if (t.equals("l")) {
parseLisp(out);
return;
}
if (t.equals("null")) {
consume();
out.set(null);
return;
}
if (eq(t, "c")) {
consume();
t = t();
assertTrue(isJavaIdentifier(t));
concepts.add(t);
}
if (eq(t, "cu")) {
consume();
t = tpp();
assertTrue(isJavaIdentifier(t));
String fullClassName = mcDollar + t;
Class _c = findAClass(fullClassName);
if (_c == null)
throw fail("Class not found: " + fullClassName);
parse(new unstructure_Receiver() {
public void set(Object value) {
out.set(call(_c, "_deserialize", value));
}
});
return;
}
}
if (eq(t, "j")) {
consume();
out.set(parseJava());
return;
}
if (eq(t, "bc")) {
consume();
String c1 = tpp();
String c2 = tpp();
baseClassMap.put(c1, c2);
{
parse_inner(refID, i, out);
return;
}
}
if (c == null && !isJavaIdentifier(t))
throw new RuntimeException("Unknown token " + (i + 1) + ": " + quote(t));
consume();
String className, fullClassName;
if (eq(t(), ".")) {
className = t;
do {
consume();
className += "." + assertIdentifier(tpp());
} while (eq(t(), "."));
fullClassName = className;
} else {
className = t;
fullClassName = mcDollar + t;
}
if (c == null && !allDynamic) {
c = findAClass(fullClassName);
handlers.put(className, c);
}
if (c == null && !allDynamic) {
Set seen = new HashSet();
String parent = className;
while (true) {
String baseName = baseClassMap.get(parent);
if (baseName == null)
break;
if (!seen.add(baseName))
throw fail("Cyclic superclass info: " + baseName);
c = findAClass(mcDollar + baseName);
if (c == null)
print("Base class " + baseName + " of " + parent + " doesn't exist either");
else if (isAbstract(c))
print("Can't instantiate abstract base class: " + c);
else {
printVars_str("Reverting to base class", "className", className, "baseName", baseName, "c", c);
handlers.put(className, c);
break;
}
parent = baseName;
}
}
boolean hasBracket = eq(t(), "(");
if (hasBracket)
consume();
boolean hasOuter = hasBracket && startsWith(t(), "this$");
DynamicObject dO = null;
Object o = null;
final String thingName = t;
try {
if (c != null) {
if (hasOuter)
try {
Constructor ctor = innerClassConstructors.get(c);
if (ctor == null)
innerClassConstructors.put(c, ctor = nuStubInnerObject_findConstructor(c, classFinder));
o = ctor.newInstance(new Object[] { null });
} catch (Exception e) {
print("Error deserializing " + c + ": " + e);
o = nuEmptyObject(c);
}
else
o = nuEmptyObject(c);
if (o instanceof DynamicObject)
dO = (DynamicObject) o;
} else {
if (concepts.contains(t) && (c = findAClass(mcDollar + "Concept")) != null)
o = dO = (DynamicObject) nuEmptyObject(c);
else
dO = new DynamicObject();
dO.className = className;
}
} catch (Throwable __e) {
pcallFail(__e);
}
if (o == null && dO == null)
dO = new DynamicObject();
if (refID >= 0)
refs.put(refID, o != null ? o : dO);
tokrefs.put(tokIndex, o != null ? o : dO);
HashMap fields = new HashMap();
Object _o = o;
DynamicObject _dO = dO;
if (hasBracket) {
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), ","))
consume();
if (eq(t(), ")")) {
consume(")");
objRead(_o, _dO, fields, hasOuter);
out.set(_o != null ? _o : _dO);
} else {
final String key = unquote(tpp());
String t = tpp();
if (!eq(t, "="))
throw fail("= expected, got " + t + " after " + quote(key) + " in object " + thingName);
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object value) {
fields.put(key, value);
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef unstructure_debug\r\n print(\"in object values, token: \" + t());\r...";
}
});
} else {
objRead(o, dO, fields, hasOuter);
out.set(o != null ? o : dO);
}
}
public void objRead(Object o, DynamicObject dO, Map fields, boolean hasOuter) {
Object outer = fields.get("this$0");
if (outer != null)
fields.put("this$1", outer);
else {
outer = fields.get("this$1");
if (outer != null)
fields.put("this$0", outer);
}
if (o != null) {
if (dO != null) {
setOptAllDyn_pcall(dO, fields);
} else {
setOptAll_pcall(o, fields);
}
if (hasOuter)
fixOuterRefs(o);
} else
for (Map.Entry e : fields.entrySet()) setDynObjectValue(dO, intern(e.getKey()), e.getValue());
if (o != null)
pcallOpt_noArgs(o, "_doneLoading");
}
public void parseSet(final Set set, final unstructure_Receiver out) {
this.parseList(new ArrayList(), new unstructure_Receiver() {
public void set(Object o) {
set.addAll((List) o);
out.set(set);
}
});
}
public void parseLisp(final unstructure_Receiver out) {
throw fail("class Lisp not included");
}
public void parseBitSet(final unstructure_Receiver out) {
consume("bitset");
consume("{");
final BitSet bs = new BitSet();
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "}")) {
consume("}");
out.set(bs);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
bs.set((Integer) o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n } els...";
}
});
}
public void parseList(final List list, final unstructure_Receiver out) {
tokrefs.put(i, list);
consume("[");
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "]")) {
consume();
out.set(list);
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
list.add(o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"]\")) {\r\n consume();\r\n ifdef unstructure_debug\r\n ...";
}
});
}
public void parseArray(unstructure_Receiver out) {
String _type = tpp();
int dims;
if (eq(t(), "S")) {
_type = "S";
consume();
}
if (eq(t(), "/")) {
consume();
dims = parseInt(tpp());
} else
dims = 1;
consume("{");
List list = new ArrayList();
String type = _type;
stack.add(new Runnable() {
public void run() {
try {
if (eq(t(), "}")) {
consume("}");
if (dims > 1) {
Class atype;
if (type.equals("intarray"))
atype = int.class;
else if (type.equals("S"))
atype = String.class;
else
throw todo("multi-dimensional arrays of other types");
out.set(list.toArray((Object[]) newMultiDimensionalOuterArray(atype, dims, l(list))));
} else
out.set(type.equals("intarray") ? toIntArray(list) : type.equals("dblarray") ? toDoubleArray(list) : type.equals("floatarray") ? toFloatArray(list) : type.equals("S") ? toStringArray(list) : list.toArray());
} else {
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
list.add(o);
if (eq(t(), ","))
consume();
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n if (dims > 1) {\r\n ...";
}
});
}
public Object parseClass() {
consume("class");
consume("(");
String name = unquote(tpp());
consume(")");
Class c = allDynamic ? null : findAClass(name);
if (c != null)
return c;
DynamicObject dO = new DynamicObject();
dO.className = "java.lang.Class";
name = dropPrefix(mcDollar, name);
dynamicObject_setRawFieldValue(dO, "name", name);
return dO;
}
public Object parseBigInt() {
consume("bigint");
consume("(");
String val = tpp();
if (eq(val, "-"))
val = "-" + tpp();
consume(")");
return new BigInteger(val);
}
public Object parseDouble() {
consume("d");
consume("(");
String val = unquote(tpp());
consume(")");
return Double.parseDouble(val);
}
public Object parseFloat() {
consume("fl");
String val;
if (eq(t(), "(")) {
consume("(");
val = unquote(tpp());
consume(")");
} else {
val = unquote(tpp());
}
return Float.parseFloat(val);
}
public void parseHashSet(unstructure_Receiver out) {
consume("hashset");
parseSet(new HashSet(), out);
}
public void parseLinkedHashSet(unstructure_Receiver out) {
consume("lhs");
parseSet(new LinkedHashSet(), out);
}
public void parseTreeSet(unstructure_Receiver out) {
consume("treeset");
parseSet(new TreeSet(), out);
}
public void parseCISet(unstructure_Receiver out) {
consume("ciset");
parseSet(ciSet(), out);
}
public void parseMap(unstructure_Receiver out) {
parseMap(new TreeMap(), out);
}
public Object parseJava() {
String j = unquote(tpp());
Matches m = new Matches();
if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m))
return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2)));
else {
warn("Unknown Java object: " + j);
return null;
}
}
public void parseMap(final Map map, final unstructure_Receiver out) {
consume("{");
stack.add(new Runnable() {
public boolean v = false;
public Object key;
public void run() {
if (v) {
v = false;
stack.add(this);
if (!eq(tpp(), "="))
throw fail("= expected, got " + t() + " in map of size " + l(map));
parse(new unstructure_Receiver() {
public void set(Object value) {
map.put(key, value);
if (eq(t(), ","))
consume();
}
});
} else {
if (eq(t(), "}")) {
consume("}");
out.set(map);
} else {
v = true;
stack.add(this);
parse(new unstructure_Receiver() {
public void set(Object o) {
key = o;
}
});
}
}
}
});
}
public void consume() {
curT = tok.next();
++i;
}
public void consume(String s) {
if (!eq(t(), s)) {
throw fail(quote(s) + " expected, got " + quote(t()));
}
consume();
}
public void parse_initial(unstructure_Receiver out) {
consume();
parse(out);
while (nempty(stack)) popLast(stack).run();
}
}
static public Object unstructure_tok(Producer tok, boolean allDynamic, Object classFinder) {
boolean debug = unstructure_debug;
AutoCloseable __1 = tempSetTL(dynamicObjectIsLoading_threadLocal(), true);
try {
Var v = new Var();
var unstructurer = new Unstructurer().tok(tok).allDynamic(allDynamic).classFinder(classFinder);
unstructurer.parse_initial(new unstructure_Receiver() {
public void set(Object o) {
v.set(o);
}
});
unstructure_tokrefs = unstructurer.tokrefs.size();
return v.get();
} finally {
_close(__1);
}
}
static public boolean unstructure_debug = false;
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 String shortName;
public List fields;
public Method customSerializer;
public IVF1 serializeObject;
public boolean special = false;
public boolean nullInstances = false;
public boolean javafy = false;
public Object emptyInstance;
public String toString() {
return commaCombine("Class " + className(c), stringIf("special", special), stringIf("customSerializer", customSerializer != null), stringIf("javafy", javafy), stringIf("nullInstances", nullInstances));
}
public void nullInstances(boolean b) {
this.nullInstances = b;
if (b)
special = true;
}
public void javafy(boolean b) {
this.javafy = b;
if (b)
special = true;
}
public boolean handle(A o) {
return 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 boolean honorFieldOrder = true;
public String mcDollar = actualMCDollar();
final public structure_Data setWarnIfUnpersistable(boolean warnIfUnpersistable) {
return warnIfUnpersistable(warnIfUnpersistable);
}
public structure_Data warnIfUnpersistable(boolean warnIfUnpersistable) {
this.warnIfUnpersistable = warnIfUnpersistable;
return this;
}
final public boolean getWarnIfUnpersistable() {
return warnIfUnpersistable();
}
public boolean warnIfUnpersistable() {
return warnIfUnpersistable;
}
public boolean warnIfUnpersistable = true;
final public structure_Data setStackTraceIfUnpersistable(boolean stackTraceIfUnpersistable) {
return stackTraceIfUnpersistable(stackTraceIfUnpersistable);
}
public structure_Data stackTraceIfUnpersistable(boolean stackTraceIfUnpersistable) {
this.stackTraceIfUnpersistable = stackTraceIfUnpersistable;
return this;
}
final public boolean getStackTraceIfUnpersistable() {
return stackTraceIfUnpersistable();
}
public boolean stackTraceIfUnpersistable() {
return stackTraceIfUnpersistable;
}
public boolean stackTraceIfUnpersistable = true;
final public structure_Data setSkipDefaultValues(boolean skipDefaultValues) {
return skipDefaultValues(skipDefaultValues);
}
public structure_Data skipDefaultValues(boolean skipDefaultValues) {
this.skipDefaultValues = skipDefaultValues;
return this;
}
final public boolean getSkipDefaultValues() {
return skipDefaultValues();
}
public boolean skipDefaultValues() {
return skipDefaultValues;
}
public boolean skipDefaultValues = false;
public structure_Data d() {
return this;
}
transient public IF1 shouldIncludeField;
public boolean shouldIncludeField(Field f) {
return shouldIncludeField != null ? shouldIncludeField.get(f) : shouldIncludeField_base(f);
}
final public boolean shouldIncludeField_fallback(IF1 _f, Field f) {
return _f != null ? _f.get(f) : shouldIncludeField_base(f);
}
public boolean shouldIncludeField_base(Field f) {
return true;
}
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_Data app(char c) {
out.print(c);
return this;
}
public structure_ClassInfo infoForClass(Class c) {
structure_ClassInfo info = infoByClass.get(c);
if (info == null)
info = newClass(c);
return info;
}
transient public IF1 realShortName;
public String realShortName(String name) {
return realShortName != null ? realShortName.get(name) : realShortName_base(name);
}
final public String realShortName_fallback(IF1 _f, String name) {
return _f != null ? _f.get(name) : realShortName_base(name);
}
public String realShortName_base(String name) {
return dropPrefix("main$", dropPrefix("loadableUtils.utils$", dropPrefix(mcDollar, name)));
}
public structure_ClassInfo newClass(Class c) {
var d = d();
boolean isJavaXClass = isJavaXClassName(c.getName(), mcDollar);
if (c == String.class)
return new structure_ClassInfo() {
@Override
public boolean handle(String o) {
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 true;
}
};
if (c == File.class)
return new structure_ClassInfo() {
@Override
public boolean handle(File o) {
append("File ").append(quote(o.getPath()));
return true;
}
};
if (!isJavaXClass) {
if (isSubClassOf(c, Set.class))
return new structure_ClassInfo() {
@Override
public boolean handle(Set o) {
writeSet(o);
return true;
}
};
if (isSubClassOf(c, Collection.class))
return new structure_ClassInfo() {
@Override
public boolean handle(Collection o) {
writeCollection(o);
return true;
}
};
if (isSubClassOf(c, Map.class))
return new structure_ClassInfo() {
@Override
public boolean handle(Map o) {
writeMap(o);
return true;
}
};
}
structure_ClassInfo info = new structure_ClassInfo();
info.c = c;
infoByClass.put(c, info);
String name = c.getName();
String shortName = realShortName(name);
if (startsWithDigit(shortName))
shortName = name;
info.shortName = shortName;
try {
if (isSyntheticOrAnonymous(c)) {
info.nullInstances(true);
return info;
}
if (c.isEnum()) {
info.special = true;
return info;
}
if (c.isArray()) {
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);
}
}
if (eqOneOf(name, "java.awt.Color", "java.lang.ThreadLocal"))
info.javafy(true);
else if (name.startsWith("sun") || !isPersistableClass(c)) {
info.javafy(true);
if (warnIfUnpersistable) {
String msg = "Class not persistable: " + c + " (anonymous or no default constructor), referenced from " + last(stack);
if (stackTraceIfUnpersistable)
printStackTrace(new Throwable(msg));
else
print(msg);
}
} else if (skipDefaultValues) {
var ctor = getDefaultConstructor(c);
if (ctor != null)
info.emptyInstance = invokeConstructor(ctor);
}
} catch (Throwable e) {
printStackTrace(e);
info.nullInstances(true);
}
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();
class WritingObject implements Runnable {
public String lastFieldWritten;
public void run() {
try {
if (!it.hasNext()) {
if (n != l)
append(")");
} else {
Map.Entry e = (Map.Entry) (it.next());
append(n == l ? "(" : ", ");
append(lastFieldWritten = (String) e.getKey()).append("=");
stack.add(this);
structure_1(e.getValue(), structure_Data.this);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return shortName + "." + lastFieldWritten;
}
}
stack.add(new WritingObject());
}
public void writeMap(Map o) {
var d = this;
String name = o.getClass().getName();
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();
class WritingMap implements Runnable {
public boolean v = false;
public Map.Entry e;
public String toString() {
return renderVars("WritingMap", "e", mapEntryToPair(e), "v", !v);
}
public void run() {
try {
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);
}
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
}
d.stack.add(new WritingMap());
}
public void writeSet(Set o) {
var d = this;
String name = o.getClass().getName();
if (o instanceof TreeSet) {
d.append(isCISet_gen(o) ? "ciset" : "treeset");
structure_1(new ArrayList(o), d);
return;
}
d.append(o instanceof LinkedHashSet ? "lhs" : "hashset");
structure_1(new ArrayList(o), d);
}
public void writeCollection(Collection o) {
var d = this;
String name = o.getClass().getName();
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("[");
int l = d.n;
Iterator it = cloneList(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.stack.add...";
}
});
}
}
static public void structure_1(Object o, 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);
boolean isJavaXName = isJavaXClassName(c.getName(), d.mcDollar);
boolean referencable = isJavaXName && !(o instanceof Number || o instanceof Character || o instanceof Boolean) || o instanceof Collection || o instanceof Map;
if (referencable) {
Integer ref = d.seen.get(o);
if (ref != null) {
d.append("t").app(ref);
return;
}
d.seen.put(o, d.n);
}
if (info.handle(o)) {
return;
}
if (info.special) {
if (info.javafy) {
d.append("j ").append(quote(str(o)));
return;
}
if (c.isEnum()) {
d.append("enum ");
d.append(info.shortName);
d.out.append(' ');
d.append(((Enum) o).ordinal());
return;
}
if (info.customSerializer != null) {
Object o2 = invokeMethod(info.customSerializer, o);
if (o2 == o) {
} else {
d.append("cu ");
String name = c.getName();
String shortName = d.realShortName(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");
}
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;
}
String name = c.getName();
if (!isJavaXName) {
if (o instanceof Set) {
d.writeSet((Set) o);
return;
}
if (o instanceof Collection) {
{
d.writeCollection((Collection) o);
return;
}
}
if (o instanceof Map) {
d.writeMap((Map) o);
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;
}
if (o instanceof short[]) {
String hex = shortArrayToHex_bigEndian((short[]) o);
d.append("shortarray \"").append(hex).app('\"');
return;
}
if (o instanceof long[]) {
String hex = longArrayToHex_bigEndian((long[]) o);
d.append("longarray \"").append(hex).app('\"');
return;
}
String atype = "array";
if (o instanceof int[]) {
atype = "intarray";
} else if (o instanceof double[]) {
atype = "dblarray";
} else if (o instanceof float[]) {
atype = "floatarray";
} 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 == float.class)
atype = "floatarray";
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;
}
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)) {
if (!d.shouldIncludeField(field))
continue;
String fieldName = field.getName();
if (fieldName.equals("_persistenceInfo"))
d.persistenceInfo.put(c, obj -> (Map) fieldGet(field, obj));
if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
continue;
fields.add(field);
}
cc = cc.getSuperclass();
}
Method persistenceInfoMethod = findInstanceMethod(c, "_persistenceInfo");
if (persistenceInfoMethod != null)
d.persistenceInfo.put(c, obj -> (Map) invokeMethod(persistenceInfoMethod, obj));
lFields = asList(d.honorFieldOrder ? fieldObjectsInFieldOrder(c, fields) : 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);
}
IF1 piGetter = d.persistenceInfo.get(c);
Map persistenceInfo = piGetter == null ? null : piGetter.get(o);
if (piGetter == null && o instanceof DynamicObject)
persistenceInfo = (Map) getOptDynOnly(((DynamicObject) o), "_persistenceInfo");
LinkedHashMap fv = new LinkedHashMap();
Object defaultInstance = info.emptyInstance;
if (!referencable)
throw fail("Not referencable: " + className(o));
for (Field f : lFields) {
Object value, defaultValue = null;
try {
value = f.get(o);
defaultValue = defaultInstance == null ? null : f.get(defaultInstance);
} catch (Exception e) {
value = "?";
}
if (!eq(defaultValue, value) && (persistenceInfo == null || !Boolean.FALSE.equals(persistenceInfo.get(f.getName()))))
fv.put(f.getName(), value);
}
String shortName = info.shortName;
Object classNameFromFV = fv.get("className");
if (concept && eq(classNameFromFV, shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
putAll(fv, (Map) fv.get("fieldValues"));
fv.remove("fieldValues");
if (((DynamicObject) o).className != null) {
shortName = shortDynClassNameForStructure((DynamicObject) o);
fv.remove("className");
if (eq(shortName, "java.lang.Class")) {
d.append("class(");
d.append(quoted(fv.get("name")));
d.append(")");
return;
}
}
}
d.writeObject(o, shortName, fv);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public BufferedImage loadImage2(String snippetIDOrURL) {
return loadBufferedImage(snippetIDOrURL);
}
static public BufferedImage loadImage2(File file) {
return loadBufferedImage(file);
}
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 Pair first(Map map) {
return mapEntryToPair(first(entrySet(map)));
}
static public Pair first(MultiMap mm) {
if (mm == null)
return null;
var e = first(mm.data.entrySet());
if (e == null)
return null;
return pair(e.getKey(), first(e.getValue()));
}
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 Double first(double[] l) {
return empty(l) ? null : l[0];
}
static public int first(IntBuffer buf) {
return buf.get(0);
}
static public A first(A[] l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(Iterable l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(IF1 pred, Iterable l) {
return firstThat(pred, l);
}
static public A first(AppendableChain a) {
return a == null ? null : a.element;
}
static public A first(IMultiSet a) {
return a == null ? null : first(a.keySet());
}
static public boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(Symbol a, Symbol b) {
return eq(a, b);
}
static public boolean eqic(Symbol a, String b) {
return eqic(asString(a), b);
}
static public boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static public JComponent jGazelleLogo() {
return setOpaqueBackground(Color.white, jimage(gazelleLogoImageID()));
}
static public A firstThat(Iterable l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(A[] l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static public A firstThat(IF1 pred, A[] l) {
return firstThat(l, pred);
}
static public boolean cic(Collection l, String s) {
return containsIgnoreCase(l, s);
}
static public boolean cic(Collection l, Symbol s) {
return contains(l, s);
}
static public boolean cic(String[] l, String s) {
return containsIgnoreCase(l, s);
}
static public boolean cic(String s, char c) {
return containsIgnoreCase(s, c);
}
static public boolean cic(String a, String b) {
return containsIgnoreCase(a, b);
}
static public JScrollPane jscroll_centered_borderless(Component c) {
return borderlessScrollPane(jscroll_centered(c));
}
static public JComponent wrap(Object swingable) {
return _recordNewSwingComponent(wrap_2(swingable));
}
static public JComponent wrap_2(Object swingable) {
if (swingable == null)
return null;
JComponent c;
if (swingable instanceof Component)
c = componentToJComponent((Component) swingable);
else if (swingable instanceof Swingable)
c = componentToJComponent(((Swingable) swingable).visualize());
else
c = componentToJComponent((Component) callOpt(swingable, "swing"));
if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
return jscroll(c);
return c == null ? jlabel(str(swingable)) : c;
}
static public List concatMap(Object f, Iterable l) {
return concatLists(map(f, l));
}
static public List concatMap(Iterable l, Object f) {
return concatMap(f, l);
}
static public List concatMap(Object f, Object[] l) {
return concatLists(map(f, l));
}
static public List concatMap(Object[] l, Object f) {
return concatMap(f, l);
}
static public > List concatMap(Iterable l, IF1 f) {
return concatMap(l, (Object) f);
}
static public > List concatMap(IF1 f, Iterable l) {
return concatMap(l, f);
}
static public > List concatMap(IF1 f, A[] l) {
return concatMap((Object) f, l);
}
static public JButton jimageButton(String imageID, Object action) {
JButton btn = jbutton("", action);
btn.setIcon(imageIcon(imageID));
return btn;
}
static public JButton jimageButton(String imageID) {
return jimageButton(imageID, null);
}
static public JButton jimageButton(Image img) {
return jimageButton(img, null, null);
}
static public JButton jimageButton(String imageID, String toolTip, Runnable action) {
return jimageButton(imageIcon(imageID), toolTip, action);
}
static public JButton jimageButton(Image img, String toolTip, Runnable action) {
var btn = jbutton("", action);
setButtonImage(btn, img);
return setToolTip(toolTip, btn);
}
static public JButton jimageButton(ImageIcon img, String toolTip, Runnable action) {
var btn = jbutton("", action);
setButtonImage(btn, img);
return setToolTip(toolTip, btn);
}
static public A registerConcept(A c) {
return registerConcept(db_mainConcepts(), c);
}
static public A registerConcept(Concepts cc, A c) {
{
if (cc != null)
cc.register(c);
}
return c;
}
static public boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static public boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static public boolean contains(Iterable it, Object a) {
if (it != null)
for (Object o : it) if (eq(a, o))
return true;
return false;
}
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 boolean contains(Rect r, Pt p) {
return rectContains(r, p);
}
static public List quoteAll(String[] l) {
return quoteAll(asList(l));
}
static public List quoteAll(Collection l) {
List x = new ArrayList();
for (String s : l) x.add(quote(s));
return x;
}
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(IMultiMap mm) {
return mm.keySet();
}
static public boolean addLibrary(String libID) {
return addLibraryToCurrentProgram(libID);
}
static public boolean addLibrary(File f) {
return addLibraryToCurrentProgram(f);
}
static public JLabel jcenteredlabel(String text) {
return jcenteredLabel(text);
}
static public JLabel jcenteredlabel() {
return jcenteredLabel();
}
static public A printStackTrace(A e) {
if (e != null)
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 JComponent jErrorView(Throwable e) {
return jSmallErrorView(e);
}
static public boolean infoMessage_alwaysOnTop = true;
static public double infoMessage_defaultTime = 5.0;
static public JWindow infoMessage(String text) {
return infoMessage(text, infoMessage_defaultTime);
}
static public JWindow infoMessage(final String text, final double seconds) {
printHidingCredentials(text);
return infoMessage_noprint(text, seconds);
}
static public JWindow infoMessage_noprint(String text) {
return infoMessage_noprint(text, infoMessage_defaultTime);
}
static public JWindow infoMessage_noprint(final String _text, final double seconds) {
final String text = hideCredentials(_text);
if (empty(text))
return null;
logQuotedWithDate(infoBoxesLogFile(), text);
if (isHeadless())
return null;
return (JWindow) swingAndWait(new F0() {
public Object get() {
try {
JWindow window = makeWindow(infoMessage_makePanel(text));
window.setSize(300, 150);
moveToTopRightCorner(window);
if (infoMessage_alwaysOnTop)
window.setAlwaysOnTop(true);
if (vmBus_noObjections("shouldShowInfoBox", window, text))
window.setVisible(true);
if (seconds != 0)
disposeWindowAfter(iround(seconds * 1000), window);
return window;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JWindow window = makeWindow(infoMessage_makePanel(text));\r\n window.setSize...";
}
});
}
static public JWindow infoMessage(Throwable e) {
printStackTrace(e);
return infoMessage(exceptionToStringShort(e));
}
static public boolean directoryIsEmpty(File f) {
return !fileExists(f) || isDirectory(f) && empty(listFiles(f));
}
static public boolean swingConfirm(Component owner, String msg) {
return confirmOKCancel(owner, msg);
}
static public boolean swingConfirm(String msg) {
return confirmOKCancel(msg);
}
static public File javaxBackupDir_dir;
static public File javaxBackupDir() {
return javaxBackupDir_dir != null ? javaxBackupDir_dir : new File(userHome(), "JavaX-Backup");
}
static public File javaxBackupDir(String sub) {
return newFile(javaxBackupDir(), sub);
}
static public String _computerID;
static public Lock computerID_lock = lock();
public static String computerID() {
if (_computerID == null) {
Lock __0 = computerID_lock;
lock(__0);
try {
if (_computerID != null)
return _computerID;
File file = computerIDFile();
_computerID = loadTextFile(file.getPath());
if (_computerID == null) {
_computerID = loadTextFile(userDir(".tinybrain/computer-id"));
if (_computerID == null)
_computerID = makeRandomID(12, new SecureRandom());
saveTextFile(file, _computerID);
}
} finally {
unlock(__0);
}
}
return _computerID;
}
static public String ymdMinusHMS() {
return ymdMinusHMS(now());
}
static public String ymdMinusHMS(long now) {
return ymd_minus_hms(now);
}
static public void moveFile(File a, File b) {
if (!renameFile(a, b))
throw fail("File move failed: " + a + " to " + b);
}
static public void zip2dir(File inZip, String outDir) {
zip2dir(inZip, newFile(outDir));
}
static public void zip2dir(File inZip, File outDir) {
zip2dir(inZip, outDir, "");
}
static public void zip2dir(File inZip, String outDir, String prefix) {
zip2dir(inZip, newFile(outDir), prefix);
}
static public void zip2dir(File inZip, File outDir, String prefix) {
try {
if (prefix.length() != 0 && !prefix.endsWith("/"))
prefix += "/";
ZipFile zipFile = new ZipFile(inZip);
try {
Enumeration entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.isDirectory())
continue;
if (!entry.getName().startsWith(prefix))
continue;
File outFile = new File(outDir, entry.getName());
print("Unzipping " + entry.getName() + " to " + outFile.getAbsolutePath());
stream2file(zipFile.getInputStream(entry), outFile);
}
} finally {
_close(zipFile);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public JWindow infoBox(Object text) {
return infoMessage(strOrNull(text));
}
static public JWindow infoBox(String text) {
return infoMessage(text);
}
static public JWindow infoBox(String text, double seconds) {
return infoMessage(text, seconds);
}
static public JWindow infoBox(Throwable e) {
return infoMessage(e);
}
static public String baseDirInZip(File zip) {
String prefix = commonPrefix(listZip(zip));
return takeFirst(prefix, indexOf(prefix, '/'));
}
static public List takeFirst(List l, int n) {
return l(l) <= n ? l : newSubListOrSame(l, 0, n);
}
static public List takeFirst(int n, List l) {
return takeFirst(l, n);
}
static public String takeFirst(int n, String s) {
return substring(s, 0, n);
}
static public String takeFirst(String s, int n) {
return substring(s, 0, n);
}
static public CharSequence takeFirst(int n, CharSequence s) {
return subCharSequence(s, 0, n);
}
static public List takeFirst(int n, Iterator it) {
if (it == null)
return null;
List l = new ArrayList();
for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) {
if (it.hasNext())
l.add(it.next());
else
break;
}
return l;
}
static public List takeFirst(int n, Iterable i) {
if (i == null)
return null;
return i == null ? null : takeFirst(n, i.iterator());
}
static public List takeFirst(int n, IterableIterator i) {
return takeFirst(n, (Iterator ) i);
}
static public int[] takeFirst(int n, int[] a) {
return takeFirstOfIntArray(n, a);
}
static public short[] takeFirst(int n, short[] a) {
return takeFirstOfShortArray(n, a);
}
static public byte[] takeFirst(int n, byte[] a) {
return takeFirstOfByteArray(n, a);
}
static public byte[] takeFirst(byte[] a, int n) {
return takeFirstOfByteArray(n, a);
}
static public double[] takeFirst(int n, double[] a) {
return takeFirstOfDoubleArray(n, a);
}
static public double[] takeFirst(double[] a, int n) {
return takeFirstOfDoubleArray(n, a);
}
static public Map takeFirst(int n, Map map) {
return takeFirstFromMap(n, map);
}
static public int smartIndexOf(String s, String sub, int i) {
if (s == null)
return 0;
i = s.indexOf(sub, min(i, l(s)));
return i >= 0 ? i : l(s);
}
static public int smartIndexOf(String s, int i, char c) {
return smartIndexOf(s, c, i);
}
static public int smartIndexOf(String s, char c, int i) {
if (s == null)
return 0;
i = s.indexOf(c, min(i, l(s)));
return i >= 0 ? i : l(s);
}
static public int smartIndexOf(String s, String sub) {
return smartIndexOf(s, sub, 0);
}
static public int smartIndexOf(String s, char c) {
return smartIndexOf(s, c, 0);
}
static public int smartIndexOf(List l, A sub) {
return smartIndexOf(l, sub, 0);
}
static public int smartIndexOf(List l, int start, A sub) {
return smartIndexOf(l, sub, start);
}
static public int smartIndexOf(List l, A sub, int start) {
int i = indexOf(l, sub, start);
return i < 0 ? l(l) : i;
}
static public void inputText(String msg, String defaultText, IVF1 action) {
inputText(msg, defaultText, (Object) action);
}
static public void inputText(String msg, IVF1 action) {
inputText(msg, (Object) action);
}
static public void inputText(String msg, Object action) {
inputText(msg, "", action);
}
static public void inputText(String msg, String defaultText, Object action) {
final Object threadInfo = _threadInfo();
swingLater(new Runnable() {
public void run() {
try {
final JTextField tf = jtextfield(defaultText);
String title = joinNemptiesWithVBar(msg, programNameOrNull());
JComponent form = showFormTitled(title, unnull(msg), tf, new Runnable() {
public void run() {
try {
vmBus_send("inputtingText_OK", threadInfo, msg, tf);
callF_thread(action, getTextTrim(tf));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "vmBus_send(\"inputtingText_OK\", threadInfo, msg, tf);\r\n callF_thread(ac...";
}
});
renameSubmitButton(form, "OK");
vmBus_send("inputtingText", threadInfo, msg, tf);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JTextField tf = jtextfield(defaultText);\r\n String title = joinNempti...";
}
});
}
static public boolean validFileName(String s) {
return isValidFileName(s);
}
static public String assertValidFileName(String s) {
if (!isValidFileName(s))
throw fail("Not a valid file name: " + quote(s));
return s;
}
static public String dropHashFromClassName(String className) {
return regexpReplace(className, "_[0-9a-f]{32}$", "");
}
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 Timestamp tsNow() {
return new Timestamp();
}
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 JButton jimageButtonScaledToWidth(int w, String imageID, Runnable action) {
return jimageButtonScaledToWidth(w, imageID, "", action);
}
static public JButton jimageButtonScaledToWidth(int w, String imageID, String toolTip, Runnable action) {
return jimageButton(scaleImageToWidth(w, imageID), toolTip, action);
}
static public List instancesOf(Iterable i, Class c) {
return collectInstances(i, c);
}
static public List instancesOf(Class c, Iterable i) {
return collectInstances(c, i);
}
static public List allCausesIncludingSelf(Throwable t) {
List out = new ArrayList();
while (t != null) {
out.add(t);
t = t.getCause();
}
return out;
}
static public List mapNotNulls(Iterable l, Object f) {
return mapNonNulls(l, f);
}
static public List mapNotNulls(Object f, Object[] l) {
return mapNonNulls(f, l);
}
static public List mapNotNulls(Object f, Iterable l) {
return mapNonNulls(f, l);
}
static public List mapNotNulls(Iterable l, F1 f) {
return mapNonNulls(l, f);
}
static public List mapNotNulls(IF1 f, Iterable l) {
return mapNonNulls(f, l);
}
static public List mapNotNulls(Iterable l, IF1 f) {
return mapNonNulls(l, f);
}
static public List mapNotNulls(F1 f, Iterable l) {
return mapNonNulls(f, l);
}
static public JPanel centerAndEastWithMargin(Swingable c, Swingable e) {
return centerAndEastWithMargin(c, toComponent(e));
}
static public JPanel centerAndEastWithMargin(Swingable c, Component e) {
return centerAndEastWithMargin(toComponent(c), e);
}
static public JPanel centerAndEastWithMargin(Component c, Swingable e) {
return centerAndEastWithMargin(c, toComponent(e));
}
static public JPanel centerAndEastWithMargin(Component c, Component e) {
return centerAndEastWithMarginInbetween(c, e);
}
static public JPanel jline(final Component... components) {
return swing(() -> {
return new LeftAlignedLine(components);
});
}
static public JPanel jline(List components) {
return jline(asArray(Component.class, components));
}
static public JButton jThreadedButton(String text, Object action) {
return swing(new F0() {
public JButton get() {
try {
String text2 = dropPrefix("[disabled] ", text);
JButton btn = basicJButton(text2);
if (l(text2) < l(text))
btn.setEnabled(false);
btn.setToolTipText(btn.getText());
if (action != null)
btn.addActionListener(actionListenerInNewThread(action, btn));
return btn;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S text2 = dropPrefix(\"[disabled] \", text);\r\n JButton btn = basicJButton(te...";
}
});
}
static public JButton jThreadedButton(String text, Runnable action) {
return jThreadedButton(text, (Object) action);
}
static public List uniquifyWith(IF1 f, Collection l) {
return uniquifyBy(f, l);
}
static public List uniquifyWith(Collection l, IF1 f) {
return uniquifyBy(l, f);
}
static public String struct(Object o) {
return structure(o);
}
static public String struct(Object o, structure_Data data) {
return structure(o, data);
}
static public Object dm_stem() {
return dm_stem(dm_current_generic());
}
static public Object dm_stem(Object moduleOrID) {
return dm_getStem(moduleOrID);
}
static public Map cloneMap(Map map) {
if (map == null)
return new HashMap();
synchronized (map) {
return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map);
}
}
static public List cloneMap(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : cloneList(l)) x.add(f.get(o));
return x;
}
static public String spaceToPercent20(String s) {
return replace(s, " ", "%20");
}
static public URLConnection urlConnection(String url) {
return openConnection(url);
}
static public URLConnection urlConnection(URL url) {
return openConnection(url);
}
static public String concat(Object... l) {
return concatStrings(l);
}
static public String concat(Iterable l) {
return concatStrings(l);
}
static public void doPostBinaryToFile(Map urlParameters, String url, File file) {
doPostBinaryToFile(makePostData(urlParameters), url, file);
}
static public void doPostBinaryToFile(String urlParameters, String url, File file) {
try {
URL _url = new URL(url);
ping();
doPostBinaryToFile(urlParameters, _url.openConnection(), file);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void doPostBinaryToFile(String urlParameters, URLConnection conn, File file) throws IOException {
setHeaders(conn);
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
try {
loadBinaryPageToFile_noHeaders(conn, file);
} finally {
writer.close();
}
}
static public String makePostData(Map map) {
StringBuilder buf = new StringBuilder();
for (Map.Entry e : castMapToMapO(map).entrySet()) {
String key = (String) (e.getKey());
Object val = e.getValue();
if (val != null) {
String value = str(val);
if (nempty(buf))
buf.append("&");
buf.append(urlencode(key)).append("=").append(urlencode((value)));
}
}
return str(buf);
}
static public String makePostData(Object... params) {
StringBuilder buf = new StringBuilder();
int n = l(params);
for (int i = 0; i + 1 < n; i += 2) {
String key = (String) (params[i]);
Object val = params[i + 1];
if (val != null) {
String value = str(val);
if (nempty(buf))
buf.append("&");
buf.append(urlencode(key)).append("=").append(urlencode((value)));
}
}
return str(buf);
}
static public boolean isZip(byte[] data) {
return isJAR(data);
}
static public boolean isZip(File f) {
return isJAR(f);
}
static public void fileSavedInfoBox(File f) {
infoBox("Saved " + fileInfo(f));
}
static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public void pcallFail(Throwable e) {
pcallPolicyForThread().handlePcallFail(e);
}
static public void pcallFail(String msg) {
pcallFail(new Throwable(msg));
}
static public LinkedHashMap cloneLinkedHashMap(Map map) {
return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
}
static public Map synchroHashMap() {
return synchronizedMap(new HashMap());
}
static public Map synchronizedMap() {
return synchroMap();
}
static public Map synchronizedMap(Map map) {
return synchroMap(map);
}
static public Set synchroLinkedHashSet() {
return synchronizedSet(new CompactLinkedHashSet());
}
static public A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static public A repaint(A c) {
if (c != null)
c.repaint();
return c;
}
static public void imageSurface_unpixelated(ImageSurface imageSurface) {
if (imageSurface == null)
return;
imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_BILINEAR;
repaint(imageSurface);
}
static public File programDir_mine;
static public File programDir() {
return programDir(getProgramID());
}
static public File programDir(String snippetID) {
boolean me = sameSnippetID(snippetID, programID());
if (programDir_mine != null && me)
return programDir_mine;
File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
if (me) {
String c = caseID();
if (nempty(c))
dir = newFile(dir, c);
}
return dir;
}
static public File programDir(String snippetID, String subPath) {
return new File(programDir(snippetID), subPath);
}
static public String dbProgramID() {
return getDBProgramID();
}
static public ArrayList emptyList() {
return new ArrayList();
}
static public ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
static public ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static public ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
static public ArrayList emptyList(Class c) {
return new ArrayList();
}
static volatile public boolean ping_pauseAll = false;
static public int ping_sleep = 100;
static volatile public boolean ping_anyActions = false;
static public Map ping_actions = newWeakHashMap();
static public ThreadLocal ping_isCleanUpThread = new ThreadLocal();
static public boolean ping(PingSource pingSource) {
return ping();
}
static public boolean ping() {
newPing();
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty())
ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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 B callF(A a, IF1 f) {
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 void callF(A a, IVF1 f) {
if (f != null)
f.get(a);
}
static public void callF(IVF1 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) {
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) {
if (f instanceof String)
throw fail("Legacy call: " + f);
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 ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(char[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (var i : a) l.add(i);
return l;
}
static public ArrayList asList(byte[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (var i : a) l.add(i);
return l;
}
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(short[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (short 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 ArrayList asList(ReverseChain c) {
return c == null ? emptyList() : c.toList();
}
static public List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
static public PingSource pingSource() {
return pingSource_tl().get();
}
static public PingSource pingSource(Thread thread) {
return pingSource_tl().get(thread);
}
static public List allToBufferedImage(Iterable l) {
return map(__40 -> toBufferedImage(__40), l);
}
static public BufferedImage toBufferedImageOpt(Object o) {
if (o instanceof BufferedImage)
return ((BufferedImage) o);
if (o instanceof Image)
return copyImage((Image) o);
if (o instanceof MakesBufferedImage)
return ((MakesBufferedImage) o).getBufferedImage();
String c = getClassName(o);
if (eqOneOf(c, "main$BWImage", "main$RGBImage"))
return (BufferedImage) call(o, "getBufferedImage");
return null;
}
static public int iteratorCount_int_close(Iterator i) {
try {
int n = 0;
if (i != null)
while (i.hasNext()) {
i.next();
++n;
}
if (i instanceof AutoCloseable)
((AutoCloseable) i).close();
return n;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ClassLoader classLoaderForObject(Object o) {
if (o instanceof ClassLoader)
return ((ClassLoader) o);
if (o == null)
return null;
return _getClass(o).getClassLoader();
}
static public String classNameToVM(String name) {
return name.replace(".", "$");
}
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 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 String getStackTrace(String msg) {
return getStackTrace_noRecord(new Throwable(msg));
}
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 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 Class mc() {
return main.class;
}
static public ThreadLocal assertVerbose_value = new ThreadLocal();
static public void assertVerbose(boolean b) {
assertVerbose_value.set(b);
}
static public boolean assertVerbose() {
return isTrue(assertVerbose_value.get());
}
static public A assertEqualsVerbose(Object x, A y) {
assertEqualsVerbose((String) null, x, y);
return y;
}
static public A assertEqualsVerbose(String msg, Object x, A y) {
if (!eq(x, y)) {
throw fail((nempty(msg) ? msg + ": " : "") + "expected: " + x + ", got: " + y);
} else
print("OK" + (empty(msg) ? "" : " " + msg) + ": " + (x));
return y;
}
static public void assertEqualsVerbose(Scorer scorer, Object x, Object y) {
assertEqualsVerbose(scorer, "", x, y);
}
static public void assertEqualsVerbose(Scorer scorer, String msg, Object x, Object y) {
if (scorer == null) {
assertEqualsVerbose(x, y);
return;
}
if (!eq(x, y)) {
print(appendColonIfNempty(msg) + y + " != " + x);
scorer.add(false);
} else {
print("OK: " + appendColonIfNempty(msg) + x);
scorer.add(true);
}
}
static public String nullIfEmpty(String s) {
return isEmpty(s) ? null : s;
}
static public Map nullIfEmpty(Map map) {
return isEmpty(map) ? null : map;
}
static public List nullIfEmpty(List l) {
return isEmpty(l) ? null : l;
}
static public void assertTrue(Object o) {
if (!(eq(o, true)))
throw fail(str(o));
}
static public boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static public boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static public boolean assertTrue(Scorer scorer, boolean b) {
scorer.add(b);
return b;
}
static public String joinNemptiesWithColon(String... strings) {
return joinNempties(": ", strings);
}
static public String joinNemptiesWithColon(Collection strings) {
return joinNempties(": ", strings);
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return c == null ? "null" : new String(c);
}
static public String str(char[] c, int offset, int count) {
return new String(c, offset, count);
}
static public File touchFile(File file) {
try {
closeRandomAccessFile(newRandomAccessFile(mkdirsForFile(file), "rw"));
return file;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean removeFile(File file) {
return deleteFile(file);
}
static public Object collectionMutex(List l) {
return l;
}
static public Object collectionMutex(Object o) {
if (o instanceof List)
return o;
String c = className(o);
return o;
}
static public void removeSubList(List l, int from, int to) {
if (l != null)
subList(l, from, to).clear();
}
static public void removeSubList(List l, int from) {
if (l != null)
subList(l, from).clear();
}
public static File mkdirsForFile(File file) {
File dir = file.getParentFile();
if (dir != null) {
dir.mkdirs();
if (!dir.isDirectory())
if (dir.isFile())
throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!");
else
throw fail("Unknown IO exception during mkdirs of " + f2s(file));
}
return file;
}
public static String mkdirsForFile(String path) {
mkdirsForFile(new File(path));
return path;
}
static public long now_virtualTime;
static public long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static public File copyFile(File src, File dest) {
try {
FileInputStream inputStream = new FileInputStream(src.getPath());
FileOutputStream outputStream = newFileOutputStream(dest.getPath());
try {
copyStream(inputStream, outputStream);
inputStream.close();
} finally {
outputStream.close();
}
return dest;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public FileOutputStream newFileOutputStream(File path) throws IOException {
return newFileOutputStream(path.getPath());
}
static public FileOutputStream newFileOutputStream(String path) throws IOException {
return newFileOutputStream(path, false);
}
static public FileOutputStream newFileOutputStream(File path, boolean append) throws IOException {
return newFileOutputStream(path.getPath(), append);
}
static public FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
mkdirsForFile(path);
FileOutputStream f = new FileOutputStream(path, append);
_registerIO(f, path, true);
return f;
}
static public String fromLines(Iterable lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines) buf.append(str(line)).append('\n');
return buf.toString();
}
static public String fromLines(String... lines) {
return fromLines(asList(lines));
}
static public IterableIterator toLines(File f) {
return linesFromFile(f);
}
static public List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
static public int toLines_nextLineBreak(String s, int start) {
int n = s.length();
for (int i = start; i < n; i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static public List mapToLines(Map map) {
List l = new ArrayList();
for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
return l;
}
static public String mapToLines(Map map, Object f) {
return lines(map(map, f));
}
static public String mapToLines(Object f, Map map) {
return lines(map(map, f));
}
static public String mapToLines(Object f, Iterable l) {
return lines(map(f, l));
}
static public String mapToLines(Iterable l, IF1 f) {
return mapToLines((Object) f, l);
}
static public String mapToLines(IF1 f, Iterable l) {
return mapToLines((Object) f, l);
}
static public String mapToLines(Map map, IF2 f) {
return lines(map(map, f));
}
static public String mapToLines(IF1 f, A data1, A... moreData) {
return lines(map(f, data1, moreData));
}
static public List toLinesFullTrim(String s) {
List l = new ArrayList();
for (String line : toLines(s)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
static public List toLinesFullTrim(File f) {
List l = new ArrayList();
for (String line : linesFromFile(f)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
static public ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal();
static public void checkFileNotTooBigToRead(File f) {
callF(checkFileNotTooBigToRead_tl.get(), f);
}
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 volatile public Concepts mainConcepts;
static public Concepts db_mainConcepts() {
if (mainConcepts == null)
mainConcepts = newConceptsWithClassFinder(getDBProgramID());
return mainConcepts;
}
static public void cleanMeUp_concepts() {
if (db_mainConcepts() != null)
db_mainConcepts().cleanMeUp();
}
static public 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 > A max(Iterable l) {
A max = null;
var it = iterator(l);
if (it.hasNext()) {
max = it.next();
while (it.hasNext()) {
A a = it.next();
if (cmp(a, max) > 0)
max = a;
}
}
return max;
}
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 > A max(A a, A b) {
return cmp(a, b) >= 0 ? a : b;
}
static public A jPreferHeight(int h, A c) {
Dimension size = c.getPreferredSize();
c.setPreferredSize(new Dimension(size.width, max(h, size.height)));
return c;
}
static public HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
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 joinNempties(String sep, Object... strings) {
return joinStrings(sep, strings);
}
static public String joinNempties(String sep, Iterable strings) {
return joinStrings(sep, strings);
}
static public String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
static public String plural(String s) {
return getPlural(s);
}
static public double fraction(double d) {
return d % 1;
}
static public String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
static public String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
static public String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
static public String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
static public String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
static public int toInt(Object o) {
if (o == null)
return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt((String) o);
if (o instanceof Boolean)
return boolToInt((Boolean) o);
throw fail("woot not int: " + getClassName(o));
}
static public int toInt(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
static public Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static public Object getOpt(String field, Object o) {
return getOpt_cached(o, field);
}
static public Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null)
return null;
makeAccessible(f);
return f.get(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object getOpt(Class c, String field) {
try {
if (c == null)
return null;
Field f = getOpt_findStaticField(c, field);
if (f == null)
return null;
makeAccessible(f);
return f.get(null);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Field getOpt_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);
return null;
}
static public String unnullForIteration(String s) {
return s == null ? "" : s;
}
static public Collection unnullForIteration(Collection l) {
return l == null ? immutableEmptyList() : l;
}
static public List unnullForIteration(List l) {
return l == null ? immutableEmptyList() : l;
}
static public byte[] unnullForIteration(byte[] l) {
return l == null ? emptyByteArray() : l;
}
static public int[] unnullForIteration(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnullForIteration(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnullForIteration(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public short[] unnullForIteration(short[] l) {
return l == null ? emptyShortArray() : l;
}
static public Map unnullForIteration(Map l) {
return l == null ? immutableEmptyMap() : l;
}
static public Iterable unnullForIteration(Iterable i) {
return i == null ? immutableEmptyList() : i;
}
static public A[] unnullForIteration(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnullForIteration(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnullForIteration(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnullForIteration(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnullForIteration(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public long unnullForIteration(Long l) {
return l == null ? 0L : l;
}
static public List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
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 odd(int i) {
return (i & 1) != 0;
}
static public boolean odd(long i) {
return (i & 1) != 0;
}
static public boolean odd(BigInteger i) {
return odd(toInt(i));
}
static public boolean isSpaceEtc(char c) {
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
static public File fileAppendToName(File f, String suffix) {
return newFile(f.getPath() + suffix);
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return strOrEmpty(first((Collection) strings));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(strOrEmpty(i.next()));
while (i.hasNext()) buf.append(glue).append(strOrEmpty(i.next()));
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(String glue, Object... 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 RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public A uniqueConcept(Class c, Object... params) {
return uniqueConcept(db_mainConcepts(), c, params);
}
static public A uniqueConcept(Concepts cc, Class c, Object... params) {
AutoCloseable __1 = tempDBLock(cc);
try {
params = expandParams(c, params);
A x = findConceptWhere(cc, c, params);
if (x == null) {
x = unlisted(c);
csetAll(x, params);
cc.register(x);
} else {
}
return x;
} finally {
_close(__1);
}
}
static public AutoCloseable tempDBLock(Concepts concepts) {
return tempLock(concepts.lock);
}
static public AutoCloseable tempDBLock() {
return tempDBLock(db_mainConcepts());
}
static public Object[] expandParams(Class c, Object[] params) {
if (l(params) == 1)
params = new Object[] { singleFieldName(c), params[0] };
else
warnIfOddCount(params);
return params;
}
static public A findConceptWhereCI(Class c, Object... params) {
return findConceptWhereCI(db_mainConcepts(), c, params);
}
static public A findConceptWhereCI(Concepts concepts, Class c, Object... params) {
params = expandParams(c, params);
Lowest>> bestIndex = new Lowest();
if (concepts.ciFieldIndices != null)
for (int i = 0; i < l(params); i += 2) {
ping();
Object val = params[i + 1];
IFieldIndex index = concepts.getCIFieldIndex(c, (String) params[i]);
if (index != null) {
Collection l = index.getAll(val);
bestIndex.put(() -> l, l(l));
}
if (concepts.useBackRefsForSearches && val instanceof Concept) {
bestIndex.put(() -> findBackRefs(((Concept) val), c), ((Concept) val)._backRefCount());
}
}
if (bestIndex.has()) {
Collection l = bestIndex.get().get();
if (l(params) == 2)
return first(l);
for (A x : l) {
ping();
if (checkConceptFieldsIC(x, params))
return x;
}
return null;
} else {
for (A x : concepts.list(c)) {
ping();
if (checkConceptFieldsIC(x, params))
return x;
}
return null;
}
}
static public Concept findConceptWhereCI(Concepts concepts, String c, Object... params) {
for (Concept x : concepts.list(c)) {
ping();
if (checkConceptFieldsIC(x, params))
return x;
}
return null;
}
static public A unlisted(Class c, Object... args) {
concepts_unlisted.set(true);
try {
return nuObject(c, args);
} finally {
concepts_unlisted.set(null);
}
}
static public Concept unlisted(String name, Object... args) {
Class extends Concept> cc = findClass(name);
concepts_unlisted.set(true);
try {
return cc != null ? nuObject(cc) : new Concept(name);
} finally {
concepts_unlisted.set(null);
}
}
static public int csetAll(Concept c, Object... values) {
return cset(c, values);
}
static public int csetAll(Iterable extends Concept> l, Object... values) {
int n = 0;
for (Concept c : unnullForIteration(l)) n += cset(c, values);
return n;
}
static public int csetAll(Concept c, Map values) {
int n = 0;
for (Map.Entry extends String, ? extends Object> __0 : _entrySet(values)) {
String field = __0.getKey();
Object value = __0.getValue();
n += cset(c, field, value);
}
return n;
}
static public String dropNumberPrefix(String s) {
return dropFirst(s, indexOfNonDigit(s));
}
static public File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
static public File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
static public String conceptsFileName() {
return "concepts.structure.gz";
}
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