Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

20985
LINES
[SHOW ALL]

< > BotCompany Repo | #1033636 // Gazelle 22 Standalone [stable version]

JavaX source code (desktop) [tags: jar-with-libs no-compiler standalone use-pretranspiled]

Download Jar. Uses 2032K of libraries. Click here for Pure Java version (21422L/120K).

lib 1033505
lib 1400521

import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import java.util.function.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.imageio.*;
import java.math.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.setOpt_raw;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.format3;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPage_utf8;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.tablePopupMenu;
import static loadableUtils.utils.tablePopupMenuFirst;
import static loadableUtils.utils.sexyTableWithoutDrag;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.cset;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.concepts_unlisted;
import static loadableUtils.utils.dynamicObjectIsLoading;
import static loadableUtils.utils.rethrow;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF0;
import loadableUtils.utils.IF1;
import loadableUtils.utils.IVF1;
import loadableUtils.utils.IVF2;
import loadableUtils.utils.Matches;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.ImageSurface;
import loadableUtils.utils.structure_Data;
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.IterableIterator;
import loadableUtils.utils.IFieldIndex;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.GlobalID;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import loadableUtils.utils.SecretValue;
import static loadableUtils.utils.fixNewLines;
import static loadableUtils.utils.getExceptionCause;
import static loadableUtils.utils.joinWithSpace;
import static loadableUtils.utils.callF;
import static loadableUtils.utils.javaTok;
import static loadableUtils.utils.jlabel;
import static loadableUtils.utils.nohupJavax;
import static loadableUtils.utils.withDBLock;
import static loadableUtils.utils.join;
import static loadableUtils.utils.isAWTThread;
import static loadableUtils.utils.set;
import static loadableUtils.utils.call;
import static loadableUtils.utils.fail;
import static loadableUtils.utils.print;
import static loadableUtils.utils.printAlsoToSystemOut;
import static loadableUtils.utils.cget;
import static loadableUtils.utils.newTypeWriterTextArea;
import static loadableUtils.utils.db;
import loadableUtils.utils.LongRange;
import loadableUtils.utils.IntRange;
import loadableUtils.utils.MultiMap;
import loadableUtils.utils.Meta;
import loadableUtils.utils.ITokCondition;
import loadableUtils.utils.PingSource;
import loadableUtils.utils.ThreadPool;
import loadableUtils.utils.SimpleLiveValue;
import loadableUtils.utils.Matrix;
import loadableUtils.utils.Best;
import loadableUtils.utils.IRef;
import loadableUtils.utils.F2;
import loadableUtils.utils.RandomAccessAbstractList;
import loadableUtils.utils.IBWIntegralImage;
import loadableUtils.utils.Producer;
import loadableUtils.utils.IntBuffer;
import loadableUtils.utils.AbstractMatrix;
import loadableUtils.utils.WithTimestamp;
import loadableUtils.utils.IMeta;
import loadableUtils.utils.LiveValue;
import loadableUtils.utils.Timestamp;
import loadableUtils.utils.DoubleRect;
import loadableUtils.utils.Complex;
import loadableUtils.utils.Either;
import loadableUtils.utils.Steppable;
import loadableUtils.utils.T3;
import loadableUtils.utils.Swingable;
import loadableUtils.utils.Average;
import loadableUtils.utils.BWIntegralImage;
import loadableUtils.utils.DoubleRange;
import loadableUtils.utils.Seconds;
import static loadableUtils.utils.withTimestamp;
import static loadableUtils.utils.score;
import static loadableUtils.utils.stepAll;
import static loadableUtils.utils.infoMessage;
import static loadableUtils.utils.brightnessToRGBA;
import static loadableUtils.utils.withBorder;
import static loadableUtils.utils.getPlural;
import static loadableUtils.utils.rcallOpt;
import static loadableUtils.utils.childrenOfType;
import static loadableUtils.utils.nanoTime;
import static loadableUtils.utils.activateFrame_v3;
import static loadableUtils.utils.b;
import static loadableUtils.utils.ewicOneOf;
import static loadableUtils.utils.n;
import static loadableUtils.utils.abs;
import static loadableUtils.utils.callMain;
import static loadableUtils.utils.caseInsensitiveComparator;
import static loadableUtils.utils.getComponents;
import static loadableUtils.utils.rep;
import static loadableUtils.utils.area;
import static loadableUtils.utils.add;
import static loadableUtils.utils.singleComponentPanel;
import static loadableUtils.utils.withMargin;
import static loadableUtils.utils.addActionListener;
import static loadableUtils.utils.hasMethod;
import static loadableUtils.utils.containsOneOf;
import static loadableUtils.utils.intersectRects;
import static loadableUtils.utils.setSCPComponent;
import static loadableUtils.utils.hideWindow;
import static loadableUtils.utils.ymdMinusHMS;
import static loadableUtils.utils.jPopDownButton_noText;
import static loadableUtils.utils.swingLater;
import static loadableUtils.utils.currentImage;
import static loadableUtils.utils._defaultClassFinder;
import static loadableUtils.utils.boolOptParam;
import static loadableUtils.utils.getOptMC;
import static loadableUtils.utils.setImage;
import static loadableUtils.utils.regexp;
import static loadableUtils.utils.alwaysOnTop;
import static loadableUtils.utils.setFrameTitle;
import static loadableUtils.utils.getScreenWidth;
import static loadableUtils.utils.tsNow;
import static loadableUtils.utils.jfind_preprocess;
import static loadableUtils.utils.dm_reload;
import static loadableUtils.utils.getDBProgramID;
import static loadableUtils.utils.setFrameIcon;
import static loadableUtils.utils.isIdentifier;
import static loadableUtils.utils.getSnippetTitle;
import static loadableUtils.utils.jFullCenter;
import static loadableUtils.utils.dm_fieldCheckBox;
import static loadableUtils.utils.indent;
import static loadableUtils.utils.infoBox;
import static loadableUtils.utils.toSeconds;
import static loadableUtils.utils.rect;
import static loadableUtils.utils.cleanUp;
import static loadableUtils.utils.forEach;
import static loadableUtils.utils.disposeWindow;
import static loadableUtils.utils.textFieldFromComboBox;
import static loadableUtils.utils.getScore;
import static loadableUtils.utils.containsNewLines;
import static loadableUtils.utils.stdcompare;
import static loadableUtils.utils.centerAndEast;
import static loadableUtils.utils.metaMapPut;
import static loadableUtils.utils.makeFrame;
import static loadableUtils.utils.setDoubleBuffered;
import static loadableUtils.utils.asVirtualList;
import static loadableUtils.utils.javaTokForJFind_array;
import static loadableUtils.utils.withLeftAndRightMargin;
import static loadableUtils.utils.dm_doEvery;
import static loadableUtils.utils.childOfType;
import static loadableUtils.utils.hgrid;
import static loadableUtils.utils.getFieldType;
import static loadableUtils.utils.ping_v3;
import static loadableUtils.utils.flattenArray2;
import static loadableUtils.utils.getParent;
import static loadableUtils.utils.strOrEmpty;
import static loadableUtils.utils.pqO;
import static loadableUtils.utils.run;
import static loadableUtils.utils.has;
import static loadableUtils.utils.last;
import static loadableUtils.utils.warn;
import static loadableUtils.utils.distance;
import static loadableUtils.utils.jrightAlignedLine;
import static loadableUtils.utils.toRect;
import static loadableUtils.utils.installWindowDragger;
import static loadableUtils.utils.addIfNotNull;
import static loadableUtils.utils.installTimer;
import static loadableUtils.utils.clipBufferedImage;
import static loadableUtils.utils.setText;
import static loadableUtils.utils.findButton;
import static loadableUtils.utils.splitAtSpace;
import static loadableUtils.utils.getBounds;
import static loadableUtils.utils.northAndCenterWithMargin;
import static loadableUtils.utils.renderUserThreadsWithStackTraces;
import static loadableUtils.utils.newConceptsWithClassFinder;
import static loadableUtils.utils.replaceSublist;
import static loadableUtils.utils.selectedItem;
import static loadableUtils.utils.joinSubList;
import static loadableUtils.utils.onSelectedItem;
import static loadableUtils.utils.muricaCredentials;
import static loadableUtils.utils.onUpdate;
import static loadableUtils.utils.activateFrame;
import static loadableUtils.utils.replace;
import static loadableUtils.utils.profileToConsole;
import static loadableUtils.utils.myLibraryFiles;
import static loadableUtils.utils.findCodeTokens;
import static loadableUtils.utils.withTypeWriterFont;
import static loadableUtils.utils.printWithMS;
import static loadableUtils.utils.format;
import static loadableUtils.utils.heightForWidth;
import static loadableUtils.utils.onEnter;
import static loadableUtils.utils.hsplit;
import static loadableUtils.utils.containsNewLine;
import static loadableUtils.utils.centerAndEastWithMargin;
import static loadableUtils.utils.getFrame;
import static loadableUtils.utils.countIterator_exclusive;
import static loadableUtils.utils.centerAndSouth;
import static loadableUtils.utils.dm_fieldLiveValue;
import static loadableUtils.utils.isLetter;
import static loadableUtils.utils.toObjectArray;
import static loadableUtils.utils.rectFromPoints;
import static loadableUtils.utils.runnableThread;
import static loadableUtils.utils.toolTip;
import static loadableUtils.utils.firstToUpper;
import static loadableUtils.utils.allScreenBounds;
import static loadableUtils.utils.findClass_fullName;
import static loadableUtils.utils.copyLocalLog;
import static loadableUtils.utils.jscroll_centered;
import static loadableUtils.utils.parentFile;
import static loadableUtils.utils.gazelle_wavySpacer;
import static loadableUtils.utils.callOnLoadMethods;
import static loadableUtils.utils.dm_rEnter;
import static loadableUtils.utils.toString;
import static loadableUtils.utils.mapI_if1;
import static loadableUtils.utils.getProgramTitle;
import static loadableUtils.utils.renameFile;
import static loadableUtils.utils.isDigit;
import static loadableUtils.utils.regionMatches;
import static loadableUtils.utils.warnIfOddCount;
import static loadableUtils.utils.synchronizedMRUCache;
import static loadableUtils.utils.printFileInfo;
import static loadableUtils.utils.bindLiveValueListenerToComponent;
import static loadableUtils.utils.screenBounds;
import static loadableUtils.utils.myFrames;
import static loadableUtils.utils.callStringifier;
import static loadableUtils.utils.toRectangle;
import static loadableUtils.utils.widthForHeight;
import static loadableUtils.utils.javaxCodeDir;
import static loadableUtils.utils.jLiveValueLabel;
import static loadableUtils.utils.shortClassName_dropNumberPrefix;
import static loadableUtils.utils.minimizeWindow;
import static loadableUtils.utils.appendToFileBaseName;
import static loadableUtils.utils.jbutton;
import static loadableUtils.utils.setEnabled;
import static loadableUtils.utils.functionCall;
import static loadableUtils.utils.javaTokForStructure;
import static loadableUtils.utils.northAndCenter;
import static loadableUtils.utils.jline;
import static loadableUtils.utils.toMS;
import static loadableUtils.utils.creator;
import static loadableUtils.utils.vmBus_query;
import static loadableUtils.utils.change;
import static loadableUtils.utils.assertEquals;
import static loadableUtils.utils.getPreferredSize;
import static loadableUtils.utils.md5;
import static loadableUtils.utils.renderFileInfo;
import static loadableUtils.utils.jCheckBoxMenuItem;
import static loadableUtils.utils.find;
import static loadableUtils.utils.jenableUndoRedo;
import static loadableUtils.utils.setChecked;
import static loadableUtils.utils.setFont;
import static loadableUtils.utils.syncList;
import static loadableUtils.utils.takeFirst;
import static loadableUtils.utils.isEditableComboBox;
import static loadableUtils.utils.numberOfCores;
import static loadableUtils.utils.showWindow;
import static loadableUtils.utils.plus;
import static loadableUtils.utils.dm_watchField;
import static loadableUtils.utils.codeTokensAsStringArray;
import static loadableUtils.utils.ifloor;
import static loadableUtils.utils.hmsWithColonsAndMS;
import static loadableUtils.utils.smartIndexOf;
import static loadableUtils.utils.repeat;
import static loadableUtils.utils.structureForUser;
import static loadableUtils.utils.ok;
import static loadableUtils.utils.nohup;
import static loadableUtils.utils.jCheckBox;
import static loadableUtils.utils.onWindowClosing;
import static loadableUtils.utils.asArray;
import static loadableUtils.utils.pt;
import static loadableUtils.utils.showText;
import static loadableUtils.utils.setDefaultClassFinder;
import static loadableUtils.utils.getBytecodePathForClass;
import static loadableUtils.utils.standardCredentials;
import static loadableUtils.utils.installWindowResizeDraggerOnBorder;
import static loadableUtils.utils.singular;
import static loadableUtils.utils.minus;
import static loadableUtils.utils.syncAddOrCreate;
import static loadableUtils.utils.keysList;
import static loadableUtils.utils.intRange;
import static loadableUtils.utils.getScreenHeight;
import static loadableUtils.utils.boolPar;
import static loadableUtils.utils.fillRect;
import static loadableUtils.utils.westCenterAndEastWithMargin;
import static loadableUtils.utils.indentx;
import static loadableUtils.utils.getSelectedItem;
import static loadableUtils.utils.loadAllClassesInByteCodePath;
import static loadableUtils.utils.isChecked;
import static loadableUtils.utils.similarEmptyMap;
import static loadableUtils.utils.toFile;
import static loadableUtils.utils.tempAdd;
import static loadableUtils.utils.appendToBaseName;
import static loadableUtils.utils.dropFirst;
import static loadableUtils.utils.nClasses;
import static loadableUtils.utils.mod;
import static loadableUtils.utils.makeUndecoratedFrame;
import static loadableUtils.utils.findClass;
import static loadableUtils.utils.humanizeFormLabel;
import static loadableUtils.utils.wrapForSmartAdd;
import static loadableUtils.utils.asSet;
import static loadableUtils.utils.autoFrameTitle;
import static loadableUtils.utils.restart;
import static loadableUtils.utils.installTrayIcon;
import static loadableUtils.utils.shootScreen2;
import static loadableUtils.utils.filter;
import static loadableUtils.utils.mapPut;
import static loadableUtils.utils.onChange;
import static loadableUtils.utils.pingSource;
import static loadableUtils.utils.mapToParams;
import static loadableUtils.utils.isNonEmptySingleZip_byMagicHeader;
import static loadableUtils.utils.withTopMargin;
import static loadableUtils.utils.error;
import static loadableUtils.utils.setBackground;
import static loadableUtils.utils.sysNow;
import static loadableUtils.utils.elapsedSeconds;
import static loadableUtils.utils.hotwire;
import static loadableUtils.utils.heldInstance;
import static loadableUtils.utils.getProgramName;
import static loadableUtils.utils.trayIcon_imageAutoSize;
import loadableUtils.utils.Pair;
import loadableUtils.utils.IBWImage;
import loadableUtils.utils.WidthAndHeight;
import loadableUtils.utils.Enterable;
import loadableUtils.utils.G2Drawable;
import static loadableUtils.utils.getPrintLog;
import static loadableUtils.utils.unstructure;
import static loadableUtils.utils.StefansOS_ConnectToServer;
import static loadableUtils.utils._MethodCache;
import static loadableUtils.utils.defaultMargin;
import static loadableUtils.utils.preferredScreen;
import javax.swing.border.*;
import java.text.NumberFormat;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.geom.*;
import java.text.SimpleDateFormat;
import java.nio.charset.Charset;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.*;

class main {

  static public String programID;

  static public void _onLoad_initUtils() {
    utils.__javax = javax();
  }

  static public void _onLoad_defaultClassFinder() {
    setDefaultClassFinder(new F1<String, Class>() {

      public Class get(String name) {
        name = replacePrefix("loadableUtils.utils$", "main$", name);
        print("_onLoad_defaultClassFinder " + name);
        Class c = findClass_fullName(name);
        if (c != null)
          return c;
        if (name.startsWith("main$"))
          return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
        return null;
      }
    });
  }

  static public ThreadLocal<Boolean> dynamicObjectIsLoading_threadLocal() {
    return DynamicObject_loading;
  }

  static public class GazelleScreenCam extends DynModule {

    volatile public boolean enabled = true;

    transient public JPanel buttons;

    public void setEnabled(boolean b) {
      setField("enabled", b);
    }

    public JComponent visualize_enabled() {
      return dm_checkBox("enabled");
    }

    public int pixelRows = 128, colors = 8;

    public String script, testScreenScript;

    public boolean animate = true;

    public boolean horizontalLayout = false;

    public WatchTarget watchTarget;

    transient public ImageSurface isPosterized, isRegions, isTestScreen;

    transient public ScreenCamStream images = new ScreenCamStream();

    transient public BWIntegralImageStream integralImages = new BWIntegralImageStream();

    transient public SourceTriggeredStream<BWImage> scaledAndPosterizedImages = new SourceTriggeredStream();

    transient public DoubleFPSCounter fpsCounter = new DoubleFPSCounter();

    transient public int fps;

    transient public WatchTargetSelector watchTargetSelector;

    transient public RollingAverage remainingMSPerFrame = new RollingAverage();

    transient public int remainingMS;

    transient public FunctionTimings<String> functionTimings = new FunctionTimings();

