Warning : session_start(): open(/var/lib/php/sessions/sess_p94l2t1fr1prileill1h0ck6e5, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.fail;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.getOpt_raw;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.getField;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.loadSnippetQuietly;
import static loadableUtils.utils.sendToLocalBot;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_top;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.componentPopupMenu_getEvent;
import static loadableUtils.utils.listPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.tablePopupMenuFirst;
import static loadableUtils.utils.rowSorter_setComparators;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.makePopupMenuConditional;
import static loadableUtils.utils.makeConceptsTable_idWidth;
import static loadableUtils.utils.showConceptsTable_afterUpdate;
import static loadableUtils.utils.dynamicObjectIsLoading;
import static loadableUtils.utils.rethrow;
import static loadableUtils.utils.concepts_internStringsLongerThan;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF1;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Snippet;
import loadableUtils.utils.Q;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.structure_ClassInfo;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.RGB;
import loadableUtils.utils.BWImage;
import loadableUtils.utils.MakesBufferedImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.RC;
import loadableUtils.utils.IConceptIndex;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.Derefable;
import loadableUtils.utils.ImageSurfaceSelector;
import loadableUtils.utils.SimpleCRUD;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.DynObjectTable;
import loadableUtils.utils.DynImageSurface;
import loadableUtils.utils.DynCalculatedList;
import loadableUtils.utils.GlobalID;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import javax.swing.border.TitledBorder;
import javax.swing.border.*;
import java.awt.datatransfer.*;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import java.text.NumberFormat;
import javax.swing.undo.UndoManager;
import java.text.SimpleDateFormat;
import java.awt.datatransfer.StringSelection;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.geom.*;
import java.text.*;
import java.util.TimeZone;
class main {
static public class Example extends Concept {
public String text;
public boolean pos = false;
}
static public class Theory extends Concept {
public String pattern;
transient public Collection solvedExamples_cache;
public Collection solvedExamples() {
if (solvedExamples_cache == null)
solvedExamples_cache = solvedExamples_load();
return solvedExamples_cache;
}
public Collection solvedExamples_load() {
return filter(list(_concepts, Example.class), e -> e.pos == mmo2_match(pattern, e.text));
}
transient public Collection unsolvedExamples_cache;
public Collection unsolvedExamples() {
if (unsolvedExamples_cache == null)
unsolvedExamples_cache = unsolvedExamples_load();
return unsolvedExamples_cache;
}
public Collection unsolvedExamples_load() {
return setMinusSet(list(_concepts, Example.class), solvedExamples());
}
public boolean isFullSolution() {
return empty(unsolvedExamples());
}
public int score() {
return l(solvedExamples());
}
transient public Integer complexityClass_cache;
public int complexityClass() {
if (complexityClass_cache == null)
complexityClass_cache = complexityClass_load();
return complexityClass_cache;
}
public Integer complexityClass_load() {
return numberOfWords2(pattern);
}
}
static public class PatternMaker extends DynModule {
static public boolean _switchableField_enabled = true;
public boolean enabled = true;
static public boolean _switchableField_caseID = true;
public String caseID = aGlobalID();
public String comment, examplesText, counterexamplesText;
transient public JTable theoriesTable, resultsTable;
transient public Concepts cc;
transient public Set examples, counterexamples;
transient public Lowest simplestFullSolutionCollector = new Lowest();
public TreeMap> bestPatternsByClass;
public String simplestFullSolution;
transient public TreeMap bestByComplexity = new TreeMap();
transient public Map> allByComplexity = autoTreeMap(() -> treeSetWithDuplicatesOverCalculatedField(__34 -> theoryScore(__34)));
public void start() {
try {
super.start();
if (enabled) {
startThread(new Runnable() {
public void run() {
try {
think();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "think();";
}
});
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String _modifyStructForDuplication(String struct) {
return jreplace_first(struct, "caseID=*", "caseID=" + quote(aGlobalID()));
}
public JComponent visualize() {
JComponent c = withCenteredButtons(northAndCenterWithMargins(dm_fieldWithLabel("comment"), jvsplit(jhgrid(jCenteredSection("Examples", dm_textArea("examplesText")), jCenteredSection("Counterexamples", dm_textArea("counterexamplesText"))), jhsplit(jCenteredSection("Results", northAndCenterWithMargin(dm_calculatedCenteredLabel(() -> empty(simplestFullSolution) ? "" : "Simplest solution pattern: " + quote(simplestFullSolution)), jtabs("Best", resultsTable = sexyTable(), "All theories", theoriesTable = sexyTable()))), dm_printLogComponent()))), jThreadedButton("Think", new Runnable() {
public void run() {
try {
AutoCloseable __12 = enter();
try {
think();
} finally {
_close(__12);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); think();";
}
}), jPopDownButton_noText(dm_importAndExportAllDataMenuItems()), dm_checkBox("Think on load", "enabled"));
{
startThread(new Runnable() {
public void run() {
try {
resultsToTables();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "resultsToTables();";
}
});
}
return c;
}
public void think() {
AutoCloseable __9 = enter();
try {
cc = new Concepts();
indexConceptFieldCI(cc, Example.class, "text");
indexConceptFieldCI(cc, Theory.class, "pattern");
setField("simplestFullSolution", null);
simplestFullSolutionCollector.clear();
examples = asLinkedHashSet(tlftj(examplesText));
counterexamples = asLinkedHashSet(tlftj(counterexamplesText));
Set intersection = setIntersection(examples, counterexamples);
if (nempty(intersection)) {
infoBox("Error: Examples appear in both lists, e.g. " + first(intersection));
return;
}
deleteConcepts(cc, Example.class);
for (String s : examples) uniqCI(cc, Example.class, "text", s, "pos", true);
for (String s : counterexamples) uniqCI(cc, Example.class, "text", s, "pos", false);
int nExamples = countConcepts(cc, Example.class);
print("Have " + nExamples(nExamples));
new Strategy2().run();
print("Have " + nTheories(countConcepts(cc, Theory.class)));
setField("bestPatternsByClass", mapValues(t -> scoredNonPercent(t.score(), t.pattern), bestByComplexity));
if (dm_vis() != null)
resultsToTables();
} finally {
_close(__9);
}
}
public class Strategy implements Runnable {
public void run() {
for (String s : examples) addPatterns(ai_inputExampleToPossibleMMOPatterns1(s));
for (int __twice = 0; __twice < 2; __twice++) {
for (Theory a : allByComplexity.get(1)) for (int n = 1; n <= 2; n++) for (Theory b : allByComplexity.get(n)) addPattern(mmo2_combineWithOr(a.pattern, b.pattern));
}
}
}
public class Strategy2 extends Strategy {
public void run() {
super.run();
for (Theory t : values(bestByComplexity)) {
print("Have theory: " + t.pattern + ", unsolved: " + t.unsolvedExamples());
for (Example e : filterWhere(t.unsolvedExamples(), "pos", false)) for (String negPat : ai_inputExampleToPossibleMMOPatterns1(e.text)) addPattern(print("Trying pattern", "(" + t.pattern + ") + !(" + negPat + ")"));
}
}
}
public Map theoryToMap(Theory t) {
return t == null ? null : litorderedmap("Pattern", t.pattern, "Complexity class", t.complexityClass(), "Solved examples", l(t.solvedExamples()) + " of " + countConcepts(cc, Example.class), "Unsolved", joinWithComma(quoteAll(collect("text", t.unsolvedExamples()))));
}
public void resultsToTables() {
AutoCloseable __10 = enter();
try {
dataToTable_uneditable_ifHasTable(resultsTable, mapValuesToList(__35 -> theoryToMap(__35), bestByComplexity));
updateTabNameWithTableCount(resultsTable);
dataToTable_uneditable_ifHasTable(theoriesTable, lambdaMap(__36 -> theoryToMap(__36), list(cc, Theory.class)));
updateTabNameWithTableCount(theoriesTable);
} finally {
_close(__10);
}
}
public void addPatterns(Iterable l) {
for (String s : unnull(l)) addPattern(s);
}
public void addPattern(String pattern) {
addToCollectors(uniqCI_returnIfNew(cc, Theory.class, "pattern", pattern));
}
public int theoryScore(Theory t) {
return t == null ? 0 : t.score();
}
public void addToCollectors(Theory t) {
if (t == null)
return;
putIfHigherByCalculatedField(__37 -> theoryScore(__37), bestByComplexity, t.complexityClass(), t);
allByComplexity.get(t.complexityClass()).add(t);
if (t.isFullSolution() && simplestFullSolutionCollector.put(t, t.complexityClass()))
setField("simplestFullSolution", t.pattern);
}
}
static public boolean _moduleClass_PatternMaker = true;
static public String programID;
static public void _onLoad_initUtils() {
utils.__javax = javax();
}
static public void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
public Class get(String name) {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (name.startsWith("main$"))
return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
return null;
}
});
}
static public List filter(Iterable c, Object pred) {
if (pred instanceof F1)
return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null)
for (Object o : c) if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
static public List filter(Object pred, Iterable c) {
return filter(c, pred);
}
static public List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
static public List filter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(B[] c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
static public List list(Class type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, Class type) {
return concepts.list(type);
}
static public List list(String type) {
return db_mainConcepts().list(type);
}
static public List list(Concepts concepts, String type) {
return concepts.list(type);
}
static public boolean mmo2_match(MMOPattern pattern, String s) {
return mmo2_match(pattern, s, false, false);
}
static public boolean mmo2_match(MMOPattern pattern, String s, boolean startOfLine, boolean endOfLine) {
if (pattern == null)
return false;
String s2 = trim(s);
if (pattern instanceof MMOPattern.StartOfLine)
return mmo2_match(((MMOPattern.StartOfLine) pattern).p, s2, true, endOfLine);
if (pattern instanceof MMOPattern.EndOfLine)
return mmo2_match(((MMOPattern.EndOfLine) pattern).p, s2, startOfLine, true);
if (pattern instanceof MMOPattern.Phrase) {
String p = ((MMOPattern.Phrase) pattern).phrase;
if (((MMOPattern.Phrase) pattern).quoted)
return cicWithSmartWordBoundary(s2, p);
if (startsWith(p, "#"))
return eqic(p, s2);
return match3_startOrEndOfLine(p, s2, startOfLine, endOfLine);
}
if (pattern instanceof MMOPattern.And)
return all(((MMOPattern.And) pattern).l, pat -> mmo2_match(pat, s2, startOfLine, endOfLine));
if (pattern instanceof MMOPattern.Or)
return any(((MMOPattern.Or) pattern).l, pat -> mmo2_match(pat, s2, startOfLine, endOfLine));
if (pattern instanceof MMOPattern.Not)
return !mmo2_match(((MMOPattern.Not) pattern).p, s2, startOfLine, endOfLine);
throw fail("what. " + pattern);
}
static public boolean mmo2_match(String pattern, String s) {
return mmo2_match(mmo2_parsePattern(pattern), s);
}
static public Set setMinusSet(Set l, Collection stuff) {
if (empty(stuff))
return l;
Set set = asSet(stuff);
Set l2 = similarEmptySet(l);
for (A a : l) if (!set.contains(a))
l2.add(a);
return l2;
}
static public Set setMinusSet(Collection l, Collection stuff) {
return setMinusSet(asSet(l), stuff);
}
static public boolean empty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean empty(Map map) {
return map == null || map.isEmpty();
}
static public boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static public boolean empty(Object o) {
if (o instanceof Collection)
return empty((Collection) o);
if (o instanceof String)
return empty((String) o);
if (o instanceof Map)
return empty((Map) o);
if (o instanceof Object[])
return empty((Object[]) o);
if (o instanceof byte[])
return empty((byte[]) o);
if (o == null)
return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static public boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
static public boolean empty(double[] a) {
return a == null || a.length == 0;
}
static public boolean empty(float[] a) {
return a == null || a.length == 0;
}
static public boolean empty(int[] a) {
return a == null || a.length == 0;
}
static public boolean empty(long[] a) {
return a == null || a.length == 0;
}
static public boolean empty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean empty(short[] a) {
return a == null || a.length == 0;
}
static public boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public int numberOfWords2(String s) {
return l(words2(s));
}
static public String aGlobalID() {
return randomID(globalIDLength());
}
static public String aGlobalID(Random random) {
return randomID(random, globalIDLength());
}
static public AutoMap autoTreeMap(IF0 f) {
AutoMap map = new AutoMap<>(f);
map.map = new TreeMap();
return map;
}
static public TreeSetWithDuplicates treeSetWithDuplicatesOverCalculatedField(IF1 f) {
return new TreeSetWithDuplicates (comparatorFromCalculatedField(f));
}
static public Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
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 void think(String thought) {
miniChat(thought);
}
static public String jreplace_first(String s, String in, String out) {
return jreplace_first(s, in, out, null);
}
static public String jreplace_first(String s, String in, String out, Object condition) {
List tok = javaTok(s);
return jreplace_first(tok, in, out, false, false, condition) ? join(tok) : s;
}
static public boolean jreplace_first(List tok, String in, String out) {
return jreplace_first(tok, in, out, false, true, null);
}
static public boolean jreplace_first(List tok, String in, String out, Object condition) {
return jreplace_first(tok, in, out, false, true, condition);
}
static public boolean jreplace_first(List tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) {
List tokin = javaTok(in);
jfind_preprocess(tokin);
boolean anyChange = false;
int i = 1;
if ((i = findCodeTokens(tok, i, ignoreCase, toStringArray(codeTokensOnly(tokin)), condition)) >= 0) {
List subList = tok.subList(i - 1, i + l(tokin) - 1);
String expansion = jreplaceExpandRefs(out, subList);
int end = i + l(tokin) - 2;
clearAllTokens(tok, i, end);
tok.set(i, expansion);
if (reTok)
reTok(tok, i, end);
anyChange = true;
}
return anyChange;
}
static public boolean jreplace_first_debug = false;
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 == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static public JPanel withCenteredButtons(JComponent center, Object... params) {
return centerAndSouth(center, withMargin(jcenteredbuttons(params)));
}
static public JPanel northAndCenterWithMargins(Component n, Component c) {
return applyDefaultMargin(northAndCenter(withBottomMargin(n), c));
}
static public JComponent dm_fieldWithLabel(String field) {
return dm_textFieldWithLabel(field);
}
static public JSplitPane jvsplit(Component n, Component s) {
return jvsplit(n, s, 0.5);
}
static public JSplitPane jvsplit(Component n, Component s, double splitPoint, int delay) {
return jvsplit(n, s, splitPoint);
}
static public JSplitPane jvsplit(Component n, Component s, double splitPoint) {
return setSplitPaneOnFirstShowing(swingNu(JSplitPane.class, JSplitPane.VERTICAL_SPLIT, wrap(n), wrap(s)), splitPoint);
}
static public JSplitPane jvsplit(double splitPoint, Component n, Component s) {
return jvsplit(n, s, splitPoint);
}
static public JPanel jhgrid(Object... parts) {
return hgrid(parts);
}
static public JPanel jCenteredSection(Component c) {
return jCenteredSection("", c);
}
static public JPanel jCenteredSection(final String title, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = jSection(title, c);
((TitledBorder) p.getBorder()).setTitleJustification(TitledBorder.CENTER);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = jSection(title, c);\r\n ((TitledBorder) p.getBorder()).setTitleJu...";
}
});
}
static public JPanel jCenteredSection(String title) {
return jCenteredSection(title, jpanel());
}
static public JTextArea dm_textArea(String field) {
return dm_fieldTextArea(field);
}
static public JSplitPane jhsplit(Component l, Component r) {
return jhsplit(l, r, 0.5);
}
static public JSplitPane jhsplit(Component l, Component r, double splitPoint, int delay) {
return jhsplit(l, r, splitPoint);
}
static public JSplitPane jhsplit(Component l, Component r, double splitPoint) {
return setSplitPaneOnFirstShowing(swingNu(JSplitPane.class, JSplitPane.HORIZONTAL_SPLIT, wrap(l), wrap(r)), splitPoint);
}
static public JSplitPane jhsplit(double splitPoint, Component l, Component r) {
return jhsplit(l, r, splitPoint);
}
static public JPanel northAndCenterWithMargin(Component n, Component c) {
return northAndCenter(withBottomMargin(n), c);
}
static public JLabel dm_calculatedCenteredLabel(IF0 calc) {
return dm_centeredCalculatedLabel(calc);
}
static public JTabbedPane jtabs(Object... x) {
return fillJTabs(swingNu(JTabbedPane.class), x);
}
static public boolean sexyTable_drag = false;
static public JTable sexyTable() {
final JTable table = sexyTableWithoutDrag();
if (sexyTable_drag)
tableEnableTextDrag(table);
return table;
}
static public JComponent dm_printLogComponent() {
DynModule mod = dm_current_mandatory();
final JTextArea ta = moveCaretToEnd(typeWriterTextArea_noUndo(str(mod._actualPrintLog())));
JComponent section = jSection("Log", awtEvery(ta, 500, new Runnable() {
public void run() {
try {
setText(ta, str(mod._actualPrintLog()));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "setText(ta, str(mod._actualPrintLog()))";
}
}));
componentPopupMenuItem(section, "Clear", new Runnable() {
public void run() {
try {
clearPrintLog();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "clearPrintLog();";
}
});
return section;
}
static public JButton jThreadedButton(final String text, final Object action) {
return swing(new F0() {
public JButton get() {
try {
String text2 = dropPrefix("[disabled] ", text);
final JButton btn = new JButton(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 final JButton btn = new JButt...";
}
});
}
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 JButton jPopDownButton_noText(final Object... menuParams) {
return toolTip("Additional commands", jPopDownButton("", menuParams));
}
static public Object[] dm_importAndExportAllDataMenuItems() {
DynModule mod = dm_current_mandatory();
return litobjectarray("Export all my data...", runnableThread(new Runnable() {
public void run() {
try {
dm_exportStructureToTextFileDialog(mod);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_exportStructureToTextFileDialog(mod)";
}
}), "Import all my data...", runnableThread(new Runnable() {
public void run() {
try {
dm_importStructureFromTextFileDialog(mod);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_importStructureFromTextFileDialog(mod)";
}
}));
}
static public JCheckBox dm_checkBox(String field) {
return dm_fieldCheckBox(field);
}
static public JCheckBox dm_checkBox(String text, String field) {
return dm_fieldCheckBox(text, field);
}
static public ConceptFieldIndexCI indexConceptFieldCI(Class c, String field) {
return indexConceptFieldCI(db_mainConcepts(), c, field);
}
static public ConceptFieldIndexCI indexConceptFieldCI(Concepts concepts, Class c, String field) {
ConceptFieldIndexCI idx = getConceptFieldCIIndex(concepts, c, field);
return idx != null ? idx : new ConceptFieldIndexCI(concepts, c, field);
}
static public LinkedHashSet asLinkedHashSet(A[] array) {
LinkedHashSet set = new LinkedHashSet();
for (A o : array) if (o != null)
set.add(o);
return set;
}
static public LinkedHashSet asLinkedHashSet(Collection l) {
if (l instanceof LinkedHashSet)
return (LinkedHashSet) l;
LinkedHashSet set = new LinkedHashSet();
for (A o : l) if (o != null)
set.add(o);
return set;
}
static public List tlftj(String text) {
return toLinesFullTrim_java(text);
}
static public Set setIntersection(Set a, Collection b) {
Set set = similarEmptySet(a);
Set bSet = asSet(b);
for (A x : a) if (bSet.contains(x))
set.add(x);
return set;
}
static public boolean nempty(Collection c) {
return !empty(c);
}
static public boolean nempty(CharSequence s) {
return !empty(s);
}
static public boolean nempty(Object[] o) {
return !empty(o);
}
static public boolean nempty(byte[] o) {
return !empty(o);
}
static public boolean nempty(int[] o) {
return !empty(o);
}
static public boolean nempty(Map m) {
return !empty(m);
}
static public boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static public boolean nempty(Object o) {
return !empty(o);
}
static public 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 Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public A first(IterableIterator i) {
return first((Iterator ) i);
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public A first(Pair p) {
return p == null ? null : p.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public void deleteConcepts(List conceptsOrIDs) {
db_mainConcepts().deleteConcepts(conceptsOrIDs);
}
static public List deleteConcepts(Class c, Object... params) {
return deleteConcepts(db_mainConcepts(), c, params);
}
static public List deleteConcepts(Concepts cc, Class c, Object... params) {
List l = asList(findConceptsWhere(cc, c, params));
deleteConcepts(l);
return l;
}
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 int countConcepts(Concepts concepts, Class c, Object... params) {
return concepts.countConcepts(c, params);
}
static public int countConcepts(Class c, Object... params) {
return db_mainConcepts().countConcepts(c, params);
}
static public int countConcepts() {
return db_mainConcepts().countConcepts();
}
static public int countConcepts(String className) {
return db_mainConcepts().countConcepts(className);
}
static public int countConcepts(Concepts concepts, String className) {
return concepts.countConcepts(className);
}
static public int countConcepts(Concepts concepts) {
return concepts.countConcepts();
}
static volatile public StringBuffer local_log = new StringBuffer();
static volatile public Appendable print_log = local_log;
static volatile public int print_log_max = 1024 * 1024;
static volatile public int local_log_max = 100 * 1024;
static public boolean print_silent = false;
static public Object print_byThread_lock = new Object();
static volatile public ThreadLocal print_byThread;
static volatile public Object print_allThreads;
static volatile public Object print_preprocess;
static public void print() {
print("");
}
static public A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
static public A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static public void print_noNewLine(String s) {
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;
print_raw(s);
}
static public void print_raw(String s) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static public void print_autoRotate() {
}
static public String nExamples(long n) {
return n2(n, "example");
}
static public String nExamples(Collection l) {
return nExamples(l(l));
}
static public String nTheories(long n) {
return n2(n, "theory", "theories");
}
static public String nTheories(Collection l) {
return nTheories(l(l));
}
static public String nTheories(Map map) {
return nTheories(l(map));
}
static public Map mapValues(Object func, Map map) {
Map m = similarEmptyMap(map);
for (Object key : keys(map)) m.put(key, callF(func, map.get(key)));
return m;
}
static public Map mapValues(Map map, IF1 f) {
return mapValues(f, map);
}
static public Map mapValues(IF1 f, Map map) {
return mapValues((Object) f, map);
}
static public Map mapValues(Map map, Object func) {
return mapValues(func, map);
}
static public ScoredNonPercent scoredNonPercent(A a, float score) {
return new ScoredNonPercent(a, score);
}
static public ScoredNonPercent scoredNonPercent(A a, double score) {
return new ScoredNonPercent(a, (float) score);
}
static public ScoredNonPercent scoredNonPercent(A a, ScoredNonPercent scoredNonPercent) {
return new ScoredNonPercent(a, getScore(scoredNonPercent));
}
static public ScoredNonPercent scoredNonPercent(double score, A a) {
return scoredNonPercent(a, score);
}
static public JComponent dm_vis(Object module) {
return dm_getVisualization(module);
}
static public JComponent dm_vis() {
return dm_getVisualization();
}
static public IterableIterator ai_inputExampleToPossibleMMOPatterns1(String s) {
List tok = simpleSpaces(javaTok(s));
return uniqueIteratorCI(subphrasesOfAnyLength(tok));
}
static public String mmo2_combineWithOr(String a, String b) {
return a + ", " + b;
}
static public Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static public Collection values(Object map) {
return values((Map) map);
}
static public List filterWhere(Collection c, Object... data) {
return filterByFields(c, data);
}
static public LinkedHashMap litorderedmap(Object... x) {
LinkedHashMap map = new LinkedHashMap();
litmap_impl(map, x);
return map;
}
static public String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static public List quoteAll(Collection l) {
List x = new ArrayList();
for (String s : l) x.add(quote(s));
return x;
}
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 JTable dataToTable_uneditable_ifHasTable(Object data, final JTable table) {
if (table != null)
dataToTable_uneditable(table, data);
return table;
}
static public JTable dataToTable_uneditable_ifHasTable(JTable table, Object data) {
return dataToTable_uneditable_ifHasTable(data, table);
}
static public List mapValuesToList(Object func, Map map) {
List out = emptyList(l(map));
for (Object key : keys(map)) out.add(callF(func, map.get(key)));
return out;
}
static public List mapValuesToList(IF1 f, Map map) {
return mapValuesToList((Object) f, map);
}
static public List mapValuesToList(Map map, IF1 f) {
return mapValuesToList(f, map);
}
static public List mapValuesToList(Map map, Object func) {
return mapValuesToList(func, map);
}
static public void updateTabNameWithTableCount(JTable table) {
Pair p = enclosingTab(table);
if (p == null)
return;
setTabTitle(p.a, p.b, appendBracketedCount(dropTrailingBracketedCount(getTabTitle(p.a, p.b)), tableRowCount(table)));
}
static public List lambdaMap(IF1 f, Iterable l) {
return map(l, f);
}
static public String unnull(String s) {
return s == null ? "" : s;
}
static public Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static public List unnull(List l) {
return l == null ? emptyList() : l;
}
static public Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static public Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static public A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static public Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public A uniqCI_returnIfNew(Class c, Object... params) {
Pair p = uniqCI2(c, params);
return p.b ? p.a : null;
}
static public A uniqCI_returnIfNew(Concepts cc, Class c, Object... params) {
Pair p = uniqCI2(cc, c, params);
return p.b ? p.a : null;
}
static public void putIfHigherByCalculatedField(IF1 scorer, Map map, A key, B value) {
if (map == null || key == null || value == null)
return;
B existing = map.get(key);
if (existing == null || cmp(scorer.get(value), scorer.get(existing)) > 0)
map.put(key, value);
}
static public Class javax() {
return getJavaX();
}
static public void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
static public HashMap findClass_fullName_cache = new HashMap();
static public Class findClass_fullName(String name) {
synchronized (findClass_fullName_cache) {
if (findClass_fullName_cache.containsKey(name))
return findClass_fullName_cache.get(name);
Class c;
try {
c = Class.forName(name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_fullName_cache.put(name, c);
return c;
}
}
static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public Object _defaultClassFinder_value = defaultDefaultClassFinder();
static public Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
static public Object callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
return x30_util.callF(f, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A callF(F0 f) {
return f == null ? null : f.get();
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
static public Object callMC(String method, Object... args) {
return call(mc(), method, args);
}
static public Object call(Object o) {
return callF(o);
}
static public Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
static volatile public Concepts mainConcepts;
static public Concepts db_mainConcepts() {
if (mainConcepts == null)
mainConcepts = newConceptsWithClassFinder(getDBProgramID());
return mainConcepts;
}
static public String trim(String s) {
return s == null ? null : s.trim();
}
static public String trim(StringBuilder buf) {
return buf.toString().trim();
}
static public String trim(StringBuffer buf) {
return buf.toString().trim();
}
static public boolean cicWithSmartWordBoundary(String a, String b) {
return containsRegexpIC(a, phraseToRegExp(b));
}
static public boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static public boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static public boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
m.m = new String[] { substring(a, strL(b)) };
return true;
}
static public boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static public boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static public boolean match3_startOrEndOfLine(String pat, String s, boolean startOfLine, boolean endOfLine) {
if (startOfLine)
return endOfLine ? match3(pat, s) : matchStart(pat, s);
else
return endOfLine ? matchEnd(pat, s) : find3(pat, s);
}
static public boolean all(Object pred, Collection l) {
if (l != null)
for (Object o : l) if (!isTrue(callF(pred, o)))
return false;
return true;
}
static public boolean all(Iterable l, IF1 f) {
if (l != null)
for (A a : l) if (!f.get(a))
return false;
return true;
}
static public boolean all(IF1 f, Iterable l) {
return all(l, f);
}
static public boolean any(Object pred, Iterable l) {
if (l != null)
for (A a : l) if (isTrue(callF(pred, a)))
return true;
return false;
}
static public boolean any(IF1 pred, Iterable l) {
return any((Object) pred, l);
}
static public boolean any(Iterable l, IF1 pred) {
return any(pred, l);
}
static public MMOPattern mmo2_parsePattern(String s) {
s = trim(tok_deRoundBracket(trim(s)));
List tok = javaTokWithBrackets(s);
List l = tok_splitAtComma(tok);
if (l(l) > 1)
return new MMOPattern.Or(lambdaMap(__38 -> mmo2_parsePattern(__38), l));
l = tok_splitAtPlus(tok);
if (l(l) > 1)
return new MMOPattern.And(lambdaMap(__39 -> mmo2_parsePattern(__39), l));
if (startsWith(s, "!"))
return new MMOPattern.Not(mmo2_parsePattern(dropFirst(s)));
if (startsWith(s, "^"))
return new MMOPattern.StartOfLine(mmo2_parsePattern(dropFirst(s)));
if (endsWith(s, "$"))
return new MMOPattern.EndOfLine(mmo2_parsePattern(dropLast(s)));
l = tok_splitAtAsterisk(tok);
if (l(l) == 2)
return new MMOPattern.Weighted(parseDouble(second(l)), mmo2_parsePattern(first(l)));
return new MMOPattern.Phrase(unquote(s), isQuoted(s));
}
static public Set asSet(Object[] array) {
HashSet set = new HashSet();
for (Object o : array) if (o != null)
set.add(o);
return set;
}
static public Set asSet(String[] array) {
TreeSet set = new TreeSet();
for (String o : array) if (o != null)
set.add(o);
return set;
}
static public Set asSet(Iterable l) {
if (l instanceof Set)
return (Set) l;
HashSet set = new HashSet();
for (A o : unnull(l)) if (o != null)
set.add(o);
return set;
}
static public Set similarEmptySet(Collection m) {
if (m instanceof TreeSet)
return new TreeSet(((TreeSet) m).comparator());
if (m instanceof LinkedHashSet)
return new LinkedHashSet();
return new HashSet();
}
static public Set similarEmptySet(Map m) {
if (m instanceof TreeMap)
return new TreeSet(((TreeMap) m).comparator());
if (m instanceof LinkedHashMap)
return new LinkedHashSet();
return new HashSet();
}
static public String getType(Object o) {
return getClassName(o);
}
static public long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static public long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static public List words2(String s) {
List l = new ArrayList();
int n = l(s);
for (int i = 0; i < n; ) {
int j = i;
while (j < n && isLetterOrDigit(s.charAt(j))) ++j;
if (j > i)
l.add(substring(s, i, j));
while (j < n && !isLetterOrDigit(s.charAt(j))) ++j;
i = j;
}
return l;
}
static public int randomID_defaultLength = 12;
static public String randomID(int length) {
return makeRandomID(length);
}
static public String randomID(Random r, int length) {
return makeRandomID(r, length);
}
static public String randomID() {
return randomID(randomID_defaultLength);
}
static public String randomID(Random r) {
return randomID(r, randomID_defaultLength);
}
static public int globalIDLength() {
return 16;
}
static public Comparator comparatorFromCalculatedField(IF1 f) {
return f == null ? null : (a, b) -> cmp(f.get(a), f.get(b));
}
static public String defaultThreadName_name;
static public String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static public Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
static public Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
static public Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static public Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
static public Runnable toRunnable(final Object o) {
if (o instanceof Runnable)
return (Runnable) o;
return new Runnable() {
public void run() {
try {
callF(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(o)";
}
};
}
static public Map _registerThread_threads;
static public Object _onRegisterThread;
static public Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static public void _registerThread() {
_registerThread(Thread.currentThread());
}
static public void miniChat(String text) {
String slackTS = getSlackTS();
if (slackTS == null) {
print("Skipping mini-chat post (not on slack): " + quote(text));
return;
}
Object mcBot = getBot("#1002433");
call(mcBot, "addToMiniChat", "dc" + slackTS, getProgramID(), text);
}
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, n = 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 && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
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));
++n;
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 + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
++n;
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);
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static public String join(Iterable strings) {
return join("", strings);
}
static public String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static public String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static public int jfind(String s, String in) {
return jfind(javaTok(s), in);
}
static public int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
static public int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, null);
}
static public int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, int startIdx, String in, Object condition) {
return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
}
static public int jfind(List tok, List tokin) {
return jfind(tok, 1, tokin);
}
static public int jfind(List tok, int startIdx, List tokin) {
return jfind(tok, startIdx, tokin, null);
}
static public int jfind(List tok, int startIdx, String[] tokinC, Object condition) {
return findCodeTokens(tok, startIdx, false, tokinC, condition);
}
static public int jfind(List tok, int startIdx, List tokin, Object condition) {
return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
}
static public List jfind_preprocess(List tok) {
for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
return tok;
}
static public int findCodeTokens(List tok, String... tokens) {
return findCodeTokens(tok, 1, false, tokens);
}
static public int findCodeTokens(List tok, boolean ignoreCase, String... tokens) {
return findCodeTokens(tok, 1, ignoreCase, tokens);
}
static public int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String... tokens) {
return findCodeTokens(tok, startIdx, ignoreCase, tokens, null);
}
static public HashSet findCodeTokens_specials = lithashset("*", "", "", "", "\\*");
static public int findCodeTokens_bails, findCodeTokens_nonbails;
static public interface findCodeTokens_Matcher {
public boolean get(String token);
}
static public int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) {
int end = tok.size() - tokens.length * 2 + 2, nTokens = tokens.length;
int i = startIdx | 1;
String firstToken = tokens[0];
if (!ignoreCase && !findCodeTokens_specials.contains(firstToken)) {
while (i < end && !firstToken.equals(tok.get(i))) i += 2;
}
findCodeTokens_Matcher[] matchers = new findCodeTokens_Matcher[nTokens];
for (int j = 0; j < nTokens; j++) {
String p = tokens[j];
findCodeTokens_Matcher matcher;
if (p.equals("*"))
matcher = t -> true;
else if (p.equals(""))
matcher = t -> isQuoted(t);
else if (p.equals(""))
matcher = t -> isIdentifier(t);
else if (p.equals(""))
matcher = t -> isInteger(t);
else if (p.equals("\\*"))
matcher = t -> t.equals("*");
else if (ignoreCase)
matcher = t -> eqic(p, t);
else
matcher = t -> t.equals(p);
matchers[j] = matcher;
}
outer: for (; i < end; i += 2) {
for (int j = 0; j < nTokens; j++) if (!matchers[j].get(tok.get(i + j * 2)))
continue outer;
if (condition == null || checkTokCondition(condition, tok, i - 1))
return i;
}
return -1;
}
static public String[] toStringArray(Collection c) {
String[] a = new String[l(c)];
Iterator it = c.iterator();
for (int i = 0; i < l(a); i++) a[i] = it.next();
return a;
}
static public String[] toStringArray(Object o) {
if (o instanceof String[])
return (String[]) o;
else if (o instanceof Collection)
return toStringArray((Collection) o);
else
throw fail("Not a collection or array: " + getClassName(o));
}
static public List codeTokensOnly(List tok) {
int n = tok.size();
List l = emptyList(n / 2);
for (int i = 1; i < n; i += 2) l.add(tok.get(i));
return l;
}
static public String jreplaceExpandRefs(String s, List tokref) {
if (!contains(s, '$'))
return s;
List tok = javaTok(s);
for (int i = 1; i < l(tok); i += 2) {
String t = tok.get(i);
if (t.startsWith("$") && isInteger(t.substring(1))) {
String x = tokref.get(-1 + parseInt(t.substring(1)) * 2);
tok.set(i, x);
} else if (t.equals("\\")) {
tok.set(i, "");
i += 2;
}
}
return join(tok);
}
static public void clearAllTokens(List tok) {
for (int i = 0; i < tok.size(); i++) tok.set(i, "");
}
static public void clearAllTokens(List tok, int i, int j) {
for (; i < j; i++) tok.set(i, "");
}
static public List reTok(List tok) {
replaceCollection(tok, javaTok(tok));
return tok;
}
static public List reTok(List tok, int i) {
return reTok(tok, i, i + 1);
}
static public List reTok(List tok, int i, int j) {
i = max(i & ~1, 0);
j = min(l(tok), j | 1);
if (i >= j)
return tok;
List t = javaTok(joinSubList(tok, i, j));
replaceListPart(tok, i, j, t);
return tok;
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public JPanel centerAndSouth(final Component c, final Component s) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
if (s != null)
panel.add(BorderLayout.SOUTH, wrap(s));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT...";
}
});
}
static public int withMargin_defaultWidth = 6;
static public JPanel withMargin(Component c) {
return withMargin(withMargin_defaultWidth, c);
}
static public JPanel withMargin(int w, Component c) {
return withMargin(w, w, c);
}
static public JPanel withMargin(int w, int h, Component c) {
return withMargin(w, h, w, h, c);
}
static public JPanel withMargin(final int top, final int left, final int bottom, final int right, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
static public JPanel jcenteredbuttons(Object... params) {
return jcenteredline(paramsToButtons(params));
}
static public A applyDefaultMargin(final A c) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth, withMargin_defaultWidth));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.setBorder(BorderFactory.createEmptyBorder(withMargin_defaultWidth, withMarg...";
}
});
}
return c;
}
static public JPanel northAndCenter(Component n, Component c) {
return centerAndNorth(c, n);
}
static public int withBottomMargin_defaultWidth = 6;
static public JPanel withBottomMargin(Component c) {
return withBottomMargin(withBottomMargin_defaultWidth, c);
}
static public JPanel withBottomMargin(final int w, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(0, 0, w, 0));
p.add(c);
return p;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel p = new JPanel(new BorderLayout);\r\n p.setBorder(BorderFactory.creat...";
}
});
}
static public JComponent dm_textFieldWithLabel(String field) {
return withLabel(humanizeLabel(field) + ":", dm_textField(field));
}
static public JSplitPane setSplitPaneOnFirstShowing(final Component c, final double value) {
final JSplitPane sp = first(childrenOfType(c, JSplitPane.class));
if (sp != null)
onFirstResize(sp, new Runnable() {
public void run() {
try {
sp.setDividerLocation(value);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "sp.setDividerLocation(value);";
}
});
return sp;
}
static public A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
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
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 JPanel hgrid(final Object... parts) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel();
Object[] _parts = flattenArray2(parts);
panel.setLayout(new GridLayout(1, _parts.length));
smartAdd(panel, _parts);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "new JPanel panel;\r\n O[] _parts = flattenArray2(parts);\r\n panel.setLayou...";
}
});
}
static public Object swing(Object f) {
return swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public JPanel jSection(Component c) {
return jSection("", c);
}
static public JPanel jSection(final String title, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
border = BorderFactory.createTitledBorder(border, title);
JSection panel = new JSection(c);
panel.setBorder(border);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);\r\n bo...";
}
});
}
static public JPanel jSection(String title) {
return jSection(title, jpanel());
}
static public JPanel jpanel(LayoutManager layout) {
return swingNu(JPanel.class, layout);
}
static public JPanel jpanel() {
return swingNu(JPanel.class);
}
static public JTextArea dm_fieldTextArea(String field) {
return jLiveValueTextArea_bothWays(dm_fieldLiveValue(field));
}
static public JLabel dm_centeredCalculatedLabel(IF0 calc) {
return centerLabel(dm_calculatedLabel(calc));
}
static public JTabbedPane fillJTabs(final JTabbedPane tabs, final Object... _x) {
if (tabs != null) {
swing(new Runnable() {
public void run() {
try {
clearTabs(tabs);
Object[] x = flattenArray2(_x);
int idx = 0;
if (get(x, 0) instanceof Integer) {
idx = asInt(get(x, 0));
x = dropFirst(x);
if (empty(x)) {
x = arrayrep(null, idx);
idx = 0;
}
}
int n = 0;
for (int i = 0; i < l(x); i++) {
++n;
if (x[i] instanceof Component)
tabs.addTab("Tab " + n, wrap((Component) x[i]));
else {
String name = str(or(x[i], "Tab " + n));
Component c;
if (get(x, i + 1) instanceof Component)
c = (Component) get(x, ++i);
else
c = new JPanel();
tabs.addTab(name, wrap(c));
}
}
if (idx != 0)
tabs.setSelectedIndex(min(tabs.getTabCount() - 1, idx));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "clearTabs(tabs);\r\n Object[] x = flattenArray2(_x);\r\n ifdef fillJTabs_de...";
}
});
}
return tabs;
}
static public void tableEnableTextDrag(final JTable table) {
TransferHandler th = new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {
return COPY;
}
@Override
public Transferable createTransferable(JComponent c) {
Object o = selectedTableCell(table);
return new StringSelection(str(o));
}
};
tableEnableDrag(table, th);
}
static public A moveCaretToEnd(A ta) {
setCaretPosition(ta, textAreaTextLength(ta));
return ta;
}
static public JTextArea typeWriterTextArea_noUndo() {
return typeWriterTextArea_noUndo("");
}
static public JTextArea typeWriterTextArea_noUndo(String text) {
return setFont(jTextArea_noUndo(text), typeWriterFont());
}
static public A awtEvery(A component, long delay, Object r) {
swingEvery(component, delay, r);
return component;
}
static public A awtEvery(A component, long delay, long firstDelay, Object r) {
swingEvery(component, delay, firstDelay, r);
return component;
}
static public void awtEvery(RootPaneContainer frame, long delay, Object r) {
swingEvery(frame, delay, r);
}
static public A awtEvery(A component, double delaySeconds, Object r) {
return awtEvery(component, toMS(delaySeconds), r);
}
static public boolean setText_opt = true;
static public A setText(A c, Object text) {
setText((JComponent) c, text);
return c;
}
static public A setText(final A c, Object text) {
final String s = strUnnull(text);
{
swing(new Runnable() {
public void run() {
try {
c.getEditor().setItem(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.getEditor().setItem(s);";
}
});
}
return c;
}
static public void setText(JLabel c, Object text) {
setText((JComponent) c, text);
}
static public JButton setText(JButton c, Object text) {
setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text)));
return c;
}
static public A setText(final A c, Object text) {
if (c == null)
return null;
final String s = strUnnull(text);
{
swing(new Runnable() {
public void run() {
try {
if (!setText_opt || neq(callOpt(c, "getText"), s))
call(c, "setText", s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n call(c, \"setText\", s);";
}
});
}
return c;
}
static public A componentPopupMenuItem(A c, final String name, final Object action) {
componentPopupMenu(c, new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItem(menu, name, action);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItem(menu, name, action);";
}
});
return c;
}
static public void componentPopupMenuItem(JComponent c, final JMenuItem menuItem) {
componentPopupMenu(c, new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItem(menu, menuItem);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItem(menu, menuItem);";
}
});
}
static public void clearPrintLog() {
clearStringBuffer_gen(local_log);
}
static public String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static public ActionListener actionListenerInNewThread(final Object runnable) {
return actionListenerInNewThread(runnable, null);
}
static public ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener)
return (ActionListener) runnable;
return new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
startThread("Action Listener", new Runnable() {
public void run() {
try {
AutoCloseable __1 = holdInstance(instanceToHold);
try {
callF(runnable);
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __1 = holdInstance(instanceToHold); try {\r\n callF(runnable...";
}
});
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
static public A toolTip(A c, final Object toolTip) {
return setToolTipText(c, toolTip);
}
static public A toolTip(Object toolTip, A c) {
return setToolTipText(toolTip, c);
}
static public JButton jPopDownButton(String text, final Object... menuParams) {
return jbutton((empty(text) ? "" : text + " ") + unicode_downPointingTriangle(), new Runnable() {
public void run() {
try {
JPopupMenu menu = new JPopupMenu();
int emptyCount = menu.getComponentCount();
String position = (String) (optPar_ignoreOddLength("position", menuParams));
fillJPopupMenu(menu, paramsWithout(menuParams, "position"));
if (menu.getComponentCount() != emptyCount) {
JButton btn = heldInstance(JButton.class);
int x = 0;
if (eq(position, "center"))
x = (btn.getWidth() - getPreferredWidth(menu)) / 2;
else if (eq(position, "right"))
x = btn.getWidth() - getPreferredWidth(menu);
menu.show(btn, x, btn.getHeight());
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "new JPopupMenu menu;\r\n int emptyCount = menu.getComponentCount();\r\n Str...";
}
});
}
static public Object[] litobjectarray(Object... l) {
return litObjectArray(l);
}
static public Runnable runnableThread(final Runnable r) {
return new Runnable() {
public void run() {
try {
startThread(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startThread(r)";
}
};
}
static public void dm_exportStructureToTextFileDialog(DynModule mod) {
inputText("Text file to save data in (" + dm_moduleName(mod) + ")", f2s(dm_structureExportDefaultFile(mod)), new VF1() {
public void get(String path) {
try {
saveTextFileWithInfoBox(newFile(path), javaTokWordWrap(dm_freshModuleStructureWithoutError(mod)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "saveTextFileWithInfoBox(newFile(path),\r\n javaTokWordWrap(dm_freshModul...";
}
});
}
static public void dm_importStructureFromTextFileDialog(DynModule mod) {
File f = showFileChooserWithDefaultDir("Module data to restore", javaxBackupDir());
if (fileExists(f)) {
infoBox("Replacing module with " + f2s(f));
dm_replaceModuleWithStructure(mod, loadTextFile(f));
}
}
static public JCheckBox dm_fieldCheckBox(String field) {
return dm_fieldCheckBox(humanizeFormLabel(field), field);
}
static public JCheckBox dm_fieldCheckBox(String text, String field) {
if (isIdentifier(text) && !isIdentifier(field)) {
String temp = field;
field = text;
text = temp;
}
return jLiveValueCheckBox(text, dm_fieldLiveValue(field));
}
static public ConceptFieldIndexCI getConceptFieldCIIndex(Class c, String field) {
return getConceptFieldCIIndex(db_mainConcepts(), c, field);
}
static public ConceptFieldIndexCI getConceptFieldCIIndex(Concepts concepts, Class c, String field) {
return (ConceptFieldIndexCI) concepts.getCIFieldIndex(c, field);
}
static public List toLinesFullTrim_java(String text) {
return tlft(joinLines(map("javaDropComments", tlft(text))));
}
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 {
final JWindow window = showWindow(infoMessage_makePanel(text));
window.setSize(300, 150);
moveToTopRightCorner(window);
if (infoMessage_alwaysOnTop)
window.setAlwaysOnTop(true);
window.setVisible(true);
if (seconds != 0)
disposeWindowAfter(iround(seconds * 1000), window);
return window;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JWindow window = showWindow(infoMessage_makePanel(text));\r\n window.s...";
}
});
}
static public JWindow infoMessage(Throwable e) {
printStackTrace(e);
return infoMessage(exceptionToStringShort(e));
}
static public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(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(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(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public Collection findConceptsWhere(Class c, Object... params) {
return findConceptsWhere(db_mainConcepts(), c, params);
}
static public Collection findConceptsWhere(String c, Object... params) {
return findConceptsWhere(db_mainConcepts(), c, params);
}
static public Collection findConceptsWhere(Concepts concepts, Class c, Object... params) {
params = expandParams(c, params);
if (concepts.fieldIndices != null)
for (int i = 0; i < l(params); i += 2) {
IFieldIndex index = concepts.getFieldIndex(c, (String) params[i]);
if (index != null) {
Collection rawList = index.getAll(params[i + 1]);
params = dropEntryFromParams(params, i);
if (params == null)
return rawList;
List l = new ArrayList();
for (A x : rawList) if (checkConceptFields(x, params))
l.add(x);
return l;
}
}
return filterConcepts(concepts.list(c), params);
}
static public Collection findConceptsWhere(Concepts concepts, String c, Object... params) {
return filterConcepts(concepts.list(c), params);
}
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);
}
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);
if (concepts.ciFieldIndices != null)
for (int i = 0; i < l(params); i += 2) {
IFieldIndex index = concepts.getCIFieldIndex(c, (String) params[i]);
if (index != null) {
for (A x : index.getAll(params[i + 1])) if (checkConceptFieldsIC(x, params))
return x;
return null;
}
}
for (A x : concepts.list(c)) if (checkConceptFieldsIC(x, params))
return x;
return null;
}
static public Concept findConceptWhereCI(Concepts concepts, String c, Object... params) {
for (Concept x : concepts.list(c)) 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 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 : unnull(l)) n += cset(c, values);
return n;
}
static public boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
static public void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
static public Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static public A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static public A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static public ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static public boolean isFalse(Object o) {
return eq(false, o);
}
static public String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0)
return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i + 1 < l && s.charAt(i + 1) == '\n')
++i;
}
}
return out.toString();
}
static public void print_append(Appendable buf, String s, int max) {
try {
synchronized (buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String n2(long l) {
return formatWithThousands(l);
}
static public String n2(Collection l) {
return n2(l(l));
}
static public String n2(Map map) {
return n2(l(map));
}
static public String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
static public String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static public String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
static public String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static public String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static public String n2(Map m, String singular) {
return n2(l(m), singular);
}
static public String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
static public String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static public Map similarEmptyMap(Map m) {
if (m instanceof TreeMap)
return new TreeMap(((TreeMap) m).comparator());
if (m instanceof LinkedHashMap)
return new LinkedHashMap();
return new HashMap();
}
static public Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keys(Object map) {
return keys((Map) map);
}
static public Set keys(MultiSet ms) {
return ms.keySet();
}
static public Set keys(MultiSetMap mm) {
return mm.keySet();
}
static public float getScore(Scored s) {
return s == null ? 0 : s.score;
}
static public JComponent dm_getVisualization(Object module) {
return callOpt(dm_getStem(module), "vis");
}
static public JComponent dm_getVisualization() {
return dm_getVisualization(dm_current_mandatory_generic());
}
static public List simpleSpaces(List tok) {
tok = cloneList(tok);
for (int i = 0; i < l(tok); i += 2) tok.set(i, tok.get(i).equals("") ? "" : " ");
return tok;
}
static public String simpleSpaces(String s) {
return join(simpleSpaces(nlTok(s)));
}
static public IterableIterator uniqueIteratorCI(Iterator it) {
Set set = ciSet();
return iff(() -> {
while (licensed()) {
if (!it.hasNext())
return endMarker();
String a = it.next();
if (set.add(a))
return a;
}
return endMarker();
});
}
static public IterableIterator subphrasesOfAnyLength(List tok) {
return mapI("joinWithoutFirstAndLast", subtokenizationsOfAnyLength(tok));
}
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 public List concatLists(Collection ... lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
static public List concatLists(Collection extends Collection > lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
static public List filterByFields(Iterable c, Object... data) {
if (c == null)
return null;
List l = new ArrayList();
for (A x : c) if (checkFields(x, data))
l.add(x);
return l;
}
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 List collectField(Iterable c, String field) {
List l = new ArrayList();
if (c != null)
for (Object a : c) l.add(getOpt(a, field));
return l;
}
static public List collectField(String field, Iterable c) {
return collectField(c, field);
}
static public JTable dataToTable_uneditable(Object data, final JTable table) {
return dataToTable_uneditable(table, data);
}
static public JTable dataToTable_uneditable(final JTable table, final Object data) {
if (table != null) {
swing(new Runnable() {
public void run() {
try {
dataToTable(table, data, true);
makeTableUneditable(table);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dataToTable(table, data, true);\r\n makeTableUneditable(table);";
}
});
}
return table;
}
static public JTable dataToTable_uneditable(final Object data) {
return dataToTable_uneditable(showTable(), data);
}
static public JTable dataToTable_uneditable(Object data, String title) {
return dataToTable_uneditable(showTable(title), data);
}
static public Pair enclosingTab(Component _c) {
return swing(() -> {
Component c = _c;
while (c != null) {
Container p = c.getParent();
if (p instanceof JTabbedPane)
return pair(((JTabbedPane) p), ((JTabbedPane) p).indexOfComponent(c));
c = c.getParent();
}
return null;
});
}
static public void setTabTitle(JTabbedPane tabs, int idx, String title) {
if (tabs != null && idx >= 0) {
swing(new Runnable() {
public void run() {
try {
if (idx < tabs.getTabCount())
tabs.setTitleAt(idx, title);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (idx < tabs.getTabCount())\r\n tabs.setTitleAt(idx, title);";
}
});
}
}
static public String appendBracketedCount(int n, String a) {
return appendBracketed(a, str(n));
}
static public String appendBracketedCount(String a, int n) {
return appendBracketedCount(n, a);
}
static public String dropTrailingBracketedCount(String s) {
return replaceAll(s, "\\s?\\(\\d+\\)$", "");
}
static public String getTabTitle(JTabbedPane tabs, int idx) {
return tabs == null || idx < 0 ? null : swing(() -> idx < tabs.getTabCount() ? tabs.getTitleAt(idx) : null);
}
static public int tableRowCount(JTable table) {
return tableRows(table);
}
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) x.add(callF(f, o));
return x;
}
static public List map(Iterable l, F1 f) {
return map(f, l);
}
static public List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(callF(f, o));
return x;
}
static public List map(IF1 f, Iterable l) {
return map(l, f);
}
static public List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
static public List map(IF1 f, A[] l) {
return map(l, f);
}
static public List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
static public List map(Object f, Object[] l) {
return map(f, asList(l));
}
static public List map(Object[] l, Object f) {
return map(f, l);
}
static public List map(Object f, Map map) {
return map(map, f);
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static public Map emptyMap() {
return new HashMap();
}
static public Object[] emptyObjectArray_a = new Object[0];
static public Object[] emptyObjectArray() {
return emptyObjectArray_a;
}
static public Pair uniqCI2(Class c, Object... params) {
return uniqCI2(db_mainConcepts(), c, params);
}
static public Pair uniqCI2(Concepts cc, Class c, Object... params) {
params = expandParams(c, params);
A x = findConceptWhereCI(cc, c, params);
if (x == null) {
x = unlisted(c);
csetAll(x, params);
cc.register(x);
return pair(x, true);
}
return pair(x, false);
}
static public int cmp(Number a, Number b) {
return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
}
static public int cmp(double a, double b) {
return a < b ? -1 : a == b ? 0 : 1;
}
static public int cmp(Object a, Object b) {
if (a == null)
return b == null ? 0 : -1;
if (b == null)
return 1;
return ((Comparable) a).compareTo(b);
}
static public Class __javax;
static public Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
static public AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
static public Object defaultDefaultClassFinder() {
return new F1() {
public Class get(String name) {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (name.startsWith("loadableUtils.utils$"))
return findClass_fullName("main" + name.substring(19));
return null;
}
};
}
static public Class mc() {
return main.class;
}
static public Object call_withVarargs(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
{
if (!(isStaticMethod(m)))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Concepts newConceptsWithClassFinder(String progID) {
Concepts cc = new Concepts(progID);
cc.classFinder = _defaultClassFinder();
return cc;
}
static public String getDBProgramID_id;
static public String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
static public boolean containsRegexpIC(String s, String pat) {
return compileRegexpIC(pat).matcher(s).find();
}
static public String phraseToRegExp(String b) {
return (startsWithLetterOrDigit(b) ? "\\b" : "") + regexpQuote(b) + (endsWithLetterOrDigit(b) ? "\\b" : "");
}
static public boolean nemptyString(String s) {
return s != null && s.length() > 0;
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
if (x >= s.length())
return "";
if (y < x)
y = x;
if (y > s.length())
y = s.length();
return s.substring(x, y);
}
static public String substring(String s, CharSequence l) {
return substring(s, l(l));
}
static public int strL(String s) {
return s == null ? 0 : s.length();
}
static public int listL(Collection l) {
return l == null ? 0 : l.size();
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static public boolean eq(Object a, Object b) {
return a == b || (a == null ? b == null : b != null && a.equals(b));
}
static public String asString(Object o) {
return o == null ? null : o.toString();
}
static public boolean match3(String pat, String s) {
return match3(pat, s, null);
}
static public boolean match3(String pat, String s, Matches matches) {
if (pat == null || s == null)
return false;
return match3(pat, parse3_cachedInput(s), matches);
}
static public boolean match3(String pat, List toks, Matches matches) {
List tokpat = parse3_cachedPattern(pat);
return match3(tokpat, toks, matches);
}
static public boolean match3(List tokpat, List toks, Matches matches) {
String[] m = match2(tokpat, toks);
if (m == null)
return false;
if (matches != null)
matches.m = m;
return true;
}
static public boolean matchStart(String pat, String s) {
return matchStart(pat, s, null);
}
static public boolean matchStart(String pat, String s, Matches matches) {
if (s == null)
return false;
return matchStart(pat, parse3_cachedInput(s), matches);
}
static public boolean matchStart(String pat, List toks, Matches matches) {
if (toks == null)
return false;
List tokpat = parse3_cachedPattern(pat);
if (toks.size() < tokpat.size())
return false;
String[] m = match2(tokpat, toks.subList(0, tokpat.size()));
if (m == null)
return false;
if (matches != null) {
matches.m = new String[m.length + 1];
arraycopy(m, matches.m);
matches.m[m.length] = joinSubList(toks, tokpat.size(), toks.size());
}
return true;
}
static public boolean matchEnd(String pat, String s) {
return matchEnd(pat, s, null);
}
static public boolean matchEnd(String pat, String s, Matches matches) {
if (s == null)
return false;
List tokpat = parse3(pat), toks = parse3(s);
if (toks.size() < tokpat.size())
return false;
String[] m = match2(tokpat, takeLast(l(tokpat), toks));
if (m == null)
return false;
if (matches != null) {
matches.m = new String[m.length + 1];
arraycopy(m, matches.m);
matches.m[m.length] = join(dropLast(l(tokpat), toks));
}
return true;
}
static public boolean find3(String pat, String s) {
return find3(pat, s, null);
}
static public boolean find3(String pat, String s, Matches matches) {
return find3(pat, parse3_cachedInput(s), matches);
}
static public boolean find3(String pat, List toks, Matches matches) {
List tokpat = parse3_cachedPattern(pat);
String[] m = find2(tokpat, toks);
if (m == null)
return false;
if (matches != null)
matches.m = m;
return true;
}
static public String tok_deRoundBracket(String s) {
return tok_isRoundBracketed(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s;
}
static public List javaTokWithBrackets(String s) {
return javaTokPlusBrackets(s);
}
static public List tok_splitAtComma(String s) {
return tok_splitAtComma(javaTok(s));
}
static public List tok_splitAtComma(List tok) {
List out = new ArrayList();
for (int i = 0; i < l(tok); i++) {
int j = smartIndexOf(tok, ",", i);
out.add(joinSubList(tok, i + 1, j - 1));
i = j;
}
return out;
}
static public List tok_splitAtPlus(String s) {
return tok_splitAtPlus(javaTokWithAllBrackets_cached(s));
}
static public List tok_splitAtPlus(List tok) {
return splitAtTokens(tok, "+");
}
static public String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
static public String[] dropFirst(String[] a) {
return drop(1, a);
}
static public Object[] dropFirst(Object[] a) {
return drop(1, a);
}
static public List dropFirst(List l) {
return dropFirst(1, l);
}
static public List dropFirst(int n, Iterable i) {
return dropFirst(n, toList(i));
}
static public List dropFirst(Iterable i) {
return dropFirst(toList(i));
}
static public List dropFirst(int n, List l) {
return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
static public List dropFirst(List l, int n) {
return dropFirst(n, l);
}
static public String dropFirst(int n, String s) {
return substring(s, n);
}
static public String dropFirst(String s, int n) {
return substring(s, n);
}
static public String dropFirst(String s) {
return substring(s, 1);
}
static public boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static public boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
static public boolean endsWith(String a, String b, Matches m) {
if (!endsWith(a, b))
return false;
m.m = new String[] { dropLast(l(b), a) };
return true;
}
static public String[] dropLast(String[] a, int n) {
n = Math.min(n, a.length);
String[] b = new String[a.length - n];
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static public List dropLast(List l) {
return subList(l, 0, l(l) - 1);
}
static public List dropLast(int n, List l) {
return subList(l, 0, l(l) - n);
}
static public List dropLast(Iterable l) {
return dropLast(asList(l));
}
static public String dropLast(String s) {
return substring(s, 0, l(s) - 1);
}
static public String dropLast(String s, int n) {
return substring(s, 0, l(s) - n);
}
static public String dropLast(int n, String s) {
return dropLast(s, n);
}
static public List tok_splitAtAsterisk(String s) {
return tok_splitAtAsterisk(javaTokWithAllBrackets_cached(s));
}
static public List tok_splitAtAsterisk(List tok) {
return splitAtTokens(tok, "*");
}
static public double parseDouble(String s) {
return Double.parseDouble(s);
}
static public A second(List l) {
return get(l, 1);
}
static public A second(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
if (!it.hasNext())
return null;
it.next();
return it.hasNext() ? it.next() : null;
}
static public A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static public B second(Pair p) {
return p == null ? null : p.b;
}
static public char second(String s) {
return charAt(s, 1);
}
static public String unquote(String s) {
if (s == null)
return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i + 1, s.length() - i - 1);
}
}
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length() - 1 : s.length();
StringBuilder sb = new StringBuilder(l - 1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch(nextChar) {
case '\"':
ch = '\"';
break;
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\'':
ch = '\'';
break;
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s;
}
static public boolean isQuoted(String s) {
if (isNormalQuoted(s))
return true;
return isMultilineQuoted(s);
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static public boolean isLetterOrDigit(char c) {
return Character.isLetterOrDigit(c);
}
static public String makeRandomID(int length) {
return makeRandomID(length, defaultRandomGenerator());
}
static public String makeRandomID(int length, Random random) {
char[] id = new char[length];
for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
static public String makeRandomID(Random r, int length) {
return makeRandomID(length, r);
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static public Runnable _topLevelErrorHandling(final Runnable runnable) {
final Object info = _threadInfo();
return new Runnable() {
public void run() {
try {
try {
_threadInheritInfo(info);
runnable.run();
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }";
}
};
}
static public WeakReference weakRef(A a) {
return newWeakReference(a);
}
static public String getSlackTS() {
return (String) callOpt(getMainBot(), "getSlackTS");
}
static public Object getBot(String botID) {
return callOpt(getMainBot(), "getBot", botID);
}
static public String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
static public String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static public String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static public String javaTok_substringN(String s, int i, int j) {
if (i == j)
return "";
if (j == i + 1 && s.charAt(i) == ' ')
return " ";
return s.substring(i, j);
}
static public String javaTok_substringC(String s, int i, int j) {
return s.substring(i, j);
}
static public List javaTokWithExisting(String s, List existing) {
++javaTok_n;
int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
int l = s.length();
int i = 0, n = 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 && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringN(s, i, j));
++n;
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) {
if (s.charAt(j) == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
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 + 1 < l && !s.substring(j, j + 2).equals("]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
j = Math.min(j + 3, l);
} else
++j;
if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
tok.add(existing.get(n));
else
tok.add(javaTok_substringC(s, i, j));
++n;
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
}
static public Map javaTokForJFind_array_cache = synchronizedMRUCache(1000);
static public String[] javaTokForJFind_array(String s) {
String[] tok = javaTokForJFind_array_cache.get(s);
if (tok == null)
javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s))));
return tok;
}
static public String[] codeTokensAsStringArray(List tok) {
int n = max(0, (l(tok) - 1) / 2);
String[] out = new String[n];
for (int i = 0; i < n; i++) out[i] = tok.get(i * 2 + 1);
return out;
}
static public ArrayList litlist(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
static public List replaceSublist(List l, List x, List y) {
if (x == null)
return l;
int i = 0;
while (true) {
i = indexOfSubList(l, x, i);
if (i < 0)
break;
replaceSublist(l, i, i + l(x), y);
i += l(y);
}
return l;
}
static public List replaceSublist(List l, int fromIndex, int toIndex, List y) {
int n = y.size(), toIndex_new = fromIndex + n;
if (toIndex_new < toIndex) {
removeSubList(l, toIndex_new, toIndex);
copyListPart(y, 0, l, fromIndex, n);
} else {
copyListPart(y, 0, l, fromIndex, toIndex - fromIndex);
if (toIndex_new > toIndex)
l.addAll(toIndex, subList(y, toIndex - fromIndex));
}
return l;
}
static public List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
static public HashSet lithashset(A... items) {
HashSet set = new HashSet();
for (A a : items) set.add(a);
return set;
}
static public boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static public boolean isInteger(String s) {
int n = l(s);
if (n == 0)
return false;
int i = 0;
if (s.charAt(0) == '-')
if (++i >= n)
return false;
while (i < n) {
char c = s.charAt(i);
if (c < '0' || c > '9')
return false;
++i;
}
return true;
}
static public boolean checkTokCondition(Object condition, List tok, int i) {
if (condition instanceof TokCondition)
return ((TokCondition) condition).get(tok, i);
return checkCondition(condition, tok, i);
}
static public boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static public boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
static public boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static public boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static public boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static public int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static public int parseInt(char c) {
return Integer.parseInt(str(c));
}
static public void replaceCollection(Collection dest, Collection src) {
if (dest == src)
return;
dest.clear();
dest.addAll(src);
}
static public int max(int a, int b) {
return Math.max(a, b);
}
static public int max(int a, int b, int c) {
return max(max(a, b), c);
}
static public long max(int a, long b) {
return Math.max((long) a, b);
}
static public long max(long a, long b) {
return Math.max(a, b);
}
static public double max(int a, double b) {
return Math.max((double) a, b);
}
static public float max(float a, float b) {
return Math.max(a, b);
}
static public double max(double a, double b) {
return Math.max(a, b);
}
static public int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static public double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
static public short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
static public int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
static public int min(int a, int b) {
return Math.min(a, b);
}
static public long min(long a, long b) {
return Math.min(a, b);
}
static public float min(float a, float b) {
return Math.min(a, b);
}
static public float min(float a, float b, float c) {
return min(min(a, b), c);
}
static public double min(double a, double b) {
return Math.min(a, b);
}
static public double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static public float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static public byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
static public short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
static public int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
static public String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
static public String joinSubList(List l, int i) {
return join(subList(l, i));
}
static public void replaceListPart(List l, int i, int j, List l2) {
replaceSublist(l, i, j, l2);
}
static public JPanel jcenteredline(final Component... components) {
return swing(new F0() {
public JPanel get() {
try {
return jFullCenter(hstackWithSpacing(components));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret jFullCenter(hstackWithSpacing(components));";
}
});
}
static public JPanel jcenteredline(List extends Component> components) {
return jcenteredline(asArray(Component.class, components));
}
static public List paramsToButtons(Object... params) {
List l = new ArrayList();
for (int i = 0; i < l(params); i += 2) if (params[i] != null)
if (params[i] instanceof JComponent)
l.add((JComponent) params[i--]);
else
l.add(jbutton((String) params[i], params[i + 1]));
return l;
}
static public JPanel centerAndNorth(final Component c, final Component n) {
return swing(new F0() {
public JPanel get() {
try {
JPanel panel = new JPanel(new BorderLayout());
panel.add(BorderLayout.CENTER, wrap(c));
panel.add(BorderLayout.NORTH, wrap(n));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JPanel panel = new JPanel(new BorderLayout);\r\n panel.add(BorderLayout.CENT...";
}
});
}
public static JComponent withLabel(String label, JComponent component) {
return westAndCenter(jlabel(label + " "), component);
}
static public String humanizeLabel(String s) {
return humanizeFormLabel(s);
}
static public JTextField dm_textField(String field) {
return dm_fieldTextField(field);
}
static public List childrenOfType(Component c, Class theClass) {
List l = new ArrayList();
scanForComponents(c, theClass, l);
return l;
}
static public List childrenOfType(Class theClass, Component c) {
return childrenOfType(c, theClass);
}
static public void onFirstResize(final Component c, final Object r) {
if (c != null && r != null) {
swing(new Runnable() {
public void run() {
try {
c.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
c.removeComponentListener(this);
pcallF(r);
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.addComponentListener(new ComponentAdapter {\r\n public void componentRes...";
}
});
}
}
static public A swingConstruct(final Class c, final Object... args) {
return swing(new F0 () {
public A get() {
try {
return nuObject(c, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret nuObject(c, args);";
}
});
}
static public A _recordNewSwingComponent(A c) {
if (c != null)
callF((Object) vm_generalMap_get("newSwingComponentRegistry"), (Object) c);
return c;
}
static public JComponent componentToJComponent(Component c) {
if (c instanceof JComponent)
return (JComponent) c;
if (c instanceof JFrame)
return ((JFrame) c).getRootPane();
if (c == null)
return null;
throw fail("boohoo " + getClassName(c));
}
static public JScrollPane jscroll(final Component c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret new JScrollPane(c);";
}
});
}
static public JLabel jlabel(final String text) {
return swingConstruct(BetterLabel.class, text);
}
static public JLabel jlabel() {
return jlabel(" ");
}
static public Object[] flattenArray2(Object... a) {
List l = new ArrayList();
if (a != null)
for (Object x : a) if (x instanceof Object[])
l.addAll(asList((Object[]) x));
else if (x instanceof Collection)
l.addAll((Collection) x);
else
l.add(x);
return asObjectArray(l);
}
static public JPanel smartAdd(JPanel panel, List parts) {
for (Object o : parts) addToContainer(panel, wrapForSmartAdd(o));
return panel;
}
static public JPanel smartAdd(JPanel panel, Object... parts) {
return smartAdd(panel, asList(parts));
}
static public void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
static public JTextArea jLiveValueTextArea_bothWays(final SimpleLiveValue lv) {
final JTextArea ta = typeWriterTextArea();
bindTextComponentToLiveValue_bothWays(ta, lv);
return ta;
}
static public SimpleLiveValue dm_fieldLiveValue(String fieldName) {
return dm_fieldLiveValue(dm_current_mandatory(), fieldName);
}
static public SimpleLiveValue dm_fieldLiveValue(final DynModule module, final String fieldName) {
Lock __0 = module.lock;
lock(__0);
try {
AutoCloseable __2 = module.enter();
try {
Class type = getFieldType(module, fieldName);
final SimpleLiveValue value = new SimpleLiveValue(type, get(module, fieldName));
dm_watchField(fieldName, new Runnable() {
public void run() {
try {
Object o = get(module, fieldName);
value.set(o);
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting \" + fi...";
}
});
value.onChange(new Runnable() {
public void run() {
try {
module.setField(fieldName, value.get());
;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ifdef dm_fieldLiveValue_debug\r\n print(\"dm_fieldLiveValue: setting 2 \" + ...";
}
});
return value;
} finally {
_close(__2);
}
} finally {
unlock(__0);
}
}
static public A centerLabel(A l) {
if (l != null)
l.setHorizontalAlignment(SwingConstants.CENTER);
return l;
}
static public JLabel dm_calculatedLabel(IF0 calc) {
return jLiveValueLabel(dm_calculatedLiveValue(Object.class, calc));
}
static public void clearTabs(final JTabbedPane tabs) {
if (tabs != null) {
swing(new Runnable() {
public void run() {
try {
tabs.removeAll();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "tabs.removeAll();";
}
});
}
}
static public int asInt(Object o) {
return toInt(o);
}
static public Object[] arrayrep(Object a, int n) {
return asArray(repeat(a, n));
}
static public A or(A a, A b) {
return a != null ? a : b;
}
static public Object selectedTableCell(JTable t, int col) {
return getTableCell(t, selectedTableRow(t), col);
}
static public Object selectedTableCell(final JTable t) {
return swing(new F0() {
public Object get() {
try {
return selectedTableCell(t, t.getSelectedColumn());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret selectedTableCell(t, t.getSelectedColumn());";
}
});
}
static public Object selectedTableCell(final JTable t, final String colName) {
return swing(new F0() {
public Object get() {
try {
return selectedTableCell(t, tableColumnViewIndex(t, colName));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret selectedTableCell(t, tableColumnViewIndex(t, colName));";
}
});
}
static public void tableEnableDrag(final JTable table, TransferHandler th) {
if (table.getDragEnabled()) {
print("Table drag already enabled");
return;
}
table.setDragEnabled(true);
table.setTransferHandler(th);
table.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == 1 && e.getClickCount() == 1)
table.getTransferHandler().exportAsDrag(table, e, TransferHandler.COPY);
}
});
}
static public void setCaretPosition(final JTextComponent c, final int pos) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
try {
int _pos = max(0, min(l(c.getText()), pos));
c.setCaretPosition(_pos);
} catch (Throwable __e) {
_handleException(__e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "pcall {\r\n int _pos = max(0, min(l(c.getText()), pos));\r\n c.setCaret...";
}
});
}
}
static public int textAreaTextLength(JTextComponent ta) {
return l(getText(ta));
}
static public A setFont(final Font font, final A a) {
if (a != null) {
swing(new Runnable() {
public void run() {
try {
a.setFont(font);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.setFont(font);";
}
});
}
return a;
}
static public A setFont(A a, Font font) {
return setFont(font, a);
}
static public A setFont(final String fontID, float fontSize, final A a) {
return setFont(loadFont_cached(fontID, fontSize), a);
}
static public JTextArea jTextArea_noUndo() {
return jTextArea_noUndo("");
}
static public JTextArea jTextArea_noUndo(final String text) {
return swingNu(JTextArea.class, text);
}
static public Font typeWriterFont() {
return typeWriterFont(iround(14 * getSwingFontScale()));
}
static public Font typeWriterFont(int size) {
return new Font("Courier", Font.PLAIN, size);
}
static public void swingEvery(JComponent component, long delay, Object r) {
installTimer(component, delay, r);
}
static public void swingEvery(JComponent component, long delay, long firstDelay, Object r) {
installTimer(component, r, delay, firstDelay);
}
static public void swingEvery(RootPaneContainer frame, long delay, Object r) {
installTimer(frame, delay, r);
}
static public void swingEvery(RootPaneContainer frame, long delay, long firstDelay, Object r) {
installTimer(frame, delay, firstDelay, r);
}
static public long toMS(double seconds) {
return (long) (seconds * 1000);
}
static public String strUnnull(Object o) {
return o == null ? "" : str(o);
}
static public String jlabel_textAsHTML_center_ifNeeded(String text) {
if (swic(text, "") && ewic(text, ""))
return text;
if (!containsNewLines(text))
return text;
return jlabel_textAsHTML_center(text);
}
static public void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static public void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static public void addMenuItem(JMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static public void addMenuItem(Menu menu, String text, Object action) {
menu.add(menuItem(text, action));
}
static public void addMenuItem(JMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static public void clearStringBuffer_gen(Object buf) {
if (buf != null) {
call(buf, "setLength", 0);
call(buf, "trimToSize");
}
}
static public ThreadLocal> holdInstance_l = new ThreadLocal();
static public AutoCloseable holdInstance(Object o) {
if (o == null)
return null;
listThreadLocalAdd(holdInstance_l, o);
return new AutoCloseable() {
public void close() {
listThreadLocalPopLast(holdInstance_l);
}
};
}
static public void messageBox(final String msg) {
if (headless())
print(msg);
else {
swing(new Runnable() {
public void run() {
try {
JOptionPane.showMessageDialog(null, msg, "JavaX", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "JOptionPane.showMessageDialog(null, msg, \"JavaX\", JOptionPane.INFORMATION_MES...";
}
});
}
}
static public void messageBox(Throwable e) {
printStackTrace(e);
messageBox(hideCredentials(innerException2(e)));
}
static public A setToolTipText(final A c, final Object toolTip) {
if (c == null)
return null;
{
swing(new Runnable() {
public void run() {
try {
String s = nullIfEmpty(str(toolTip));
if (neq(s, c.getToolTipText()))
c.setToolTipText(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "String s = nullIfEmpty(str(toolTip));\r\n if (neq(s, c.getToolTipText()))\r\n ...";
}
});
}
return c;
}
static public A setToolTipText(Object toolTip, A c) {
return setToolTipText(c, toolTip);
}
static public JButton jbutton(String text, Object action) {
return newButton(text, action);
}
static public JButton jbutton(String text) {
return newButton(text, null);
}
static public JButton jbutton(Action action) {
return swingNu(JButton.class, action);
}
static public String unicode_downPointingTriangle() {
return charToString(0x25BC);
}
static public A optPar_ignoreOddLength(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
for (int i = 0; i + 1 < l(opt); i += 2) if (eq(opt[i], name))
return (A) opt[i + 1];
return defaultValue;
}
static public Object optPar_ignoreOddLength(Object[] opt, String name) {
return optPar_ignoreOddLength(opt, name, null);
}
static public Object optPar_ignoreOddLength(String name, Object[] params) {
return optPar_ignoreOddLength(params, name);
}
static public void fillJPopupMenu(JPopupMenu m, Object... x) {
if (x == null)
return;
for (int i = 0; i < l(x); i++) {
Object o = x[i], y = get(x, i + 1);
if (o instanceof IVF1)
callF(o, m);
else if (o instanceof List)
fillJPopupMenu(m, asArray((List) o));
else if (isMenuSeparatorIndicator(o))
m.addSeparator();
else if (o instanceof LiveValue && ((LiveValue) o).getType() == String.class && isRunnableX(y)) {
final LiveValue lv = (LiveValue) o;
final JMenuItem mi = jmenuItem("", y);
bindLiveValueListenerToComponent(mi, lv, new Runnable() {
public void run() {
try {
String s = lv.get();
if (isCurlyBracketed(s)) {
setEnabled(mi, false);
s = unCurlyBracket(s);
} else
setEnabled(mi, true);
setText(mi, s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "String s = lv.get();\r\n if (isCurlyBracketed(s)) {\r\n setEnable...";
}
});
m.add(mi);
} else if (o instanceof String && isRunnableX(y)) {
m.add(jmenuItem((String) o, y));
++i;
} else if (o instanceof JMenuItem)
m.add((JMenuItem) o);
else if (o instanceof String || o instanceof Action || o instanceof Component)
call(m, "add", o);
else if (o != null)
print("Unknown menu item: " + o);
}
}
static public Object[] paramsWithout(Object[] a1, Object... keys) {
if (l(a1) == 1 && a1[0] instanceof Map)
return new Object[] { mapMinus((Map) a1[0], keys) };
Set set = lithashset(keys);
List l = new ArrayList();
int n = l(a1);
for (int i = 0; i < n; i += 2) if (i == n - 1)
l.add(a1[i]);
else if (!set.contains(a1[i])) {
l.add(a1[i]);
l.add(a1[i + 1]);
}
return toObjectArray(l);
}
static public A heldInstance(Class c) {
List l = holdInstance_l.get();
for (int i = l(l) - 1; i >= 0; i--) {
Object o = l.get(i);
if (isInstanceOf(o, c))
return (A) o;
}
throw fail("No instance of " + className(c) + " held");
}
static public int getPreferredWidth(Component c) {
return preferredWidth(c);
}
static public Object[] litObjectArray(Object... l) {
return l;
}
static public void inputText(final String msg, final Object action) {
inputText(msg, "", action);
}
static public void inputText(final String msg, final String defaultText, final Object action) {
final Object threadInfo = _threadInfo();
swingLater(new Runnable() {
public void run() {
try {
final JTextField tf = jtextfield(defaultText);
String title = joinStrings(" | ", msg, programName());
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 = joinString...";
}
});
}
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 String dm_moduleName() {
return dm_moduleName(assertNotNull(dm_current_generic()));
}
static public String dm_moduleName(Object module) {
return (String) callOpt(dm_getStem(module), "moduleName");
}
static public String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static public String f2s(String s) {
return f2s(newFile(s));
}
static public String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
static public File dm_structureExportDefaultFile(DynModule mod) {
return javaxBackupDir("module-" + shortClassName(mod) + "-" + ymdMinusHms() + ".txt");
}
static public void saveTextFileWithInfoBox(File f, String text) {
saveTextFile(f, text);
fileSavedInfoBox(f);
}
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 String javaTokWordWrap(String s) {
return javaTokWordWrap(120, s);
}
static public String javaTokWordWrap(int cols, String s) {
int col = 0;
List tok = javaTok(s);
for (int i = 0; i < l(tok); i++) {
String t = tok.get(i);
if (odd(i) && col >= cols && !containsNewLine(t))
tok.set(i, t = rtrimSpaces(t) + "\n");
int idx = t.lastIndexOf('\n');
if (idx >= 0)
col = l(t) - (idx + 1);
else
col += l(t);
}
return join(tok);
}
static public String dm_freshModuleStructureWithoutError(Object module) {
dm_clearError(module);
return dm_freshModuleStructure(module);
}
static public File showFileChooserWithDefaultDir(String title, File defaultDir) {
JFileChooser fc = new JFileChooser();
fc.setDialogTitle(title);
fc.setCurrentDirectory(defaultDir);
return execFileChooser(fc);
}
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 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 dm_replaceModuleWithStructure(Object mod, String struct) {
setAll(dm_getStem(mod), "contentsDirty", false, "oStruct", struct);
dm_reloadModule(mod);
}
static public String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
static public String loadTextFile(File f, String defaultContents) {
try {
checkFileNotTooBigToRead(f);
if (f == null || !f.exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(f);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
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 Map humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5");
static public String humanizeFormLabel(String s) {
if (containsSpace(s))
return s;
return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID"));
}
static public JCheckBox jLiveValueCheckBox(String text, final SimpleLiveValue