    transient public ReliableSingleThread rstRunScript = dm_rst(me(), new Runnable() {

      public void run() {
        try {
          _runScript();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "_runScript();";
      }
    });

    transient public JGazelleVScriptRunner scriptRunner;

    transient public JGazelleVScriptRunner testScreenScriptRunner;

    transient public Animation animation;

    transient public FastRegions_BWImage mainScreenRegions;

    transient public ImageSurface_HighlightRegion regionHighlighter;

    transient public UIURLSystem uiURLs;

    transient public Concepts concepts;

    public String uiURL;

    public void start() {
      try {
        super.start();
        dm_onFieldChange("horizontalLayout", new Runnable() {

          public void run() {
            try {
              dm_reload();
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "dm_reload();";
          }
        });
        if (concepts == null) {
          db();
          concepts = db_mainConcepts();
        }
        uiURLs = new UIURLSystem(me(), dm_fieldLiveValue("uiURL"));
        scriptRunner = new JGazelleVScriptRunner(dm_fieldLiveValue("script", me()));
        testScreenScriptRunner = new JGazelleVScriptRunner(dm_fieldLiveValue("testScreenScript", me()));
        images.directlyFeedInto(integralImages);
        integralImages.onNewElement(ii -> scaledAndPosterizedImages.newElement(posterizeBWImage_withMeta(colors, scaledBWImageFromBWIntegralImage_withMeta_height(pixelRows, ii))));
        integralImages.onNewElement(new Runnable() {

          public void run() {
            try {
              if (shouldRunScript())
                rstRunScript.go();
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "if (shouldRunScript()) rstRunScript.go();";
          }
        });
        scaledAndPosterizedImages.onNewElement(img -> {
          fpsCounter.inc();
          setField("fps", iround(fpsCounter.get()));
          {
            if (isPosterized != null)
              isPosterized.setImage_thisThread(img);
          }
          floodFill(img);
        });
        dm_doEvery(1000 / 20, new Runnable() {

          public void run() {
            try {
              if (enabled) {
                {
                  if (watchTargetSelector != null)
                    watchTargetSelector.updateScreenCount();
                }
                Timestamp deadline = tsNowPlusMS(1000 / 20);
                if (watchTarget instanceof WatchScreen)
                  images.useScreen(((WatchScreen) watchTarget).screenNr - 1);
                else if (watchTarget instanceof WatchMouse)
                  images.area(mouseArea(((WatchMouse) watchTarget).width, ((WatchMouse) watchTarget).height));
                images.step();
                long remaining = deadline.minus(tsNow());
                remainingMSPerFrame.add(remaining);
                setField("remainingMS", iround(remainingMSPerFrame.get()));
              }
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "if (enabled) {\r\n        watchTargetSelector?.updateScreenCount();\r\n        Ti...";
          }
        });
      } catch (Exception __e) {
        throw rethrow(__e);
      }
    }

    public ImageSurface stdImageSurface() {
      return pixelatedImageSurface().setAutoZoomToDisplay(true).repaintInThread(false);
    }

    public JComponent visualize() {
      isPosterized = stdImageSurface();
      regionHighlighter = new ImageSurface_HighlightRegion(isPosterized);
      regionHighlighter.regionPainter(new RegionFillPainter());
      isRegions = stdImageSurface();
      isTestScreen = stdImageSurface();
      awtEvery(isTestScreen, 1000 / 20, new Runnable() {

        public void run() {
          try {
            stepAnimation();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "stepAnimation();";
        }
      });
      JTextArea taTimings = jTextArea_noUndo();
      awtEveryAndNow(taTimings, .5, new Runnable() {

        public void run() {
          try {
            setText(taTimings, renderFunctionTimings());
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "setText(taTimings, renderFunctionTimings())";
        }
      });
      var jSpeedInfo = dm_transientCalculatedToolTip(() -> speedInfo_long(), rightAlignLabel(dm_transientCalculatedLabel(() -> speedInfo())));
      print("Labels: " + list(concepts, Label.class));
      SimpleCRUD_v2 labelCRUD = new SimpleCRUD_v2(concepts, Label.class);
      labelCRUD.hideFields("globalID");
      labelCRUD.addCountToEnclosingTab(true);
      SimpleCRUD_v2 imageCRUD = new SimpleCRUD_v2(concepts, SavedImage.class);
      imageCRUD.addCountToEnclosingTab(true);
      var tabs = scrollingTabs(jTopOrLeftTabs(horizontalLayout, "Posterized", withTools(isPosterized), "Regions", jscroll_centered_borderless(isRegions), "Labels", labelCRUD.make_dontStartBots(), "Saved Images", imageCRUD.make_dontStartBots(), "Script", scriptRunner.scriptAndResultPanel(), "Test Screen", testScreenPanel(), "Timings", withRightAlignedButtons(taTimings, "Reset", new Runnable() {

        public void run() {
          try {
            resetTimings();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "resetTimings();";
        }
      })));
      labelCRUD.update();
      imageCRUD.update();
      watchTargetSelector = new WatchTargetSelector();
      var vis = northAndCenter(withSideAndTopMargin(uiURLs.urlBar()), centerAndSouthOrEast(horizontalLayout, horizontalLayout ? withMargin(tabs) : withSideMargin(tabs), (borderlessScrollPane(jHigherScrollPane(jfullcenter(vstack(withLeftAndRightMargin(hstack(dm_rcheckBox("enabled", "Watch"), watchTargetSelector.visualize(), jlabel(" in "), withLabelToTheRight("colors @ ", dm_spinner("colors", 2, 256)), withLabelToTheRight("p", dm_powersOfTwoSpinner("pixelRows", 512)))), verticalStrut(2), withRightMargin(jSpeedInfo))))))));
      setHorizontalMarginForAllButtons(vis, 4);
      return vis;
    }

    public String speedInfo() {
      return "FPS " + fps + " idle " + remainingMS + " ms";
    }

    public String speedInfo_long() {
      return "Screen cam running at " + nFrames(fps) + "/second. " + n2(remainingMS) + " ms remaining per frame in first core.";
    }

    public void floodFill(BWImage img) {
      FastRegions_BWImage ff = new FastRegions_BWImage(img);
      ff.collectBounds();
      functionTimings.time("Regions", ff);
      mainScreenRegions = ff;
      {
        if (regionHighlighter != null)
          regionHighlighter.setRegions(ff);
      }
      if (isRegions != null && isRegions.isShowing_quick()) {
        isRegions.setImage_thisThread(ff.regionsImage());
      }
      setEnclosingTabTitle(isRegions, nRegions(ff.regionCount()));
    }

    public boolean useErrorHandling() {
      return false;
    }

    public String renderFunctionTimings() {
      return lines(ciSorted(map(functionTimings.get(), (f, avg) -> firstToUpper(f) + ": " + n2(iround(nsToMicroseconds(avg.get()))) + " " + microSymbol() + "s (" + n2(iround(avg.n())) + ")")));
    }

    transient public long _runScript_idx;

    public void _runScript() {
      long n = integralImages.elementCount();
      if (n > _runScript_idx) {
        _runScript_idx = n;
        scriptRunner.parseAndRunOn(integralImages.get());
      }
    }

    public boolean shouldRunScript() {
      return isShowing(scriptRunner.scpScriptResult);
    }

    public void stepAnimation() {
      if (!animate)
        return;
      if (animation == null) {
        animation = new AnimatedLine();
        animation.start();
      }
      animation.nextFrame();
      var img = whiteImage(animation.w, animation.h);
      animation.setGraphics(createGraphics(img));
      animation.paint();
      {
        if (isTestScreen != null)
          isTestScreen.setImage(img);
      }
      var ii = bwIntegralImage_withMeta(img);
      testScreenScriptRunner.parseAndRunOn(ii);
    }

    public JComponent testScreenPanel() {
      return centerAndSouthWithMargin(hsplit(northAndCenterWithMargin(centerAndEastWithMargin(jlabel("Input"), dm_fieldCheckBox("animate")), jscroll_centered_borderless(isTestScreen)), northAndCenterWithMargin(centerAndEastWithMargin(jlabel("Output"), testScreenScriptRunner.lblScore), testScreenScriptRunner.scpScriptResult)), testScreenScriptRunner.scriptInputField());
    }

    public List popDownItems() {
      return ll(jCheckBoxMenuItem_dyn("Horizontal Layout", () -> horizontalLayout, b -> setField("horizontalLayout", b)));
    }

    public void unvisualize() {
    }

    public void resetTimings() {
      functionTimings.reset();
    }

    public JComponent withTools(ImageSurface is) {
      new ImageSurface_PositionToolTip(is);
      return centerAndEastWithMargin(jscroll_centered_borderless(is), vstackWithSpacing(3, jbutton("A"), jbutton("B"), jbutton("C")));
    }

    public class WatchTargetSelector {

      public JComboBox<WatchTarget> cb = jComboBox();

      public int screenCount;

      public JComponent visualize() {
        updateList();
        print("Selecting watchTarget: " + watchTarget);
        selectItem(cb, watchTarget);
        loadableUtils.utils.onChange(cb, watchTarget -> {
          setField("watchTarget", watchTarget);
          print("Chose watchTarget: " + GazelleScreenCam.this.watchTarget);
        });
        return cb;
      }

      public void updateScreenCount() {
        if (screenCount != screenCount())
          updateList();
      }

      public void updateList() {
        swing(() -> {
          setComboBoxItems(cb, makeWatchTargets());
        });
      }

      public List<WatchTarget> makeWatchTargets() {
        return flattenToList(countIteratorAsList_incl(1, screenCount = screenCount(), i -> new WatchScreen(i)), new WatchMouse());
      }
    }
  }

  static public boolean _moduleClass_GazelleScreenCam = true;

  static public class Label extends ConceptWithGlobalID {

    public String name;

    public String toString() {
      return "Label " + name;
    }
  }

  static public class SavedImage extends Concept {

    public File path;
  }

  static public class SavedRegion extends Concept {

    static final public String _fieldOrder = "image area";

    public Concept image;

    public Rect area;
  }

  static public class ExampleForLabel extends Concept {

    static final public String _fieldOrder = "label example confidence";

    public Ref<Label> label = new Ref();

    public Ref example = new Ref();

    public double confidence = 1;
  }

  static public class IfThenTheory extends Concept {

    public Ref if_ = new Ref();

    public Ref then = new Ref();
  }

  static public class WatchTarget {
  }

  static public class WatchScreen extends WatchTarget implements IFieldsToList {

    public int screenNr;

    public WatchScreen() {
    }

    public WatchScreen(int screenNr) {
      this.screenNr = screenNr;
    }

    public boolean equals(Object o) {
      if (!(o instanceof WatchScreen))
        return false;
      WatchScreen __1 = (WatchScreen) o;
      return screenNr == __1.screenNr;
    }

    public int hashCode() {
      int h = -1787428357;
      h = boostHashCombine(h, _hashCode(screenNr));
      return h;
    }

    public Object[] _fieldsToList() {
      return new Object[] { screenNr };
    }

    public String toString() {
      return "Screen " + screenNr;
    }
  }

  static public class WatchMouse extends WatchTarget implements IFieldsToList {

    static final public String _fieldOrder = "width height";

    public int width;

    public int height;

    public WatchMouse(int width, int height) {
      this.height = height;
      this.width = width;
    }

    public boolean equals(Object o) {
      if (!(o instanceof WatchMouse))
        return false;
      WatchMouse __2 = (WatchMouse) o;
      return width == __2.width && height == __2.height;
    }

    public int hashCode() {
      int h = 1876823350;
      h = boostHashCombine(h, _hashCode(width));
      h = boostHashCombine(h, _hashCode(height));
      return h;
    }

    public Object[] _fieldsToList() {
      return new Object[] { width, height };
    }

    public WatchMouse() {
      height = 256;
      width = iround(height * 16.0 / 9);
    }

    public String toString() {
      return "Mouse";
    }
  }

  static public void standaloneInit() {
    __javax = x30.class;
    x30.__javax = x30.class;
    x30_pkg.x30_util.__setJavaX(x30.class);
    x30.cleanKillMsg = "";
    callOnLoadMethods(mc());
  }

  static public class PrintLogModule extends DynPrintLog {

    public PrintLogModule() {
      setModuleName("Print Log");
    }

    public String getPrintLog() {
      return printLog();
    }

    public boolean useErrorHandling() {
      return false;
    }
  }

  static public class Stem extends Concept {

    static final public String _fieldOrder = "host module frameRect maximized alwaysOnTop autoUpdate window btnMax";

    transient public GazelleHost host;

    public DynModule module;

    public Rect frameRect;

    public boolean maximized, alwaysOnTop, autoUpdate;

    transient public JFrame window;

    transient public JButton btnMax;

    public Stem() {
    }

    public Stem(GazelleHost host) {
      this.host = host;
    }

    public Stem(GazelleHost host, DynModule module) {
      this.module = module;
      this.host = host;
    }

    public Rect getFrameRect() {
      return toRect(getBounds(window));
    }

    public void saveFrameRect() {
      setField("frameRect", getFrameRect());
    }

    public void setAlwaysOnTop(boolean alwaysOnTop) {
      this.alwaysOnTop = alwaysOnTop;
      change();
      alwaysOnTop(window, alwaysOnTop);
    }

    public void setWindow(JFrame window) {
      this.window = window;
      if (frameRect != null)
        setBounds(window, frameRect);
      onBoundsChange(window, new Runnable() {

        public void run() {
          try {
            saveFrameRect();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "saveFrameRect();";
        }
      });
      alwaysOnTop(window, alwaysOnTop);
    }

    public boolean isMain() {
      return this == host.stem;
    }

    public void minimize() {
      if (host.trayIcon == null || !isMain())
        minimizeWindow(window);
      else
        hideWindow(window);
    }

    public void deleteMe() {
      printAlsoToSystemOut = true;
      print("deleteMe " + isMain());
      if (isMain()) {
        host.cleanExit();
      } else {
        disposeWindow(window);
        {
          cleanUp(module);
          module = null;
        }
        cdelete(this);
      }
    }

    public void grabWindowState() {
      setField("maximized", !isExtendedStateNormal(window));
    }

    public void updateBtnMax() {
      if (!isShowing(btnMax))
        return;
      grabWindowState();
      setText(btnMax, maximized ? "NORM" : "MAX");
    }

    public JComponent makeWindowBorderAndTitle(JComponent contents, String title) {
      var icons = jline();
      if (host.allowFrameMaximization) {
        icons.add(btnMax = jbutton("", runnableThread(new Runnable() {

          public void run() {
            try {
              maximizeOrRestoreFrame(window);
              updateBtnMax();
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "maximizeOrRestoreFrame(window);\r\n        updateBtnMax();";
          }
        })));
        onFirstShowing(btnMax, new Runnable() {

          public void run() {
            try {
              updateBtnMax();
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "updateBtnMax();";
          }
        });
      }
      icons.add(jbutton("MIN", new Runnable() {

        public void run() {
          try {
            minimize();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "minimize();";
        }
      }));
      icons.add(jbutton("QUIT", runnableThread(new Runnable() {

        public void run() {
          try {
            if (swingConfirm("Really quit Gazelle?"))
              deleteMe();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (swingConfirm(\"Really quit Gazelle?\"))\r\n        deleteMe();";
        }
      })));
      setHorizontalMarginForAllButtons(icons, 4);
      icons.add(jPopDownButton_noText(flattenToList(!isMain() ? null : ll("Restart", runnableThread(new Runnable() {

        public void run() {
          try {
            host.restart();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "host.restart()";
        }
      }), "Update Gazelle", runnableThread(new Runnable() {

        public void run() {
          try {
            host.upgradeGazelle();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "host.upgradeGazelle()";
        }
      }), jCheckBoxMenuItem_dyn("Auto-Update", () -> autoUpdate, b -> cset(Stem.this, "autoUpdate", b))), "---", jCheckBoxMenuItem_dyn("Always on top", () -> alwaysOnTop, alwaysOnTop -> setAlwaysOnTop(alwaysOnTop)), "---", !isMain() ? null : ll("Screenshoot this window", runnableThread(new Runnable() {

        public void run() {
          try {
            shootWindow();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "shootWindow();";
        }
      }), "Dump threads", runnableThread(new Runnable() {

        public void run() {
          try {
            showText("User threads", renderUserThreadsWithStackTraces());
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "showText(\"User threads\", renderUserThreadsWithStackTraces());";
        }
      }), !isMain() ? null : "Print log", !isMain() ? null : runnableThread(new Runnable() {

        public void run() {
          try {
            host.showPrintLog();
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "host.showPrintLog()";
        }
      })), ccallOpt(module, "popDownItems"))));
      JComponent actualTitle = fontSizePlus(7, jCenteredLabel(title));
      installWindowDragger(actualTitle);
      if (isMain() && haveMuricaPassword())
        actualTitle = centerAndEastWithMargin(actualTitle, compileButton());
      var spacer = gazelle_wavySpacer();
      var titleBarMain = setOpaqueBackground(host.color1, jtransparent_recursive(westCenterAndEastWithMargin(jImage_scaledToHeight(24, host.trayIconImageID), actualTitle, setOpaqueBackground(host.color2, spacer))));
      installWindowDragger(spacer);
      var titleBar = setBackground(host.color2, centerAndEast(titleBarMain, icons));
      var border = BorderFactory.createLineBorder(host.color1, host.borderSize);
      var outerPanel = withBorder(border, northAndCenter(titleBar, contents));
      installWindowResizeDraggerOnBorder(outerPanel);
      return outerPanel;
    }

    public JComponent compileButton() {
      return jimageButton(scaleImageToWidth(16, "#1101268"), "Compile & update", disableButtonWhileCalcing3(() -> compile()));
    }

    public void compile() {
      transpileOnServerWithErrorWindow(programID, true, null);
    }

    public void startAndShow() {
      module._host = this;
      setOpt_raw(module, "threadPool", threadPool);
      setOpt_raw(module, "concepts", host.concepts);
      copyLocalLog(module, mc());
      var __15 = makeVisAndTitle();
      var vis = __15.a;
      var title = __15.b;
      printWithMS("Show frame");
      JFrame frame = makeUndecoratedFrame(title, vis);
      setFrameIcon(frame, host.trayIconImageID);
      setWindow(frame);
      showWindow(window);
      if (maximized && host.allowFrameMaximization)
        maximizeFrame(window);
    }

    public Pair<JComponent, String> makeVisAndTitle() {
      JComponent vis;
      {
        AutoCloseable __13 = module.enter();
        try {
          module.start();
          printWithMS("Visualize");
          vis = swing(() -> {
            AutoCloseable __14 = module.enter();
            try {
              return module.visualize();
            } finally {
              _close(__14);
            }
          });
        } finally {
          _close(__13);
        }
      }
      String title = host.windowTitle;
      if (!isMain())
        title += appendWithColon(module.moduleName());
      vis = makeWindowBorderAndTitle(vis, title);
      return pair(vis, title);
    }

    public void revisualize() {
      if (window == null)
        return;
      try {
        module.unvisualize();
      } catch (Throwable __e) {
        printStackTrace(__e);
      }
      var __16 = makeVisAndTitle();
      var vis = __16.a;
      var title = __16.b;
      setFrameContents(window, vis);
    }

    public void shootWindow() {
      var img = renderComponentToImage(window);
      copyImageToClipboard(img);
      saveInImageDirectoryWithCounter("Gazelle/Gazelle", img);
    }
  }

  static public class GazelleHost {

    public boolean _isTransient() {
      return true;
    }

    public Stem stem;

    public DynModule gazelle;

    transient public String windowTitle = "November Gazelle v1";

    transient public String trayIconImageID = "#1103047";

    transient public int borderSize = 5;

    transient public Color color1 = awtColor("ADD8E6");

    transient public Color color2 = awtColor("EEEEEE");

    transient public Color color3 = awtColor("A3C0AA");

    transient public IF0<DynModule> moduleMaker;

    transient public ThreadPool threadPool;

    transient public TrayIcon trayIcon;

    transient public TrayIconLastPosition trayIconLastPosition;

    transient public Set<String> argsSet;

    transient public Concepts concepts;

    transient public boolean allowFrameMaximization = false;

    public GazelleHost(ThreadPool threadPool, IF0<DynModule> moduleMaker) {
      this.moduleMaker = moduleMaker;
      this.threadPool = threadPool;
    }

    public void trayIconLeftClick() {
      activateFrame_v3(mainWindow());
    }

    public void makeTrayIcon() {
      try {
        trayIcon_imageAutoSize = false;
        trayIcon = installTrayIcon(trayIconImageID, windowTitle, new Runnable() {

          public void run() {
            try {
              trayIconLeftClick();
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "trayIconLeftClick();";
          }
        }, "Show Gazelle", new Runnable() {

          public void run() {
            try {
              trayIconLeftClick();
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "trayIconLeftClick();";
          }
        }, "Exit Gazelle", new Runnable() {

          public void run() {
            try {
              cleanExit();
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "cleanExit();";
          }
        });
        trayIconLastPosition = new TrayIconLastPosition(trayIcon);
      } catch (Throwable __e) {
        print(exceptionToStringShort(__e));
      }
    }

    public void run(String[] args) {
      try {
        run2(args);
      } catch (Throwable e) {
        printStackTrace(e);
        hideTrayIcon(trayIcon);
        onWindowClosing(() -> systemExit(1), getWindow(showText_fast_noWrap("Gazelle Error", renderStackTrace(e))));
      }
    }

    public void run2(String[] args) {
      argsSet = asSet(args);
      if (!argsSet.contains("noflatlaf"))
        com.formdev.flatlaf.FlatLightLaf.setup();
      if (contains(args, "profile"))
        profileToConsole(() -> actualMain(args));
      else
        actualMain(args);
      if (argsSet.contains("brexit"))
        System.exit(0);
    }

    public void actualMain(String... args) {
      vm_generalMap_put("stefansOS", this);
      System.out.println(hmsWithColonsAndMS() + ": Init");
      if (containsOneOf(argsSet, "upgrade", "update")) {
        upgradeGazelle();
        return;
      }
      makeTrayIcon();
      initAutoUpdate();
      assertEquals(callF(_defaultClassFinder(), "main$Stem"), Stem.class);
      concepts = newConceptsWithClassFinder(programID);
      concepts.makeStructureData = () -> {
        structure_Data data = concepts.makeStructureData_base();
        data.mcDollar = mcDollar();
        return data;
      };
      concepts.fileLock().lockOrFail();
      concepts.fileLock().deleteOnExit();
      concepts.persist();
      print("Concepts loaded: " + map(__33 -> className(__33), allConcepts(concepts)));
      var stems = findConcepts(concepts, Stem.class);
      print("Stems in DB: " + l(stems));
      stem = first(stems);
      if (stem == null) {
        print("Starting new module");
        makeModule();
        stem = registerConcept(concepts, new Stem(this, gazelle));
      }
      gazelle = stem.module;
      for (var stem : list(Stem.class, concepts)) {
        stem.host = this;
        stem.startAndShow();
      }
      printWithMS("Dudadoneski");
    }

    public void showPrintLog() {
      registerConcept(concepts, new Stem(this, new PrintLogModule())).startAndShow();
    }

    public JFrame mainWindow() {
      return stem == null ? null : stem.window;
    }

    public Object dm_getStem(Object moduleOrID) {
      return stem;
    }

    public Object resolveModule(Object moduleOrID) {
      return moduleOrID == stem ? gazelle : moduleOrID;
    }

    public void cleanExit() {
      {
        startThread(new Runnable() {

          public void run() {
            try {
              print("Saving DB for exit");
              {
                cleanUp(concepts);
                concepts = null;
              }
              System.exit(0);
            } catch (Exception __e) {
              throw rethrow(__e);
            }
          }

          public String toString() {
            return "print(\"Saving DB for exit\");\r\n      { cleanUp(concepts); concepts = null; }\r\n...";
          }
        });
      }
    }

    public File myJar() {
      return getBytecodePathForClass(this);
    }

    public void upgradeGazelle() {
      File myJar = myJar();
      print("myJar", myJar);
      String date = ymdMinusHMS();
      File f = javaxCodeDir("Downloaded Updates/" + "gazelle-" + date + ".jar");
      infoBox("Downloading Update...");
      loadBinaryPageToFile(downloadURL(), f);
      printFileInfo(f);
      if (!isNonEmptySingleZip_byMagicHeader(f)) {
        infoBox("Bad file downloaded... :(");
        return;
      }
      boolean replaced = false;
      if (isFile(myJar)) {
        print("Loaded " + nClasses(loadAllClassesInByteCodePath(myJar)));
        print("Replacing with new version: " + myJar);
        renameFile(myJar, appendToBaseName(myJar, ".bak." + date));
        copyFile(f, myJar);
        printFileInfo(myJar);
        replaced = true;
      }
      infoBox(replaced ? "Installed update, replaced " + f2s(myJar) + " - now starting" : "Starting update, but could not replace originally downloaded jar");
      restart(replaced ? myJar : f);
    }

    public void restart() {
      restart(myJar());
    }

    public void restart(File jar) {
      String javaCmd = or2(currentProcessCommand(), "java");
      String cmd = pqO(javaCmd) + " -jar " + pqO(jar);
      print(cmd);
      nohup(cmd);
      cleanExit();
    }

    public void makeModule() {
      if (gazelle == null)
        gazelle = callF(moduleMaker);
    }

    public void reloadModuleInBackground(Stem mod) {
      restart();
    }

    public void initAutoUpdate() {
      print("Making SnippetUpdateConnector.");
      snippetUpdateConnector("verbose", true);
      vmBus_onMessage("snippetUpdate", new VF1<List>() {

        public void get(List l) {
          try {
            String uri = getString(l, 1);
            Matches m = new Matches();
            if (swic(uri, "/transpileOK/", m))
              if (sameSnippetID(programID(), firstIntAsString(m.rest()))) {
                if (stem.autoUpdate)
                  upgradeGazelle();
              }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "S uri = getString(l, 1);\r\n      new Matches m;\r\n      if (swic(uri, \"/transpi...";
        }
      });
    }

    public String downloadURL() {
      return "https://botcompany.de/jar/" + psI(programID()) + "?withLibs=1&noCompiler=1" + (downloadUncompressedJAR() ? "&uncompressed=1" : "");
    }

    public boolean downloadUncompressedJAR() {
      return false;
    }

    public void revisualizeModule(Stem stem) {
      stem.revisualize();
    }
  }

  static public String windowTitle = "Gazelle 22";

  static public String progIDForDBAndAutoUpdate = "#1033636";

  static public boolean pingSourceStrictMode = false;

  static public GazelleHost host;

  static public GazelleScreenCam client;

  static public ThreadPool threadPool;

  public static void main(final String[] args) throws Exception {
    loadableUtils.utils.__setJavaX(main.class);
    standaloneInit();
    ping_v3_setPingSourceMaker(() -> {
      System.out.println("pingSourceMaker");
      if (pingSourceStrictMode)
        throw fail("Strict mode - make a ping source first!!");
      return new PingSource(threadPool, "legacy");
    });
    threadPool = new ThreadPool(findIntArg("cores", args, numberOfCores()));
    print(threadPool);
    PingSource ps = new PingSource(threadPool, print("Starting Gazelle"));
    ps.dO(() -> {
      System.out.println("Pinging");
      ping();
      print("Pinged");
      programID = progIDForDBAndAutoUpdate;
      preferredScreen = () -> {
        if (host == null)
          return 0;
        var stem = host.stem;
        if (stem == null)
          return 0;
        int screen = max(0, screenNrOfWindow(stem.window));
        print("preferredScreen", screen);
        return screen;
      };
      if (cic(args, "delete-session")) {
        print("Deleting session (" + programDir(programID) + ")");
        clearConceptsOf(programID);
      }
      host = new GazelleHost(threadPool, () -> {
        return client = new GazelleScreenCam();
      });
      if (sameSnippetID(programID, "#1033860"))
        windowTitle += " dev";
      host.windowTitle = windowTitle;
      host.run(args);
      if (!cic(args, "console")) {
        print("Stopping System.out");
        printAlsoToSystemOut = false;
      }
    });
    print("aha.");
  }

  static public Map generalMap = syncMap();

  static volatile public Concepts mainConcepts;

  static public Concepts db_mainConcepts() {
    if (mainConcepts == null)
      mainConcepts = newConceptsWithClassFinder(getDBProgramID());
    return mainConcepts;
  }

  static public void cleanMeUp_concepts() {
    if (db_mainConcepts() != null)
      db_mainConcepts().cleanMeUp();
  }

  static public Class javax() {
    return getJavaX();
  }

  static public String replacePrefix(String prefix, String replacement, String s) {
    if (!startsWith(s, prefix))
      return s;
    return replacement + substring(s, l(prefix));
  }

  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 ReliableSingleThread dm_rst(Runnable r) {
    return dm_rst(dm_current_mandatory(), r);
  }

  static public ReliableSingleThread dm_rst(DynModule mod, Runnable r) {
    return dm_rst(mod, new ReliableSingleThread(r));
  }

  static public ReliableSingleThread dm_rst(DynModule mod, ReliableSingleThread rst) {
    rst.enter = dm_rEnter(mod);
    return rst;
  }

  static public void dm_onFieldChange(String field, Runnable onChange) {
    dm_watchField(field, onChange);
  }

  static public void dm_onFieldChange(Collection<String> fields, Runnable onChange) {
    dm_watchFields(fields, onChange);
  }

  static public BWImage posterizeBWImage_withMeta(int brightnessLevels, BWImage img) {
    return setMetaSrcUnlessSame(img, posterizeBWImage(brightnessLevels, img), functionCall("posterizeBWImage", brightnessLevels, img));
  }

  static public BWImage scaledBWImageFromBWIntegralImage_withMeta(int w, BWIntegralImage img) {
    return scaledBWImageFromBWIntegralImage(img, w);
  }

  static public BWImage scaledBWImageFromBWIntegralImage_withMeta_height(int h, BWIntegralImage img) {
    return scaledBWImageFromBWIntegralImage(img, widthForHeight(img, h), h);
  }

  static public BWImage scaledBWImageFromBWIntegralImage_withMeta(BWIntegralImage img, int w) {
    return scaledBWImageFromBWIntegralImage_withMeta(img, w, heightForWidth(img, w));
  }

  static public BWImage scaledBWImageFromBWIntegralImage_withMeta(BWIntegralImage img, int w, int h) {
    return setMetaSrc(scaledBWImageFromBWIntegralImage(img, w, h), functionCall("scaledBWImageFromBWIntegralImage", img, w, h));
  }

  static public BWImage scaledBWImageFromBWIntegralImage_withMeta(int w, IBWIntegralImage img) {
    return scaledBWImageFromBWIntegralImage(img, w);
  }

  static public BWImage scaledBWImageFromBWIntegralImage_withMeta_height(int h, IBWIntegralImage img) {
    return scaledBWImageFromBWIntegralImage(img, widthForHeight(img, h), h);
  }

  static public BWImage scaledBWImageFromBWIntegralImage_withMeta(IBWIntegralImage img, int w) {
    return scaledBWImageFromBWIntegralImage_withMeta(img, w, heightForWidth(img, w));
  }

  static public BWImage scaledBWImageFromBWIntegralImage_withMeta(IBWIntegralImage img, int w, int h) {
    return setMetaSrc(scaledBWImageFromBWIntegralImage(img, w, h), functionCall("scaledBWImageFromBWIntegralImage", img, w, h));
  }

  static public int iround(double d) {
    return (int) Math.round(d);
  }

  static public int iround(Number n) {
    return iround(toDouble(n));
  }

  static public Timestamp tsNowPlusMS(long ms) {
    return tsNow().plus(msToSeconds(ms));
  }

  static public Rect mouseArea(int w) {
    return mouseArea(w, w);
  }

  static public Rect mouseArea(int w, int h) {
    Point p = mouseLocation();
    return new Rect(p.x - w / 2, p.y - h / 2, w, h);
  }

  static public ImageSurface pixelatedImageSurface() {
    var is = imageSurface();
    imageSurface_pixelated(is);
    return is;
  }

  static public ImageSurface pixelatedImageSurface(MakesBufferedImage img) {
    return pixelatedImageSurface(toBufferedImage(img));
  }

  static public ImageSurface pixelatedImageSurface(BufferedImage img) {
    var is = pixelatedImageSurface();
    is.setImage(img);
    return is;
  }

  static public <A extends JComponent> A awtEvery(A component, long delay, Object r) {
    swingEvery(component, delay, r);
    return component;
  }

  static public <A extends JComponent> 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 extends JComponent> A awtEvery(A component, double delaySeconds, Object r) {
    return awtEvery(component, toMS(delaySeconds), r);
  }

  static public JTextArea jTextArea_noUndo() {
    return jTextArea_noUndo("");
  }

  static public JTextArea jTextArea_noUndo(final String text) {
    return swingNu(JTextArea.class, text);
  }

  static public <A extends JComponent> A awtEveryAndNow(A component, long delay, Object r) {
    swingEvery(component, delay, 0, r);
    return component;
  }

  static public <A extends JComponent> A awtEveryAndNow(A component, double delaySeconds, Object r) {
    return awtEveryAndNow(component, toMS(delaySeconds), r);
  }

  static public void awtEveryAndNow(RootPaneContainer frame, long delay, Object r) {
    swingEvery(frame, delay, 0, r);
  }

  static public <A extends JComponent> A dm_transientCalculatedToolTip(IF0<Object> calc, A component) {
    return toolTipFromLiveValue(dm_transientCalculatedLiveValue(Object.class, calc), component);
  }

  static public <A extends JLabel> A rightAlignLabel(final A a) {
    return setHorizontalAlignment(JLabel.RIGHT, a);
  }

  static public JLabel dm_transientCalculatedLabel(IF0<Object> calc) {
    return jLiveValueLabel(dm_transientCalculatedLiveValue(Object.class, calc));
  }

  static public <A extends Concept> List<A> list(Class<A> type) {
    return list(type, db_mainConcepts());
  }

  static public <A extends Concept> List<A> list(Class<A> type, Concepts cc) {
    return cc.list(type);
  }

  static public <A extends Concept> List<A> list(Concepts concepts, Class<A> type) {
    return concepts.list(type);
  }

  static public List<Concept> list(String type) {
    return db_mainConcepts().list(type);
  }

  static public List<Concept> list(Concepts concepts, String type) {
    return concepts.list(type);
  }

  static public JTabbedPane scrollingTabs(JTabbedPane pane) {
    if (pane != null) {
      swing(() -> {
        pane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
      });
    }
    return pane;
  }

  static public JTabbedPane jTopOrLeftTabs(boolean horizontal, Object... x) {
    return jLeftOrTopTabs(horizontal, x);
  }

  static public JTabbedPane jTopOrLeftTabs(boolean horizontal, Collection c) {
    return jLeftOrTopTabs(horizontal, c);
  }

  static public JScrollPane jscroll_centered_borderless(Component c) {
    return borderlessScrollPane(jscroll_centered(c));
  }

  static public JPanel withRightAlignedButtons(JComponent center, Object... params) {
    return centerAndSouth(center, withMargin(jRightAlignedButtons(params)));
  }

  static public JPanel withRightAlignedButtons(Swingable center, Object... params) {
    return withRightAlignedButtons(wrap(center), params);
  }

  static public JPanel withSideAndTopMargin(Component c) {
    return withSideAndTopMargin(defaultMargin(), c);
  }

  static public JPanel withSideAndTopMargin(int w, Component c) {
    return swing(() -> {
      JPanel p = marginPanel();
      p.setBorder(BorderFactory.createEmptyBorder(w, w, 0, w));
      p.add(c);
      return p;
    });
  }

  static public JPanel centerAndSouthOrEast(boolean horizontal, Component c, Component s) {
    return horizontal ? centerAndEast(c, s) : centerAndSouth(c, s);
  }

  static public JPanel withSideMargin(Component c) {
    return withLeftAndRightMargin(c);
  }

  static public JPanel withSideMargin(int w, Component c) {
    return withLeftAndRightMargin(w, c);
  }

  static public JPanel withSideMargin(int w1, int w2, Component c) {
    return withLeftAndRightMargin(w1, w2, c);
  }

  static public JScrollPane borderlessScrollPane(JScrollPane sp) {
    return setBorder(null, withoutViewportBorder(sp));
  }

  static public JScrollPane jHigherScrollPane(final JComponent c) {
    return swing(new F0<JScrollPane>() {

      public JScrollPane get() {
        try {
          return new JScrollPane(c) {

            public Dimension getPreferredSize() {
              Component view = getViewport().getView();
              if (view == null)
                return super.getPreferredSize();
              int pref_width = view.getPreferredSize().width;
              setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              Dimension dim = new Dimension(pref_width, super.getPreferredSize().height + getHorizontalScrollBar().getSize().height);
              setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              return dim;
            }
          };
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret new JScrollPane(c) {\r\n    public Dimension getPreferredSize() {\r\n      Co...";
      }
    });
  }

  static public JPanel jfullcenter(Component c) {
    return jFullCenter(c);
  }

  static public JPanel vstack(Object... parts) {
    return vstack2(parts);
  }

  static public JPanel vstack(List parts) {
    return vstack(toObjectArray(parts));
  }

  static public JPanel hstack(Object... parts) {
    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.VERTICAL;
    gbc.gridheight = GridBagConstraints.REMAINDER;
    smartAddWithLayout(panel, gbc, parts);
    gbc.weightx = 1;
    panel.add(jrigid(), gbc);
    return panel;
  }

  static public JCheckBox dm_rcheckBox(String field) {
    return dm_fieldCheckBox(field);
  }

  static public JCheckBox dm_rcheckBox(String field, String text) {
    return dm_fieldCheckBox(text, field);
  }

  static public JComponent withLabelToTheRight(JComponent component, String label) {
    return centerAndEast(component, jlabel(" " + label));
  }

  static public JComponent withLabelToTheRight(String label, JComponent component) {
    return withLabelToTheRight(component, label);
  }

  static public JSpinner dm_spinner(String field, int min, int max) {
    return liveValueSpinner(dm_fieldLiveValue(field), min, max);
  }

  static public JSpinner dm_powersOfTwoSpinner(String field, int max) {
    SimpleLiveValue<Integer> lv = dm_fieldLiveValue(field);
    return bindLiveValueToSpinner(lv, jPowersOfTwoSpinner(max, lv.get()));
  }

  static public Component verticalStrut(int height) {
    return Box.createVerticalStrut(height);
  }

  static public int withRightMargin_defaultWidth = 6;

  static public JPanel withRightMargin(Component c) {
    return withRightMargin(withRightMargin_defaultWidth, c);
  }

  static public JPanel withRightMargin(final int w, final Component c) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel p = marginPanel();
          p.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, w));
          p.add(c);
          return p;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel p = marginPanel();\r\n    p.setBorder(BorderFactory.createEmptyBorder(0,...";
      }
    });
  }

  static public void setHorizontalMarginForAllButtons(int margin, Component c) {
    for (var btn : allButtons(c)) setHorizontalMargin(btn, margin);
  }

  static public void setHorizontalMarginForAllButtons(Component c, int margin) {
    setHorizontalMarginForAllButtons(margin, c);
  }

  static public String nFrames(long n) {
    return n2(n, "frame");
  }

  static public String nFrames(Collection l) {
    return nFrames(l(l));
  }

  static public String nFrames(Map map) {
    return nFrames(l(map));
  }

  static public String n2(long l) {
    return formatWithThousands(l);
  }

  static public String n2(AtomicLong l) {
    return n2(l.get());
  }

  static public String n2(Collection l) {
    return n2(l(l));
  }

  static public String n2(Map map) {
    return n2(l(map));
  }

  static public String n2(double l, String singular) {
    return empty(singular) ? str(l) : 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 empty(singular) ? n2(l) : n_fancy2(l, singular, singular + "s");
  }

  static public String n2(Collection l, String singular) {
    return n2(l(l), singular);
  }

  static public String n2(Collection l, String singular, String plural) {
    return n_fancy2(l, singular, plural);
  }

  static public String n2(Map m, String singular, String plural) {
    return n_fancy2(m, singular, plural);
  }

  static public String n2(Map m, String singular) {
    return n2(l(m), singular);
  }

  static public String n2(long[] a, String singular) {
    return n2(l(a), singular);
  }

  static public String n2(Object[] a, String singular) {
    return n2(l(a), singular);
  }

  static public String n2(Object[] a, String singular, String plural) {
    return n_fancy2(a, singular, plural);
  }

  static public String n2(MultiSet ms, String singular, String plural) {
    return n_fancy2(ms, singular, plural);
  }

  static public void setEnclosingTabTitle(JComponent c, String title) {
    swing(() -> {
      Pair<JTabbedPane, Integer> p = enclosingTab(c);
      if (p == null)
        return;
      setTabTitle(p.a, p.b, title);
    });
  }

  static public String nRegions(long n) {
    return n2(n, "region");
  }

  static public String nRegions(Collection l) {
    return nRegions(l(l));
  }

  static public String nRegions(Map map) {
    return nRegions(l(map));
  }

  static public String lines(Iterable lines) {
    return fromLines(lines);
  }

  static public String lines(Object[] lines) {
    return fromLines(asList(lines));
  }

  static public List<String> lines(String s) {
    return toLines(s);
  }

  static public <A> String lines(Iterable<A> l, IF1<A, String> f) {
    return mapToLines(l, f);
  }

  static public List<String> ciSorted(Collection<String> c) {
    return sortedIgnoreCase(c);
  }

  static public List map(Iterable l, Object f) {
    return map(f, l);
  }

  static public List map(Object f, Iterable l) {
    List x = emptyList(l);
    if (l != null)
      for (Object o : l) {
        ping();
        x.add(callF(f, o));
      }
    return x;
  }

  static public <A, B> List<B> map(Iterable<A> l, F1<A, B> f) {
    return map(f, l);
  }

  static public <A, B> List<B> map(F1<A, B> f, Iterable<A> l) {
    List x = emptyList(l);
    if (l != null)
      for (A o : l) {
        ping();
        x.add(callF(f, o));
      }
    return x;
  }

  static public <A, B> List<B> map(IF1<A, B> f, Iterable<A> l) {
    return map(l, f);
  }

  static public <A, B> List<B> map(Iterable<A> l, IF1<A, B> f) {
    List x = emptyList(l);
    if (l != null)
      for (A o : l) {
        ping();
        x.add(f.get(o));
      }
    return x;
  }

  static public <A, B> List<B> map(IF1<A, B> f, A[] l) {
    return map(l, f);
  }

  static public <A, B> List<B> map(A[] l, IF1<A, B> f) {
    List x = emptyList(l);
    if (l != null)
      for (A o : l) {
        ping();
        x.add(f.get(o));
      }
    return x;
  }

  static public List map(Object f, Object[] l) {
    return map(f, asList(l));
  }

  static public List map(Object[] l, Object f) {
    return map(f, l);
  }

  static public List map(Object f, Map map) {
    return map(map, f);
  }

  static public List map(Map map, Object f) {
    List x = new ArrayList();
    if (map != null)
      for (Object _e : map.entrySet()) {
        ping();
        Map.Entry e = (Map.Entry) _e;
        x.add(callF(f, e.getKey(), e.getValue()));
      }
    return x;
  }

  static public <A, B, C> List<C> map(Map<A, B> map, IF2<A, B, C> f) {
    return map(map, (Object) f);
  }

  static public <A, B> List<A> map(IF1<A, B> f, A data1, A... moreData) {
    List x = emptyList(l(moreData) + 1);
    x.add(f.get(data1));
    if (moreData != null)
      for (A o : moreData) {
        ping();
        x.add(f.get(o));
      }
    return x;
  }

  static public double nsToMicroseconds(double ns) {
    return nanosToMicroseconds(ns);
  }

  static public String microSymbol() {
    return "\u00B5";
  }

  static public boolean isShowing(Component c) {
    return isComponentShowing(c);
  }

  static public BufferedImage whiteImage(int w, int h) {
    return newBufferedImage(w, h, Color.white);
  }

  static public BufferedImage whiteImage(int size) {
    return whiteImage(size, size);
  }

  static public Map<BufferedImage, Object> createGraphics_modulators = synchroIdentityHashMap();

  static public Graphics2D createGraphics(BufferedImage img) {
    Graphics2D g = img.createGraphics();
    Object mod = createGraphics_modulators.get(img);
    if (mod != null)
      callF(mod, g);
    return g;
  }

  static public void createGraphics_modulate(BufferedImage img, Object mod) {
    mapPut2(createGraphics_modulators, img, mod);
  }

  static public BWIntegralImage bwIntegralImage_withMeta(BufferedImage img) {
    return setMetaSrc(bwIntegralImage(img), img);
  }

  static public BWIntegralImage bwIntegralImage_withMeta(BWImage img) {
    return setMetaSrc(bwIntegralImage(img), img);
  }

  static public JPanel centerAndSouthWithMargin(Component c, Component s) {
    return centerAndSouth(c, withTopMargin(s));
  }

  static public JPanel centerAndSouthWithMargin(int margin, Component c, Component s) {
    return centerAndSouth(c, withTopMargin(margin, s));
  }

  static public <A> List<A> ll(A... a) {
    ArrayList l = new ArrayList(a.length);
    if (a != null)
      for (A x : a) l.add(x);
    return l;
  }

  static public JCheckBoxMenuItem jCheckBoxMenuItem_dyn(String text, IF0<Boolean> checked, Object r) {
    JCheckBoxMenuItem mi = jCheckBoxMenuItem(text, false, r);
    if (checked != null)
      bindToComponent(mi, new Runnable() {

        public void run() {
          try {
            boolean b = isTrue(checked.get());
            setChecked(mi, b);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "boolean b = isTrue(checked!);\r\n    ifdef jCheckBoxMenuItem_dyn_debug\r\n      p...";
        }
      }, new Runnable() {

        public void run() {
          try {
            ;
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "ifdef jCheckBoxMenuItem_dyn_debug\r\n      print(\"jCheckBoxMenuItem_dyn: hiding...";
        }
      });
    return mi;
  }

  static public JCheckBoxMenuItem jCheckBoxMenuItem_dyn(String text, IF0<Boolean> checked, IVF1<Boolean> r) {
    return jCheckBoxMenuItem_dyn(text, checked, (Object) r);
  }

  static public int vstackWithSpacing_default = 10;

  static public JPanel vstackWithSpacing(final List parts) {
    return vstackWithSpacing(parts, vstackWithSpacing_default);
  }

  static public JPanel vstackWithSpacing(final List parts, final int spacing) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new GridBagLayout());
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.weightx = 1;
          gbc.fill = GridBagConstraints.HORIZONTAL;
          gbc.gridwidth = GridBagConstraints.REMAINDER;
          gbc.insets = new Insets(spacing / 2, 0, (spacing + 1) / 2, 0);
          smartAddWithLayout(panel, gbc, toObjectArray(nonNulls(parts)));
          gbc.weighty = 1;
          gbc.insets = new Insets(0, 0, 0, 0);
          panel.add(jrigid(), gbc);
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new GridBagLayout);\r\n    new GridBagConstraints gbc...";
      }
    });
  }

  static public JPanel vstackWithSpacing(Component... parts) {
    return vstackWithSpacing(asList(parts), vstackWithSpacing_default);
  }

  static public JPanel vstackWithSpacing(int spacing, Component... parts) {
    return vstackWithSpacing(asList(parts), spacing);
  }

  static public JComboBox jComboBox(final String... items) {
    return jcombobox(items);
  }

  static public JComboBox jComboBox(Collection<String> items) {
    return jcombobox(items);
  }

  static public JComboBox jComboBox(Collection<String> items, String selectedItem) {
    return jcombobox(items, selectedItem);
  }

  static public <A> JComboBox<A> selectItem(A item, JComboBox<A> cb) {
    if (cb != null) {
      swing(() -> {
        cb.setSelectedItem(item);
      });
    }
    return cb;
  }

  static public <A> JComboBox<A> selectItem(JComboBox<A> cb, A item) {
    return selectItem(item, cb);
  }

  static public <A> JList<A> selectItem(JList<A> list, A item) {
    {
      swing(() -> {
        selectRow(list, jlist_indexOf(list, item));
      });
    }
    return list;
  }

  static public int screenCount() {
    return l(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices());
  }

  static public Object swing(Object f) {
    return swingAndWait(f);
  }

  static public void swing(Runnable f) {
    swingAndWait(f);
  }

  static public <A> A swing(F0<A> f) {
    return (A) swingAndWait(f);
  }

  static public <A> A swing(IF0<A> f) {
    return (A) swingAndWait(f);
  }

  static public <A> void setComboBoxItems(JComboBox<A> cb, Collection<A> items) {
    if (cb != null) {
      swing(() -> {
        cb.setModel(new DefaultComboBoxModel(new Vector(items)));
      });
    }
  }

  static public List flattenToList(Object... l) {
    Flattener f = new Flattener();
    f.add(l);
    return f.toList();
  }

  static public List<Integer> countIteratorAsList_incl(int b) {
    return countIteratorAsList_incl(0, b);
  }

  static public List<Integer> countIteratorAsList_incl(int a, int b) {
    return countIteratorToList_inclusive(a, b);
  }

  static public <A> List<A> countIteratorAsList_incl(int b, IF1<Integer, A> f) {
    return countIteratorAsList_incl(0, b, f);
  }

  static public <A> List<A> countIteratorAsList_incl(int a, int b, IF1<Integer, A> f) {
    return countIteratorToList_inclusive(a, b, f);
  }

  static public List<Integer> countIteratorAsList_incl(int a, int b, int step) {
    return countIteratorToList_inclusive(a, b, step);
  }

  static public <A> List<A> countIteratorAsList_incl(double a, double b, double step, IF1<Double, A> f) {
    return countIteratorToList_inclusive(a, b, step, f);
  }

  static public <A> List<Double> countIteratorAsList_incl(double a, double b, double step) {
    return countIteratorToList_inclusive(a, b, step);
  }

  static public <A> List<A> countIteratorAsList_incl(IF1<Double, A> f, double a, double b, double step) {
    return countIteratorToList_inclusive(f, a, b, step);
  }

  static public <A> List<A> countIteratorAsList_incl(IF1<Integer, A> f, int a, int b) {
    return countIteratorAsList_incl(f, a, b, 1);
  }

  static public <A> List<A> countIteratorAsList_incl(IF1<Integer, A> f, int a, int b, int step) {
    return countIteratorToList_inclusive(f, a, b, step);
  }

  static public int boostHashCombine(int a, int b) {
    return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
  }

  static public int _hashCode(Object a) {
    return a == null ? 0 : a.hashCode();
  }

  static public Class mc() {
    return main.class;
  }

  static public String printLog() {
    return getPrintLog();
  }

  static public <A extends Component> A setBounds(final int x, final int y, final int w, final int h, final A a) {
    if (a != null) {
      swing(() -> {
        a.setBounds(x, y, w, h);
      });
    }
    return a;
  }

  static public <A extends Component> A setBounds(A a, Rect r) {
    if (a != null && r != null) {
      swing(() -> {
        a.setBounds(toRectangle(r));
      });
    }
    return a;
  }

  static public <A extends Component> A setBounds(Rect r, A a) {
    return setBounds(a, r);
  }

  static public <A extends Component> A setBounds(A a, int x, int y, int w, int h) {
    return setBounds(x, y, w, h, a);
  }

  static public <A extends Component> A onBoundsChange(A c, final Object r) {
    if (c != null && r != null) {
      swing(() -> {
        c.addComponentListener(new ComponentAdapter() {

          public void componentResized(ComponentEvent e) {
            pcallF(r);
          }

          public void componentMoved(ComponentEvent e) {
            pcallF(r);
          }
        });
      });
    }
    return c;
  }

  static public <A extends Component> A onBoundsChange(Object r, A c) {
    return onBoundsChange(c, r);
  }

  static public boolean isMain() {
    return isMainProgram();
  }

  static public <A extends Concept> List<A> cdelete(Class<A> c, Object... params) {
    return deleteConcepts(c, params);
  }

  static public void cdelete(Concept c) {
    deleteConcept(c);
  }

  static public <A extends Concept> void cdelete(Collection<A> c) {
    for (A a : cloneList(c)) cdelete(a);
  }

  static public boolean isExtendedStateNormal(JFrame f) {
    return f != null && swing(() -> f.getExtendedState() == JFrame.NORMAL);
  }

  static public void maximizeOrRestoreFrame(JFrame f) {
    if (f == null)
      return;
    if (!isExtendedStateNormal(f)) {
      swing(() -> {
        f.setExtendedState(JFrame.NORMAL);
      });
    } else
      maximizeFrame(f);
  }

  static public <A extends JComponent> A onFirstShowing(A component, Runnable onShow) {
    return onFirstComponentShow(component, onShow);
  }

  static public boolean swingConfirm(Component owner, String msg) {
    return confirmOKCancel(owner, msg);
  }

  static public boolean swingConfirm(String msg) {
    return confirmOKCancel(msg);
  }

  static public <A extends Component> A setAlwaysOnTop(A c) {
    return alwaysOnTop(c);
  }

  static public BufferedImage shootWindow(Window w) {
    w.toFront();
    sleep(50);
    return shootScreen2(w.getBounds());
  }

  static public Object ccallOpt(Concept.Ref ref, String method, Object... args) {
    return callOptWithEnter(cDeref(ref), method, args);
  }

  static public Object ccallOpt(Object object, String method, Object... args) {
    return callOptWithEnter(object, method, args);
  }

  static public <A extends JComponent> A fontSizePlus(final int delta, final A c) {
    if (c != null) {
      swing(() -> {
        Font font = c.getFont();
        c.setFont(font.deriveFont(font.getSize2D() + delta));
      });
    }
    return c;
  }

  static public JLabel jCenteredLabel(String text) {
    return jcenteredLabel(text);
  }

  static public JLabel jCenteredLabel() {
    return jcenteredLabel();
  }

  static public boolean haveMuricaPassword() {
    return nempty(muricaPassword());
  }

  static public <A extends JComponent> A setOpaqueBackground(final Color color, final A a) {
    if (a != null) {
      swing(() -> {
        a.setBackground(color);
        a.setOpaque(true);
        a.putClientProperty("substancelaf.colorizationFactor", 1.0);
      });
    }
    return a;
  }

  static public <A extends Component> A jtransparent_recursive(A a) {
    if (a instanceof JPanel) {
      ((JPanel) a).setOpaque(false);
      for (Component c : getSwingChildren(a)) jtransparent_recursive(c);
    }
    return a;
  }

  static public JLabel jImage_scaledToHeight(String imageID, int height) {
    return jImage(resizeImageToHeight_bilinear(loadImage2(imageID), height));
  }

  static public JLabel jImage_scaledToHeight(int height, String imageID) {
    return jImage_scaledToHeight(imageID, height);
  }

  static public JButton jimageButton(String imageID, Object action) {
    JButton btn = jbutton("", action);
    btn.setIcon(imageIcon(imageID));
    return btn;
  }

  static public JButton jimageButton(String imageID) {
    return jimageButton(imageID, null);
  }

  static public JButton jimageButton(BufferedImage img, String toolTip, Runnable action) {
    var btn = jbutton("", action);
    setButtonImage(btn, img);
    return setToolTip(toolTip, btn);
  }

  static public BufferedImage scaleImageToWidth(BufferedImage img, int newW) {
    return resizeImage(img, newW);
  }

  static public BufferedImage scaleImageToWidth(int newW, BufferedImage img) {
    return scaleImageToWidth(img, newW);
  }

  static public BufferedImage scaleImageToWidth(int newW, String imageID) {
    return scaleImageToWidth(newW, loadImage2(imageID));
  }

  static public Runnable disableButtonWhileCalcing3(final Runnable r) {
    return new Runnable() {

      public void run() {
        try {
          disableButtonWhileCalcing2(r);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "disableButtonWhileCalcing2(r)";
      }
    };
  }

  static public class transpileOnServerWithErrorWindow_DaClass {

    public String snippetID;

    public JFastLogView_noWrap transpilationErrorBox;

    public Runnable onSuccess;

    public Object onError;

    public void go(boolean medium) {
      infoBox("Transpiling " + snippetID);
      final Pair<Boolean, String> p = transpileOnBestServer(snippetID, medium ? "medium" : "quick");
      swingLater(new Runnable() {

        public void run() {
          try {
            if (p.a) {
              infoBox("Transpiled OK!");
              hideWindow(transpilationErrorBox);
              transpilationErrorBox = null;
              callFInNewThread(onSuccess);
            } else {
              infoBox("Transpilation error. " + p.b);
              boolean first = transpilationErrorBox == null;
              transpilationErrorBox = maximizeFrame(scrollAllTheWayDown(showText_fast_noWrap(transpilationErrorBox, "Transpilation Error", p.b)));
              if (first) {
                setFrameIcon("#1101268", transpilationErrorBox);
                addButtonsToWindow(transpilationErrorBox, "Medium transpile", runnableThread(new Runnable() {

                  public void run() {
                    try {
                      go(true);
                    } catch (Exception __e) {
                      throw rethrow(__e);
                    }
                  }

                  public String toString() {
                    return "go(true)";
                  }
                }));
              }
              callFInNewThread(onError, p.b);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "if (p.a) {\r\n        infoBox(\"Transpiled OK!\");\r\n        hideWindow(transpilat...";
        }
      });
    }
  }

  static public void transpileOnServerWithErrorWindow(String snippetID, boolean medium, final Runnable onSuccess, Object... __) {
    nu(transpileOnServerWithErrorWindow_DaClass.class, paramsPlus(__, "snippetID", snippetID, "onSuccess", onSuccess)).go(medium);
  }

  static public <A extends Component> A maximizeFrame(A c) {
    JFrame f = swing(new F0<JFrame>() {

      public JFrame get() {
        try {
          JFrame f = getFrame(c);
          if (f != null)
            f.setExtendedState(JFrame.MAXIMIZED_BOTH);
          return f;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JFrame f = getFrame(c);\r\n    if (f != null)\r\n      f.setExtendedState(JFrame....";
      }
    });
    if (f != null && !isAWTThread()) {
      Dimension d = maximumWindowBounds().getSize();
      long start = sysNow();
      while (licensed()) {
        try {
          if (f.getWidth() >= d.getWidth() - 100 && f.getHeight() >= d.getHeight() - 100)
            break;
          if (sysNow() >= start + 100) {
            warn("maximizeFrame timeout");
            break;
          }
        } catch (Throwable __e) {
          printStackTrace(__e);
        }
        sleep(1);
      }
    }
    return c;
  }

  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 String appendWithColon(String s) {
    return prependColonSpaceIfNempty(s);
  }

  static public <A, B> Pair<A, B> pair(A a, B b) {
    return new Pair(a, b);
  }

  static public <A> Pair<A, A> pair(A a) {
    return new Pair(a, a);
  }

  static public <A extends Throwable> A printStackTrace(A e) {
    if (e != null)
      print(getStackTrace(e));
    return e;
  }

  static public void printStackTrace() {
    printStackTrace(new Throwable());
  }

  static public void printStackTrace(String msg) {
    printStackTrace(new Throwable(msg));
  }

  static public void printStackTrace(String msg, Throwable e) {
    printStackTrace(new Throwable(msg, e));
  }

  static public void setFrameContents(final Component c, final Object contents) {
    swing(() -> {
      JFrame frame = getFrame(c);
      if (frame == null)
        return;
      frame.getContentPane().removeAll();
      frame.getContentPane().setLayout(new BorderLayout());
      frame.getContentPane().add(wrap(contents));
      revalidate(frame);
    });
  }

  static public BufferedImage renderComponentToImage(final Component c) {
    if (c == null)
      return null;
    return swing(new F0<BufferedImage>() {

      public BufferedImage get() {
        try {
          int w = getWidth(c), h = getHeight(c);
          BufferedImage img = newBufferedImage(w, h);
          c.paint(createGraphics(img));
          return img;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "int w = getWidth(c), h = getHeight(c);\r\n    BufferedImage img = newBufferedIm...";
      }
    });
  }

  static public <A extends Image> A copyImageToClipboard(A img) {
    TransferableImage trans = new TransferableImage(img);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);
    vmBus_send("newClipboardContents", img);
    print("Copied image to clipboard (" + img.getWidth(null) + "*" + img.getHeight(null) + " px)");
    return img;
  }

  static public File saveInImageDirectoryWithCounter(String subPath, BufferedImage img) {
    if (img == null)
      return null;
    assertNempty(subPath);
    File dir = imagesDir();
    if (!isImageFileName(subPath))
      subPath += ".png";
    File f = makeFileNameUnique_beforeExtension_startWith1_noDot(newFile(dir, subPath));
    saveImage(f, img);
    infoBox("Saved image " + appendBracketed(img.getWidth(null) + "*" + img.getHeight(null)) + ": " + fileInfo(f));
    return f;
  }

  static public java.awt.Color awtColor(String hex) {
    byte[] b = bytesFromHex(dropPrefix("#", hex));
    return new Color(ubyteToInt(b[0]), ubyteToInt(b[1]), ubyteToInt(b[2]));
  }

  static public CleanExit cleanExit(String msg) {
    throw new CleanExit(msg);
  }

  static public CleanExit cleanExit() {
    throw new CleanExit();
  }

  static public String exceptionToStringShort(Throwable e) {
    lastException(e);
    e = getInnerException(e);
    String msg = hideCredentials(unnull(e.getMessage()));
    if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
      return baseClassName(e) + prependIfNempty(": ", msg);
    else
      return msg;
  }

  static public void hideTrayIcon(TrayIcon t) {
    removeTrayIcon(t);
  }

  static public void systemExit(int code) {
    System.exit(code);
  }

  static public Window getWindow(Object o) {
    if (!(o instanceof Component))
      return null;
    return swing(() -> {
      Component c = (Component) o;
      while (c != null) {
        if (c instanceof Window)
          return ((Window) c);
        c = c.getParent();
      }
      return null;
    });
  }

  static public JFastLogView_noWrap showText_fast_noWrap(String title, Object text) {
    return showText_fast_noWrap(null, title, text);
  }

  static public JFastLogView_noWrap showText_fast_noWrap(JFastLogView_noWrap view, String title, Object text) {
    if (view != null) {
      view.setText(str(text));
      return view;
    }
    view = jFastLogView_noWrap(str(text));
    makeFrame(title, jscroll_copyBackground(view));
    return view;
  }

  static public JFastLogView_noWrap showText_fast_noWrap(Object text) {
    return showText_fast_noWrap(autoFrameTitle(), text);
  }

  static public String renderStackTrace(StackTraceElement[] st) {
    return stackTraceToString(st);
  }

  static public String renderStackTrace(Throwable e) {
    return stackTraceToString(e);
  }

  static public String renderStackTrace(String msg) {
    return renderStackTrace(new Throwable(msg));
  }

  static public boolean contains(Collection c, Object o) {
    return c != null && c.contains(o);
  }

  static public boolean contains(Iterable it, Object a) {
    if (it != null)
      for (Object o : it) if (eq(a, o))
        return true;
    return false;
  }

  static public boolean contains(Object[] x, Object o) {
    if (x != null)
      for (Object a : x) if (eq(a, o))
        return true;
    return false;
  }

  static public boolean contains(String s, char c) {
    return s != null && s.indexOf(c) >= 0;
  }

  static public boolean contains(String s, String b) {
    return s != null && s.indexOf(b) >= 0;
  }

  static public boolean contains(BitSet bs, int i) {
    return bs != null && bs.get(i);
  }

  static public <A> boolean contains(Producer<A> p, A a) {
    if (p != null && a != null)
      while (true) {
        A x = p.next();
        if (x == null)
          break;
        if (eq(x, a))
          return true;
      }
    return false;
  }

  static public Object vm_generalMap_put(Object key, Object value) {
    return mapPutOrRemove(vm_generalMap(), key, value);
  }

  static public String mcDollar() {
    return mcName() + "$";
  }

  static public String className(Object o) {
    return getClassName(o);
  }

  static public Collection<Concept> allConcepts() {
    return db_mainConcepts().allConcepts();
  }

  static public Collection<Concept> allConcepts(Concepts concepts) {
    return concepts.allConcepts();
  }

  static public <A extends Concept> Collection<A> findConcepts(Class<A> c, Object... params) {
    return findConceptsWhere(c, params);
  }

  static public Collection<Concept> findConcepts(String c, Object... params) {
    return findConceptsWhere(c, params);
  }

  static public <A extends Concept> Collection<A> findConcepts(Concepts concepts, Class<A> c, Object... params) {
    return findConceptsWhere(concepts, c, params);
  }

  static public Collection<Concept> findConcepts(Concepts concepts, String c, Object... params) {
    return findConceptsWhere(concepts, c, params);
  }

  static public int l(Object[] a) {
    return a == null ? 0 : a.length;
  }

  static public int l(boolean[] a) {
    return a == null ? 0 : a.length;
  }

  static public int l(byte[] a) {
    return a == null ? 0 : a.length;
  }

  static public int l(short[] a) {
    return a == null ? 0 : a.length;
  }

  static public int l(long[] a) {
    return a == null ? 0 : a.length;
  }

  static public int l(int[] a) {
    return a == null ? 0 : a.length;
  }

  static public int l(float[] a) {
    return a == null ? 0 : a.length;
  }

  static public int l(double[] a) {
    return a == null ? 0 : a.length;
  }

  static public int l(char[] a) {
    return a == null ? 0 : a.length;
  }

  static public int l(Collection c) {
    return c == null ? 0 : c.size();
  }

  static public int l(Iterator i) {
    return iteratorCount_int_close(i);
  }

  static public int l(Map m) {
    return m == null ? 0 : m.size();
  }

  static public int l(CharSequence s) {
    return s == null ? 0 : s.length();
  }

  static public long l(File f) {
    return f == null ? 0 : f.length();
  }

  static public int l(Object o) {
    return o == null ? 0 : o instanceof String ? l((String) o) : o instanceof Map ? l((Map) o) : o instanceof Collection ? l((Collection) o) : o instanceof Object[] ? l((Object[]) o) : o instanceof boolean[] ? l((boolean[]) o) : o instanceof byte[] ? l((byte[]) o) : o instanceof char[] ? l((char[]) o) : o instanceof short[] ? l((short[]) o) : o instanceof int[] ? l((int[]) o) : o instanceof float[] ? l((float[]) o) : o instanceof double[] ? l((double[]) o) : o instanceof long[] ? l((long[]) o) : (Integer) call(o, "size");
  }

  static public int l(MultiSet ms) {
    return ms == null ? 0 : ms.size();
  }

  static public int l(IntRange r) {
    return r == null ? 0 : r.length();
  }

  static public long l(LongRange r) {
    return r == null ? 0 : r.length();
  }

  static public double l(DoubleRange r) {
    return r == null ? 0 : r.length();
  }

  static public int l(IntBuffer b) {
    return b == null ? 0 : b.size();
  }

  static public Object first(Object list) {
    return first((Iterable) list);
  }

  static public <A> A first(List<A> list) {
    return empty(list) ? null : list.get(0);
  }

  static public <A> A first(A[] bla) {
    return bla == null || bla.length == 0 ? null : bla[0];
  }

  static public <A, B> Pair<A, B> first(Map<A, B> map) {
    return mapEntryToPair(first(entrySet(map)));
  }

  static public <A, B> Pair<A, B> first(MultiMap<A, B> mm) {
    if (mm == null)
      return null;
    var e = first(mm.data.entrySet());
    if (e == null)
      return null;
    return pair(e.getKey(), first(e.getValue()));
  }

  static public <A> A first(IterableIterator<A> i) {
    return first((Iterator<A>) i);
  }

  static public <A> A first(Iterator<A> i) {
    return i == null || !i.hasNext() ? null : i.next();
  }

  static public <A> A first(Iterable<A> i) {
    if (i == null)
      return null;
    Iterator<A> it = i.iterator();
    return it.hasNext() ? it.next() : null;
  }

  static public Character first(String s) {
    return empty(s) ? null : s.charAt(0);
  }

  static public Character first(CharSequence s) {
    return empty(s) ? null : s.charAt(0);
  }

  static public <A, B> A first(Pair<A, B> p) {
    return p == null ? null : p.a;
  }

  static public <A, B, C> A first(T3<A, B, C> t) {
    return t == null ? null : t.a;
  }

  static public Byte first(byte[] l) {
    return empty(l) ? null : l[0];
  }

  static public int first(IntBuffer buf) {
    return buf.get(0);
  }

  static public <A> A first(A[] l, IF1<A, Boolean> pred) {
    return firstThat(l, pred);
  }

  static public <A> A first(Iterable<A> l, IF1<A, Boolean> pred) {
    return firstThat(l, pred);
  }

  static public <A> A first(IF1<A, Boolean> pred, Iterable<A> l) {
    return firstThat(pred, l);
  }

  static public <A extends Concept> A registerConcept(A c) {
    return registerConcept(db_mainConcepts(), c);
  }

  static public <A extends Concept> A registerConcept(Concepts cc, A c) {
    {
      if (cc != null)
        cc.register(c);
    }
    return c;
  }

  static public Thread startThread(Object runnable) {
    return startThread(defaultThreadName(), runnable);
  }

  static public Thread startThread(String name, Runnable runnable) {
    runnable = wrapAsActivity(runnable);
    return startThread(newThread(runnable, name));
  }

  static public Thread startThread(String name, Object runnable) {
    runnable = wrapAsActivity(runnable);
    return startThread(newThread(toRunnable(runnable), name));
  }

  static public Thread startThread(Thread t) {
    _registerThread(t);
    t.start();
    return t;
  }

  static public File myJar() {
    return first(myLibraryFiles());
  }

  static public void loadBinaryPageToFile(String url, File file) {
    try {
      print("Loading " + url);
      loadBinaryPageToFile(openConnection(new URL(url)), file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void loadBinaryPageToFile(URLConnection con, File file) {
    try {
      setHeaders(con);
      loadBinaryPageToFile_noHeaders(con, file);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void loadBinaryPageToFile_noHeaders(URLConnection con, File file) {
    try {
      File ftemp = new File(f2s(file) + "_temp");
      FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp));
      try {
        InputStream inputStream = con.getInputStream();
        long len = 0;
        try {
          len = con.getContentLength();
        } catch (Throwable e) {
          printStackTrace(e);
        }
        String pat = "  {*}" + (len != 0 ? "/" + len : "") + " bytes loaded.";
        copyStreamWithPrints(inputStream, buf, pat);
        inputStream.close();
        buf.close();
        file.delete();
        renameFile_assertTrue(ftemp, file);
      } finally {
        if (buf != null)
          buf.close();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public boolean isFile(File f) {
    return f != null && f.isFile();
  }

  static public boolean isFile(String path) {
    return isFile(newFile(path));
  }

  static public File copyFile(File src, File dest) {
    try {
      FileInputStream inputStream = new FileInputStream(src.getPath());
      FileOutputStream outputStream = newFileOutputStream(dest.getPath());
      try {
        copyStream(inputStream, outputStream);
        inputStream.close();
      } finally {
        outputStream.close();
      }
      return dest;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public 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 String or2(String a, String b) {
    return nempty(a) ? a : b;
  }

  static public String or2(String a, String b, String c) {
    return or2(or2(a, b), c);
  }

  static public String currentProcessCommand() {
    ProcessHandle processHandle = ProcessHandle.current();
    return getVar(processHandle.info().command());
  }

  static public StefansOS_ConnectToServer snippetUpdateConnector(Object... __) {
    boolean verbose = boolPar("verbose", __);
    StefansOS_ConnectToServer connector = new StefansOS_ConnectToServer();
    connector.onLine = new VF1<String>() {

      public void get(String line) {
        try {
          Matches m = new Matches();
          if (startsWith(line, "snippetUpdates:", m)) {
            if (verbose)
              print(line);
            String msg = m.rest();
            vmBus_send("snippetUpdate", safeUnstruct(msg));
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "new Matches m;\r\n    if (startsWith(line, \"snippetUpdates:\", m)) {\r\n      if (...";
      }
    };
    connector.startWithSubs("snippetUpdates");
    return connector;
  }

  static public <A> AutoCloseable vmBus_onMessage(String msg, IVF1<A> onMessage) {
    return vmBus_onMessage(msg, ivf1ToVF1(onMessage));
  }

  static public <A> AutoCloseable vmBus_onMessage(final String msg, final VF1<A> onMessage) {
    Map<String, Set> map = vm_busListenersByMessage_live();
    synchronized (map) {
      Set listeners = map.get(msg);
      if (listeners == null)
        map.put(msg, listeners = syncIdentityHashSet());
      return tempAdd(listeners, new VF2<String, Object>() {

        public void get(String _msg, Object arg) {
          try {
            callF(onMessage, arg);
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "callF(onMessage, arg)";
        }
      });
    }
  }

  static public <A, B> AutoCloseable vmBus_onMessage(String msg, final VF2<A, B> onMessage) {
    return vmBus_onMessage(msg, new VF1<Object[]>() {

      public void get(Object[] o) {
        try {
          callF(onMessage, first(o), second(o));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(onMessage, first(o), second(o));";
      }
    });
  }

  static public <A, B> AutoCloseable vmBus_onMessage(String msg, final IVF2<A, B> onMessage) {
    return vmBus_onMessage(msg, new VF1<Object[]>() {

      public void get(Object[] o) {
        try {
          callF(onMessage, first(o), second(o));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(onMessage, first(o), second(o));";
      }
    });
  }

  static public AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) {
    return vmBus_onMessage(msg, runnableToVF1(onMessage));
  }

  static public String getString(Map map, Object key) {
    return map == null ? null : (String) map.get(key);
  }

  static public String getString(List l, int idx) {
    return (String) get(l, idx);
  }

  static public String getString(Object o, Object key) {
    if (o instanceof Map)
      return getString((Map) o, key);
    if (key instanceof String)
      return (String) getOpt(o, (String) key);
    throw fail("Not a string key: " + getClassName(key));
  }

  static public String getString(String key, Object o) {
    return getString(o, (Object) key);
  }

  static public boolean swic(String a, String b) {
    return startsWithIgnoreCase(a, b);
  }

  static public boolean swic(String a, String b, Matches m) {
    if (!swic(a, b))
      return false;
    m.m = new String[] { substring(a, l(b)) };
    return true;
  }

  static public boolean sameSnippetID(String a, String b) {
    if (!isSnippetID(a) || !isSnippetID(b))
      return false;
    return parseSnippetID(a) == parseSnippetID(b);
  }

  static public String programID() {
    return getProgramID();
  }

  static public String programID(Object o) {
    return getProgramID(o);
  }

  static public String firstIntAsString(String s) {
    return jextract("<int>", s);
  }

  static public long psI(String snippetID) {
    return parseSnippetID(snippetID);
  }

  static public void ping_v3_setPingSourceMaker(IF0<PingSource> pingMaker) {
    vm_generalMap_set("ping_v3_pingSourceMaker", pingMaker);
  }

  static public int findIntArg(String name, String[] args, int defaultValue) {
    int i = indexOfIC(args, name);
    return i >= 0 && i + 1 < l(args) ? parseInt(args[i + 1]) : defaultValue;
  }

  static public int cores() {
    return numberOfCores();
  }

  static public boolean ping() {
    return ping(pingSource());
  }

  static public boolean ping(PingSource source) {
    ping_v3(source);
    return true;
  }

  static public boolean ping_impl(boolean okInCleanUp) {
    return ping();
  }

  static volatile public boolean ping_pauseAll = false;

  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<Integer> 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 <A extends Comparable<A>> A max(A a, A b) {
    return cmp(a, b) >= 0 ? a : b;
  }

  static public int screenNrOfWindow(Window w) {
    if (w == null)
      return -1;
    Rect bounds = boundsAsRect(w);
    return indexOfMax(allScreenBounds(), screen -> area(intersectRects(bounds, screen)));
  }

  static public boolean cic(Collection<String> l, String s) {
    return containsIgnoreCase(l, s);
  }

  static public boolean cic(String[] l, String s) {
    return containsIgnoreCase(l, s);
  }

  static public boolean cic(String s, char c) {
    return containsIgnoreCase(s, c);
  }

  static public boolean cic(String a, String b) {
    return containsIgnoreCase(a, b);
  }

  static public File programDir_mine;

  static public File programDir() {
    return programDir(getProgramID());
  }

  static public File programDir(String snippetID) {
    boolean me = sameSnippetID(snippetID, programID());
    if (programDir_mine != null && me)
      return programDir_mine;
    File dir = new File(javaxDataDir(), formatSnippetIDOpt(snippetID));
    if (me) {
      String c = caseID();
      if (nempty(c))
        dir = newFile(dir, c);
    }
    return dir;
  }

  static public File programDir(String snippetID, String subPath) {
    return new File(programDir(snippetID), subPath);
  }

  static public void clearConceptsOf(String progID) {
    getProgramFile(progID, "concepts.structure").delete();
    getProgramFile(progID, "concepts.structure.gz").delete();
    getProgramFile(progID, "idCounter.structure").delete();
  }

  static public List syncMap(Object f, Map map) {
    return syncMap(map, f);
  }

  static public List syncMap(Map map, Object f) {
    return map(cloneLinkedHashMap(map), f);
  }

  static public <A, B> Map<A, B> syncMap() {
    return synchroHashMap();
  }

  static public <A, B> Map<A, B> syncMap(Map map) {
    return synchronizedMap(map);
  }

  static public Class __javax;

  static public Class getJavaX() {
    try {
      return __javax;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void __setJavaX(Class j) {
    __javax = j;
    _onJavaXSet();
  }

  static public boolean startsWith(String a, String b) {
    return a != null && a.startsWith(unnull(b));
  }

  static public boolean startsWith(String a, char c) {
    return nemptyString(a) && a.charAt(0) == c;
  }

  static public boolean startsWith(String a, String b, Matches m) {
    if (!startsWith(a, b))
      return false;
    if (m != null)
      m.m = new String[] { substring(a, strL(b)) };
    return true;
  }

  static public boolean startsWith(List a, List b) {
    if (a == null || listL(b) > listL(a))
      return false;
    for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
      return false;
    return true;
  }

  static public String substring(String s, int x) {
    return substring(s, x, strL(s));
  }

  static public String substring(String s, int x, int y) {
    if (s == null)
      return null;
    if (x < 0)
      x = 0;
    int n = s.length();
    if (y < x)
      y = x;
    if (y > n)
      y = n;
    if (x >= y)
      return "";
    return s.substring(x, y);
  }

  static public String substring(String s, IntRange r) {
    return r == null ? null : substring(s, r.start, r.end);
  }

  static public String substring(String s, CharSequence l) {
    return substring(s, lCharSequence(l));
  }

  static public void dm_watchFields(Collection<String> fields, Runnable onChange) {
    for (String field : unnullForIteration(fields)) dm_watchField(field, onChange);
  }

  static public <A extends IMeta> A setMetaSrcUnlessSame(Object b, A a, Object src) {
    if (a != b)
      setMeta(a, "src", src);
    return a;
  }

  static public BWImage posterizeBWImage(int brightnessLevels, BWImage img) {
    if (brightnessLevels >= 256 || img == null)
      return img;
    byte[] pixels = img.getBytes();
    int w = img.getWidth(), h = img.getHeight(), n = pixels.length;
    byte[] pixels2 = new byte[n];
    double factor1 = doubleRatio(brightnessLevels, 256);
    double factor2 = doubleRatio(255, brightnessLevels - 1);
    for (int i = 0; i < n; i++) pixels2[i] = (byte) iround(ifloor(ubyteToInt(pixels[i]) * factor1) * factor2);
    return new BWImage(w, h, pixels2);
  }

  static public BWImage scaledBWImageFromBWIntegralImage(int w, BWIntegralImage img) {
    return scaledBWImageFromBWIntegralImage(img, w);
  }

  static public BWImage scaledBWImageFromBWIntegralImage(BWIntegralImage img, int w) {
    return scaledBWImageFromBWIntegralImage(img, w, heightForWidth(img, w));
  }

  static public BWImage scaledBWImageFromBWIntegralImage(BWIntegralImage img, int w, int h) {
    byte[] pixels = scaledGrayBytesFromBWIntegralImage(img, w, h);
    return new BWImage(w, h, pixels);
  }

  static public BWImage scaledBWImageFromBWIntegralImage(int w, IBWIntegralImage img) {
    return scaledBWImageFromBWIntegralImage(img, w);
  }

  static public BWImage scaledBWImageFromBWIntegralImage(IBWIntegralImage img, int w) {
    return scaledBWImageFromBWIntegralImage(img, w, heightForWidth(img, w));
  }

  static public BWImage scaledBWImageFromBWIntegralImage(IBWIntegralImage img, int w, int h) {
    byte[] pixels = scaledGrayBytesFromBWIntegralImage(img, w, h);
    return new BWImage(w, h, pixels);
  }

  static public <A extends IMeta> A setMetaSrc(A a, Object src) {
    setMeta(a, "src", src);
    return a;
  }

  static public double toDouble(Object o) {
    if (o instanceof Number)
      return ((Number) o).doubleValue();
    if (o instanceof BigInteger)
      return ((BigInteger) o).doubleValue();
    if (o instanceof String)
      return parseDouble((String) o);
    if (o == null)
      return 0.0;
    throw fail(o);
  }

  static public double msToSeconds(long ms) {
    return toSeconds(ms);
  }

  static public Point mouseLocation() {
    return getMouseLocation();
  }

  static public ImageSurface imageSurface(BufferedImage img) {
    return swingNu(ImageSurface.class, img);
  }

  static public ImageSurface imageSurface(MakesBufferedImage img) {
    return swingNu(ImageSurface.class, img);
  }

  static public ImageSurface imageSurface() {
    return swingNu(ImageSurface.class);
  }

  static public void imageSurface_pixelated(ImageSurface imageSurface) {
    if (imageSurface == null)
      return;
    imageSurface.setDoubleBuffered(true);
    imageSurface.noAlpha = true;
    imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR;
    repaint(imageSurface);
  }

  static public void imageSurface_pixelated(ImageSurface imageSurface, boolean pixelated) {
    if (pixelated)
      imageSurface_pixelated(imageSurface);
    else
      imageSurface_unpixelated(imageSurface);
  }

  static public BufferedImage toBufferedImage(Object o) {
    return toBufferedImageOpt(o);
  }

  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 <A> A swingNu(final Class<A> c, final Object... args) {
    return swingConstruct(c, args);
  }

  static public <A extends JComponent> A toolTipFromLiveValue(LiveValue lv, A c) {
    return bindToolTipToLiveValue(lv, c);
  }

  static public <A> LiveValue<A> dm_transientCalculatedLiveValue(Class type, IF0<A> calc) {
    return dm_transientCalculatedLiveValue(dm_current_mandatory(), type, calc);
  }

  static public <A> LiveValue<A> dm_transientCalculatedLiveValue(DynModule mod, Class type, IF0<A> calc) {
    Lock __0 = mod.lock;
    lock(__0);
    try {
      SimpleLiveValue value = new SimpleLiveValue(type, calc.get());
      mod.onFieldChange(new VF1<String>() {

        public void get(String field) {
          try {
            value.set(calc.get());
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "value.set(calc!)";
        }
      });
      return value;
    } finally {
      unlock(__0);
    }
  }

  static public LiveValue<Object> dm_transientCalculatedLiveValue(IF0<Object> calc) {
    return dm_transientCalculatedLiveValue(Object.class, calc);
  }

  static public <A extends JLabel> A setHorizontalAlignment(final int pos, final A a) {
    swingCall(a, "setHorizontalAlignment", pos);
    return a;
  }

  static public <A extends AbstractButton> A setHorizontalAlignment(final int pos, final A a) {
    swingCall(a, "setHorizontalAlignment", pos);
    return a;
  }

  static public <A extends JTextField> A setHorizontalAlignment(final int pos, final A a) {
    swingCall(a, "setHorizontalAlignment", pos);
    return a;
  }

  static public JTabbedPane jLeftOrTopTabs(boolean horizontal, Object... x) {
    return horizontal ? jLeftTabs(x) : jtabs(x);
  }

  static public JTabbedPane jLeftOrTopTabs(boolean horizontal, Collection c) {
    return horizontal ? jLeftTabs(c) : jtabs(c);
  }

  static public JPanel jRightAlignedButtons(Object... params) {
    List<JComponent> 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 jRightAlignedLine(l);
  }

  static public JComponent wrap(Object swingable) {
    return _recordNewSwingComponent(wrap_2(swingable));
  }

  static public JComponent wrap_2(Object swingable) {
    if (swingable == null)
      return null;
    JComponent c;
    if (swingable instanceof Component)
      c = componentToJComponent((Component) swingable);
    else if (swingable instanceof Swingable)
      c = componentToJComponent(((Swingable) swingable).visualize());
    else
      c = componentToJComponent((Component) callOpt(swingable, "swing"));
    if (c instanceof JTable || c instanceof JList || c instanceof JTextArea || c instanceof JEditorPane || c instanceof JTextPane || c instanceof JTree)
      return jscroll(c);
    return c == null ? jlabel(str(swingable)) : c;
  }

  static public JPanel marginPanel() {
    return jtransparent(borderLayoutPanel());
  }

  static public <A extends JComponent> A setBorder(Border border, A c) {
    if (c != null) {
      swing(() -> {
        c.setBorder(border);
      });
    }
    return c;
  }

  static public JScrollPane withoutViewportBorder(JScrollPane sp) {
    if (sp != null) {
      swing(() -> {
        sp.setViewportBorder(null);
      });
    }
    return sp;
  }

  static public JPanel vstack2(final Object... parts) {
    return swing(new F0<JPanel>() {

      public JPanel get() {
        try {
          JPanel panel = new JPanel(new GridBagLayout());
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.weightx = 1;
          gbc.fill = GridBagConstraints.HORIZONTAL;
          gbc.gridwidth = GridBagConstraints.REMAINDER;
          smartAddWithLayout(panel, gbc, parts);
          gbc.weighty = 1;
          panel.add(jrigid(), gbc);
          return panel;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "JPanel panel = new JPanel(new GridBagLayout);\r\n    new GridBagConstraints gbc...";
      }
    });
  }

  static public JPanel smartAddWithLayout(JPanel panel, Object layout, List parts) {
    for (Object o : parts) panel.add(wrapForSmartAdd(o), layout);
    return panel;
  }

  static public JPanel smartAddWithLayout(JPanel panel, Object layout, Object... parts) {
    return smartAddWithLayout(panel, layout, asList(flattenArray2(parts)));
  }

  static public Component jrigid() {
    return javax.swing.Box.createRigidArea(new Dimension(0, 0));
  }

  static public JSpinner liveValueSpinner(SimpleLiveValue<Integer> lv, int min, int max) {
    JSpinner spinner = jSpinner(lv.get(), min, max);
    return bindLiveValueToSpinner(lv, spinner);
  }

  static public JSpinner bindLiveValueToSpinner(SimpleLiveValue<Integer> lv, JSpinner spinner) {
    onChange(spinner, new Runnable() {

      public void run() {
        try {
          lv.set(intFromSpinner(spinner));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "lv.set(intFromSpinner(spinner))";
      }
    });
    lv.onChange(new Runnable() {

      public void run() {
        try {
          setSpinnerValue(spinner, lv.get());
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "setSpinnerValue(spinner, lv!)";
      }
    });
    return spinner;
  }

  static public <A> JSpinner jPowersOfTwoSpinner(int max, int defaultValue) {
    return rightAlignSpinner(jListSpinner(powersOfTwoUpTo(max), defaultValue));
  }

  static public List<JButton> allButtons(Component c) {
    return childrenOfType(c, JButton.class);
  }

  static public <A extends AbstractButton> A setHorizontalMargin(final int margin, final A a) {
    {
      swing(() -> {
        Insets i = a.getMargin();
        a.setMargin(new Insets(i.top, margin, i.bottom, margin));
      });
    }
    return a;
  }

  static public <A extends AbstractButton> A setHorizontalMargin(A a, int margin) {
    return setHorizontalMargin(margin, a);
  }

  static public String formatWithThousands(long l) {
    return formatWithThousandsSeparator(l);
  }

  static public boolean empty(Collection c) {
    return c == null || c.isEmpty();
  }

  static public boolean empty(Iterable c) {
    return c == null || !c.iterator().hasNext();
  }

  static public boolean empty(CharSequence s) {
    return s == null || s.length() == 0;
  }

  static public boolean empty(Map map) {
    return map == null || map.isEmpty();
  }

  static public boolean empty(Object[] o) {
    return o == null || o.length == 0;
  }

  static public boolean empty(BitSet bs) {
    return bs == null || bs.isEmpty();
  }

  static public boolean empty(Object o) {
    if (o instanceof Collection)
      return empty((Collection) o);
    if (o instanceof String)
      return empty((String) o);
    if (o instanceof Map)
      return empty((Map) o);
    if (o instanceof Object[])
      return empty((Object[]) o);
    if (o instanceof byte[])
      return empty((byte[]) o);
    if (o == null)
      return true;
    throw fail("unknown type for 'empty': " + getType(o));
  }

  static public boolean empty(Iterator i) {
    return i == null || !i.hasNext();
  }

  static public boolean empty(double[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(float[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(int[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(long[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(byte[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(short[] a) {
    return a == null || a.length == 0;
  }

  static public boolean empty(MultiSet ms) {
    return ms == null || ms.isEmpty();
  }

  static public boolean empty(MultiMap mm) {
    return mm == null || mm.isEmpty();
  }

  static public boolean empty(File f) {
    return getFileSize(f) == 0;
  }

  static public boolean empty(IntRange r) {
    return r == null || r.empty();
  }

  static public boolean empty(DoubleRange r) {
    return r == null || r.isEmpty();
  }

  static public boolean empty(IntBuffer b) {
    return b == null || b.isEmpty();
  }

  static public boolean empty(Rect r) {
    return !(r != null && r.w != 0 && r.h != 0);
  }

  static public String str(Object o) {
    return o == null ? "null" : o.toString();
  }

  static public String str(char[] c) {
    return new String(c);
  }

  static public double fraction(double d) {
    return d % 1;
  }

  static public String n_fancy2(long l, String singular, String plural) {
    return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
  }

  static public String n_fancy2(Collection l, String singular, String plural) {
    return n_fancy2(l(l), singular, plural);
  }

  static public String n_fancy2(Map m, String singular, String plural) {
    return n_fancy2(l(m), singular, plural);
  }

  static public String n_fancy2(Object[] a, String singular, String plural) {
    return n_fancy2(l(a), singular, plural);
  }

  static public String n_fancy2(MultiSet ms, String singular, String plural) {
    return n_fancy2(l(ms), singular, plural);
  }

  static public Pair<JTabbedPane, Integer> 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(() -> {
        if (idx < tabs.getTabCount())
          tabs.setTitleAt(idx, title);
      });
    }
  }

  static public String fromLines(Iterable lines) {
    StringBuilder buf = new StringBuilder();
    if (lines != null)
      for (Object line : lines) buf.append(str(line)).append('\n');
    return buf.toString();
  }

  static public String fromLines(String... lines) {
    return fromLines(asList(lines));
  }

  static public <A> ArrayList<A> asList(A[] a) {
    return a == null ? new ArrayList<A>() : new ArrayList<A>(Arrays.asList(a));
  }

  static public ArrayList<Integer> asList(int[] a) {
    if (a == null)
      return null;
    ArrayList<Integer> l = emptyList(a.length);
    for (int i : a) l.add(i);
    return l;
  }

  static public ArrayList<Long> asList(long[] a) {
    if (a == null)
      return null;
    ArrayList<Long> l = emptyList(a.length);
    for (long i : a) l.add(i);
    return l;
  }

  static public ArrayList<Float> asList(float[] a) {
    if (a == null)
      return null;
    ArrayList<Float> l = emptyList(a.length);
    for (float i : a) l.add(i);
    return l;
  }

  static public ArrayList<Double> asList(double[] a) {
    if (a == null)
      return null;
    ArrayList<Double> l = emptyList(a.length);
    for (double i : a) l.add(i);
    return l;
  }

  static public ArrayList<Short> asList(short[] a) {
    if (a == null)
      return null;
    ArrayList<Short> l = emptyList(a.length);
    for (short i : a) l.add(i);
    return l;
  }

  static public <A> ArrayList<A> asList(Iterator<A> it) {
    ArrayList l = new ArrayList();
    if (it != null)
      while (it.hasNext()) l.add(it.next());
    return l;
  }

  static public <A> ArrayList<A> asList(IterableIterator<A> s) {
    return asList((Iterator) s);
  }

  static public <A> ArrayList<A> asList(Iterable<A> 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 <A> ArrayList<A> asList(Producer<A> p) {
    ArrayList l = new ArrayList();
    A a;
    if (p != null)
      while ((a = p.next()) != null) l.add(a);
    return l;
  }

  static public <A> ArrayList<A> asList(Enumeration<A> e) {
    ArrayList l = new ArrayList();
    if (e != null)
      while (e.hasMoreElements()) l.add(e.nextElement());
    return l;
  }

  static public <A> List<A> asList(Pair<A, A> p) {
    return p == null ? null : ll(p.a, p.b);
  }

  static public IterableIterator<String> toLines(File f) {
    return linesFromFile(f);
  }

  static public List<String> toLines(String s) {
    List<String> lines = new ArrayList<String>();
    if (s == null)
      return lines;
    int start = 0;
    while (true) {
      int i = toLines_nextLineBreak(s, start);
      if (i < 0) {
        if (s.length() > start)
          lines.add(s.substring(start));
        break;
      }
      lines.add(s.substring(start, i));
      if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
        i += 2;
      else
        ++i;
      start = i;
    }
    return lines;
  }

  static public int toLines_nextLineBreak(String s, int start) {
    int n = s.length();
    for (int i = start; i < n; i++) {
      char c = s.charAt(i);
      if (c == '\r' || c == '\n')
        return i;
    }
    return -1;
  }

  static public List<String> mapToLines(Map map) {
    List<String> l = new ArrayList();
    for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
    return l;
  }

  static public String mapToLines(Map map, Object f) {
    return lines(map(map, f));
  }

  static public String mapToLines(Object f, Map map) {
    return lines(map(map, f));
  }

  static public String mapToLines(Object f, Iterable l) {
    return lines(map(f, l));
  }

  static public <A> String mapToLines(Iterable<A> l, IF1<A, String> f) {
    return mapToLines((Object) f, l);
  }

  static public <A> String mapToLines(IF1<A, String> f, Iterable<A> l) {
    return mapToLines((Object) f, l);
  }

  static public <A, B> String mapToLines(Map<A, B> map, IF2<A, B, String> f) {
    return lines(map(map, f));
  }

  static public <A> String mapToLines(IF1<A, String> f, A data1, A... moreData) {
    return lines(map(f, data1, moreData));
  }

  static public List<String> sortedIgnoreCase(Collection<String> c) {
    List<String> l = cloneList(c);
    Collections.sort(l, caseInsensitiveComparator());
    return l;
  }

  static public ArrayList emptyList() {
    return new ArrayList();
  }

  static public ArrayList emptyList(int capacity) {
    return new ArrayList(max(0, capacity));
  }

  static public ArrayList emptyList(Iterable l) {
    return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
  }

  static public ArrayList emptyList(Object[] l) {
    return emptyList(l(l));
  }

  static public <A> ArrayList<A> emptyList(Class<A> c) {
    return new ArrayList();
  }

  static public double nanosToMicroseconds(double ns) {
    return ns / 1000;
  }

  static public boolean isComponentShowing(final Component c) {
    return c != null && swing(new F0<Boolean>() {

      public Boolean get() {
        try {
          return c.isShowing();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret c.isShowing();";
      }
    });
  }

  static public BufferedImage newBufferedImage(int w, int h) {
    return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  }

  static public BufferedImage newBufferedImage(int w, int h, RGB rgb) {
    return newBufferedImage(w, h, rgb.getColor());
  }

  static public BufferedImage newBufferedImage(int w, int h, Color color) {
    BufferedImage img = newBufferedImage(w, h);
    Graphics2D g = img.createGraphics();
    g.setColor(or(color, Color.white));
    g.fillRect(0, 0, w, h);
    return img;
  }

  static public BufferedImage newBufferedImage(Pt p, Color color) {
    return newBufferedImage(p.x, p.y, color);
  }

  static public BufferedImage newBufferedImage(int w, int h, int[] pixels) {
    return intArrayToBufferedImage(pixels, w, h);
  }

  static public <A, B> Map<A, B> synchroIdentityHashMap() {
    return synchroMap(new IdentityHashMap());
  }

  static public <A, B> void mapPut2(Map<A, B> map, A key, B value) {
    if (map != null && key != null)
      if (value != null)
        map.put(key, value);
      else
        map.remove(key);
  }

  static public BWIntegralImage bwIntegralImage(BufferedImage img) {
    return img == null ? null : new BWIntegralImage(img);
  }

  static public BWIntegralImage bwIntegralImage(BWImage img) {
    return img == null ? null : new BWIntegralImage(img);
  }

  static public <A> List<A> nonNulls(Iterable<A> l) {
    return withoutNulls(l);
  }

  static public <A> List<A> nonNulls(A[] l) {
    return withoutNulls(l);
  }

  static public <A, B> Map<A, B> nonNulls(Map<A, B> map) {
    return withoutNulls(map);
  }

  static public JComboBox jcombobox(final String... items) {
    return swing(new F0<JComboBox>() {

      public JComboBox get() {
        try {
          return new JComboBox(items);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret new JComboBox(items);";
      }
    });
  }

  static public JComboBox jcombobox(Collection<String> items) {
    return jcombobox(toStringArray(items));
  }

  static public JComboBox jcombobox(Collection<String> items, String selectedItem) {
    return selectItem(selectedItem, jcombobox(items));
  }

  static public void selectRow(final JTable table, final int i) {
    if (table != null) {
      swing(() -> {
        if (i >= 0 && i < table.getRowCount()) {
          table.setRowSelectionInterval(i, i);
          scrollRowToVisible(table, i);
        } else
          table.clearSelection();
      });
    }
  }

  static public void selectRow(final JList list, final int i) {
    if (list != null) {
      swing(() -> {
        if (i >= 0 && i < listRowCount(list))
          list.setSelectedIndex(i);
        else
          list.clearSelection();
      });
    }
  }

  static public <A> int jlist_indexOf(JList<A> list, A item) {
    return swing(new F0<Integer>() {

      public Integer get() {
        try {
          ListModel<A> model = list.getModel();
          int n = model.getSize();
          for (int i = 0; i < n; i++) if (eq(model.getElementAt(i), item))
            return i;
          return -1;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ListModel<A> model = list.getModel();\r\n    int n = model.getSize();\r\n    for ...";
      }
    });
  }

  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 List<Integer> countIteratorToList_inclusive(int b) {
    return countIteratorToList_inclusive(0, b);
  }

  static public List<Integer> countIteratorToList_inclusive(int a, int b) {
    return asList(countIterator_inclusive(a, b));
  }

  static public <A> List<A> countIteratorToList_inclusive(int b, IF1<Integer, A> f) {
    return countIteratorToList_inclusive(0, b, f);
  }

  static public <A> List<A> countIteratorToList_inclusive(int a, int b, IF1<Integer, A> f) {
    return asList(countIterator_inclusive(a, b, f));
  }

  static public List<Integer> countIteratorToList_inclusive(int a, int b, int step) {
    return asList(countIterator_inclusive_step(a, b, step));
  }

  static public <A> List<A> countIteratorToList_inclusive(double a, double b, double step, IF1<Double, A> f) {
    return asList(countIterator_inclusive(a, b, step, f));
  }

  static public <A> List<Double> countIteratorToList_inclusive(double a, double b, double step) {
    return asList(countIterator_inclusive_step(a, b, step));
  }

  static public <A> List<A> countIteratorToList_inclusive(IF1<Double, A> f, double a, double b, double step) {
    return asList(countIterator_inclusive_step(a, b, step, f));
  }

  static public <A> List<A> countIteratorToList_inclusive(IF1<Integer, A> f, int a, int b) {
    return countIteratorToList_inclusive(f, a, b, 1);
  }

  static public <A> List<A> countIteratorToList_inclusive(IF1<Integer, A> f, int a, int b, int step) {
    return asList(countIterator_inclusive(a, b, step, f));
  }

  static public Object pcallF(Object f, Object... args) {
    return pcallFunction(f, args);
  }

  static public <A> A pcallF(F0<A> f) {
    try {
      return f == null ? null : f.get();
    } catch (Throwable __e) {
      return null;
    }
  }

  static public <A, B> B pcallF(F1<A, B> f, A a) {
    try {
      return f == null ? null : f.get(a);
    } catch (Throwable __e) {
      return null;
    }
  }

  static public <A> void pcallF(VF1<A> f, A a) {
    try {
      {
        if (f != null)
          f.get(a);
      }
    } catch (Throwable __e) {
      printStackTrace(__e);
    }
  }

  static public Object pcallF(Runnable r) {
    try {
      {
        if (r != null)
          r.run();
      }
      return null;
    } catch (Throwable __e) {
      return null;
    }
  }

  static public <A> A pcallF(IF0<A> f) {
    try {
      return f == null ? null : f.get();
    } catch (Throwable __e) {
      return null;
    }
  }

  static public <A, B> B pcallF(IF1<A, B> f, A a) {
    try {
      return f == null ? null : f.get(a);
    } catch (Throwable __e) {
      return null;
    }
  }

  static public boolean isMainProgram() {
    return creator() == null;
  }

  static public void deleteConcepts(Collection conceptsOrIDs) {
    db_mainConcepts().deleteConcepts(asList(conceptsOrIDs));
  }

  static public <A extends Concept> List<A> deleteConcepts(Class<A> c, Object... params) {
    return deleteConcepts(db_mainConcepts(), c, params);
  }

  static public <A extends Concept> List<A> deleteConcepts(Concepts cc, Class<A> c, Object... params) {
    List<A> l = asList(findConceptsWhere(cc, c, params));
    deleteConcepts(l);
    return l;
  }

  static public <A extends Concept> void deleteConcepts(Class<A> c, IF1<A, Boolean> pred) {
    deleteConcepts(db_mainConcepts(), c, pred);
  }

  static public <A extends Concept> void deleteConcepts(Concepts cc, Class<A> c, IF1<A, Boolean> pred) {
    deleteConcepts(filter(list(cc, c), pred));
  }

  static public List<Concept> deleteConcepts(Concepts cc) {
    return deleteConcepts(cc, Concept.class);
  }

  static public void deleteConcept(long id) {
    db_mainConcepts().deleteConcept(id);
  }

  static public void deleteConcept(Concepts concepts, long id) {
    concepts.deleteConcept(id);
  }

  static public void deleteConcept(Concept c) {
    if (c != null)
      c.delete();
  }

  static public void deleteConcept(Concept.Ref ref) {
    if (ref != null)
      deleteConcept(ref.get());
  }

  static public <A> ArrayList<A> cloneList(Iterable<A> l) {
    return l instanceof Collection ? cloneList((Collection) l) : asList(l);
  }

  static public <A> ArrayList<A> cloneList(Collection<A> l) {
    if (l == null)
      return new ArrayList();
    synchronized (collectionMutex(l)) {
      return new ArrayList<A>(l);
    }
  }

  static public <A extends JComponent> A onFirstComponentShow(final A component, final Runnable onShow) {
    {
      swing(() -> {
        component.addAncestorListener(new AncestorListener() {

          public void ancestorAdded(AncestorEvent event) {
            component.removeAncestorListener(this);
            pcallF(onShow);
          }

          public void ancestorRemoved(AncestorEvent event) {
          }

          public void ancestorMoved(AncestorEvent event) {
          }
        });
      });
    }
    return component;
  }

  static public boolean confirmOKCancel(final Component owner, final String msg) {
    return isTrue(swingAndWait(new F0<Object>() {

      public Object get() {
        try {
          return JOptionPane.showConfirmDialog(owner, msg, "JavaX", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION;
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret JOptionPane.showConfirmDialog(owner,\r\n      msg, \"JavaX\", JOptionPane.OK_...";
      }
    }));
  }

  static public boolean confirmOKCancel(String msg) {
    return confirmOKCancel(null, msg);
  }

  static volatile public boolean sleep_noSleep = false;

  static public void sleep(long ms) {
    ping();
    if (ms < 0)
      return;
    if (isAWTThread() && ms > 100)
      throw fail("Should not sleep on AWT thread");
    try {
      Thread.sleep(ms);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  static public void sleep() {
    try {
      if (sleep_noSleep)
        throw fail("nosleep");
      print("Sleeping.");
      sleepQuietly();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Object callOptWithEnter(Object o, String method, String[] arg) {
    return callOptWithEnter(o, method, new Object[] { arg });
  }

  static public Object callOptWithEnter(Object o, String method, Object... args) {
    if (o == null)
      return null;
    AutoCloseable __1 = tempEnter(o);
    try {
      return callOpt_withVarargs(o, method, args);
    } finally {
      _close(__1);
    }
  }

  static public <A extends Concept> A cDeref(Concept.Ref<A> ref) {
    return ref == null ? null : ref.get();
  }

  static public JLabel jcenteredLabel(String text) {
    return setHorizontalAlignment(JLabel.CENTER, jLabel(text));
  }

  static public JLabel jcenteredLabel() {
    return jcenteredLabel(" ");
  }

  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(BitSet bs) {
    return !empty(bs);
  }

  static public boolean nempty(Map m) {
    return !empty(m);
  }

  static public boolean nempty(Iterator i) {
    return i != null && i.hasNext();
  }

  static public boolean nempty(MultiMap mm) {
    return mm != null && !mm.isEmpty();
  }

  static public boolean nempty(Object o) {
    return !empty(o);
  }

  static public boolean nempty(IntRange r) {
    return !empty(r);
  }

  static public boolean nempty(IntBuffer b) {
    return b != null && !b.isEmpty();
  }

  static public boolean nempty(Rect r) {
    return r != null && r.w != 0 && r.h != 0;
  }

  static public boolean nempty(MultiSet ms) {
    return ms != null && !ms.isEmpty();
  }

  static volatile public boolean muricaPassword_pretendNotAuthed = false;

  static public String muricaPassword() {
    if (muricaPassword_pretendNotAuthed)
      return null;
    return trim(loadTextFile(muricaPasswordFile()));
  }

  static public List<Component> getSwingChildren(Component c) {
    if (c instanceof Container)
      return asList(((Container) c).getComponents());
    return emptyList();
  }

  static public JLabel jImage(Image img) {
    return jimage(img);
  }

  static public JLabel jImage(String imageID) {
    return jimage(imageID);
  }

  static public BufferedImage resizeImageToHeight_bilinear(BufferedImage img, int newH) {
    return scaleImage_bilinear(doubleRatio(newH, img.getHeight()), img);
  }

  static public BufferedImage loadImage2(String snippetIDOrURL) {
    return loadBufferedImage(snippetIDOrURL);
  }

  static public BufferedImage loadImage2(File file) {
    return loadBufferedImage(file);
  }

  static public int imageIcon_cacheSize = 10;

  static public boolean imageIcon_verbose = false;

  static public Map<String, ImageIcon> imageIcon_cache;

  static public Lock imageIcon_lock = lock();

  static public ThreadLocal<Boolean> imageIcon_fixGIF = new ThreadLocal();

  static public ImageIcon imageIcon(String imageID) {
    try {
      if (imageID == null)
        return null;
      Lock __0 = imageIcon_lock;
      lock(__0);
      try {
        if (imageIcon_cache == null)
          imageIcon_cache = new MRUCache(imageIcon_cacheSize);
        imageID = fsI(imageID);
        ImageIcon ii = imageIcon_cache.get(imageID);
        if (ii == null) {
          if (imageIcon_verbose)
            print("Loading image icon: " + imageID);
          File f = loadBinarySnippet(imageID);
          Boolean b = imageIcon_fixGIF.get();
          if (!isFalse(b))
            ii = new ImageIcon(loadBufferedImageFixingGIFs(f));
          else
            ii = new ImageIcon(f.toURI().toURL());
        } else
          imageIcon_cache.remove(imageID);
        imageIcon_cache.put(imageID, ii);
        return ii;
      } finally {
        unlock(__0);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ImageIcon imageIcon(File f) {
    try {
      return new ImageIcon(f.toURI().toURL());
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public ImageIcon imageIcon(Image img) {
    return new ImageIcon(img);
  }

  static public ImageIcon imageIcon(RGBImage img) {
    return imageIcon(img.getBufferedImage());
  }

  static public JButton setButtonImage(BufferedImage img, JButton btn) {
    btn.setIcon(imageIcon(img));
    return btn;
  }

  static public JButton setButtonImage(JButton btn, BufferedImage img) {
    return setButtonImage(img, btn);
  }

  static public <A extends JComponent> A setToolTip(A c, Object toolTip) {
    return setToolTipText(c, toolTip);
  }

  static public <A extends JComponent> A setToolTip(Object toolTip, A c) {
    return setToolTipText(c, toolTip);
  }

  static public void setToolTip(TrayIcon trayIcon, String toolTip) {
    setTrayIconToolTip(trayIcon, toolTip);
  }

  static public BufferedImage resizeImage(BufferedImage img, int newW, int newH) {
    return resizeImage(img, newW, newH, Image.SCALE_SMOOTH);
  }

  static public BufferedImage resizeImage(BufferedImage img, int newW, int newH, int scaleType) {
    if (newW == img.getWidth() && newH == img.getHeight())
      return img;
    Image tmp = img.getScaledInstance(newW, newH, scaleType);
    BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = dimg.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();
    return dimg;
  }

  static public BufferedImage resizeImage(BufferedImage img, int newW) {
    int newH = iround(img.getHeight() * (double) newW / img.getWidth());
    return resizeImage(img, newW, newH);
  }

  static public BufferedImage resizeImage(int newW, BufferedImage img) {
    return resizeImage(img, newW);
  }

  static public void disableButtonWhileCalcing2(final Object f) {
    final JButton button = heldInstance(JButton.class);
    disableButton(button);
    {
      startThread(new Runnable() {

        public void run() {
          try {
            try {
              boolean ok = isTrue(callF(f));
              if (ok)
                disposePossiblyInternalFrame(button);
            } finally {
              enableButton(button);
            }
          } catch (Exception __e) {
            throw rethrow(__e);
          }
        }

        public String toString() {
          return "try {\r\n      boolean ok = isTrue(callF(f));\r\n      if (ok) disposePossiblyInt...";
        }
      });
    }
  }

  static public Pair<Boolean, String> transpileOnBestServer(String snippetID, String mode) {
    try {
      return haveMuricaPassword() ? transpileOnNewServer(snippetID, mode) : transpileOnServer(snippetID, mode);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public Pair<Boolean, String> transpileOnBestServer(String snippetID) {
    return transpileOnBestServer(snippetID, "quick");
  }

  static public void callFInNewThread(Object f, Object... args) {
    callF_thread(f, args);
  }

  static public boolean scrollAllTheWayDown_bruteForce = true;

  static public <A extends JComponent> A scrollAllTheWayDown(A c) {
    if (c != null) {
      swing(() -> {
        int h = c.getHeight() - 1;
        if (scrollAllTheWayDown_bruteForce)
          h = max(h, 100000);
        c.scrollRectToVisible(new Rectangle(0, h, 1, 1));
      });
    }
    return c;
  }

  static public void addButtonsToWindow(Component c, Object... buttonParams) {
    addToWindowWithMargin(c, jcenteredbuttons(buttonParams));
  }

  static public <A> A nu(Class<A> c, Object... values) {
    A a = nuObject(c);
    setAll(a, values);
    return a;
  }

  static public Object[] paramsPlus(Object[] a1, Object... a2) {
    if (a2 == null)
      return a1;
    if (a1 == null)
      return a2;
    if (l(a1) == 1 && a1[0] instanceof Map)
      return new Object[] { mapPlus((Map) a1[0], a2) };
    assertEvenLength(a1);
    assertEvenLength(a2);
    Map map = paramsToOrderedMap(a1);
    int n = l(a2);
    for (int i = 0; i < n; i += 2) {
      Object key = a2[i];
      if (key != null)
        map.put(key, a2[i + 1]);
    }
    return mapToParams(map);
  }

  static public Object[] paramsPlus(Map a1, Object... a2) {
    return paramsPlus(new Object[] { a1 }, a2);
  }

  static public Rectangle maximumWindowBounds() {
    return maxWindowBounds();
  }

  static volatile public boolean licensed_yes = true;

  static public boolean licensed() {
    if (!licensed_yes)
      return false;
    ping_okInCleanUp();
    return true;
  }

  static public void licensed_off() {
    licensed_yes = false;
  }

  static public String prependColonSpaceIfNempty(String s) {
    return empty(s) ? "" : ": " + s;
  }

  static public String getStackTrace(Throwable throwable) {
    lastException(throwable);
    return getStackTrace_noRecord(throwable);
  }

  static public String getStackTrace_noRecord(Throwable throwable) {
    StringWriter writer = new StringWriter();
    throwable.printStackTrace(new PrintWriter(writer));
    return hideCredentials(writer.toString());
  }

  static public String getStackTrace() {
    return getStackTrace_noRecord(new Throwable());
  }

  static public String getStackTrace(String msg) {
    return getStackTrace_noRecord(new Throwable(msg));
  }

  static public <A extends Component> A revalidate(final A c) {
    if (c == null || !c.isShowing())
      return c;
    {
      swing(() -> {
        c.revalidate();
        c.repaint();
      });
    }
    return c;
  }

  static public void revalidate(JFrame f) {
    revalidate((Component) f);
  }

  static public void revalidate(JInternalFrame f) {
    revalidate((Component) f);
  }

  static public int getWidth(Component c) {
    return c == null ? 0 : (int) swingCall(c, "getWidth");
  }

  static public int getHeight(Component c) {
    return c == null ? 0 : (int) swingCall(c, "getHeight");
  }

  static public void vmBus_send(String msg, Object... args) {
    Object arg = vmBus_wrapArgs(args);
    pcallFAll_minimalExceptionHandling(vm_busListeners_live(), msg, arg);
    pcallFAll_minimalExceptionHandling(vm_busListenersByMessage_live().get(msg), msg, arg);
  }

  static public void vmBus_send(String msg) {
    vmBus_send(msg, (Object) null);
  }

  static public <A> A assertNempty(A a) {
    return assertNempty("empty", a);
  }

  static public <A> A assertNempty(String msg, A a) {
    if (empty(a))
      throw fail(msg + ": " + a);
    return a;
  }

  static public File imagesDir() {
    return userDir_oneOf_createIfNone("Pictures", "OneDrive/Pictures", "OneDrive/Bilder", "Pictures", "Bilder");
  }

  static public File imagesDir(String sub) {
    return newFile(imagesDir(), sub);
  }

  static public boolean isImageFileName(String s) {
    return eqicOneOf(fileExtension(s), ".png", ".jpg", ".jpeg", ".gif");
  }

  static public File makeFileNameUnique_beforeExtension_startWith1_noDot(File f) {
    File orig = f;
    int n = 1;
    do {
      f = appendToFileBaseName(orig, str(n++));
    } while (f.exists());
    return 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 void saveImage(File f, BufferedImage img) {
    if (hasJPEGExtension(f))
      saveJPG(f, img);
    else
      savePNG(f, img);
  }

  static public String appendBracketed(Object o) {
    String b = strOrNull(o);
    return empty(b) ? "" : "" + " (" + b + ")";
  }

  static public String appendBracketed(String a, String b) {
    return a + appendBracketed(b);
  }

  static public String fileInfo(File f) {
    return renderFileInfo(f);
  }

  static public String fileInfo(String f) {
    return renderFileInfo(newFile(f));
  }

  static public byte[] bytesFromHex(String s) {
    return hexToBytes(s);
  }

  static public String dropPrefix(String prefix, String s) {
    return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
  }

  static public int ubyteToInt(byte b) {
    return b & 0x0FF;
  }

  static public int ubyteToInt(char c) {
    return c & 0x0FF;
  }

  static volatile public PersistableThrowable lastException_lastException;

  static public PersistableThrowable lastException() {
    return lastException_lastException;
  }

  static public void lastException(Throwable e) {
    lastException_lastException = persistableThrowable(e);
  }

  static public Throwable getInnerException(Throwable e) {
    if (e == null)
      return null;
    while (e.getCause() != null) e = e.getCause();
    return e;
  }

  static public Throwable getInnerException(Runnable r) {
    return getInnerException(getException(r));
  }

  static public String hideCredentials(URL url) {
    return url == null ? null : hideCredentials(str(url));
  }

  static public String hideCredentials(String url) {
    try {
      if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url)))
        return url;
    } catch (Throwable e) {
      print("HideCredentials", e);
    }
    return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=<hidden>");
  }

  static public String hideCredentials(Object o) {
    return hideCredentials(str(o));
  }

  static public String unnull(String s) {
    return s == null ? "" : s;
  }

  static public <A> Collection<A> unnull(Collection<A> l) {
    return l == null ? emptyList() : l;
  }

  static public <A> List<A> unnull(List<A> l) {
    return l == null ? emptyList() : l;
  }

  static public int[] unnull(int[] l) {
    return l == null ? emptyIntArray() : l;
  }

  static public char[] unnull(char[] l) {
    return l == null ? emptyCharArray() : l;
  }

  static public double[] unnull(double[] l) {
    return l == null ? emptyDoubleArray() : l;
  }

  static public <A, B> Map<A, B> unnull(Map<A, B> l) {
    return l == null ? emptyMap() : l;
  }

  static public <A> Iterable<A> unnull(Iterable<A> i) {
    return i == null ? emptyList() : i;
  }

  static public <A> 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 <A, B> Pair<A, B> unnull(Pair<A, B> p) {
    return p != null ? p : new Pair(null, null);
  }

  static public int unnull(Integer i) {
    return i == null ? 0 : i;
  }

  static public long unnull(Long l) {
    return l == null ? 0L : l;
  }

  static public double unnull(Double l) {
    return l == null ? 0.0 : l;
  }

  static public String baseClassName(String className) {
    return substring(className, className.lastIndexOf('.') + 1);
  }

  static public String baseClassName(Object o) {
    return baseClassName(getClassName(o));
  }

  static public String prependIfNempty(String prefix, String s) {
    return empty(s) ? unnull(s) : prefix + s;
  }

  static public void removeTrayIcon(final TrayIcon t) {
    if (t != null) {
      swing(() -> {
        SystemTray.getSystemTray().remove(t);
      });
    }
  }

  static public JFastLogView_noWrap jFastLogView_noWrap() {
    return jFastLogView_noWrap("");
  }

  static public JFastLogView_noWrap jFastLogView_noWrap(String text) {
    return withTypeWriterFont(swingNu(JFastLogView_noWrap.class, text));
  }

  static public JScrollPane jscroll_copyBackground(Component c) {
    return setScrollPaneBackground(getBackground(c), jscroll(c));
  }

  static public String stackTraceToString(StackTraceElement[] st) {
    return lines(st);
  }

  static public String stackTraceToString(Throwable e) {
    return getStackTrace_noRecord(e);
  }

  static public boolean eq(Object a, Object b) {
    return a == b || a != null && b != null && a.equals(b);
  }

  static public <A, B> B mapPutOrRemove(Map<A, B> map, A key, B value) {
    if (map != null && key != null)
      if (value != null)
        return map.put(key, value);
      else
        return map.remove(key);
    return null;
  }

  static public Map vm_generalMap_map;

  static public Map vm_generalMap() {
    if (vm_generalMap_map == null)
      vm_generalMap_map = (Map) get(javax(), "generalMap");
    return vm_generalMap_map;
  }

  static public String mcName() {
    return mc().getName();
  }

  static public String getClassName(Object o) {
    return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
  }

  static public <A extends Concept> Collection<A> findConceptsWhere(Class<A> c, Object... params) {
    return findConceptsWhere(db_mainConcepts(), c, params);
  }

  static public Collection<Concept> findConceptsWhere(String c, Object... params) {
    return findConceptsWhere(db_mainConcepts(), c, params);
  }

  static public <A extends Concept> Collection<A> findConceptsWhere(Concepts concepts, Class<A> c, Object... params) {
    ping();
    params = expandParams(c, params);
    if (concepts.fieldIndices != null)
      for (int i = 0; i < l(params); i += 2) {
        IFieldIndex<A, Object> index = concepts.getFieldIndex(c, (String) params[i]);
        if (index != null) {
          Collection<A> rawList = index.getAll(params[i + 1]);
          params = dropEntryFromParams(params, i);
          if (params == null)
            return rawList;
          List<A> 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<Concept> findConceptsWhere(Concepts concepts, String c, Object... params) {
    return filterConcepts(concepts.list(c), params);
  }

  static public <A> int iteratorCount_int_close(Iterator<A> i) {
    try {
      int n = 0;
      if (i != null)
        while (i.hasNext()) {
          i.next();
          ++n;
        }
      if (i instanceof AutoCloseable)
        ((AutoCloseable) i).close();
      return n;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A, B> Pair<A, B> mapEntryToPair(Map.Entry<A, B> e) {
    return e == null ? null : pair(e.getKey(), e.getValue());
  }

  static public <A, B> Set<Map.Entry<A, B>> entrySet(Map<A, B> map) {
    return _entrySet(map);
  }

  static public <A> A firstThat(Iterable<A> l, IF1<A, Boolean> pred) {
    for (A a : unnullForIteration(l)) if (pred.get(a))
      return a;
    return null;
  }

  static public <A> A firstThat(A[] l, IF1<A, Boolean> pred) {
    for (A a : unnullForIteration(l)) if (pred.get(a))
      return a;
    return null;
  }

  static public <A> A firstThat(IF1<A, Boolean> pred, Iterable<A> l) {
    return firstThat(l, pred);
  }

  static public <A> A firstThat(IF1<A, Boolean> pred, A[] l) {
    return firstThat(l, pred);
  }

  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) {
    if (r == null)
      return null;
    Runnable r2 = toRunnable(r);
    Object mod = dm_current_generic();
    if (mod == null)
      return r2;
    return new Runnable() {

      public void run() {
        try {
          AutoCloseable c = (AutoCloseable) (rcall("enter", mod));
          AutoCloseable __1 = c;
          try {
            r2.run();
          } finally {
            _close(__1);
          }
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "AutoCloseable c =  (AutoCloseable) (rcall enter(mod));\r\n    temp c;\r\n    r2.r...";
      }
    };
  }

  static public Thread newThread(Object runnable) {
    return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)));
  }

  static public Thread newThread(Object runnable, String name) {
    if (name == null)
      name = defaultThreadName();
    return new BetterThread(_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;
    if (o instanceof String)
      throw fail("callF_legacy");
    return new Runnable() {

      public void run() {
        try {
          callF(o);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "callF(o)";
      }
    };
  }

  static public Map<Thread, Boolean> _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 URLConnection openConnection(String url) {
    try {
      return openConnection(new URL(url));
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public URLConnection openConnection(URL url) {
    try {
      ping();
      callOpt(javax(), "recordOpenURLConnection", str(url));
      return url.openConnection();
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void setHeaders(URLConnection con) throws IOException {
    String computerID = getComputerID_quick();
    if (computerID != null)
      try {
        con.setRequestProperty("X-ComputerID", computerID);
        con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version"));
      } catch (Throwable e) {
      }
  }

  static public FileOutputStream newFileOutputStream(File path) throws IOException {
    return newFileOutputStream(path.getPath());
  }

  static public FileOutputStream newFileOutputStream(String path) throws IOException {
    return newFileOutputStream(path, false);
  }

  static public FileOutputStream newFileOutputStream(File path, boolean append) throws IOException {
    return newFileOutputStream(path.getPath(), append);
  }

  static public FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
    mkdirsForFile(path);
    FileOutputStream f = new FileOutputStream(path, append);
    _registerIO(f, path, true);
    return f;
  }

  public static File mkdirsFor(File file) {
    return mkdirsForFile(file);
  }

  static public void copyStreamWithPrints(InputStream in, OutputStream out, String pat) {
    try {
      byte[] buf = new byte[65536];
      int total = 0;
      while (true) {
        int n = in.read(buf);
        if (n <= 0)
          return;
        out.write(buf, 0, n);
        if ((total + n) / 100000 > total / 100000)
          print(pat.replace("{*}", str(roundDownTo(100000, total))));
        total += n;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public File renameFile_assertTrue(File a, File b) {
    try {
      if (a.equals(b))
        return b;
      if (!a.exists())
        throw fail("Source file not found: " + f2s(a));
      if (b.exists())
        throw fail("Target file exists: " + f2s(b));
      mkdirsForFile(b);
      if (!a.renameTo(b))
        throw fail("Can't rename " + f2s(a) + " to " + f2s(b));
      return b;
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void copyStream(InputStream in, OutputStream out) {
    try {
      byte[] buf = new byte[65536];
      while (true) {
        int n = in.read(buf);
        if (n <= 0)
          return;
        out.write(buf, 0, n);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public <A> A getVar(IF0<A> v) {
    return v == null ? null : v.get();
  }

  static public <A> A getVar(Optional<A> v) {
    return v == null ? null : v.orElse(null);
  }

  static public Object safeUnstruct(String s) {
    return unstructure(s, true);
  }

  static public <A> VF1<A> ivf1ToVF1(IVF1<A> f) {
    return f == null ? null : new VF1<A>() {

      public void get(A a) {
        try {
          f.get(a);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "f.get(a)";
      }
    };
  }

  static public Map<String, Set> vm_busListenersByMessage_live_cache;

  static public Map<String, Set> vm_busListenersByMessage_live() {
    if (vm_busListenersByMessage_live_cache == null)
      vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
    return vm_busListenersByMessage_live_cache;
  }

  static public Map<String, Set> vm_busListenersByMessage_live_load() {
    return vm_generalHashMap("busListenersByMessage");
  }

  static public <A> Set<A> syncIdentityHashSet() {
    return (Set) synchronizedSet(identityHashSet());
  }

  static public <A> A second(List<A> l) {
    return get(l, 1);
  }

  static public <A> A second(Iterable<A> l) {
    if (l == null)
      return null;
    Iterator<A> it = iterator(l);
    if (!it.hasNext())
      return null;
    it.next();
    return it.hasNext() ? it.next() : null;
  }

  static public <A> A second(A[] bla) {
    return bla == null || bla.length <= 1 ? null : bla[1];
  }

  static public <A, B> B second(Pair<A, B> p) {
    return p == null ? null : p.b;
  }

  static public <A, B, C> B second(T3<A, B, C> t) {
    return t == null ? null : t.b;
  }

  static public <A> A second(Producer<A> p) {
    if (p == null)
      return null;
    if (p.next() == null)
      return null;
    return p.next();
  }

  static public char second(String s) {
    return charAt(s, 1);
  }

  static public <A, B> B second(Either<A, B> e) {
    return e == null ? null : e.bOpt();
  }

  static public <A> A third(List<A> l) {
    return _get(l, 2);
  }

  static public <A> A third(Iterable<A> l) {
    if (l == null)
      return null;
    Iterator<A> it = iterator(l);
    for (int _repeat_0 = 0; _repeat_0 < 2; _repeat_0++) {
      if (!it.hasNext())
        return null;
      it.next();
    }
    return it.hasNext() ? it.next() : null;
  }

  static public <A> A third(Producer<A> p) {
    if (p == null)
      return null;
    for (int _repeat_1 = 0; _repeat_1 < 2; _repeat_1++) {
      if (p.next() == null)
        return null;
    }
    return p.next();
  }

  static public <A> A third(A[] bla) {
    return bla == null || bla.length <= 2 ? null : bla[2];
  }

  static public <A, B, C> C third(T3<A, B, C> t) {
    return t == null ? null : t.c;
  }

  static public <A> VF1<A> runnableToVF1(final Runnable r) {
    return r == null ? null : new VF1<A>() {

      public void get(A a) {
        try {
          r.run();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "r.run()";
      }
    };
  }

  static public boolean startsWithIgnoreCase(String a, String b) {
    return regionMatchesIC(a, 0, b, 0, b.length());
  }

  public static boolean isSnippetID(String s) {
    try {
      parseSnippetID(s);
      return true;
    } catch (RuntimeException e) {
      return false;
    }
  }

  public static long parseSnippetID(String snippetID) {
    long id = Long.parseLong(shortenSnippetID(snippetID));
    if (id == 0)
      throw fail("0 is not a snippet ID");
    return id;
  }

  static public 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 jextract(String pat, String s) {
    return jextract(pat, javaTok(s));
  }

  static public String jextract(String pat, List<String> tok) {
    List<String> tokpat = javaTok(pat);
    jfind_preprocess(tokpat);
    int i = jfind(tok, tokpat);
    if (i < 0)
      return null;
    int j = i + l(tokpat) - 2;
    return joinSubList(tok, i, j);
  }

  static public Object vm_generalMap_set(Object key, Object value) {
    return vm_generalMap_put(key, value);
  }

  static public int indexOfIC(List<String> a, String b) {
    return indexOfIgnoreCase(a, b);
  }

  static public int indexOfIC(List<String> a, String b, int i) {
    return indexOfIgnoreCase(a, b, i);
  }

  static public int indexOfIC(String[] a, String b) {
    return indexOfIC(a, b, 0);
  }

  static public int indexOfIC(String[] a, String b, int i) {
    return indexOfIgnoreCase(a, b, i);
  }

  static public int indexOfIC(String a, String b) {
    return indexOfIgnoreCase(a, b);
  }

  static public int indexOfIC(String a, String b, int i) {
    return indexOfIgnoreCase(a, b, 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 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(int a, int b) {
    return a < b ? -1 : a == b ? 0 : 1;
  }

  static public int cmp(long a, long 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 Rect boundsAsRect(Component c) {
    return boundsRect(c);
  }

  static public <A> int indexOfMax(List<A> l, IF1<A, Comparable> f) {
    Best_comparable<Integer> best = new Best_comparable();
    for (int i = 0; i < l(l); i++) best.put(i, f.get(l.get(i)));
    return or(best.get(), -1);
  }

  static public boolean containsIgnoreCase(Collection<String> l, String s) {
    if (l != null)
      for (String x : l) if (eqic(x, s))
        return true;
    return false;
  }

  static public boolean containsIgnoreCase(String[] l, String s) {
    if (l != null)
      for (String x : l) if (eqic(x, s))
        return true;
    return false;
  }

  static public boolean containsIgnoreCase(String s, char c) {
    return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
  }

  static public boolean containsIgnoreCase(String a, String b) {
    return indexOfIgnoreCase(a, b) >= 0;
  }

  static public File javaxDataDir_dir;

  static public File javaxDataDir() {
    return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
  }

  static public File javaxDataDir(String... subs) {
    return newFile(javaxDataDir(), subs);
  }

  static public String formatSnippetIDOpt(String s) {
    return isSnippetID(s) ? formatSnippetID(s) : s;
  }

  static volatile public String caseID_caseID;

  static public String caseID() {
    return caseID_caseID;
  }

  static public void caseID(String id) {
    caseID_caseID = id;
  }

  static public File getProgramFile(String progID, String fileName) {
    if (new File(fileName).isAbsolute())
      return new File(fileName);
    return new File(getProgramDir(progID), fileName);
  }

  static public File getProgramFile(String fileName) {
    return getProgramFile(getProgramID(), fileName);
  }

  static public <A, B> LinkedHashMap<A, B> cloneLinkedHashMap(Map<A, B> map) {
    return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
  }

  static public Map synchroHashMap() {
    return synchronizedMap(new HashMap());
  }

  static public Map synchronizedMap() {
    return synchroMap();
  }

  static public <A, B> Map<A, B> synchronizedMap(Map<A, B> map) {
    return synchroMap(map);
  }

  static public void _onJavaXSet() {
  }

  static public boolean nemptyString(String s) {
    return s != null && s.length() > 0;
  }

  static public int strL(String s) {
    return s == null ? 0 : s.length();
  }

  static public int listL(Collection l) {
    return l == null ? 0 : l.size();
  }

  static public boolean neq(Object a, Object b) {
    return !eq(a, b);
  }

  static public int lCharSequence(CharSequence s) {
    return s == null ? 0 : s.length();
  }

  static public String unnullForIteration(String s) {
    return s == null ? "" : s;
  }

  static public <A> Collection<A> unnullForIteration(Collection<A> l) {
    return l == null ? immutableEmptyList() : l;
  }

  static public <A> List<A> unnullForIteration(List<A> l) {
    return l == null ? immutableEmptyList() : l;
  }

  static public int[] unnullForIteration(int[] l) {
    return l == null ? emptyIntArray() : l;
  }

  static public char[] unnullForIteration(char[] l) {
    return l == null ? emptyCharArray() : l;
  }

  static public double[] unnullForIteration(double[] l) {
    return l == null ? emptyDoubleArray() : l;
  }

  static public short[] unnullForIteration(short[] l) {
    return l == null ? emptyShortArray() : l;
  }

  static public <A, B> Map<A, B> unnullForIteration(Map<A, B> l) {
    return l == null ? immutableEmptyMap() : l;
  }

  static public <A> Iterable<A> unnullForIteration(Iterable<A> i) {
    return i == null ? immutableEmptyList() : i;
  }

  static public <A> A[] unnullForIteration(A[] a) {
    return a == null ? (A[]) emptyObjectArray() : a;
  }

  static public BitSet unnullForIteration(BitSet b) {
    return b == null ? new BitSet() : b;
  }

  static public Pt unnullForIteration(Pt p) {
    return p == null ? new Pt() : p;
  }

  static public <A, B> Pair<A, B> unnullForIteration(Pair<A, B> p) {
    return p != null ? p : new Pair(null, null);
  }

  static public long unnullForIteration(Long l) {
    return l == null ? 0L : l;
  }

  static public void setMeta(IMeta o, Object key, Object value) {
    metaMapPut(o, key, value);
  }

  static public double doubleRatio(double x, double y) {
    return y == 0 ? 0 : x / y;
  }

  static public double doubleRatio(Seconds x, Seconds y) {
    return doubleRatio(x.get(), y.get());
  }

  static public byte[] scaledGrayBytesFromBWIntegralImage(int w, BWIntegralImage img) {
    return scaledGrayBytesFromBWIntegralImage(img, w);
  }

  static public byte[] scaledGrayBytesFromBWIntegralImage(BWIntegralImage img, int w) {
    return scaledGrayBytesFromBWIntegralImage(img, w, heightForWidth(img, w));
  }

  static public byte[] scaledGrayBytesFromBWIntegralImage(BWIntegralImage img, int w, int h) {
    int w1 = img.getWidth(), h1 = img.getHeight();
    double stepX = doubleRatio(w1, w), stepY = doubleRatio(h1, h);
    byte[] pixels = new byte[w * h];
    int i = 0;
    double srcY = 0;
    for (int y = 0; y < h; y++) {
      double srcX = 0, nextSrcY = srcY + stepY;
      for (int x = 0; x < w; x++) {
        double nextSrcX = srcX + stepX;
        int pixel = iround(img.getPixelAverage(srcX, srcY, nextSrcX, nextSrcY));
        pixels[i++] = clampToUByte(pixel);
        srcX = nextSrcX;
      }
      srcY = nextSrcY;
    }
    return pixels;
  }

  static public byte[] scaledGrayBytesFromBWIntegralImage(int w, IBWIntegralImage img) {
    return scaledGrayBytesFromBWIntegralImage(img, w);
  }

  static public byte[] scaledGrayBytesFromBWIntegralImage(IBWIntegralImage img, int w) {
    return scaledGrayBytesFromBWIntegralImage(img, w, heightForWidth(img, w));
  }

  static public byte[] scaledGrayBytesFromBWIntegralImage(IBWIntegralImage img, int w, int h) {
    int w1 = img.getWidth(), h1 = img.getHeight();
    double stepX = doubleRatio(w1, w), stepY = doubleRatio(h1, h);
    byte[] pixels = new byte[w * h];
    int i = 0;
    double srcY = 0;
    for (int y = 0; y < h; y++) {
      double srcX = 0, nextSrcY = srcY + stepY;
      for (int x = 0; x < w; x++) {
        double nextSrcX = srcX + stepX;
        int pixel = iround(img.getPixelAverage(srcX, srcY, nextSrcX, nextSrcY));
        pixels[i++] = clampToUByte(pixel);
        srcX = nextSrcX;
      }
      srcY = nextSrcY;
    }
    return pixels;
  }

  static public double parseDouble(String s) {
    return empty(s) ? 0.0 : Double.parseDouble(s);
  }

  static public Point getMouseLocation() {
    return MouseInfo.getPointerInfo().getLocation();
  }

  static public <A extends Component> A repaint(A c) {
    if (c != null)
      c.repaint();
    return c;
  }

  static public void imageSurface_unpixelated(ImageSurface imageSurface) {
    if (imageSurface == null)
      return;
    imageSurface.interpolationMode = RenderingHints.VALUE_INTERPOLATION_BILINEAR;
    repaint(imageSurface);
  }

  static public BufferedImage toBufferedImageOpt(Object o) {
    if (o instanceof BufferedImage)
      return ((BufferedImage) o);
    if (o instanceof Image)
      return copyImage((Image) o);
    if (o instanceof MakesBufferedImage)
      return ((MakesBufferedImage) o).getBufferedImage();
    if (o instanceof File)
      if (isImageFile((File) o))
        return loadBufferedImageFile((File) o);
    String c = getClassName(o);
    if (eqOneOf(c, "main$BWImage", "main$RGBImage"))
      return (BufferedImage) call(o, "getBufferedImage");
    if (eq(c, "main$PNGFile"))
      return (BufferedImage) call(o, "getImage");
    return null;
  }

  static public <A> A swingConstruct(final Class<A> c, final Object... args) {
    return swing(new F0<A>() {

      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 extends JComponent> A bindToolTipToLiveValue(LiveValue lv, A c) {
    bindLiveValueListenerToComponent(c, lv, new Runnable() {

      public void run() {
        try {
          setToolTipText(c, strOrNull(lv.get()));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "setToolTipText(c, strOrNull(lv!))";
      }
    });
    return c;
  }

  static public void lock(Lock lock) {
    try {
      ping();
      if (lock == null)
        return;
      try {
        vmBus_send("locking", lock, "thread", currentThread());
        lock.lockInterruptibly();
        vmBus_send("locked", lock, "thread", currentThread());
      } catch (InterruptedException e) {
        Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
        print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
        printStackTrace(e);
        rethrow(e);
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public void lock(Lock lock, String msg) {
    print("Locking: " + msg);
    lock(lock);
  }

  static public void lock(Lock lock, String msg, long timeout) {
    print("Locking: " + msg);
    lockOrFail(lock, timeout);
  }

  static public ReentrantLock lock() {
    return fairLock();
  }

  static public void unlock(Lock lock, String msg) {
    if (lock == null)
      return;
    lock.unlock();
    vmBus_send("unlocked", lock, "thread", currentThread());
    print("Unlocked: " + msg);
  }

  static public void unlock(Lock lock) {
    if (lock == null)
      return;
    lock.unlock();
    vmBus_send("unlocked", lock, "thread", currentThread());
  }

  static public Object swingCall(final Object o, final String method, final Object... args) {
    return swing(new F0<Object>() {

      public Object get() {
        try {
          return call(o, method, args);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret call(o, method, args);";
      }
    });
  }

  static public JTabbedPane jLeftTabs(Object... x) {
    JTabbedPane tabs = jtabs(x);
    tabs.setTabPlacement(JTabbedPane.LEFT);
    return tabs;
  }

  static public JTabbedPane jLeftTabs(Collection c) {
    return jLeftTabs(toObjectArray(c));
  }

  static public JTabbedPane jtabs(Object... x) {
    return fillJTabs(swingNu(JTabbedPane.class), x);
  }

  static public JPanel jRightAlignedLine(Component... components) {
    return jrightAlignedLine(components);
  }

  static public JPanel jRightAlignedLine(List<? extends Component> components) {
    return jrightAlignedLine(components);
  }

  static public <A extends Component> 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<JScrollPane>() {

      public JScrollPane get() {
        try {
          return new JScrollPane(c);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret new JScrollPane(c);";
      }
    });
  }

  static public <A extends JComponent> A jtransparent(final A a) {
    {
      swing(() -> {
        a.setOpaque(false);
      });
    }
    return a;
  }

  static public JPanel borderLayoutPanel() {
    return jpanel(new BorderLayout());
  }

  static public JSpinner jSpinner(final int value) {
    return swing(new F0<JSpinner>() {

      public JSpinner get() {
        try {
          JSpinner s = new JSpinner();
          s.setValue(value);
          return jSpinnerCommitOnValidEdit(s);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "new JSpinner s;\r\n    s.setValue(value);\r\n    ret jSpinnerCommitOnValidEdit(s);";
      }
    });
  }

  static public JSpinner jSpinner(final int value, final int min, final int max) {
    return swing(new F0<JSpinner>() {

      public JSpinner get() {
        try {
          return jSpinnerCommitOnValidEdit(new JSpinner(new SpinnerNumberModel(value, min, max, 1)));
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret jSpinnerCommitOnValidEdit(new JSpinner(new SpinnerNumberModel(value, min,...";
      }
    });
  }

  static public int intFromSpinner(JSpinner s) {
    return toInt(s.getValue());
  }

  static public void setSpinnerValue(JSpinner s, int value) {
    setSpinnerValue(s, (Integer) value);
  }

  static public void setSpinnerValue(JSpinner s, Object value) {
    try {
      if (s != null) {
        swing(() -> {
          s.setValue(value);
        });
      }
    } catch (Throwable __e) {
      printStackTrace(__e);
    }
  }

  static public JSpinner rightAlignSpinner(JSpinner spinner) {
    setHorizontalAlignment(JTextField.RIGHT, getTextFieldFromSpinner(spinner));
    return spinner;
  }

  static public <A> JSpinner jListSpinner(List<A> entries, A defaultValue) {
    return swing(() -> {
      JSpinner s = new JSpinner();
      s.setModel(new SpinnerListModel(entries));
      if (contains(entries, defaultValue))
        setSpinnerValue(s, defaultValue);
      return s;
    });
  }

  static public List<Integer> powersOfTwoUpTo(int n) {
    IntBuffer l = new IntBuffer();
    int i = 1;
    while (i <= n && i > 0) {
      l.add(i);
      i *= 2;
    }
    return l.asVirtualList();
  }

  static public String formatWithThousandsSeparator(long l) {
    return NumberFormat.getInstance(new Locale("en_US")).format(l);
  }

  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 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 CloseableIterableIterator<String> linesFromFile(File f) {
    return linesFromFile(f, null);
  }

  static public CloseableIterableIterator<String> linesFromFile(File f, IResourceHolder resourceHolder) {
    try {
      if (!f.exists())
        return emptyCloseableIterableIterator();
      if (ewic(f.getName(), ".gz"))
        return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)), resourceHolder);
      return linesFromReader(utf8bufferedReader(f), resourceHolder);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public CloseableIterableIterator<String> linesFromFile(String path) {
    return linesFromFile(path, null);
  }

  static public CloseableIterableIterator<String> linesFromFile(String path, IResourceHolder resourceHolder) {
    return linesFromFile(newFile(path), resourceHolder);
  }

  static public <A, B> Set<A> keys(Map<A, B> map) {
    return map == null ? new HashSet() : map.keySet();
  }

  static public Set keys(Object map) {
    return keys((Map) map);
  }

  static public <A> Set<A> keys(MultiSet<A> ms) {
    return ms.keySet();
  }

  static public <A, B> Set<A> keys(MultiMap<A, B> mm) {
    return mm.keySet();
  }

  static public <A> A or(A a, A b) {
    return a != null ? a : b;
  }

  static public BufferedImage intArrayToBufferedImage(int[] pixels, int w, int h) {
    int[] bitMasks = new int[] { 0xFF0000, 0xFF00, 0xFF, 0xFF000000 };
    SinglePixelPackedSampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, w, h, bitMasks);
    DataBufferInt db = new DataBufferInt(pixels, pixels.length);
    WritableRaster wr = Raster.createWritableRaster(sm, db, new Point());
    return new BufferedImage(ColorModel.getRGBdefault(), wr, false, null);
  }

  static public Map synchroMap() {
    return synchroHashMap();
  }

  static public <A, B> Map<A, B> synchroMap(Map<A, B> map) {
    return new SynchronizedMap(map);
  }

  static public <A> List<A> withoutNulls(Iterable<A> l) {
    if (l instanceof List)
      if (!containsNulls((List) l))
        return ((List) l);
    List<A> l2 = new ArrayList();
    for (A a : l) if (a != null)
      l2.add(a);
    return l2;
  }

  static public <A, B> Map<A, B> withoutNulls(Map<A, B> map) {
    Map<A, B> map2 = similarEmptyMap(map);
    for (A a : keys(map)) if (a != null) {
      B b = map.get(a);
      if (b != null)
        map2.put(a, b);
    }
    return map2;
  }

  static public <A> List<A> withoutNulls(A[] l) {
    List<A> l2 = new ArrayList();
    if (l != null)
      for (A a : l) if (a != null)
        l2.add(a);
    return l2;
  }

  static public String[] toStringArray(Collection<String> c) {
    String[] a = new String[l(c)];
    Iterator<String> 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<String>) o);
    else
      throw fail("Not a collection or array: " + getClassName(o));
  }

  static public void scrollRowToVisible(JTable t, int rowIndex) {
    int colIndex = 0;
    if (!(t.getParent() instanceof JViewport))
      return;
    JViewport viewport = (JViewport) t.getParent();
    Rectangle rect = t.getCellRect(rowIndex, colIndex, true);
    Rectangle viewRect = viewport.getViewRect();
    int x = viewRect.x;
    int y = viewRect.y;
    if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)) {
    } else if (rect.x < viewRect.x) {
      x = rect.x;
    } else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
      x = rect.x - viewRect.width + rect.width;
    }
    if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)) {
    } else if (rect.y < viewRect.y) {
      y = rect.y;
    } else if (rect.y > (viewRect.y + viewRect.height - rect.height)) {
      y = rect.y - viewRect.height + rect.height;
    }
    viewport.setViewPosition(new Point(x, y));
  }

  static public int listRowCount(JList list) {
    return list == null ? 0 : swing(new F0<Integer>() {

      public Integer get() {
        try {
          return list.getModel().getSize();
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "ret list.getModel().getSize();";
      }
    });
  }

  static public Runnable addThreadInfoToRunnable(final Object r) {
    final Object info = _threadInfo();
    return info == null ? asRunnable(r) : new Runnable() {

      public void run() {
        try {
          _inheritThreadInfo(info);
          callF(r);
        } catch (Exception __e) {
          throw rethrow(__e);
        }
      }

      public String toString() {
        return "_inheritThreadInfo(info); callF(r);";
      }
    };
  }

  static public IterableIterator<Integer> countIterator_inclusive(final int a, final int b) {
    return countIterator_exclusive(a, b + 1);
  }

  static public <A> IterableIterator<A> countIterator_inclusive(int a, int b, IF1<Integer, A> f) {
    return countIterator_inclusive(a, b, 1, f);
  }

  static public <A> IterableIterator<A> countIterator_inclusive(int a, int b, int step, IF1<Integer, A> f) {
    return countIterator_inclusive_step(a, b, 1, f);
  }

  static public <A> IterableIterator<A> countIterator_inclusive(double a, double b, double step, IF1<Double, A> f) {
    return countIterator_inclusive_step(a, b, step, f);
  }

  static public IterableIterator<Integer> countIterator_inclusive_step(int a, final int b, int step) {
    assertTrue("step > 0", step > 0);
    return new IterableIterator<Integer>() {

      public int i = a;

      public boolean hasNext() {
        return i <= b;
      }

      public Integer next() {
        var j = i;
        i += step;
        return j;
      }
    };
  }

  static public IterableIterator<Double> countIterator_inclusive_step(double a, double b, double step) {
    assertTrue("step > 0", step > 0);
    return new IterableIterator<Double>() {

      public double i = a;

      public boolean hasNext() {
        return i <= b;
      }

      public Double next() {
        var j = i;
        i += step;
        return j;
      }
    };
  }

  static public <A> IterableIterator<A> countIterator_inclusive_step(double a, double b, double step, IF1<Double, A> f) {
    return mapI_if1(f, countIterator_inclusive_step(a, b, step));
  }

  static public <A> IterableIterator<A> countIterator_inclusive_step(int a, int b, int step, IF1<Integer, A> f) {
    return mapI_if1(f, countIterator_inclusive_step(a, b, step));
  }

  static public Object pcallFunction(Object f, Object... args) {
    try {
      return callFunction(f, args);
    } catch (Throwable __e) {
      printStackTrace(__e);
    }
    return null;
  }

  static public Object collectionMutex(List l) {
    return l;
  }

  static public Object collectionMutex(Object o) {
    if (o instanceof List)
      return o;
    String c = className(o);
    if (eq(c, "java.util.TreeMap$KeySet"))
      c = className(o = getOpt(o, "m"));
    else if (eq(c, "java.util.HashMap$KeySet"))
      c = className(o = get_raw(o, "this$0"));
    if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
      c = className(o = get_raw(o, "m"));
    return o;
  }

  static public Object sleepQuietly_monitor = new Object();

  static public void sleepQuietly() {
    try {
      assertFalse(isAWTThread());
      synchronized (sleepQuietly_monitor) {
        sleepQuietly_monitor.wait();
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public AutoCloseable tempEnter(Object o) {
    return o == null ? null : optCast(AutoCloseable.class, rcallOpt("enter", o));
  }

  static public AutoCloseable tempEnter(Enterable o) {
    return o == null ? null : o.enter();
  }

  static public Object callOpt_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.findMethod(method, args);
        if (me == null) {
          return null;
        }
        if ((me.getModifiers() & Modifier.STATIC) == 0)
          return null;
        return invokeMethod(me, null, args);
      } else {
        Class c = o.getClass();
        _MethodCache cache = callOpt_getCache(c);
        Method me = cache.findMethod(method, args);
        if (me != null)
          return invokeMethod(me, o, args);
        List<Method> 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);
          }
        return null;
      }
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  static public JLabel jLabel(String text) {
    return jlabel(text);
  }

  static public JLabel jLabel() {
    return jlabel();
  }

  static public String loadTextFile(String fileName) {
    return loadTextFile(fileName, null);
  }

  static public String loadTextFile(File f, String defaultContents) {
    return loadTextFile(f, defaultContents, "UTF-8");
  }

  static public String loadTextFile(File f, String defaultContents, String encoding) {
    try {
      checkFileNotTooBigToRead(f);
      if (f == null || !f.exists())
        return defaultContents;
      FileInputStream fileInputStream = new FileInputStream(f);
      InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, encoding);
      return loadTextFile(inputStreamReader);
    } catch (Exception __e) {
      throw rethrow(__e);
    }
  }

  public static String loadTextFile(File fileName) {
    return loadTextFile(fileName, null);
  }

  static public String loadTextFile(String fileName, String defaultContents) {
    return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
  }

  static public String loadTextFile(Reader reader) throws IOException {
    StringBuilder builder = new StringBuilder();
    try {
      char[] buffer = new char[1024];
      int n;
      while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
    } finally {
      reader.close();
    }
    return str(builder);
  }

  static public File muricaPasswordFile() {
    return new File(javaxSecretDir(), "murica/muricaPasswordFile");
  }

  static public JLabel jim
[...]

Author comment

Began life as a copy of #1033525

full source  download  show line numbers  debug dex  old transpilations   

Travelled to 3 computer(s): bhatertpkbcr, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1033636
Snippet name: Gazelle 22 Standalone [stable version]
Eternal ID of this version: #1033636/25
Text MD5: 51a7295aa229a4ae9c8b296f2d932f51
Transpilation MD5: 4c6fa38870f514b15736bd85f2cbcc56
Author: stefan
Category: javax / screen recognition
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-01-09 16:30:36
Source code size: 604779 bytes / 20985 lines
Pitched / IR pitched: No / No
Views / Downloads: 505 / 2797
Version history: 24 change(s)
Referenced in: [show references]