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

6088
LINES

< > BotCompany Repo | #1028472 // Older version of #1028445, not fully working either (working transpilation is probably older than this)

JavaX source code (Dynamic Module) [tags: use-pretranspiled] - run with: Stefan's OS

Uses 911K of libraries. Click here for Pure Java version (6236L/30K).

1  
!7
2  
3  
lib 1019849
4  
5  
import java.util.*;
6  
import java.util.zip.*;
7  
import java.util.List;
8  
import java.util.regex.*;
9  
import java.util.concurrent.*;
10  
import java.util.concurrent.atomic.*;
11  
import java.util.concurrent.locks.*;
12  
import javax.swing.*;
13  
import javax.swing.event.*;
14  
import javax.swing.text.*;
15  
import javax.swing.table.*;
16  
import java.io.*;
17  
import java.net.*;
18  
import java.lang.reflect.*;
19  
import java.lang.ref.*;
20  
import java.lang.management.*;
21  
import java.security.*;
22  
import java.security.spec.*;
23  
import java.awt.*;
24  
import java.awt.event.*;
25  
import java.awt.image.*;
26  
import javax.imageio.*;
27  
import java.math.*;
28  
import x30_pkg.x30_util;
29  
import static x30_pkg.x30_util.VF1;
30  
import static x30_pkg.x30_util.l;
31  
import static x30_pkg.x30_util.fail;
32  
import static x30_pkg.x30_util.indexOf;
33  
import static x30_pkg.x30_util.getOpt;
34  
import static x30_pkg.x30_util.setOpt;
35  
import static x30_pkg.x30_util.callOpt;
36  
import static x30_pkg.x30_util.newWeakHashMap;
37  
import static x30_pkg.x30_util.newDangerousWeakHashMap;
38  
import static x30_pkg.x30_util.get;
39  
import static x30_pkg.x30_util.get_raw;
40  
import static x30_pkg.x30_util.assertTrue;
41  
import static x30_pkg.x30_util.isHeadless;
42  
import static x30_pkg.x30_util.isAndroid;
43  
import static x30_pkg.x30_util.isTrue;
44  
import x30_pkg.x30_util.DynamicObject;
45  
import loadableUtils.utils;
46  
import static loadableUtils.utils._threadInfo;
47  
import static loadableUtils.utils._threadInheritInfo;
48  
import static loadableUtils.utils._threadInfo_addMakerAndRetriever;
49  
import static loadableUtils.utils.dm_currentModule;
50  
import static loadableUtils.utils.dm_current_mandatory;
51  
import static loadableUtils.utils.match;
52  
import static loadableUtils.utils.getOpt_raw;
53  
import static loadableUtils.utils.setOpt_raw;
54  
import static loadableUtils.utils.getField;
55  
import static loadableUtils.utils.fieldType;
56  
import static loadableUtils.utils.format3;
57  
import static loadableUtils.utils.vm_generalIdentityHashSet;
58  
import static loadableUtils.utils.vm_generalHashMap;
59  
import static loadableUtils.utils.vm_generalWeakSubMap;
60  
import static loadableUtils.utils.bindToComponent;
61  
import static loadableUtils.utils.struct;
62  
import static loadableUtils.utils.structure;
63  
import static loadableUtils.utils.loadPage;
64  
import static loadableUtils.utils.loadPage_utf8;
65  
import static loadableUtils.utils.loadPageSilentlyWithTimeout;
66  
import static loadableUtils.utils.loadPageSilently;
67  
import static loadableUtils.utils.loadSnippet;
68  
import static loadableUtils.utils.loadSnippetQuietly;
69  
import static loadableUtils.utils.sendToLocalBot;
70  
import static loadableUtils.utils.sendToLocalBotOpt;
71  
import static loadableUtils.utils.sendToLocalBotQuietly;
72  
import static loadableUtils.utils.componentPopupMenu;
73  
import static loadableUtils.utils.componentPopupMenu_top;
74  
import static loadableUtils.utils.componentPopupMenu_initForComponent;
75  
import static loadableUtils.utils.componentPopupMenu_getEvent;
76  
import static loadableUtils.utils.listPopupMenu;
77  
import static loadableUtils.utils.tablePopupMenu;
78  
import static loadableUtils.utils.tablePopupMenuFirst;
79  
import static loadableUtils.utils.rowSorter_setComparators;
80  
import static loadableUtils.utils.sexyTableWithoutDrag;
81  
import static loadableUtils.utils.dm_current_generic;
82  
import static loadableUtils.utils.dm_current_mandatory_generic;
83  
import static loadableUtils.utils.cset;
84  
import static loadableUtils.utils.DynamicObject_loading;
85  
import static loadableUtils.utils.concepts_unlisted;
86  
import static loadableUtils.utils.makePopupMenuConditional;
87  
import static loadableUtils.utils.makeConceptsTable_idWidth;
88  
import static loadableUtils.utils.showConceptsTable_afterUpdate;
89  
import static loadableUtils.utils.dynamicObjectIsLoading;
90  
import static loadableUtils.utils.rethrow;
91  
import static loadableUtils.utils.hasBot;
92  
import static loadableUtils.utils.concepts_internStringsLongerThan;
93  
import loadableUtils.utils.F0;
94  
import loadableUtils.utils.F1;
95  
import loadableUtils.utils.IF1;
96  
import loadableUtils.utils.Matches;
97  
import loadableUtils.utils.BetterLabel;
98  
import loadableUtils.utils.SingleComponentPanel;
99  
import loadableUtils.utils.Snippet;
100  
import loadableUtils.utils.Q;
101  
import loadableUtils.utils.ImageSurface;
102  
import loadableUtils.utils.structure_Data;
103  
import loadableUtils.utils.structure_ClassInfo;
104  
import loadableUtils.utils.RGBImage;
105  
import loadableUtils.utils.RGB;
106  
import loadableUtils.utils.BWImage;
107  
import loadableUtils.utils.MakesBufferedImage;
108  
import loadableUtils.utils.MultiSet;
109  
import loadableUtils.utils.Concept;
110  
import loadableUtils.utils.Concepts;
111  
import loadableUtils.utils.RC;
112  
import loadableUtils.utils.IConceptIndex;
113  
import loadableUtils.utils.IFieldIndex;
114  
import loadableUtils.utils.Derefable;
115  
import loadableUtils.utils.ImageSurfaceSelector;
116  
import loadableUtils.utils.SimpleCRUD;
117  
import loadableUtils.utils.PersistableThrowable;
118  
import loadableUtils.utils.DynModule;
119  
import loadableUtils.utils.DynPrintLog;
120  
import loadableUtils.utils.DynObjectTable;
121  
import loadableUtils.utils.DynImageSurface;
122  
import loadableUtils.utils.DynCalculatedList;
123  
import loadableUtils.utils.GlobalID;
124  
import loadableUtils.utils.Rect;
125  
import loadableUtils.utils.Pt;
126  
import loadableUtils.utils.SynchronizedArrayList;
127  
import java.text.NumberFormat;
128  
129  
class main {
130  
131  
  static public class ToParse implements IFieldsToList {
132  
133  
    public Object text;
134  
135  
    public ToParse() {
136  
    }
137  
138  
    public ToParse(Object text) {
139  
      this.text = text;
140  
    }
141  
142  
    public String toString() {
143  
      return shortClassName(this) + "(" + text + ")";
144  
    }
145  
146  
    public boolean equals(Object o) {
147  
      if (!(o instanceof ToParse))
148  
        return false;
149  
      ToParse x = (ToParse) o;
150  
      return eq(text, x.text);
151  
    }
152  
153  
    public int hashCode() {
154  
      int h = 495618264;
155  
      h = boostHashCombine(h, _hashCode(text));
156  
      return h;
157  
    }
158  
159  
    public Object[] _fieldsToList() {
160  
      return new Object[] { text };
161  
    }
162  
  }
163  
164  
  static public class StarPattern implements IFieldsToList {
165  
166  
    public Object text;
167  
168  
    public StarPattern() {
169  
    }
170  
171  
    public StarPattern(Object text) {
172  
      this.text = text;
173  
    }
174  
175  
    public String toString() {
176  
      return shortClassName(this) + "(" + text + ")";
177  
    }
178  
179  
    public boolean equals(Object o) {
180  
      if (!(o instanceof StarPattern))
181  
        return false;
182  
      StarPattern x = (StarPattern) o;
183  
      return eq(text, x.text);
184  
    }
185  
186  
    public int hashCode() {
187  
      int h = -1682783042;
188  
      h = boostHashCombine(h, _hashCode(text));
189  
      return h;
190  
    }
191  
192  
    public Object[] _fieldsToList() {
193  
      return new Object[] { text };
194  
    }
195  
  }
196  
197  
  static public class QuotedString implements IFieldsToList {
198  
199  
    public Object text;
200  
201  
    public QuotedString() {
202  
    }
203  
204  
    public QuotedString(Object text) {
205  
      this.text = text;
206  
    }
207  
208  
    public boolean equals(Object o) {
209  
      if (!(o instanceof QuotedString))
210  
        return false;
211  
      QuotedString x = (QuotedString) o;
212  
      return eq(text, x.text);
213  
    }
214  
215  
    public int hashCode() {
216  
      int h = -795507783;
217  
      h = boostHashCombine(h, _hashCode(text));
218  
      return h;
219  
    }
220  
221  
    public Object[] _fieldsToList() {
222  
      return new Object[] { text };
223  
    }
224  
225  
    public String toString() {
226  
      return recordToString_quoted(this);
227  
    }
228  
  }
229  
230  
  static public class PossibleReplacement implements IFieldsToList {
231  
232  
    public Object a;
233  
234  
    public Object b;
235  
236  
    public PossibleReplacement() {
237  
    }
238  
239  
    public PossibleReplacement(Object a, Object b) {
240  
      this.b = b;
241  
      this.a = a;
242  
    }
243  
244  
    public String toString() {
245  
      return shortClassName(this) + "(" + a + ", " + b + ")";
246  
    }
247  
248  
    public boolean equals(Object o) {
249  
      if (!(o instanceof PossibleReplacement))
250  
        return false;
251  
      PossibleReplacement x = (PossibleReplacement) o;
252  
      return eq(a, x.a) && eq(b, x.b);
253  
    }
254  
255  
    public int hashCode() {
256  
      int h = -2001685567;
257  
      h = boostHashCombine(h, _hashCode(a));
258  
      h = boostHashCombine(h, _hashCode(b));
259  
      return h;
260  
    }
261  
262  
    public Object[] _fieldsToList() {
263  
      return new Object[] { a, b };
264  
    }
265  
  }
266  
267  
  static public class AModule extends DynPrintLog {
268  
269  
    transient public TransformersOnObjects too = new TransformersOnObjects();
270  
271  
    static public boolean _switchableField_maxSteps = true;
272  
273  
    public long maxSteps = 10000;
274  
275  
    transient public F1 starPatternWrapper, quotedStringMaker;
276  
277  
    public void start() {
278  
      try {
279  
        super.start();
280  
        startThread("Start", new Runnable() {
281  
282  
          public void run() {
283  
            try {
284  
              AutoCloseable __11 = enter();
285  
              try {
286  
                try {
287  
                  too.autoUnpackIterables = false;
288  
                  String ruleText = "LineByUser(\"a * is something like *\") => Assumption(\"* is a noun\")";
289  
                  too.add(new ToParse(ruleText));
290  
                  too.addTransformer(new F1<ToParse, Object>() {
291  
292  
                    public Object get(ToParse x) {
293  
                      try {
294  
                        return x.text;
295  
                      } catch (Exception __e) {
296  
                        throw rethrow(__e);
297  
                      }
298  
                    }
299  
300  
                    public String toString() {
301  
                      return "x.text";
302  
                    }
303  
                  }, new F1<Object, Object>() {
304  
305  
                    public Object get(Object o) {
306  
                      try {
307  
                        return new ToParse(o);
308  
                      } catch (Exception __e) {
309  
                        throw rethrow(__e);
310  
                      }
311  
                    }
312  
313  
                    public String toString() {
314  
                      return "ToParse(o)";
315  
                    }
316  
                  });
317  
                  too.addTransformer(new F1<String, Object>() {
318  
319  
                    public Object get(String x) {
320  
                      try {
321  
                        return splitAtDoubleArrow_pair(x);
322  
                      } catch (Exception __e) {
323  
                        throw rethrow(__e);
324  
                      }
325  
                    }
326  
327  
                    public String toString() {
328  
                      return "splitAtDoubleArrow_pair(x)";
329  
                    }
330  
                  }, new F1<Pair, Object>() {
331  
332  
                    public Object get(Pair x) {
333  
                      try {
334  
                        return joinPairWithDoubleArrow(x);
335  
                      } catch (Exception __e) {
336  
                        throw rethrow(__e);
337  
                      }
338  
                    }
339  
340  
                    public String toString() {
341  
                      return "joinPairWithDoubleArrow(x)";
342  
                    }
343  
                  });
344  
                  too.addTransformer(new F1<String, Object>() {
345  
346  
                    public Object get(String x) {
347  
                      try {
348  
                        return parseFunctionCall(x);
349  
                      } catch (Exception __e) {
350  
                        throw rethrow(__e);
351  
                      }
352  
                    }
353  
354  
                    public String toString() {
355  
                      return "parseFunctionCall(x)";
356  
                    }
357  
                  }, new F1<Pair<String, List<String>>, Object>() {
358  
359  
                    public Object get(Pair<String, List<String>> x) {
360  
                      try {
361  
                        return unparseFunctionCall(x);
362  
                      } catch (Exception __e) {
363  
                        throw rethrow(__e);
364  
                      }
365  
                    }
366  
367  
                    public String toString() {
368  
                      return "unparseFunctionCall(x)";
369  
                    }
370  
                  });
371  
                  too.addTransformer(new F1<String, Object>() {
372  
373  
                    public Object get(String x) {
374  
                      try {
375  
                        return unquoteOrNull(x);
376  
                      } catch (Exception __e) {
377  
                        throw rethrow(__e);
378  
                      }
379  
                    }
380  
381  
                    public String toString() {
382  
                      return "unquoteOrNull(x)";
383  
                    }
384  
                  }, new F1<String, String>() {
385  
386  
                    public String get(String x) {
387  
                      try {
388  
                        return quote(x);
389  
                      } catch (Exception __e) {
390  
                        throw rethrow(__e);
391  
                      }
392  
                    }
393  
394  
                    public String toString() {
395  
                      return "quote(x)";
396  
                    }
397  
                  });
398  
                  too.addTransformer(new F1<Pair, Object>() {
399  
400  
                    public Object get(Pair x) {
401  
                      try {
402  
                        return pairA(x);
403  
                      } catch (Exception __e) {
404  
                        throw rethrow(__e);
405  
                      }
406  
                    }
407  
408  
                    public String toString() {
409  
                      return "pairA(x)";
410  
                    }
411  
                  }, (p, o) -> replacePairA((Pair) p, o));
412  
                  too.addTransformer(new F1<Pair, Object>() {
413  
414  
                    public Object get(Pair x) {
415  
                      try {
416  
                        return pairB(x);
417  
                      } catch (Exception __e) {
418  
                        throw rethrow(__e);
419  
                      }
420  
                    }
421  
422  
                    public String toString() {
423  
                      return "pairB(x)";
424  
                    }
425  
                  }, (p, o) -> replacePairB((Pair) p, o));
426  
                  too.addTransformer(new F1<List, Object>() {
427  
428  
                    public Object get(List x) {
429  
                      try {
430  
                        return first(x);
431  
                      } catch (Exception __e) {
432  
                        throw rethrow(__e);
433  
                      }
434  
                    }
435  
436  
                    public String toString() {
437  
                      return "first(x)";
438  
                    }
439  
                  }, (list, element) -> cloneListReplacingElementAtIndex((List) list, 0, element));
440  
                  too.addTransformer(new F1<List, Object>() {
441  
442  
                    public Object get(List x) {
443  
                      try {
444  
                        return second(x);
445  
                      } catch (Exception __e) {
446  
                        throw rethrow(__e);
447  
                      }
448  
                    }
449  
450  
                    public String toString() {
451  
                      return "second(x)";
452  
                    }
453  
                  }, (list, element) -> cloneListReplacingElementAtIndex((List) list, 1, element));
454  
                  too.addTransformer(starPatternWrapper = new F1<QuotedString, Object>() {
455  
456  
                    public Object get(QuotedString s) {
457  
                      try {
458  
                        return s.text instanceof String && isStarPattern((String) s.text) ? new StarPattern(s.text) : null;
459  
                      } catch (Exception __e) {
460  
                        throw rethrow(__e);
461  
                      }
462  
                    }
463  
464  
                    public String toString() {
465  
                      return "s.text instanceof S && isStarPattern((S) s.text) ? StarPattern(s.text) : null";
466  
                    }
467  
                  });
468  
                  too.addTransformer(quotedStringMaker = new F1<String, Object>() {
469  
470  
                    public Object get(String s) {
471  
                      try {
472  
                        return isQuoted(s) ? new QuotedString(unquote(s)) : null;
473  
                      } catch (Exception __e) {
474  
                        throw rethrow(__e);
475  
                      }
476  
                    }
477  
478  
                    public String toString() {
479  
                      return "isQuoted(s) ? QuotedString(unquote(s)) : null";
480  
                    }
481  
                  }, new F1<Object, Object>() {
482  
483  
                    public Object get(Object o) {
484  
                      try {
485  
                        return o instanceof QuotedString ? quote(((QuotedString) o).text) : o;
486  
                      } catch (Exception __e) {
487  
                        throw rethrow(__e);
488  
                      }
489  
                    }
490  
491  
                    public String toString() {
492  
                      return "o instanceof QuotedString ? quote(o/QuotedString.text) : o";
493  
                    }
494  
                  });
495  
                  too.addTransformer(new F1<StarPattern, Object>() {
496  
497  
                    public Object get(StarPattern s) {
498  
                      try {
499  
                        Object madeFrom = too.getTrailBy(s, starPatternWrapper).argument;
500  
                        return new WithProbability(0.9, new PossibleReplacement(madeFrom, s));
501  
                      } catch (Exception __e) {
502  
                        throw rethrow(__e);
503  
                      }
504  
                    }
505  
506  
                    public String toString() {
507  
                      return "O madeFrom = too.getTrailBy(s, starPatternWrapper).argument;\r\n      ret WithP...";
508  
                    }
509  
                  });
510  
                  too.addTransformer(new F1<QuotedString, Object>() {
511  
512  
                    public Object get(QuotedString s) {
513  
                      try {
514  
                        Object madeFrom = too.getTrailBy(s, quotedStringMaker).argument;
515  
                        return new WithProbability(0.8, new PossibleReplacement(madeFrom, s));
516  
                      } catch (Exception __e) {
517  
                        throw rethrow(__e);
518  
                      }
519  
                    }
520  
521  
                    public String toString() {
522  
                      return "O madeFrom = too.getTrailBy(s, quotedStringMaker).argument;\r\n      ret WithPr...";
523  
                    }
524  
                  });
525  
                  too.addTransformer(new F1<PossibleReplacement, Object>() {
526  
527  
                    public Object get(PossibleReplacement r) {
528  
                      try {
529  
                        replaceInSource(r.a, r.b);
530  
                        return null;
531  
                      } catch (Exception __e) {
532  
                        throw rethrow(__e);
533  
                      }
534  
                    }
535  
536  
                    public String toString() {
537  
                      return "replaceInSource(r.a, r.b);\r\n      null;";
538  
                    }
539  
                  });
540  
                  stepAllWithStats(too, maxSteps);
541  
                  print();
542  
                  pnl("ToParse", map(instancesOf(ToParse.class, too.getObjects()), t -> new WithProbability(too.getProbability(t), t.text)));
543  
                } catch (Throwable __e) {
544  
                  _handleException(__e);
545  
                }
546  
              } finally {
547  
                _close(__11);
548  
              }
549  
            } catch (Exception __e) {
550  
              throw rethrow(__e);
551  
            }
552  
          }
553  
554  
          public String toString() {
555  
            return "AutoCloseable __11 = enter(); try { try {\r\n    too.autoUnpackIterables = fals...";
556  
          }
557  
        });
558  
      } catch (Exception __e) {
559  
        throw rethrow(__e);
560  
      }
561  
    }
562  
563  
    public void replaceInSource(Object a, Object b) {
564  
      print(formatFunctionCall_struct("replaceInSource", a, b));
565  
      Collection<TransformersOnObjects.TransformationTrail> trails2 = too.getTrails(a);
566  
      for (TransformersOnObjects.TransformationTrail trail2 : unnull(trails2)) {
567  
        IF2 back = too.getBackTransformer(trail2.transformer);
568  
        print("  Path back: " + trail2);
569  
        if (back == null)
570  
          print("NO BACK TRANSFORMER for " + trail2.transformer);
571  
        else {
572  
          Object c = callFIfActuallyCallable(back, trail2.argument, b);
573  
          if (c == null)
574  
            continue;
575  
          print("  Transformed " + sfu(trail2.argument) + " into " + sfu(c));
576  
          too.addObject(c, "replaceInSource");
577  
          too.addObject(new PossibleReplacement(trail2.argument, c), "replaceInSource");
578  
        }
579  
      }
580  
    }
581  
  }
582  
583  
  static public boolean _moduleClass_AModule = true;
584  
585  
  static public String programID;
586  
587  
  static public void _onLoad_initUtils() {
588  
    utils.__javax = javax();
589  
  }
590  
591  
  static public void _onLoad_defaultClassFinder() {
592  
    setDefaultClassFinder(new F1<String, Class>() {
593  
594  
      public Class get(String name) {
595  
        Class c = findClass_fullName(name);
596  
        if (c != null)
597  
          return c;
598  
        if (name.startsWith("main$"))
599  
          return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
600  
        return null;
601  
      }
602  
    });
603  
  }
604  
605  
  static public ThreadLocal<Boolean> dynamicObjectIsLoading_threadLocal() {
606  
    return DynamicObject_loading;
607  
  }
608  
609  
  static public String shortClassName(Object o) {
610  
    if (o == null)
611  
      return null;
612  
    Class c = o instanceof Class ? (Class) o : o.getClass();
613  
    String name = c.getName();
614  
    return shortenClassName(name);
615  
  }
616  
617  
  static public boolean eq(Object a, Object b) {
618  
    return a == b || a != null && b != null && a.equals(b);
619  
  }
620  
621  
  static public int boostHashCombine(int a, int b) {
622  
    return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
623  
  }
624  
625  
  static public int _hashCode(Object a) {
626  
    return a == null ? 0 : a.hashCode();
627  
  }
628  
629  
  static public String recordToString_quoted(IFieldsToList r) {
630  
    return r == null ? "null" : formatFunctionCall_quoteAll(shortName(r), r._fieldsToList());
631  
  }
632  
633  
  static public Thread startThread(Object runnable) {
634  
    return startThread(defaultThreadName(), runnable);
635  
  }
636  
637  
  static public Thread startThread(String name, Object runnable) {
638  
    runnable = wrapAsActivity(runnable);
639  
    return startThread(newThread(toRunnable(runnable), name));
640  
  }
641  
642  
  static public Thread startThread(Thread t) {
643  
    _registerThread(t);
644  
    t.start();
645  
    return t;
646  
  }
647  
648  
  static public Pair<String, String> splitAtDoubleArrow_pair(String s) {
649  
    return splitAtDoubleArrow_pair(javaTokWithBrackets(s));
650  
  }
651  
652  
  static public Pair<String, String> splitAtDoubleArrow_pair(List<String> tok) {
653  
    return listToPair(splitAtDoubleArrow(tok));
654  
  }
655  
656  
  static public String joinPairWithDoubleArrow(Pair p) {
657  
    return p == null ? "" : str(p.a) + " => " + str(p.b);
658  
  }
659  
660  
  static public Pair<String, List<String>> parseFunctionCall(String s) {
661  
    return tok_parseFunctionCall(s);
662  
  }
663  
664  
  static public Pair<String, List<String>> parseFunctionCall(List<String> tok) {
665  
    return tok_parseFunctionCall(tok);
666  
  }
667  
668  
  static public String unparseFunctionCall(Pair<String, List<String>> p) {
669  
    return p == null ? null : formatFunctionCall(p.a, toObjectArray(p.b));
670  
  }
671  
672  
  static public String unquoteOrNull(String s) {
673  
    return forceProperUnquote(s);
674  
  }
675  
676  
  static public String quote(Object o) {
677  
    if (o == null)
678  
      return "null";
679  
    return quote(str(o));
680  
  }
681  
682  
  static public String quote(String s) {
683  
    if (s == null)
684  
      return "null";
685  
    StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
686  
    quote_impl(s, out);
687  
    return out.toString();
688  
  }
689  
690  
  static public void quote_impl(String s, StringBuilder out) {
691  
    out.append('"');
692  
    int l = s.length();
693  
    for (int i = 0; i < l; i++) {
694  
      char c = s.charAt(i);
695  
      if (c == '\\' || c == '"')
696  
        out.append('\\').append(c);
697  
      else if (c == '\r')
698  
        out.append("\\r");
699  
      else if (c == '\n')
700  
        out.append("\\n");
701  
      else if (c == '\0')
702  
        out.append("\\0");
703  
      else
704  
        out.append(c);
705  
    }
706  
    out.append('"');
707  
  }
708  
709  
  static public <A, B> A pairA(Pair<A, B> p) {
710  
    return p == null ? null : p.a;
711  
  }
712  
713  
  static public <A, B> Pair<A, B> replacePairA(Pair<A, B> p, A a) {
714  
    return p == null ? null : pair(a, p.b);
715  
  }
716  
717  
  static public <A, B> B pairB(Pair<A, B> p) {
718  
    return p == null ? null : p.b;
719  
  }
720  
721  
  static public <A, B> Pair<A, B> replacePairB(Pair<A, B> p, B b) {
722  
    return p == null ? null : pair(p.a, b);
723  
  }
724  
725  
  static public Object first(Object list) {
726  
    return first((Iterable) list);
727  
  }
728  
729  
  static public <A> A first(List<A> list) {
730  
    return empty(list) ? null : list.get(0);
731  
  }
732  
733  
  static public <A> A first(A[] bla) {
734  
    return bla == null || bla.length == 0 ? null : bla[0];
735  
  }
736  
737  
  static public <A> A first(IterableIterator<A> i) {
738  
    return first((Iterator<A>) i);
739  
  }
740  
741  
  static public <A> A first(Iterator<A> i) {
742  
    return i == null || !i.hasNext() ? null : i.next();
743  
  }
744  
745  
  static public <A> A first(Iterable<A> i) {
746  
    if (i == null)
747  
      return null;
748  
    Iterator<A> it = i.iterator();
749  
    return it.hasNext() ? it.next() : null;
750  
  }
751  
752  
  static public Character first(String s) {
753  
    return empty(s) ? null : s.charAt(0);
754  
  }
755  
756  
  static public <A, B> A first(Pair<A, B> p) {
757  
    return p == null ? null : p.a;
758  
  }
759  
760  
  static public Byte first(byte[] l) {
761  
    return empty(l) ? null : l[0];
762  
  }
763  
764  
  static public <A> List<A> cloneListReplacingElementAtIndex(List<A> l, int i, A a) {
765  
    listSetIfInRange(l = cloneList(l), i, a);
766  
    return l;
767  
  }
768  
769  
  static public <A> A second(List<A> l) {
770  
    return get(l, 1);
771  
  }
772  
773  
  static public <A> A second(Iterable<A> l) {
774  
    if (l == null)
775  
      return null;
776  
    Iterator<A> it = iterator(l);
777  
    if (!it.hasNext())
778  
      return null;
779  
    it.next();
780  
    return it.hasNext() ? it.next() : null;
781  
  }
782  
783  
  static public <A> A second(A[] bla) {
784  
    return bla == null || bla.length <= 1 ? null : bla[1];
785  
  }
786  
787  
  static public <A, B> B second(Pair<A, B> p) {
788  
    return p == null ? null : p.b;
789  
  }
790  
791  
  static public <A> A second(Producer<A> p) {
792  
    if (p == null)
793  
      return null;
794  
    if (p.next() == null)
795  
      return null;
796  
    return p.next();
797  
  }
798  
799  
  static public char second(String s) {
800  
    return charAt(s, 1);
801  
  }
802  
803  
  static public boolean isStarPattern(String s) {
804  
    return containsStars(s);
805  
  }
806  
807  
  static public boolean isStarPattern(List<String> tok) {
808  
    return containsStars(tok);
809  
  }
810  
811  
  static public boolean isQuoted(String s) {
812  
    if (isNormalQuoted(s))
813  
      return true;
814  
    return isMultilineQuoted(s);
815  
  }
816  
817  
  static public String unquote(String s) {
818  
    if (s == null)
819  
      return null;
820  
    if (startsWith(s, '[')) {
821  
      int i = 1;
822  
      while (i < s.length() && s.charAt(i) == '=') ++i;
823  
      if (i < s.length() && s.charAt(i) == '[') {
824  
        String m = s.substring(1, i);
825  
        if (s.endsWith("]" + m + "]"))
826  
          return s.substring(i + 1, s.length() - i - 1);
827  
      }
828  
    }
829  
    if (s.length() > 1) {
830  
      char c = s.charAt(0);
831  
      if (c == '\"' || c == '\'') {
832  
        int l = endsWith(s, c) ? s.length() - 1 : s.length();
833  
        StringBuilder sb = new StringBuilder(l - 1);
834  
        for (int i = 1; i < l; i++) {
835  
          char ch = s.charAt(i);
836  
          if (ch == '\\') {
837  
            char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
838  
            if (nextChar >= '0' && nextChar <= '7') {
839  
              String code = "" + nextChar;
840  
              i++;
841  
              if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
842  
                code += s.charAt(i + 1);
843  
                i++;
844  
                if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
845  
                  code += s.charAt(i + 1);
846  
                  i++;
847  
                }
848  
              }
849  
              sb.append((char) Integer.parseInt(code, 8));
850  
              continue;
851  
            }
852  
            switch(nextChar) {
853  
              case '\"':
854  
                ch = '\"';
855  
                break;
856  
              case '\\':
857  
                ch = '\\';
858  
                break;
859  
              case 'b':
860  
                ch = '\b';
861  
                break;
862  
              case 'f':
863  
                ch = '\f';
864  
                break;
865  
              case 'n':
866  
                ch = '\n';
867  
                break;
868  
              case 'r':
869  
                ch = '\r';
870  
                break;
871  
              case 't':
872  
                ch = '\t';
873  
                break;
874  
              case '\'':
875  
                ch = '\'';
876  
                break;
877  
              case 'u':
878  
                if (i >= l - 5) {
879  
                  ch = 'u';
880  
                  break;
881  
                }
882  
                int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
883  
                sb.append(Character.toChars(code));
884  
                i += 5;
885  
                continue;
886  
              default:
887  
                ch = nextChar;
888  
            }
889  
            i++;
890  
          }
891  
          sb.append(ch);
892  
        }
893  
        return sb.toString();
894  
      }
895  
    }
896  
    return s;
897  
  }
898  
899  
  static public void stepAllWithStats(Steppable s) {
900  
    stepAllWithStats(s, null);
901  
  }
902  
903  
  static public void stepAllWithStats(Steppable s, Long maxSteps) {
904  
    if (s == null)
905  
      return;
906  
    long n = 0;
907  
    {
908  
      long _startTime_0 = sysNow();
909  
      try {
910  
        if (maxSteps == null)
911  
          while (s.step()) {
912  
            ping();
913  
            ++n;
914  
          }
915  
        else
916  
          while (n < maxSteps && s.step()) {
917  
            ping();
918  
            ++n;
919  
          }
920  
      } finally {
921  
        _startTime_0 = sysNow() - _startTime_0;
922  
        saveTiming(_startTime_0);
923  
      }
924  
    }
925  
    print(n2(n, "step") + " in " + lastTiming() + " ms");
926  
  }
927  
928  
  static volatile public StringBuffer local_log = new StringBuffer();
929  
930  
  static volatile public Appendable print_log = local_log;
931  
932  
  static volatile public int print_log_max = 1024 * 1024;
933  
934  
  static volatile public int local_log_max = 100 * 1024;
935  
936  
  static public boolean print_silent = false;
937  
938  
  static public Object print_byThread_lock = new Object();
939  
940  
  static volatile public ThreadLocal<Object> print_byThread;
941  
942  
  static volatile public Object print_allThreads;
943  
944  
  static volatile public Object print_preprocess;
945  
946  
  static public void print() {
947  
    print("");
948  
  }
949  
950  
  static public <A> A print(String s, A o) {
951  
    print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
952  
    return o;
953  
  }
954  
955  
  static public <A> A print(A o) {
956  
    ping_okInCleanUp();
957  
    if (print_silent)
958  
      return o;
959  
    String s = String.valueOf(o) + "\n";
960  
    print_noNewLine(s);
961  
    return o;
962  
  }
963  
964  
  static public void print_noNewLine(String s) {
965  
    Object f = getThreadLocal(print_byThread_dontCreate());
966  
    if (f == null)
967  
      f = print_allThreads;
968  
    if (f != null)
969  
      if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
970  
        return;
971  
    print_raw(s);
972  
  }
973  
974  
  static public void print_raw(String s) {
975  
    if (print_preprocess != null)
976  
      s = (String) callF(print_preprocess, s);
977  
    s = fixNewLines(s);
978  
    Appendable loc = local_log;
979  
    Appendable buf = print_log;
980  
    int loc_max = print_log_max;
981  
    if (buf != loc && buf != null) {
982  
      print_append(buf, s, print_log_max);
983  
      loc_max = local_log_max;
984  
    }
985  
    if (loc != null)
986  
      print_append(loc, s, loc_max);
987  
    System.out.print(s);
988  
  }
989  
990  
  static public void print_autoRotate() {
991  
  }
992  
993  
  static public <A extends Iterable> A pnl(String prefix, A l) {
994  
    printNumberedLines(prefix, l);
995  
    return l;
996  
  }
997  
998  
  static public <A extends Iterable> A pnl(A l) {
999  
    printNumberedLines(l);
1000  
    return l;
1001  
  }
1002  
1003  
  static public <A extends Map> A pnl(A map) {
1004  
    printNumberedLines(map);
1005  
    return map;
1006  
  }
1007  
1008  
  static public <A extends Map> A pnl(String prefix, A map) {
1009  
    printNumberedLines(prefix, map);
1010  
    return map;
1011  
  }
1012  
1013  
  static public <A> A[] pnl(A[] a) {
1014  
    printNumberedLines(a);
1015  
    return a;
1016  
  }
1017  
1018  
  static public String pnl(String s) {
1019  
    printNumberedLines(lines(s));
1020  
    return s;
1021  
  }
1022  
1023  
  static public List map(Iterable l, Object f) {
1024  
    return map(f, l);
1025  
  }
1026  
1027  
  static public List map(Object f, Iterable l) {
1028  
    List x = emptyList(l);
1029  
    if (l != null)
1030  
      for (Object o : l) x.add(callF(f, o));
1031  
    return x;
1032  
  }
1033  
1034  
  static public <A, B> List<B> map(Iterable<A> l, F1<A, B> f) {
1035  
    return map(f, l);
1036  
  }
1037  
1038  
  static public <A, B> List<B> map(F1<A, B> f, Iterable<A> l) {
1039  
    List x = emptyList(l);
1040  
    if (l != null)
1041  
      for (A o : l) x.add(callF(f, o));
1042  
    return x;
1043  
  }
1044  
1045  
  static public <A, B> List<B> map(IF1<A, B> f, Iterable<A> l) {
1046  
    return map(l, f);
1047  
  }
1048  
1049  
  static public <A, B> List<B> map(Iterable<A> l, IF1<A, B> f) {
1050  
    List x = emptyList(l);
1051  
    if (l != null)
1052  
      for (A o : l) x.add(f.get(o));
1053  
    return x;
1054  
  }
1055  
1056  
  static public <A, B> List<B> map(IF1<A, B> f, A[] l) {
1057  
    return map(l, f);
1058  
  }
1059  
1060  
  static public <A, B> List<B> map(A[] l, IF1<A, B> f) {
1061  
    List x = emptyList(l);
1062  
    if (l != null)
1063  
      for (A o : l) x.add(f.get(o));
1064  
    return x;
1065  
  }
1066  
1067  
  static public List map(Object f, Object[] l) {
1068  
    return map(f, asList(l));
1069  
  }
1070  
1071  
  static public List map(Object[] l, Object f) {
1072  
    return map(f, l);
1073  
  }
1074  
1075  
  static public List map(Object f, Map map) {
1076  
    return map(map, f);
1077  
  }
1078  
1079  
  static public List map(Map map, Object f) {
1080  
    List x = new ArrayList();
1081  
    if (map != null)
1082  
      for (Object _e : map.entrySet()) {
1083  
        Map.Entry e = (Map.Entry) _e;
1084  
        x.add(callF(f, e.getKey(), e.getValue()));
1085  
      }
1086  
    return x;
1087  
  }
1088  
1089  
  static public <A, B, C> List<C> map(Map<A, B> map, IF2<A, B, C> f) {
1090  
    return map(map, (Object) f);
1091  
  }
1092  
1093  
  static public <A> List<A> instancesOf(Iterable i, Class<A> c) {
1094  
    return collectInstances(i, c);
1095  
  }
1096  
1097  
  static public <A> List<A> instancesOf(Class<A> c, Iterable i) {
1098  
    return collectInstances(c, i);
1099  
  }
1100  
1101  
  static volatile public PersistableThrowable _handleException_lastException;
1102  
1103  
  static public List _handleException_onException = synchroList(ll("printStackTrace2"));
1104  
1105  
  static public void _handleException(Throwable e) {
1106  
    _handleException_lastException = persistableThrowable(e);
1107  
    Throwable e2 = innerException(e);
1108  
    if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
1109  
      return;
1110  
    for (Object f : cloneList(_handleException_onException)) try {
1111  
      callF(f, e);
1112  
    } catch (Throwable e3) {
1113  
      printStackTrace2(e3);
1114  
    }
1115  
  }
1116  
1117  
  static public void _close(AutoCloseable c) {
1118  
    if (c != null)
1119  
      try {
1120  
        c.close();
1121  
      } catch (Throwable e) {
1122  
        if (c instanceof javax.imageio.stream.ImageOutputStream)
1123  
          return;
1124  
        else
1125  
          throw rethrow(e);
1126  
      }
1127  
  }
1128  
1129  
  static public String formatFunctionCall_struct(String fname, Object... args) {
1130  
    return fname + "(" + joinWithComma(map("sfu", args)) + ")";
1131  
  }
1132  
1133  
  static public String unnull(String s) {
1134  
    return s == null ? "" : s;
1135  
  }
1136  
1137  
  static public <A> Collection<A> unnull(Collection<A> l) {
1138  
    return l == null ? emptyList() : l;
1139  
  }
1140  
1141  
  static public <A> List<A> unnull(List<A> l) {
1142  
    return l == null ? emptyList() : l;
1143  
  }
1144  
1145  
  static public <A, B> Map<A, B> unnull(Map<A, B> l) {
1146  
    return l == null ? emptyMap() : l;
1147  
  }
1148  
1149  
  static public <A> Iterable<A> unnull(Iterable<A> i) {
1150  
    return i == null ? emptyList() : i;
1151  
  }
1152  
1153  
  static public <A> A[] unnull(A[] a) {
1154  
    return a == null ? (A[]) emptyObjectArray() : a;
1155  
  }
1156  
1157  
  static public BitSet unnull(BitSet b) {
1158  
    return b == null ? new BitSet() : b;
1159  
  }
1160  
1161  
  static public Pt unnull(Pt p) {
1162  
    return p == null ? new Pt() : p;
1163  
  }
1164  
1165  
  static public <A, B> Pair<A, B> unnull(Pair<A, B> p) {
1166  
    return p != null ? p : new Pair(null, null);
1167  
  }
1168  
1169  
  static public Object callFIfActuallyCallable(Object f, Object... args) {
1170  
    return functionCallableOn_nonSynthetic(f, args) ? callF(f, args) : null;
1171  
  }
1172  
1173  
  static public String sfu(Object o) {
1174  
    return structureForUser(o);
1175  
  }
1176  
1177  
  static public Class javax() {
1178  
    return getJavaX();
1179  
  }
1180  
1181  
  static public void setDefaultClassFinder(Object cf) {
1182  
    _defaultClassFinder_value = cf;
1183  
  }
1184  
1185  
  static public HashMap<String, Class> findClass_fullName_cache = new HashMap();
1186  
1187  
  static public Class findClass_fullName(String name) {
1188  
    synchronized (findClass_fullName_cache) {
1189  
      if (findClass_fullName_cache.containsKey(name))
1190  
        return findClass_fullName_cache.get(name);
1191  
      Class c;
1192  
      try {
1193  
        c = Class.forName(name);
1194  
      } catch (ClassNotFoundException e) {
1195  
        c = null;
1196  
      }
1197  
      findClass_fullName_cache.put(name, c);
1198  
      return c;
1199  
    }
1200  
  }
1201  
1202  
  static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1<String, Boolean> f) {
1203  
    return print_byThread().get() == null ? tempInterceptPrint(f) : null;
1204  
  }
1205  
1206  
  static public Throwable printStackTrace2(Throwable e) {
1207  
    print(getStackTrace2(e));
1208  
    return e;
1209  
  }
1210  
1211  
  static public void printStackTrace2() {
1212  
    printStackTrace2(new Throwable());
1213  
  }
1214  
1215  
  static public void printStackTrace2(String msg) {
1216  
    printStackTrace2(new Throwable(msg));
1217  
  }
1218  
1219  
  static public Object _defaultClassFinder_value = defaultDefaultClassFinder();
1220  
1221  
  static public Object _defaultClassFinder() {
1222  
    return _defaultClassFinder_value;
1223  
  }
1224  
1225  
  static public String shortenClassName(String name) {
1226  
    if (name == null)
1227  
      return null;
1228  
    int i = lastIndexOf(name, "$");
1229  
    if (i < 0)
1230  
      i = lastIndexOf(name, ".");
1231  
    return i < 0 ? name : substring(name, i + 1);
1232  
  }
1233  
1234  
  static public String str(Object o) {
1235  
    return o == null ? "null" : o.toString();
1236  
  }
1237  
1238  
  static public String str(char[] c) {
1239  
    return new String(c);
1240  
  }
1241  
1242  
  static public String formatFunctionCall_quoteAll(String fname, Object... args) {
1243  
    return formatFunctionCall(fname, mapObjectArray(__29 -> quote(__29), args));
1244  
  }
1245  
1246  
  static public String shortName(Object o) {
1247  
    return shortClassName(o);
1248  
  }
1249  
1250  
  static public String defaultThreadName_name;
1251  
1252  
  static public String defaultThreadName() {
1253  
    if (defaultThreadName_name == null)
1254  
      defaultThreadName_name = "A thread by " + programID();
1255  
    return defaultThreadName_name;
1256  
  }
1257  
1258  
  static public Runnable wrapAsActivity(Object r) {
1259  
    return toRunnable(r);
1260  
  }
1261  
1262  
  static public Thread newThread(Object runnable) {
1263  
    return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
1264  
  }
1265  
1266  
  static public Thread newThread(Object runnable, String name) {
1267  
    if (name == null)
1268  
      name = defaultThreadName();
1269  
    return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
1270  
  }
1271  
1272  
  static public Thread newThread(String name, Object runnable) {
1273  
    return newThread(runnable, name);
1274  
  }
1275  
1276  
  static public Runnable toRunnable(final Object o) {
1277  
    if (o instanceof Runnable)
1278  
      return (Runnable) o;
1279  
    return new Runnable() {
1280  
1281  
      public void run() {
1282  
        try {
1283  
          callF(o);
1284  
        } catch (Exception __e) {
1285  
          throw rethrow(__e);
1286  
        }
1287  
      }
1288  
1289  
      public String toString() {
1290  
        return "callF(o)";
1291  
      }
1292  
    };
1293  
  }
1294  
1295  
  static public Map<Thread, Boolean> _registerThread_threads;
1296  
1297  
  static public Object _onRegisterThread;
1298  
1299  
  static public Thread _registerThread(Thread t) {
1300  
    if (_registerThread_threads == null)
1301  
      _registerThread_threads = newWeakHashMap();
1302  
    _registerThread_threads.put(t, true);
1303  
    vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
1304  
    callF(_onRegisterThread, t);
1305  
    return t;
1306  
  }
1307  
1308  
  static public void _registerThread() {
1309  
    _registerThread(Thread.currentThread());
1310  
  }
1311  
1312  
  static public List<String> javaTokWithBrackets(String s) {
1313  
    return javaTokPlusBrackets(s);
1314  
  }
1315  
1316  
  static public <A> Pair<A, A> listToPair(List<A> l) {
1317  
    return l(l) != 2 ? null : pair(first(l), second(l));
1318  
  }
1319  
1320  
  static public List<String> splitAtDoubleArrow(String s) {
1321  
    return splitAtDoubleArrow(javaTok(s));
1322  
  }
1323  
1324  
  static public List<String> splitAtDoubleArrow(List<String> tok) {
1325  
    List<String> l = new ArrayList();
1326  
    int i = 0;
1327  
    while (i < l(tok)) {
1328  
      int j = indexOfSubList(tok, splitAtDoubleArrow_tok(), i);
1329  
      if (j < 0)
1330  
        j = l(tok);
1331  
      l.add(trimJoin(tok.subList(i, j)));
1332  
      i = j + 3;
1333  
    }
1334  
    return l;
1335  
  }
1336  
1337  
  static public Pair<String, List<String>> tok_parseFunctionCall(String s) {
1338  
    return tok_parseFunctionCall(javaTok(s));
1339  
  }
1340  
1341  
  static public Pair<String, List<String>> tok_parseFunctionCall(List<String> tok) {
1342  
    if (!(isIdentifier(get(tok, 1)) && eqGet(tok, 3, "(")))
1343  
      return null;
1344  
    Map<Integer, Integer> bracketMap = getBracketMap(tok);
1345  
    Integer iClosing = bracketMap.get(3);
1346  
    if (!(eq(iClosing, l(tok) - 4) && eqGet(tok, l(tok) - 2, ";")) && neq(iClosing, l(tok) - 2))
1347  
      return null;
1348  
    int i = 5, argStart = 5;
1349  
    List<String> args = new ArrayList();
1350  
    while (i < iClosing) {
1351  
      Integer j = bracketMap.get(i);
1352  
      if (j != null) {
1353  
        i = j + 2;
1354  
        continue;
1355  
      }
1356  
      if (eqGetOneOf(tok, i, ",")) {
1357  
        if (i > argStart)
1358  
          args.add(trimJoinSubList(tok, argStart, i));
1359  
        argStart = i + 2;
1360  
      }
1361  
      i += 2;
1362  
    }
1363  
    if (i > argStart)
1364  
      args.add(trimJoinSubList(tok, argStart, i));
1365  
    return pair(tok.get(1), args);
1366  
  }
1367  
1368  
  static public String formatFunctionCall(String fname, Object... args) {
1369  
    return fname + "(" + joinWithComma(allToString(args)) + ")";
1370  
  }
1371  
1372  
  static public Object[] toObjectArray(Collection c) {
1373  
    List l = asList(c);
1374  
    return l.toArray(new Object[l.size()]);
1375  
  }
1376  
1377  
  static public String forceProperUnquote(String s) {
1378  
    return isProperlyQuoted(s) ? unquote(s) : null;
1379  
  }
1380  
1381  
  static public <A, B> Pair<A, B> pair(A a, B b) {
1382  
    return new Pair(a, b);
1383  
  }
1384  
1385  
  static public <A> Pair<A, A> pair(A a) {
1386  
    return new Pair(a, a);
1387  
  }
1388  
1389  
  static public boolean empty(Collection c) {
1390  
    return c == null || c.isEmpty();
1391  
  }
1392  
1393  
  static public boolean empty(CharSequence s) {
1394  
    return s == null || s.length() == 0;
1395  
  }
1396  
1397  
  static public boolean empty(Map map) {
1398  
    return map == null || map.isEmpty();
1399  
  }
1400  
1401  
  static public boolean empty(Object[] o) {
1402  
    return o == null || o.length == 0;
1403  
  }
1404  
1405  
  static public boolean empty(Object o) {
1406  
    if (o instanceof Collection)
1407  
      return empty((Collection) o);
1408  
    if (o instanceof String)
1409  
      return empty((String) o);
1410  
    if (o instanceof Map)
1411  
      return empty((Map) o);
1412  
    if (o instanceof Object[])
1413  
      return empty((Object[]) o);
1414  
    if (o instanceof byte[])
1415  
      return empty((byte[]) o);
1416  
    if (o == null)
1417  
      return true;
1418  
    throw fail("unknown type for 'empty': " + getType(o));
1419  
  }
1420  
1421  
  static public boolean empty(Iterator i) {
1422  
    return i == null || !i.hasNext();
1423  
  }
1424  
1425  
  static public boolean empty(double[] a) {
1426  
    return a == null || a.length == 0;
1427  
  }
1428  
1429  
  static public boolean empty(float[] a) {
1430  
    return a == null || a.length == 0;
1431  
  }
1432  
1433  
  static public boolean empty(int[] a) {
1434  
    return a == null || a.length == 0;
1435  
  }
1436  
1437  
  static public boolean empty(long[] a) {
1438  
    return a == null || a.length == 0;
1439  
  }
1440  
1441  
  static public boolean empty(byte[] a) {
1442  
    return a == null || a.length == 0;
1443  
  }
1444  
1445  
  static public boolean empty(short[] a) {
1446  
    return a == null || a.length == 0;
1447  
  }
1448  
1449  
  static public boolean empty(MultiSet ms) {
1450  
    return ms == null || ms.isEmpty();
1451  
  }
1452  
1453  
  static public boolean empty(File f) {
1454  
    return getFileSize(f) == 0;
1455  
  }
1456  
1457  
  static public <A> void listSetIfInRange(List<A> l, int i, A a) {
1458  
    if (i >= 0 && i < l(l))
1459  
      l.set(i, a);
1460  
  }
1461  
1462  
  static public <A> ArrayList<A> cloneList(Iterable<A> l) {
1463  
    return l instanceof Collection ? cloneList((Collection) l) : asList(l);
1464  
  }
1465  
1466  
  static public <A> ArrayList<A> cloneList(Collection<A> l) {
1467  
    if (l == null)
1468  
      return new ArrayList();
1469  
    synchronized (collectionMutex(l)) {
1470  
      return new ArrayList<A>(l);
1471  
    }
1472  
  }
1473  
1474  
  static public <A> Iterator<A> iterator(Iterable<A> c) {
1475  
    return c == null ? emptyIterator() : c.iterator();
1476  
  }
1477  
1478  
  static public char charAt(String s, int i) {
1479  
    return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0';
1480  
  }
1481  
1482  
  static public boolean containsStars(String s) {
1483  
    return containsStars(javaTok_cached(s));
1484  
  }
1485  
1486  
  static public boolean containsStars(List<String> tok) {
1487  
    for (int i = 1; i < l(tok); i += 2) if (eq(tok.get(i), "*"))
1488  
      return true;
1489  
    return false;
1490  
  }
1491  
1492  
  static public boolean isNormalQuoted(String s) {
1493  
    int l = l(s);
1494  
    if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"'))
1495  
      return false;
1496  
    int j = 1;
1497  
    while (j < l) if (s.charAt(j) == '"')
1498  
      return j == l - 1;
1499  
    else if (s.charAt(j) == '\\' && j + 1 < l)
1500  
      j += 2;
1501  
    else
1502  
      ++j;
1503  
    return false;
1504  
  }
1505  
1506  
  static public boolean isMultilineQuoted(String s) {
1507  
    if (!startsWith(s, "["))
1508  
      return false;
1509  
    int i = 1;
1510  
    while (i < s.length() && s.charAt(i) == '=') ++i;
1511  
    return i < s.length() && s.charAt(i) == '[';
1512  
  }
1513  
1514  
  static public boolean startsWith(String a, String b) {
1515  
    return a != null && a.startsWith(b);
1516  
  }
1517  
1518  
  static public boolean startsWith(String a, char c) {
1519  
    return nemptyString(a) && a.charAt(0) == c;
1520  
  }
1521  
1522  
  static public boolean startsWith(String a, String b, Matches m) {
1523  
    if (!startsWith(a, b))
1524  
      return false;
1525  
    m.m = new String[] { substring(a, strL(b)) };
1526  
    return true;
1527  
  }
1528  
1529  
  static public boolean startsWith(List a, List b) {
1530  
    if (a == null || listL(b) > listL(a))
1531  
      return false;
1532  
    for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
1533  
      return false;
1534  
    return true;
1535  
  }
1536  
1537  
  static public boolean endsWith(String a, String b) {
1538  
    return a != null && a.endsWith(b);
1539  
  }
1540  
1541  
  static public boolean endsWith(String a, char c) {
1542  
    return nempty(a) && lastChar(a) == c;
1543  
  }
1544  
1545  
  static public boolean endsWith(String a, String b, Matches m) {
1546  
    if (!endsWith(a, b))
1547  
      return false;
1548  
    m.m = new String[] { dropLast(l(b), a) };
1549  
    return true;
1550  
  }
1551  
1552  
  static public long sysNow() {
1553  
    ping();
1554  
    return System.nanoTime() / 1000000;
1555  
  }
1556  
1557  
  static volatile public boolean ping_pauseAll = false;
1558  
1559  
  static public int ping_sleep = 100;
1560  
1561  
  static volatile public boolean ping_anyActions = false;
1562  
1563  
  static public Map<Thread, Object> ping_actions = newWeakHashMap();
1564  
1565  
  static public ThreadLocal<Boolean> ping_isCleanUpThread = new ThreadLocal();
1566  
1567  
  static public boolean ping() {
1568  
    if (ping_pauseAll || ping_anyActions)
1569  
      ping_impl(true);
1570  
    return true;
1571  
  }
1572  
1573  
  static public boolean ping_impl(boolean okInCleanUp) {
1574  
    try {
1575  
      if (ping_pauseAll && !isAWTThread()) {
1576  
        do Thread.sleep(ping_sleep); while (ping_pauseAll);
1577  
        return true;
1578  
      }
1579  
      if (ping_anyActions) {
1580  
        if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
1581  
          failIfUnlicensed();
1582  
        Object action = null;
1583  
        synchronized (ping_actions) {
1584  
          if (!ping_actions.isEmpty()) {
1585  
            action = ping_actions.get(currentThread());
1586  
            if (action instanceof Runnable)
1587  
              ping_actions.remove(currentThread());
1588  
            if (ping_actions.isEmpty())
1589  
              ping_anyActions = false;
1590  
          }
1591  
        }
1592  
        if (action instanceof Runnable)
1593  
          ((Runnable) action).run();
1594  
        else if (eq(action, "cancelled"))
1595  
          throw fail("Thread cancelled.");
1596  
      }
1597  
      return false;
1598  
    } catch (Exception __e) {
1599  
      throw rethrow(__e);
1600  
    }
1601  
  }
1602  
1603  
  static public ThreadLocal<Long> saveTiming_last = new ThreadLocal();
1604  
1605  
  static public void saveTiming(long ms) {
1606  
    print(ms + " ms");
1607  
    saveTiming_noPrint(ms);
1608  
  }
1609  
1610  
  static public void saveTiming_noPrint(long ms) {
1611  
    saveTiming_last.set(ms);
1612  
  }
1613  
1614  
  static public String n2(long l) {
1615  
    return formatWithThousands(l);
1616  
  }
1617  
1618  
  static public String n2(Collection l) {
1619  
    return n2(l(l));
1620  
  }
1621  
1622  
  static public String n2(Map map) {
1623  
    return n2(l(map));
1624  
  }
1625  
1626  
  static public String n2(double l, String singular) {
1627  
    return n2(l, singular, singular + "s");
1628  
  }
1629  
1630  
  static public String n2(double l, String singular, String plural) {
1631  
    if (fraction(l) == 0)
1632  
      return n2((long) l, singular, plural);
1633  
    else
1634  
      return l + " " + plural;
1635  
  }
1636  
1637  
  static public String n2(long l, String singular, String plural) {
1638  
    return n_fancy2(l, singular, plural);
1639  
  }
1640  
1641  
  static public String n2(long l, String singular) {
1642  
    return n_fancy2(l, singular, singular + "s");
1643  
  }
1644  
1645  
  static public String n2(Collection l, String singular) {
1646  
    return n2(l(l), singular);
1647  
  }
1648  
1649  
  static public String n2(Collection l, String singular, String plural) {
1650  
    return n_fancy2(l, singular, plural);
1651  
  }
1652  
1653  
  static public String n2(Map m, String singular, String plural) {
1654  
    return n_fancy2(m, singular, plural);
1655  
  }
1656  
1657  
  static public String n2(Map m, String singular) {
1658  
    return n2(l(m), singular);
1659  
  }
1660  
1661  
  static public String n2(Object[] a, String singular) {
1662  
    return n2(l(a), singular);
1663  
  }
1664  
1665  
  static public String n2(Object[] a, String singular, String plural) {
1666  
    return n_fancy2(a, singular, plural);
1667  
  }
1668  
1669  
  static public String n2(MultiSet ms, String singular, String plural) {
1670  
    return n_fancy2(ms, singular, plural);
1671  
  }
1672  
1673  
  static public long lastTiming() {
1674  
    return getLastTiming();
1675  
  }
1676  
1677  
  static public boolean endsWithLetterOrDigit(String s) {
1678  
    return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
1679  
  }
1680  
1681  
  static public void ping_okInCleanUp() {
1682  
    if (ping_pauseAll || ping_anyActions)
1683  
      ping_impl(true);
1684  
  }
1685  
1686  
  static public Object getThreadLocal(Object o, String name) {
1687  
    ThreadLocal t = (ThreadLocal) (getOpt(o, name));
1688  
    return t != null ? t.get() : null;
1689  
  }
1690  
1691  
  static public <A> A getThreadLocal(ThreadLocal<A> tl) {
1692  
    return tl == null ? null : tl.get();
1693  
  }
1694  
1695  
  static public <A> A getThreadLocal(ThreadLocal<A> tl, A defaultValue) {
1696  
    return or(getThreadLocal(tl), defaultValue);
1697  
  }
1698  
1699  
  static public ThreadLocal<Object> print_byThread_dontCreate() {
1700  
    return print_byThread;
1701  
  }
1702  
1703  
  static public boolean isFalse(Object o) {
1704  
    return eq(false, o);
1705  
  }
1706  
1707  
  static public Object callF(Object f, Object... args) {
1708  
    try {
1709  
      if (f instanceof String)
1710  
        return callMC((String) f, args);
1711  
      return x30_util.callF(f, args);
1712  
    } catch (Exception __e) {
1713  
      throw rethrow(__e);
1714  
    }
1715  
  }
1716  
1717  
  static public <A> A callF(F0<A> f) {
1718  
    return f == null ? null : f.get();
1719  
  }
1720  
1721  
  static public <A> A callF(IF0<A> f) {
1722  
    return f == null ? null : f.get();
1723  
  }
1724  
1725  
  static public <A, B> B callF(F1<A, B> f, A a) {
1726  
    return f == null ? null : f.get(a);
1727  
  }
1728  
1729  
  static public <A, B> B callF(IF1<A, B> f, A a) {
1730  
    return f == null ? null : f.get(a);
1731  
  }
1732  
1733  
  static public <A, B, C> C callF(F2<A, B, C> f, A a, B b) {
1734  
    return f == null ? null : f.get(a, b);
1735  
  }
1736  
1737  
  static public <A> void callF(VF1<A> f, A a) {
1738  
    if (f != null)
1739  
      f.get(a);
1740  
  }
1741  
1742  
  static public Object callMC(String method, Object... args) {
1743  
    return call(mc(), method, args);
1744  
  }
1745  
1746  
  static public Object call(Object o) {
1747  
    return callF(o);
1748  
  }
1749  
1750  
  static public Object call(Object o, String method, Object... args) {
1751  
    return call_withVarargs(o, method, args);
1752  
  }
1753  
1754  
  static public String fixNewLines(String s) {
1755  
    int i = indexOf(s, '\r');
1756  
    if (i < 0)
1757  
      return s;
1758  
    int l = s.length();
1759  
    StringBuilder out = new StringBuilder(l);
1760  
    out.append(s, 0, i);
1761  
    for (; i < l; i++) {
1762  
      char c = s.charAt(i);
1763  
      if (c != '\r')
1764  
        out.append(c);
1765  
      else {
1766  
        out.append('\n');
1767  
        if (i + 1 < l && s.charAt(i + 1) == '\n')
1768  
          ++i;
1769  
      }
1770  
    }
1771  
    return out.toString();
1772  
  }
1773  
1774  
  static public void print_append(Appendable buf, String s, int max) {
1775  
    try {
1776  
      synchronized (buf) {
1777  
        buf.append(s);
1778  
        if (buf instanceof StringBuffer)
1779  
          rotateStringBuffer(((StringBuffer) buf), max);
1780  
        else if (buf instanceof StringBuilder)
1781  
          rotateStringBuilder(((StringBuilder) buf), max);
1782  
      }
1783  
    } catch (Exception __e) {
1784  
      throw rethrow(__e);
1785  
    }
1786  
  }
1787  
1788  
  static public void printNumberedLines(Map map) {
1789  
    printNumberedLines(mapToLines(map));
1790  
  }
1791  
1792  
  static public void printNumberedLines(String prefix, Map map) {
1793  
    printNumberedLines(prefix, mapToLines(map));
1794  
  }
1795  
1796  
  static public <A extends Iterable> A printNumberedLines(A l) {
1797  
    int i = 0;
1798  
    if (l != null)
1799  
      for (Object a : l) print((++i) + ". " + str(a));
1800  
    return l;
1801  
  }
1802  
1803  
  static public <A extends Iterable> A printNumberedLines(String prefix, A l) {
1804  
    int i = 0;
1805  
    if (l != null)
1806  
      for (Object a : l) print(prefix + (++i) + ". " + str(a));
1807  
    return l;
1808  
  }
1809  
1810  
  static public void printNumberedLines(Object[] l) {
1811  
    printNumberedLines(asList(l));
1812  
  }
1813  
1814  
  static public void printNumberedLines(Object o) {
1815  
    printNumberedLines(lines(str(o)));
1816  
  }
1817  
1818  
  static public String lines(Iterable lines) {
1819  
    return fromLines(lines);
1820  
  }
1821  
1822  
  static public String lines(Object[] lines) {
1823  
    return fromLines(asList(lines));
1824  
  }
1825  
1826  
  static public List<String> lines(String s) {
1827  
    return toLines(s);
1828  
  }
1829  
1830  
  static public ArrayList emptyList() {
1831  
    return new ArrayList();
1832  
  }
1833  
1834  
  static public ArrayList emptyList(int capacity) {
1835  
    return new ArrayList(max(0, capacity));
1836  
  }
1837  
1838  
  static public ArrayList emptyList(Iterable l) {
1839  
    return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
1840  
  }
1841  
1842  
  static public ArrayList emptyList(Object[] l) {
1843  
    return emptyList(l(l));
1844  
  }
1845  
1846  
  static public <A> ArrayList<A> emptyList(Class<A> c) {
1847  
    return new ArrayList();
1848  
  }
1849  
1850  
  static public <A> ArrayList<A> asList(A[] a) {
1851  
    return a == null ? new ArrayList<A>() : new ArrayList<A>(Arrays.asList(a));
1852  
  }
1853  
1854  
  static public ArrayList<Integer> asList(int[] a) {
1855  
    if (a == null)
1856  
      return null;
1857  
    ArrayList<Integer> l = emptyList(a.length);
1858  
    for (int i : a) l.add(i);
1859  
    return l;
1860  
  }
1861  
1862  
  static public ArrayList<Float> asList(float[] a) {
1863  
    if (a == null)
1864  
      return null;
1865  
    ArrayList<Float> l = emptyList(a.length);
1866  
    for (float i : a) l.add(i);
1867  
    return l;
1868  
  }
1869  
1870  
  static public ArrayList<Double> asList(double[] a) {
1871  
    if (a == null)
1872  
      return null;
1873  
    ArrayList<Double> l = emptyList(a.length);
1874  
    for (double i : a) l.add(i);
1875  
    return l;
1876  
  }
1877  
1878  
  static public <A> ArrayList<A> asList(Iterable<A> s) {
1879  
    if (s instanceof ArrayList)
1880  
      return (ArrayList) s;
1881  
    ArrayList l = new ArrayList();
1882  
    if (s != null)
1883  
      for (A a : s) l.add(a);
1884  
    return l;
1885  
  }
1886  
1887  
  static public <A> ArrayList<A> asList(Producer<A> p) {
1888  
    ArrayList l = new ArrayList();
1889  
    A a;
1890  
    if (p != null)
1891  
      while ((a = p.next()) != null) l.add(a);
1892  
    return l;
1893  
  }
1894  
1895  
  static public <A> ArrayList<A> asList(Enumeration<A> e) {
1896  
    ArrayList l = new ArrayList();
1897  
    if (e != null)
1898  
      while (e.hasMoreElements()) l.add(e.nextElement());
1899  
    return l;
1900  
  }
1901  
1902  
  static public <A> List<A> collectInstances(Iterable i, Class<A> c) {
1903  
    List l = new ArrayList();
1904  
    if (i == null)
1905  
      return l;
1906  
    c = primitiveToBoxedTypeOpt(c);
1907  
    for (Object o : i) if (isInstance(c, o))
1908  
      l.add(o);
1909  
    return l;
1910  
  }
1911  
1912  
  static public <A> List<A> collectInstances(Class<A> c, Iterable i) {
1913  
    return collectInstances(i, c);
1914  
  }
1915  
1916  
  static public <A> List<A> synchroList() {
1917  
    return Collections.synchronizedList(new ArrayList<A>());
1918  
  }
1919  
1920  
  static public <A> List<A> synchroList(List<A> l) {
1921  
    return Collections.synchronizedList(l);
1922  
  }
1923  
1924  
  static public <A> List<A> ll(A... a) {
1925  
    ArrayList l = new ArrayList(a.length);
1926  
    if (a != null)
1927  
      for (A x : a) l.add(x);
1928  
    return l;
1929  
  }
1930  
1931  
  static public PersistableThrowable persistableThrowable(Throwable e) {
1932  
    return e == null ? null : new PersistableThrowable(e);
1933  
  }
1934  
1935  
  static public Throwable innerException(Throwable e) {
1936  
    return getInnerException(e);
1937  
  }
1938  
1939  
  static public <A> String joinWithComma(Collection<A> c) {
1940  
    return join(", ", c);
1941  
  }
1942  
1943  
  static public String joinWithComma(String... c) {
1944  
    return join(", ", c);
1945  
  }
1946  
1947  
  static public String joinWithComma(Pair p) {
1948  
    return p == null ? "" : joinWithComma(str(p.a), str(p.b));
1949  
  }
1950  
1951  
  static public Map emptyMap() {
1952  
    return new HashMap();
1953  
  }
1954  
1955  
  static public Object[] emptyObjectArray_a = new Object[0];
1956  
1957  
  static public Object[] emptyObjectArray() {
1958  
    return emptyObjectArray_a;
1959  
  }
1960  
1961  
  static public boolean functionCallableOn_nonSynthetic(Object f, Object... args) {
1962  
    return callableOn_nonSynthetic(f, "get", args);
1963  
  }
1964  
1965  
  static public String structureForUser(Object o) {
1966  
    return beautifyStructure(struct_noStringSharing(o));
1967  
  }
1968  
1969  
  static public Class __javax;
1970  
1971  
  static public Class getJavaX() {
1972  
    try {
1973  
      return __javax;
1974  
    } catch (Exception __e) {
1975  
      throw rethrow(__e);
1976  
    }
1977  
  }
1978  
1979  
  static public ThreadLocal<Object> print_byThread() {
1980  
    synchronized (print_byThread_lock) {
1981  
      if (print_byThread == null)
1982  
        print_byThread = new ThreadLocal();
1983  
    }
1984  
    return print_byThread;
1985  
  }
1986  
1987  
  static public AutoCloseable tempInterceptPrint(F1<String, Boolean> f) {
1988  
    return tempSetThreadLocal(print_byThread(), f);
1989  
  }
1990  
1991  
  static public String getStackTrace2(Throwable e) {
1992  
    return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n");
1993  
  }
1994  
1995  
  static public Object defaultDefaultClassFinder() {
1996  
    return new F1<String, Class>() {
1997  
1998  
      public Class get(String name) {
1999  
        Class c = findClass_fullName(name);
2000  
        if (c != null)
2001  
          return c;
2002  
        if (name.startsWith("loadableUtils.utils$"))
2003  
          return findClass_fullName("main" + name.substring(19));
2004  
        return null;
2005  
      }
2006  
    };
2007  
  }
2008  
2009  
  static public int lastIndexOf(String a, String b) {
2010  
    return a == null || b == null ? -1 : a.lastIndexOf(b);
2011  
  }
2012  
2013  
  static public int lastIndexOf(String a, char b) {
2014  
    return a == null ? -1 : a.lastIndexOf(b);
2015  
  }
2016  
2017  
  static public <A> int lastIndexOf(List<A> l, int i, A a) {
2018  
    if (l == null)
2019  
      return -1;
2020  
    for (i = min(l(l), i) - 1; i >= 0; i--) if (eq(l.get(i), a))
2021  
      return i;
2022  
    return -1;
2023  
  }
2024  
2025  
  static public String substring(String s, int x) {
2026  
    return substring(s, x, strL(s));
2027  
  }
2028  
2029  
  static public String substring(String s, int x, int y) {
2030  
    if (s == null)
2031  
      return null;
2032  
    if (x < 0)
2033  
      x = 0;
2034  
    if (x >= s.length())
2035  
      return "";
2036  
    if (y < x)
2037  
      y = x;
2038  
    if (y > s.length())
2039  
      y = s.length();
2040  
    return s.substring(x, y);
2041  
  }
2042  
2043  
  static public String substring(String s, IntRange r) {
2044  
    return r == null ? null : substring(s, r.start, r.end);
2045  
  }
2046  
2047  
  static public String substring(String s, CharSequence l) {
2048  
    return substring(s, l(l));
2049  
  }
2050  
2051  
  static public Object[] mapObjectArray(IF1 f, Object[] l) {
2052  
    if (empty(l))
2053  
      return l;
2054  
    int n = l.length;
2055  
    Object[] a2 = new Object[n];
2056  
    for (int i = 0; i < n; i++) a2[i] = f.get(l[i]);
2057  
    return a2;
2058  
  }
2059  
2060  
  static public String programID() {
2061  
    return getProgramID();
2062  
  }
2063  
2064  
  static public String programID(Object o) {
2065  
    return getProgramID(o);
2066  
  }
2067  
2068  
  static public Runnable _topLevelErrorHandling(final Runnable runnable) {
2069  
    final Object info = _threadInfo();
2070  
    return new Runnable() {
2071  
2072  
      public void run() {
2073  
        try {
2074  
          try {
2075  
            _threadInheritInfo(info);
2076  
            runnable.run();
2077  
          } catch (Throwable __e) {
2078  
            _handleException(__e);
2079  
          }
2080  
        } catch (Exception __e) {
2081  
          throw rethrow(__e);
2082  
        }
2083  
      }
2084  
2085  
      public String toString() {
2086  
        return "pcall {\r\n      _threadInheritInfo(info);\r\n      runnable.run();\r\n    }";
2087  
      }
2088  
    };
2089  
  }
2090  
2091  
  static public <A> WeakReference<A> weakRef(A a) {
2092  
    return newWeakReference(a);
2093  
  }
2094  
2095  
  static public Class mc() {
2096  
    return main.class;
2097  
  }
2098  
2099  
  static public List<String> javaTokPlusBrackets(String s) {
2100  
    return tok_combineRoundOrCurlyBrackets_keep(javaTok(s));
2101  
  }
2102  
2103  
  static public int javaTok_n, javaTok_elements;
2104  
2105  
  static public boolean javaTok_opt = false;
2106  
2107  
  static public List<String> javaTok(String s) {
2108  
    ++javaTok_n;
2109  
    ArrayList<String> tok = new ArrayList();
2110  
    int l = s == null ? 0 : s.length();
2111  
    int i = 0, n = 0;
2112  
    while (i < l) {
2113  
      int j = i;
2114  
      char c, d;
2115  
      while (j < l) {
2116  
        c = s.charAt(j);
2117  
        d = j + 1 >= l ? '\0' : s.charAt(j + 1);
2118  
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
2119  
          ++j;
2120  
        else if (c == '/' && d == '*') {
2121  
          do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
2122  
          j = Math.min(j + 2, l);
2123  
        } else if (c == '/' && d == '/') {
2124  
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
2125  
        } else
2126  
          break;
2127  
      }
2128  
      tok.add(javaTok_substringN(s, i, j));
2129  
      ++n;
2130  
      i = j;
2131  
      if (i >= l)
2132  
        break;
2133  
      c = s.charAt(i);
2134  
      d = i + 1 >= l ? '\0' : s.charAt(i + 1);
2135  
      if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
2136  
        j += 2;
2137  
        while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
2138  
      } else if (c == '\'' || c == '"') {
2139  
        char opener = c;
2140  
        ++j;
2141  
        while (j < l) {
2142  
          int c2 = s.charAt(j);
2143  
          if (c2 == opener || c2 == '\n' && opener == '\'') {
2144  
            ++j;
2145  
            break;
2146  
          } else if (c2 == '\\' && j + 1 < l)
2147  
            j += 2;
2148  
          else
2149  
            ++j;
2150  
        }
2151  
      } else if (Character.isJavaIdentifierStart(c))
2152  
        do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
2153  
      else if (Character.isDigit(c)) {
2154  
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
2155  
        if (j < l && s.charAt(j) == 'L')
2156  
          ++j;
2157  
      } else if (c == '[' && d == '[') {
2158  
        do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
2159  
        j = Math.min(j + 2, l);
2160  
      } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
2161  
        do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
2162  
        j = Math.min(j + 3, l);
2163  
      } else
2164  
        ++j;
2165  
      tok.add(javaTok_substringC(s, i, j));
2166  
      ++n;
2167  
      i = j;
2168  
    }
2169  
    if ((tok.size() % 2) == 0)
2170  
      tok.add("");
2171  
    javaTok_elements += tok.size();
2172  
    return tok;
2173  
  }
2174  
2175  
  static public List<String> javaTok(List<String> tok) {
2176  
    return javaTokWithExisting(join(tok), tok);
2177  
  }
2178  
2179  
  static public <A> int indexOfSubList(List<A> x, List<A> y) {
2180  
    return indexOfSubList(x, y, 0);
2181  
  }
2182  
2183  
  static public <A> int indexOfSubList(List<A> x, List<A> y, int i) {
2184  
    outer: for (; i + l(y) <= l(x); i++) {
2185  
      for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y.get(j)))
2186  
        continue outer;
2187  
      return i;
2188  
    }
2189  
    return -1;
2190  
  }
2191  
2192  
  static public <A> int indexOfSubList(List<A> x, A[] y, int i) {
2193  
    outer: for (; i + l(y) <= l(x); i++) {
2194  
      for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y[j]))
2195  
        continue outer;
2196  
      return i;
2197  
    }
2198  
    return -1;
2199  
  }
2200  
2201  
  static public List<String> splitAtDoubleArrow_tok;
2202  
2203  
  static public List<String> splitAtDoubleArrow_tok() {
2204  
    if (splitAtDoubleArrow_tok == null)
2205  
      splitAtDoubleArrow_tok = ll("=", "", ">");
2206  
    return splitAtDoubleArrow_tok;
2207  
  }
2208  
2209  
  static public String trimJoin(List<String> s) {
2210  
    return trim(join(s));
2211  
  }
2212  
2213  
  static public boolean isIdentifier(String s) {
2214  
    return isJavaIdentifier(s);
2215  
  }
2216  
2217  
  static public boolean eqGet(List l, int i, Object o) {
2218  
    return eq(get(l, i), o);
2219  
  }
2220  
2221  
  static public <A, B> boolean eqGet(Map<A, B> map, A key, Object o) {
2222  
    return eq(mapGet(map, key), o);
2223  
  }
2224  
2225  
  static public Map<Integer, Integer> getBracketMap(List tok) {
2226  
    return getBracketMap(tok, getBracketMap_opening, getBracketMap_closing);
2227  
  }
2228  
2229  
  static public Map<Integer, Integer> getBracketMap(List tok, Collection<String> opening, Collection<String> closing) {
2230  
    return getBracketMap(tok, opening, closing, 0, l(tok));
2231  
  }
2232  
2233  
  static public Map<Integer, Integer> getBracketMap(List tok, Collection<String> opening, Collection<String> closing, int from, int to) {
2234  
    TreeMap<Integer, Integer> map = new TreeMap();
2235  
    List<Integer> stack = new ArrayList();
2236  
    for (int i = from | 1; i < to; i += 2) {
2237  
      if (opening.contains(tok.get(i)))
2238  
        stack.add(i);
2239  
      else if (closing.contains(tok.get(i))) {
2240  
        if (!empty(stack))
2241  
          map.put(liftLast(stack), i);
2242  
      }
2243  
    }
2244  
    return map;
2245  
  }
2246  
2247  
  static public Set<String> getBracketMap_opening = lithashset("{", "(");
2248  
2249  
  static public Set<String> getBracketMap_closing = lithashset("}", ")");
2250  
2251  
  static public boolean neq(Object a, Object b) {
2252  
    return !eq(a, b);
2253  
  }
2254  
2255  
  static public <A> boolean eqGetOneOf(List<A> l, int i, A... options) {
2256  
    return eqOneOf(get(l, i), options);
2257  
  }
2258  
2259  
  static public String trimJoinSubList(List<String> l, int i, int j) {
2260  
    return trim(join(subList(l, i, j)));
2261  
  }
2262  
2263  
  static public String trimJoinSubList(List<String> l, int i) {
2264  
    return trim(join(subList(l, i)));
2265  
  }
2266  
2267  
  static public List<String> allToString(Iterable c) {
2268  
    List<String> l = new ArrayList();
2269  
    for (Object o : unnull(c)) l.add(str(o));
2270  
    return l;
2271  
  }
2272  
2273  
  static public List<String> allToString(Object[] c) {
2274  
    List<String> l = new ArrayList();
2275  
    for (Object o : unnull(c)) l.add(str(o));
2276  
    return l;
2277  
  }
2278  
2279  
  static public boolean isProperlyQuoted(String s) {
2280  
    return s.length() >= 2 && s.startsWith("\"") && s.endsWith("\"") && (!s.endsWith("\\\"") || s.endsWith("\\\\\"")) && !containsNewLine(s);
2281  
  }
2282  
2283  
  static public String getType(Object o) {
2284  
    return getClassName(o);
2285  
  }
2286  
2287  
  static public long getFileSize(String path) {
2288  
    return path == null ? 0 : new File(path).length();
2289  
  }
2290  
2291  
  static public long getFileSize(File f) {
2292  
    return f == null ? 0 : f.length();
2293  
  }
2294  
2295  
  static public Object collectionMutex(List l) {
2296  
    return l;
2297  
  }
2298  
2299  
  static public Object collectionMutex(Object o) {
2300  
    if (o instanceof List)
2301  
      return o;
2302  
    String c = className(o);
2303  
    if (eq(c, "java.util.TreeMap$KeySet"))
2304  
      c = className(o = getOpt(o, "m"));
2305  
    else if (eq(c, "java.util.HashMap$KeySet"))
2306  
      c = className(o = get_raw(o, "this$0"));
2307  
    if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
2308  
      c = className(o = get_raw(o, "m"));
2309  
    return o;
2310  
  }
2311  
2312  
  static public Iterator emptyIterator() {
2313  
    return Collections.emptyIterator();
2314  
  }
2315  
2316  
  static public Map<String, List<String>> javaTok_cached_cache = synchronizedMRUCache(100);
2317  
2318  
  static public List<String> javaTok_cached(String s) {
2319  
    List<String> tok = javaTok_cached_cache.get(s);
2320  
    if (tok == null)
2321  
      javaTok_cached_cache.put(s, tok = javaTok(s));
2322  
    return tok;
2323  
  }
2324  
2325  
  static public char lastChar(String s) {
2326  
    return empty(s) ? '\0' : s.charAt(l(s) - 1);
2327  
  }
2328  
2329  
  static public boolean nemptyString(String s) {
2330  
    return s != null && s.length() > 0;
2331  
  }
2332  
2333  
  static public int strL(String s) {
2334  
    return s == null ? 0 : s.length();
2335  
  }
2336  
2337  
  static public int listL(Collection l) {
2338  
    return l == null ? 0 : l.size();
2339  
  }
2340  
2341  
  static public boolean nempty(Collection c) {
2342  
    return !empty(c);
2343  
  }
2344  
2345  
  static public boolean nempty(CharSequence s) {
2346  
    return !empty(s);
2347  
  }
2348  
2349  
  static public boolean nempty(Object[] o) {
2350  
    return !empty(o);
2351  
  }
2352  
2353  
  static public boolean nempty(byte[] o) {
2354  
    return !empty(o);
2355  
  }
2356  
2357  
  static public boolean nempty(int[] o) {
2358  
    return !empty(o);
2359  
  }
2360  
2361  
  static public boolean nempty(Map m) {
2362  
    return !empty(m);
2363  
  }
2364  
2365  
  static public boolean nempty(Iterator i) {
2366  
    return i != null && i.hasNext();
2367  
  }
2368  
2369  
  static public boolean nempty(Object o) {
2370  
    return !empty(o);
2371  
  }
2372  
2373  
  static public String[] dropLast(String[] a, int n) {
2374  
    n = Math.min(n, a.length);
2375  
    String[] b = new String[a.length - n];
2376  
    System.arraycopy(a, 0, b, 0, b.length);
2377  
    return b;
2378  
  }
2379  
2380  
  static public <A> List<A> dropLast(List<A> l) {
2381  
    return subList(l, 0, l(l) - 1);
2382  
  }
2383  
2384  
  static public <A> List<A> dropLast(int n, List<A> l) {
2385  
    return subList(l, 0, l(l) - n);
2386  
  }
2387  
2388  
  static public <A> List<A> dropLast(Iterable<A> l) {
2389  
    return dropLast(asList(l));
2390  
  }
2391  
2392  
  static public String dropLast(String s) {
2393  
    return substring(s, 0, l(s) - 1);
2394  
  }
2395  
2396  
  static public String dropLast(String s, int n) {
2397  
    return substring(s, 0, l(s) - n);
2398  
  }
2399  
2400  
  static public String dropLast(int n, String s) {
2401  
    return dropLast(s, n);
2402  
  }
2403  
2404  
  static public boolean isAWTThread() {
2405  
    if (isAndroid())
2406  
      return false;
2407  
    if (isHeadless())
2408  
      return false;
2409  
    return isAWTThread_awt();
2410  
  }
2411  
2412  
  static public boolean isAWTThread_awt() {
2413  
    return SwingUtilities.isEventDispatchThread();
2414  
  }
2415  
2416  
  static public void failIfUnlicensed() {
2417  
    assertTrue("license off", licensed());
2418  
  }
2419  
2420  
  static public Thread currentThread() {
2421  
    return Thread.currentThread();
2422  
  }
2423  
2424  
  static public String formatWithThousands(long l) {
2425  
    return formatWithThousandsSeparator(l);
2426  
  }
2427  
2428  
  static public double fraction(double d) {
2429  
    return d % 1;
2430  
  }
2431  
2432  
  static public String n_fancy2(long l, String singular, String plural) {
2433  
    return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
2434  
  }
2435  
2436  
  static public String n_fancy2(Collection l, String singular, String plural) {
2437  
    return n_fancy2(l(l), singular, plural);
2438  
  }
2439  
2440  
  static public String n_fancy2(Map m, String singular, String plural) {
2441  
    return n_fancy2(l(m), singular, plural);
2442  
  }
2443  
2444  
  static public String n_fancy2(Object[] a, String singular, String plural) {
2445  
    return n_fancy2(l(a), singular, plural);
2446  
  }
2447  
2448  
  static public String n_fancy2(MultiSet ms, String singular, String plural) {
2449  
    return n_fancy2(l(ms), singular, plural);
2450  
  }
2451  
2452  
  static public long getLastTiming() {
2453  
    ThreadLocal<Long> tl = (ThreadLocal<Long>) (getOpt(getMainClass(), "saveTiming_last"));
2454  
    if (tl == null)
2455  
      return -1;
2456  
    Long l = tl.get();
2457  
    return l == null ? -1 : l;
2458  
  }
2459  
2460  
  static public <A> A or(A a, A b) {
2461  
    return a != null ? a : b;
2462  
  }
2463  
2464  
  static public Object call_withVarargs(Object o, String method, Object... args) {
2465  
    try {
2466  
      if (o == null)
2467  
        return null;
2468  
      if (o instanceof Class) {
2469  
        Class c = (Class) o;
2470  
        _MethodCache cache = callOpt_getCache(c);
2471  
        Method me = cache.findStaticMethod(method, args);
2472  
        if (me != null)
2473  
          return invokeMethod(me, null, args);
2474  
        List<Method> methods = cache.cache.get(method);
2475  
        if (methods != null)
2476  
          methodSearch: for (Method m : methods) {
2477  
            {
2478  
              if (!(m.isVarArgs()))
2479  
                continue;
2480  
            }
2481  
            {
2482  
              if (!(isStaticMethod(m)))
2483  
                continue;
2484  
            }
2485  
            Object[] newArgs = massageArgsForVarArgsCall(m, args);
2486  
            if (newArgs != null)
2487  
              return invokeMethod(m, null, newArgs);
2488  
          }
2489  
        throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
2490  
      } else {
2491  
        Class c = o.getClass();
2492  
        _MethodCache cache = callOpt_getCache(c);
2493  
        Method me = cache.findMethod(method, args);
2494  
        if (me != null)
2495  
          return invokeMethod(me, o, args);
2496  
        List<Method> methods = cache.cache.get(method);
2497  
        if (methods != null)
2498  
          methodSearch: for (Method m : methods) {
2499  
            {
2500  
              if (!(m.isVarArgs()))
2501  
                continue;
2502  
            }
2503  
            Object[] newArgs = massageArgsForVarArgsCall(m, args);
2504  
            if (newArgs != null)
2505  
              return invokeMethod(m, o, newArgs);
2506  
          }
2507  
        throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
2508  
      }
2509  
    } catch (Exception __e) {
2510  
      throw rethrow(__e);
2511  
    }
2512  
  }
2513  
2514  
  static public void rotateStringBuffer(StringBuffer buf, int max) {
2515  
    try {
2516  
      if (buf == null)
2517  
        return;
2518  
      synchronized (buf) {
2519  
        if (buf.length() <= max)
2520  
          return;
2521  
        try {
2522  
          int newLength = max / 2;
2523  
          int ofs = buf.length() - newLength;
2524  
          String newString = buf.substring(ofs);
2525  
          buf.setLength(0);
2526  
          buf.append("[...] ").append(newString);
2527  
        } catch (Exception e) {
2528  
          buf.setLength(0);
2529  
        }
2530  
        buf.trimToSize();
2531  
      }
2532  
    } catch (Exception __e) {
2533  
      throw rethrow(__e);
2534  
    }
2535  
  }
2536  
2537  
  static public void rotateStringBuilder(StringBuilder buf, int max) {
2538  
    try {
2539  
      if (buf == null)
2540  
        return;
2541  
      synchronized (buf) {
2542  
        if (buf.length() <= max)
2543  
          return;
2544  
        try {
2545  
          int newLength = max / 2;
2546  
          int ofs = buf.length() - newLength;
2547  
          String newString = buf.substring(ofs);
2548  
          buf.setLength(0);
2549  
          buf.append("[...] ").append(newString);
2550  
        } catch (Exception e) {
2551  
          buf.setLength(0);
2552  
        }
2553  
        buf.trimToSize();
2554  
      }
2555  
    } catch (Exception __e) {
2556  
      throw rethrow(__e);
2557  
    }
2558  
  }
2559  
2560  
  static public List<String> mapToLines(Map map) {
2561  
    List<String> l = new ArrayList();
2562  
    for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
2563  
    return l;
2564  
  }
2565  
2566  
  static public String mapToLines(Map map, Object f) {
2567  
    return lines(map(map, f));
2568  
  }
2569  
2570  
  static public String mapToLines(Object f, Map map) {
2571  
    return lines(map(map, f));
2572  
  }
2573  
2574  
  static public String mapToLines(Object f, Iterable l) {
2575  
    return lines(map(f, l));
2576  
  }
2577  
2578  
  static public <A> String mapToLines(Iterable<A> l, IF1<A, String> f) {
2579  
    return mapToLines((Object) f, l);
2580  
  }
2581  
2582  
  static public <A> String mapToLines(IF1<A, String> f, Iterable<A> l) {
2583  
    return mapToLines((Object) f, l);
2584  
  }
2585  
2586  
  static public <A, B> String mapToLines(Map<A, B> map, IF2<A, B, String> f) {
2587  
    return lines(map(map, f));
2588  
  }
2589  
2590  
  static public String fromLines(Iterable lines) {
2591  
    StringBuilder buf = new StringBuilder();
2592  
    if (lines != null)
2593  
      for (Object line : lines) buf.append(str(line)).append('\n');
2594  
    return buf.toString();
2595  
  }
2596  
2597  
  static public String fromLines(String... lines) {
2598  
    return fromLines(asList(lines));
2599  
  }
2600  
2601  
  static public IterableIterator<String> toLines(File f) {
2602  
    return linesFromFile(f);
2603  
  }
2604  
2605  
  static public List<String> toLines(String s) {
2606  
    List<String> lines = new ArrayList<String>();
2607  
    if (s == null)
2608  
      return lines;
2609  
    int start = 0;
2610  
    while (true) {
2611  
      int i = toLines_nextLineBreak(s, start);
2612  
      if (i < 0) {
2613  
        if (s.length() > start)
2614  
          lines.add(s.substring(start));
2615  
        break;
2616  
      }
2617  
      lines.add(s.substring(start, i));
2618  
      if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
2619  
        i += 2;
2620  
      else
2621  
        ++i;
2622  
      start = i;
2623  
    }
2624  
    return lines;
2625  
  }
2626  
2627  
  static public int toLines_nextLineBreak(String s, int start) {
2628  
    int n = s.length();
2629  
    for (int i = start; i < n; i++) {
2630  
      char c = s.charAt(i);
2631  
      if (c == '\r' || c == '\n')
2632  
        return i;
2633  
    }
2634  
    return -1;
2635  
  }
2636  
2637  
  static public int max(int a, int b) {
2638  
    return Math.max(a, b);
2639  
  }
2640  
2641  
  static public int max(int a, int b, int c) {
2642  
    return max(max(a, b), c);
2643  
  }
2644  
2645  
  static public long max(int a, long b) {
2646  
    return Math.max((long) a, b);
2647  
  }
2648  
2649  
  static public long max(long a, long b) {
2650  
    return Math.max(a, b);
2651  
  }
2652  
2653  
  static public double max(int a, double b) {
2654  
    return Math.max((double) a, b);
2655  
  }
2656  
2657  
  static public float max(float a, float b) {
2658  
    return Math.max(a, b);
2659  
  }
2660  
2661  
  static public double max(double a, double b) {
2662  
    return Math.max(a, b);
2663  
  }
2664  
2665  
  static public int max(Collection<Integer> c) {
2666  
    int x = Integer.MIN_VALUE;
2667  
    for (int i : c) x = max(x, i);
2668  
    return x;
2669  
  }
2670  
2671  
  static public double max(double[] c) {
2672  
    if (c.length == 0)
2673  
      return Double.MIN_VALUE;
2674  
    double x = c[0];
2675  
    for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
2676  
    return x;
2677  
  }
2678  
2679  
  static public float max(float[] c) {
2680  
    if (c.length == 0)
2681  
      return Float.MAX_VALUE;
2682  
    float x = c[0];
2683  
    for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
2684  
    return x;
2685  
  }
2686  
2687  
  static public byte max(byte[] c) {
2688  
    byte x = -128;
2689  
    for (byte d : c) if (d > x)
2690  
      x = d;
2691  
    return x;
2692  
  }
2693  
2694  
  static public short max(short[] c) {
2695  
    short x = -0x8000;
2696  
    for (short d : c) if (d > x)
2697  
      x = d;
2698  
    return x;
2699  
  }
2700  
2701  
  static public int max(int[] c) {
2702  
    int x = Integer.MIN_VALUE;
2703  
    for (int d : c) if (d > x)
2704  
      x = d;
2705  
    return x;
2706  
  }
2707  
2708  
  static public Class primitiveToBoxedTypeOpt(Class type) {
2709  
    return or(primitiveToBoxedType(type), type);
2710  
  }
2711  
2712  
  static public boolean isInstance(Class type, Object arg) {
2713  
    return type.isInstance(arg);
2714  
  }
2715  
2716  
  static public Throwable getInnerException(Throwable e) {
2717  
    if (e == null)
2718  
      return null;
2719  
    while (e.getCause() != null) e = e.getCause();
2720  
    return e;
2721  
  }
2722  
2723  
  static public Throwable getInnerException(Runnable r) {
2724  
    return getInnerException(getException(r));
2725  
  }
2726  
2727  
  public static <A> String join(String glue, Iterable<A> strings) {
2728  
    if (strings == null)
2729  
      return "";
2730  
    if (strings instanceof Collection) {
2731  
      if (((Collection) strings).size() == 1)
2732  
        return str(first(((Collection) strings)));
2733  
    }
2734  
    StringBuilder buf = new StringBuilder();
2735  
    Iterator<A> i = strings.iterator();
2736  
    if (i.hasNext()) {
2737  
      buf.append(i.next());
2738  
      while (i.hasNext()) buf.append(glue).append(i.next());
2739  
    }
2740  
    return buf.toString();
2741  
  }
2742  
2743  
  public static String join(String glue, String... strings) {
2744  
    return join(glue, Arrays.asList(strings));
2745  
  }
2746  
2747  
  static public <A> String join(Iterable<A> strings) {
2748  
    return join("", strings);
2749  
  }
2750  
2751  
  static public <A> String join(Iterable<A> strings, String glue) {
2752  
    return join(glue, strings);
2753  
  }
2754  
2755  
  public static String join(String[] strings) {
2756  
    return join("", strings);
2757  
  }
2758  
2759  
  static public String join(String glue, Pair p) {
2760  
    return p == null ? "" : str(p.a) + glue + str(p.b);
2761  
  }
2762  
2763  
  static public boolean callableOn_nonSynthetic(Object o, String method, Object... args) {
2764  
    List<Method> l = findMethods_precise_onTypes(o, method, getClasses_array(args));
2765  
    if (l != null)
2766  
      for (Method m : l) if (isNonSynthetic(m))
2767  
        return true;
2768  
    return false;
2769  
  }
2770  
2771  
  static public String beautifyStructure(String s) {
2772  
    List<String> tok = javaTokForStructure(s);
2773  
    structure_addTokenMarkers(tok);
2774  
    jreplace(tok, "lhm", "");
2775  
    return join(tok);
2776  
  }
2777  
2778  
  static public String struct_noStringSharing(Object o) {
2779  
    structure_Data d = new structure_Data();
2780  
    d.noStringSharing = true;
2781  
    return structure(o, d);
2782  
  }
2783  
2784  
  static public <A> AutoCloseable tempSetThreadLocal(final ThreadLocal<A> tl, A a) {
2785  
    if (tl == null)
2786  
      return null;
2787  
    final A prev = setThreadLocal(tl, a);
2788  
    return new AutoCloseable() {
2789  
2790  
      public String toString() {
2791  
        return "tl.set(prev);";
2792  
      }
2793  
2794  
      public void close() throws Exception {
2795  
        tl.set(prev);
2796  
      }
2797  
    };
2798  
  }
2799  
2800  
  static public String hideCredentials(URL url) {
2801  
    return url == null ? null : hideCredentials(str(url));
2802  
  }
2803  
2804  
  static public String hideCredentials(String url) {
2805  
    try {
2806  
      if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url)))
2807  
        return url;
2808  
    } catch (Throwable e) {
2809  
      print("HideCredentials", e);
2810  
    }
2811  
    return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=<hidden>");
2812  
  }
2813  
2814  
  static public String hideCredentials(Object o) {
2815  
    return hideCredentials(str(o));
2816  
  }
2817  
2818  
  static public String getStackTrace(Throwable throwable) {
2819  
    lastException(throwable);
2820  
    return getStackTrace_noRecord(throwable);
2821  
  }
2822  
2823  
  static public String getStackTrace_noRecord(Throwable throwable) {
2824  
    StringWriter writer = new StringWriter();
2825  
    throwable.printStackTrace(new PrintWriter(writer));
2826  
    return hideCredentials(writer.toString());
2827  
  }
2828  
2829  
  static public String getStackTrace() {
2830  
    return getStackTrace_noRecord(new Throwable());
2831  
  }
2832  
2833  
  static public Throwable unwrapTrivialExceptionWraps(Throwable e) {
2834  
    if (e == null)
2835  
      return e;
2836  
    while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause();
2837  
    return e;
2838  
  }
2839  
2840  
  static public String replacePrefix(String prefix, String replacement, String s) {
2841  
    if (!startsWith(s, prefix))
2842  
      return s;
2843  
    return replacement + substring(s, l(prefix));
2844  
  }
2845  
2846  
  static public Throwable innerException2(Throwable e) {
2847  
    if (e == null)
2848  
      return null;
2849  
    while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause();
2850  
    return e;
2851  
  }
2852  
2853  
  static public int min(int a, int b) {
2854  
    return Math.min(a, b);
2855  
  }
2856  
2857  
  static public long min(long a, long b) {
2858  
    return Math.min(a, b);
2859  
  }
2860  
2861  
  static public float min(float a, float b) {
2862  
    return Math.min(a, b);
2863  
  }
2864  
2865  
  static public float min(float a, float b, float c) {
2866  
    return min(min(a, b), c);
2867  
  }
2868  
2869  
  static public double min(double a, double b) {
2870  
    return Math.min(a, b);
2871  
  }
2872  
2873  
  static public double min(double[] c) {
2874  
    double x = Double.MAX_VALUE;
2875  
    for (double d : c) x = Math.min(x, d);
2876  
    return x;
2877  
  }
2878  
2879  
  static public float min(float[] c) {
2880  
    float x = Float.MAX_VALUE;
2881  
    for (float d : c) x = Math.min(x, d);
2882  
    return x;
2883  
  }
2884  
2885  
  static public byte min(byte[] c) {
2886  
    byte x = 127;
2887  
    for (byte d : c) if (d < x)
2888  
      x = d;
2889  
    return x;
2890  
  }
2891  
2892  
  static public short min(short[] c) {
2893  
    short x = 0x7FFF;
2894  
    for (short d : c) if (d < x)
2895  
      x = d;
2896  
    return x;
2897  
  }
2898  
2899  
  static public int min(int[] c) {
2900  
    int x = Integer.MAX_VALUE;
2901  
    for (int d : c) if (d < x)
2902  
      x = d;
2903  
    return x;
2904  
  }
2905  
2906  
  static public String getProgramID() {
2907  
    return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
2908  
  }
2909  
2910  
  static public String getProgramID(Class c) {
2911  
    String id = (String) getOpt(c, "programID");
2912  
    if (nempty(id))
2913  
      return formatSnippetID(id);
2914  
    return "?";
2915  
  }
2916  
2917  
  static public String getProgramID(Object o) {
2918  
    return getProgramID(getMainClass(o));
2919  
  }
2920  
2921  
  static public <A> WeakReference<A> newWeakReference(A a) {
2922  
    return a == null ? null : new WeakReference(a);
2923  
  }
2924  
2925  
  static public List<String> tok_combineRoundOrCurlyBrackets_keep(List<String> tok) {
2926  
    List<String> l = new ArrayList();
2927  
    for (int i = 0; i < l(tok); i++) {
2928  
      String t = tok.get(i);
2929  
      if (odd(i) && eqOneOf(t, "{", "(")) {
2930  
        int j = findEndOfBracketPart(tok, i);
2931  
        l.add(joinSubList(tok, i, j));
2932  
        i = j - 1;
2933  
      } else
2934  
        l.add(t);
2935  
    }
2936  
    return l;
2937  
  }
2938  
2939  
  static public String javaTok_substringN(String s, int i, int j) {
2940  
    if (i == j)
2941  
      return "";
2942  
    if (j == i + 1 && s.charAt(i) == ' ')
2943  
      return " ";
2944  
    return s.substring(i, j);
2945  
  }
2946  
2947  
  static public String javaTok_substringC(String s, int i, int j) {
2948  
    return s.substring(i, j);
2949  
  }
2950  
2951  
  static public List<String> javaTokWithExisting(String s, List<String> existing) {
2952  
    ++javaTok_n;
2953  
    int nExisting = javaTok_opt && existing != null ? existing.size() : 0;
2954  
    ArrayList<String> tok = existing != null ? new ArrayList(nExisting) : new ArrayList();
2955  
    int l = s.length();
2956  
    int i = 0, n = 0;
2957  
    while (i < l) {
2958  
      int j = i;
2959  
      char c, d;
2960  
      while (j < l) {
2961  
        c = s.charAt(j);
2962  
        d = j + 1 >= l ? '\0' : s.charAt(j + 1);
2963  
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
2964  
          ++j;
2965  
        else if (c == '/' && d == '*') {
2966  
          do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
2967  
          j = Math.min(j + 2, l);
2968  
        } else if (c == '/' && d == '/') {
2969  
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
2970  
        } else
2971  
          break;
2972  
      }
2973  
      if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
2974  
        tok.add(existing.get(n));
2975  
      else
2976  
        tok.add(javaTok_substringN(s, i, j));
2977  
      ++n;
2978  
      i = j;
2979  
      if (i >= l)
2980  
        break;
2981  
      c = s.charAt(i);
2982  
      d = i + 1 >= l ? '\0' : s.charAt(i + 1);
2983  
      if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
2984  
        j += 2;
2985  
        while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
2986  
      } else if (c == '\'' || c == '"') {
2987  
        char opener = c;
2988  
        ++j;
2989  
        while (j < l) {
2990  
          if (s.charAt(j) == opener) {
2991  
            ++j;
2992  
            break;
2993  
          } else if (s.charAt(j) == '\\' && j + 1 < l)
2994  
            j += 2;
2995  
          else
2996  
            ++j;
2997  
        }
2998  
      } else if (Character.isJavaIdentifierStart(c))
2999  
        do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0));
3000  
      else if (Character.isDigit(c)) {
3001  
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
3002  
        if (j < l && s.charAt(j) == 'L')
3003  
          ++j;
3004  
      } else if (c == '[' && d == '[') {
3005  
        do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]"));
3006  
        j = Math.min(j + 2, l);
3007  
      } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
3008  
        do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]"));
3009  
        j = Math.min(j + 3, l);
3010  
      } else
3011  
        ++j;
3012  
      if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j))
3013  
        tok.add(existing.get(n));
3014  
      else
3015  
        tok.add(javaTok_substringC(s, i, j));
3016  
      ++n;
3017  
      i = j;
3018  
    }
3019  
    if ((tok.size() % 2) == 0)
3020  
      tok.add("");
3021  
    javaTok_elements += tok.size();
3022  
    return tok;
3023  
  }
3024  
3025  
  static public boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) {
3026  
    return t.length() == j - i && s.regionMatches(i, t, 0, j - i);
3027  
  }
3028  
3029  
  static public String trim(String s) {
3030  
    return s == null ? null : s.trim();
3031  
  }
3032  
3033  
  static public String trim(StringBuilder buf) {
3034  
    return buf.toString().trim();
3035  
  }
3036  
3037  
  static public String trim(StringBuffer buf) {
3038  
    return buf.toString().trim();
3039  
  }
3040  
3041  
  static public boolean isJavaIdentifier(String s) {
3042  
    if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0)))
3043  
      return false;
3044  
    for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)))
3045  
      return false;
3046  
    return true;
3047  
  }
3048  
3049  
  static public <A, B> B mapGet(Map<A, B> map, A a) {
3050  
    return map == null || a == null ? null : map.get(a);
3051  
  }
3052  
3053  
  static public <A, B> B mapGet(A a, Map<A, B> map) {
3054  
    return map == null || a == null ? null : map.get(a);
3055  
  }
3056  
3057  
  static public <A> A liftLast(List<A> l) {
3058  
    if (empty(l))
3059  
      return null;
3060  
    int i = l(l) - 1;
3061  
    A a = l.get(i);
3062  
    l.remove(i);
3063  
    return a;
3064  
  }
3065  
3066  
  static public <A> List<A> liftLast(int n, List<A> l) {
3067  
    int i = l(l) - n;
3068  
    List<A> part = cloneSubList(l, i);
3069  
    removeSubList(l, i);
3070  
    return part;
3071  
  }
3072  
3073  
  static public <A> HashSet<A> lithashset(A... items) {
3074  
    HashSet<A> set = new HashSet();
3075  
    for (A a : items) set.add(a);
3076  
    return set;
3077  
  }
3078  
3079  
  static public boolean eqOneOf(Object o, Object... l) {
3080  
    for (Object x : l) if (eq(o, x))
3081  
      return true;
3082  
    return false;
3083  
  }
3084  
3085  
  static public <A> List<A> subList(List<A> l, int startIndex) {
3086  
    return subList(l, startIndex, l(l));
3087  
  }
3088  
3089  
  static public <A> List<A> subList(int startIndex, int endIndex, List<A> l) {
3090  
    return subList(l, startIndex, endIndex);
3091  
  }
3092  
3093  
  static public <A> List<A> subList(List<A> l, int startIndex, int endIndex) {
3094  
    if (l == null)
3095  
      return null;
3096  
    int n = l(l);
3097  
    startIndex = Math.max(0, startIndex);
3098  
    endIndex = Math.min(n, endIndex);
3099  
    if (startIndex >= endIndex)
3100  
      return ll();
3101  
    if (startIndex == 0 && endIndex == n)
3102  
      return l;
3103  
    return l.subList(startIndex, endIndex);
3104  
  }
3105  
3106  
  static public <A> List<A> subList(List<A> l, IntRange r) {
3107  
    return subList(l, r.start, r.end);
3108  
  }
3109  
3110  
  static public boolean containsNewLine(String s) {
3111  
    return contains(s, '\n');
3112  
  }
3113  
3114  
  static public String getClassName(Object o) {
3115  
    return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
3116  
  }
3117  
3118  
  static public String className(Object o) {
3119  
    return getClassName(o);
3120  
  }
3121  
3122  
  static public <A, B> Map<A, B> synchronizedMRUCache(int maxSize) {
3123  
    return synchroMap(new MRUCache(maxSize));
3124  
  }
3125  
3126  
  static volatile public boolean licensed_yes = true;
3127  
3128  
  static public boolean licensed() {
3129  
    if (!licensed_yes)
3130  
      return false;
3131  
    ping_okInCleanUp();
3132  
    return true;
3133  
  }
3134  
3135  
  static public void licensed_off() {
3136  
    licensed_yes = false;
3137  
  }
3138  
3139  
  static public String formatWithThousandsSeparator(long l) {
3140  
    return NumberFormat.getInstance(new Locale("en_US")).format(l);
3141  
  }
3142  
3143  
  static public Class getMainClass() {
3144  
    return mc();
3145  
  }
3146  
3147  
  static public Class getMainClass(Object o) {
3148  
    try {
3149  
      if (o == null)
3150  
        return null;
3151  
      if (o instanceof Class && eq(((Class) o).getName(), "x30"))
3152  
        return (Class) o;
3153  
      return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
3154  
    } catch (Exception __e) {
3155  
      throw rethrow(__e);
3156  
    }
3157  
  }
3158  
3159  
  static final public Map<Class, _MethodCache> callOpt_cache = newDangerousWeakHashMap();
3160  
3161  
  static public Object callOpt_cached(Object o, String methodName, Object... args) {
3162  
    try {
3163  
      if (o == null)
3164  
        return null;
3165  
      if (o instanceof Class) {
3166  
        Class c = (Class) o;
3167  
        _MethodCache cache = callOpt_getCache(c);
3168  
        Method me = cache.findMethod(methodName, args);
3169  
        if (me == null || (me.getModifiers() & Modifier.STATIC) == 0)
3170  
          return null;
3171  
        return invokeMethod(me, null, args);
3172  
      } else {
3173  
        Class c = o.getClass();
3174  
        _MethodCache cache = callOpt_getCache(c);
3175  
        Method me = cache.findMethod(methodName, args);
3176  
        if (me == null)
3177  
          return null;
3178  
        return invokeMethod(me, o, args);
3179  
      }
3180  
    } catch (Exception __e) {
3181  
      throw rethrow(__e);
3182  
    }
3183  
  }
3184  
3185  
  static public _MethodCache callOpt_getCache(Class c) {
3186  
    synchronized (callOpt_cache) {
3187  
      _MethodCache cache = callOpt_cache.get(c);
3188  
      if (cache == null)
3189  
        callOpt_cache.put(c, cache = new _MethodCache(c));
3190  
      return cache;
3191  
    }
3192  
  }
3193  
3194  
  static public Object invokeMethod(Method m, Object o, Object... args) {
3195  
    try {
3196  
      try {
3197  
        return m.invoke(o, args);
3198  
      } catch (InvocationTargetException e) {
3199  
        throw rethrow(getExceptionCause(e));
3200  
      } catch (IllegalArgumentException e) {
3201  
        throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args)));
3202  
      }
3203  
    } catch (Exception __e) {
3204  
      throw rethrow(__e);
3205  
    }
3206  
  }
3207  
3208  
  static public boolean isStaticMethod(Method m) {
3209  
    return methodIsStatic(m);
3210  
  }
3211  
3212  
  static public Object[] massageArgsForVarArgsCall(Method m, Object[] args) {
3213  
    Class<?>[] types = m.getParameterTypes();
3214  
    int n = types.length - 1, nArgs = args.length;
3215  
    if (nArgs < n)
3216  
      return null;
3217  
    for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i]))
3218  
      return null;
3219  
    Class varArgType = types[n].getComponentType();
3220  
    for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType))
3221  
      return null;
3222  
    Object[] newArgs = new Object[n + 1];
3223  
    arraycopy(args, 0, newArgs, 0, n);
3224  
    Object[] varArgs = arrayOfType(varArgType, nArgs - n);
3225  
    arraycopy(args, n, varArgs, 0, nArgs - n);
3226  
    newArgs[n] = varArgs;
3227  
    return newArgs;
3228  
  }
3229  
3230  
  static public List<String> classNames(Collection l) {
3231  
    return getClassNames(l);
3232  
  }
3233  
3234  
  static public List<String> classNames(Object[] l) {
3235  
    return getClassNames(Arrays.asList(l));
3236  
  }
3237  
3238  
  static public <A, B> Set<A> keys(Map<A, B> map) {
3239  
    return map == null ? new HashSet() : map.keySet();
3240  
  }
3241  
3242  
  static public Set keys(Object map) {
3243  
    return keys((Map) map);
3244  
  }
3245  
3246  
  static public <A> Set<A> keys(MultiSet<A> ms) {
3247  
    return ms.keySet();
3248  
  }
3249  
3250  
  static public <A, B> Set<A> keys(MultiSetMap<A, B> mm) {
3251  
    return mm.keySet();
3252  
  }
3253  
3254  
  static public CloseableIterableIterator<String> linesFromFile(File f) {
3255  
    try {
3256  
      if (!f.exists())
3257  
        return emptyCloseableIterableIterator();
3258  
      if (ewic(f.getName(), ".gz"))
3259  
        return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)));
3260  
      return linesFromReader(utf8bufferedReader(f));
3261  
    } catch (Exception __e) {
3262  
      throw rethrow(__e);
3263  
    }
3264  
  }
3265  
3266  
  static public CloseableIterableIterator<String> linesFromFile(String path) {
3267  
    return linesFromFile(newFile(path));
3268  
  }
3269  
3270  
  static public Class primitiveToBoxedType(Class type) {
3271  
    if (type == boolean.class)
3272  
      return Boolean.class;
3273  
    if (type == int.class)
3274  
      return Integer.class;
3275  
    if (type == long.class)
3276  
      return Long.class;
3277  
    if (type == float.class)
3278  
      return Float.class;
3279  
    if (type == short.class)
3280  
      return Short.class;
3281  
    if (type == char.class)
3282  
      return Character.class;
3283  
    if (type == byte.class)
3284  
      return Byte.class;
3285  
    if (type == double.class)
3286  
      return Double.class;
3287  
    return null;
3288  
  }
3289  
3290  
  static public Throwable getException(Runnable r) {
3291  
    try {
3292  
      callF(r);
3293  
      return null;
3294  
    } catch (Throwable e) {
3295  
      return e;
3296  
    }
3297  
  }
3298  
3299  
  static public List<Method> findMethods_precise_onTypes(Object o, String method, Class... argTypes) {
3300  
    try {
3301  
      if (o instanceof Class) {
3302  
        _MethodCache cache = callOpt_getCache(((Class) o));
3303  
        List<Method> methods = cache.cache.get(method);
3304  
        Map<Method, Integer> scores = new HashMap();
3305  
        if (methods != null)
3306  
          for (Method m : methods) {
3307  
            {
3308  
              if (!(isStaticMethod(m)))
3309  
                continue;
3310  
            }
3311  
            int score = methodApplicabilityScore_onTypes(m, argTypes);
3312  
            if (score < Integer.MAX_VALUE) {
3313  
              scores.put(m, score);
3314  
            }
3315  
          }
3316  
        return keysSortedByValue(scores);
3317  
      }
3318  
      if (o == null)
3319  
        return null;
3320  
      _MethodCache cache = callOpt_getCache(o.getClass());
3321  
      List<Method> methods = cache.cache.get(method);
3322  
      Map<Method, Integer> best = new HashMap();
3323  
      if (methods != null)
3324  
        for (Method m : methods) {
3325  
          int score = methodApplicabilityScore_onTypes(m, argTypes);
3326  
          if (score < Integer.MAX_VALUE)
3327  
            best.put(m, score);
3328  
        }
3329  
      return keysSortedByValue(best);
3330  
    } catch (Exception __e) {
3331  
      throw rethrow(__e);
3332  
    }
3333  
  }
3334  
3335  
  static public Class[] getClasses_array(Object[] array) {
3336  
    if (array == null)
3337  
      return null;
3338  
    int n = array.length;
3339  
    Class[] l = new Class[n];
3340  
    for (int i = 0; i < n; i++) l[i] = _getClass(array[i]);
3341  
    return l;
3342  
  }
3343  
3344  
  static public boolean isNonSynthetic(Method m) {
3345  
    return m != null && !m.isSynthetic();
3346  
  }
3347  
3348  
  static public List<String> javaTokForStructure(String s) {
3349  
    return javaTok_noMLS(s);
3350  
  }
3351  
3352  
  static public String structure_addTokenMarkers(String s) {
3353  
    return join(structure_addTokenMarkers(javaTokForStructure(s)));
3354  
  }
3355  
3356  
  static public List<String> structure_addTokenMarkers(List<String> tok) {
3357  
    TreeSet<Integer> refs = new TreeSet();
3358  
    for (int i = 1; i < l(tok); i += 2) {
3359  
      String t = tok.get(i);
3360  
      if (t.startsWith("t") && isInteger(t.substring(1)))
3361  
        refs.add(parseInt(t.substring(1)));
3362  
    }
3363  
    if (empty(refs))
3364  
      return tok;
3365  
    for (int i : refs) {
3366  
      int idx = i * 2 + 1;
3367  
      if (idx >= l(tok))
3368  
        continue;
3369  
      String t = "";
3370  
      if (endsWithLetterOrDigit(tok.get(idx - 1)))
3371  
        t = " ";
3372  
      tok.set(idx, t + "m" + i + " " + tok.get(idx));
3373  
    }
3374  
    return tok;
3375  
  }
3376  
3377  
  static public String jreplace(String s, String in, String out) {
3378  
    return jreplace(s, in, out, null);
3379  
  }
3380  
3381  
  static public String jreplace(String s, String in, String out, Object condition) {
3382  
    List<String> tok = javaTok(s);
3383  
    return jreplace(tok, in, out, condition) ? join(tok) : s;
3384  
  }
3385  
3386  
  static public boolean jreplace(List<String> tok, String in, String out) {
3387  
    return jreplace(tok, in, out, false, true, null);
3388  
  }
3389  
3390  
  static public boolean jreplace(List<String> tok, String in, String out, Object condition) {
3391  
    return jreplace(tok, in, out, false, true, condition);
3392  
  }
3393  
3394  
  static public boolean jreplace(List<String> tok, String in, String out, IF2<List<String>, Integer, Boolean> condition) {
3395  
    return jreplace(tok, in, out, (Object) condition);
3396  
  }
3397  
3398  
  static public boolean jreplace(List<String> tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) {
3399  
    String[] toks = javaTokForJFind_array(in);
3400  
    int lTokin = toks.length * 2 + 1;
3401  
    boolean anyChange = false;
3402  
    int i = -1;
3403  
    for (int n = 0; n < 10000; n++) {
3404  
      i = findCodeTokens(tok, i + 1, ignoreCase, toks, condition);
3405  
      if (i < 0)
3406  
        return anyChange;
3407  
      List<String> subList = tok.subList(i - 1, i + lTokin - 1);
3408  
      String expansion = jreplaceExpandRefs(out, subList);
3409  
      int end = i + lTokin - 2;
3410  
      clearAllTokens(tok, i, end);
3411  
      tok.set(i, expansion);
3412  
      if (reTok)
3413  
        reTok(tok, i, end);
3414  
      i = end;
3415  
      anyChange = true;
3416  
    }
3417  
    throw fail("woot? 10000! " + quote(in) + " => " + quote(out));
3418  
  }
3419  
3420  
  static public boolean jreplace_debug = false;
3421  
3422  
  static public <A> A setThreadLocal(ThreadLocal<A> tl, A value) {
3423  
    if (tl == null)
3424  
      return null;
3425  
    A old = tl.get();
3426  
    tl.set(value);
3427  
    return old;
3428  
  }
3429  
3430  
  static public boolean startsWithOneOf(String s, String... l) {
3431  
    for (String x : l) if (startsWith(s, x))
3432  
      return true;
3433  
    return false;
3434  
  }
3435  
3436  
  static public boolean startsWithOneOf(String s, Matches m, String... l) {
3437  
    for (String x : l) if (startsWith(s, x, m))
3438  
      return true;
3439  
    return false;
3440  
  }
3441  
3442  
  static public boolean isAGIBlueDomain(String domain) {
3443  
    return domainIsUnder(domain, theAGIBlueDomain());
3444  
  }
3445  
3446  
  static public String hostNameFromURL(String url) {
3447  
    try {
3448  
      return new URL(url).getHost();
3449  
    } catch (Exception __e) {
3450  
      throw rethrow(__e);
3451  
    }
3452  
  }
3453  
3454  
  static volatile public PersistableThrowable lastException_lastException;
3455  
3456  
  static public PersistableThrowable lastException() {
3457  
    return lastException_lastException;
3458  
  }
3459  
3460  
  static public void lastException(Throwable e) {
3461  
    lastException_lastException = persistableThrowable(e);
3462  
  }
3463  
3464  
  static public String formatSnippetIDOpt(String s) {
3465  
    return isSnippetID(s) ? formatSnippetID(s) : s;
3466  
  }
3467  
3468  
  static public String formatSnippetID(String id) {
3469  
    return "#" + parseSnippetID(id);
3470  
  }
3471  
3472  
  static public String formatSnippetID(long id) {
3473  
    return "#" + id;
3474  
  }
3475  
3476  
  static public boolean odd(int i) {
3477  
    return (i & 1) != 0;
3478  
  }
3479  
3480  
  static public boolean odd(long i) {
3481  
    return (i & 1) != 0;
3482  
  }
3483  
3484  
  static public boolean odd(BigInteger i) {
3485  
    return odd(toInt(i));
3486  
  }
3487  
3488  
  static public int findEndOfBracketPart(List<String> cnc, int i) {
3489  
    int j = i + 2, level = 1;
3490  
    while (j < cnc.size()) {
3491  
      if (eqOneOf(cnc.get(j), "{", "("))
3492  
        ++level;
3493  
      else if (eqOneOf(cnc.get(j), "}", ")"))
3494  
        --level;
3495  
      if (level == 0)
3496  
        return j + 1;
3497  
      ++j;
3498  
    }
3499  
    return cnc.size();
3500  
  }
3501  
3502  
  static public String joinSubList(List<String> l, int i, int j) {
3503  
    return join(subList(l, i, j));
3504  
  }
3505  
3506  
  static public String joinSubList(List<String> l, int i) {
3507  
    return join(subList(l, i));
3508  
  }
3509  
3510  
  static public String joinSubList(List<String> l, IntRange r) {
3511  
    return r == null ? null : joinSubList(l, r.start, r.end);
3512  
  }
3513  
3514  
  static public <A> List<A> cloneSubList(List<A> l, int startIndex, int endIndex) {
3515  
    return newSubList(l, startIndex, endIndex);
3516  
  }
3517  
3518  
  static public <A> List<A> cloneSubList(List<A> l, int startIndex) {
3519  
    return newSubList(l, startIndex);
3520  
  }
3521  
3522  
  static public void removeSubList(List l, int from, int to) {
3523  
    if (l != null)
3524  
      subList(l, from, to).clear();
3525  
  }
3526  
3527  
  static public void removeSubList(List l, int from) {
3528  
    if (l != null)
3529  
      subList(l, from).clear();
3530  
  }
3531  
3532  
  static public boolean contains(Collection c, Object o) {
3533  
    return c != null && c.contains(o);
3534  
  }
3535  
3536  
  static public boolean contains(Object[] x, Object o) {
3537  
    if (x != null)
3538  
      for (Object a : x) if (eq(a, o))
3539  
        return true;
3540  
    return false;
3541  
  }
3542  
3543  
  static public boolean contains(String s, char c) {
3544  
    return s != null && s.indexOf(c) >= 0;
3545  
  }
3546  
3547  
  static public boolean contains(String s, String b) {
3548  
    return s != null && s.indexOf(b) >= 0;
3549  
  }
3550  
3551  
  static public boolean contains(BitSet bs, int i) {
3552  
    return bs != null && bs.get(i);
3553  
  }
3554  
3555  
  static public <A> boolean contains(Producer<A> p, A a) {
3556  
    if (p != null && a != null)
3557  
      while (true) {
3558  
        A x = p.next();
3559  
        if (x == null)
3560  
          break;
3561  
        if (eq(x, a))
3562  
          return true;
3563  
      }
3564  
    return false;
3565  
  }
3566  
3567  
  static public Map synchroMap() {
3568  
    return synchroHashMap();
3569  
  }
3570  
3571  
  static public <A, B> Map<A, B> synchroMap(Map<A, B> map) {
3572  
    return Collections.synchronizedMap(map);
3573  
  }
3574  
3575  
  static public Throwable getExceptionCause(Throwable e) {
3576  
    Throwable c = e.getCause();
3577  
    return c != null ? c : e;
3578  
  }
3579  
3580  
  static public String joinWithSpace(Iterable c) {
3581  
    return join(" ", c);
3582  
  }
3583  
3584  
  static public String joinWithSpace(String... c) {
3585  
    return join(" ", c);
3586  
  }
3587  
3588  
  static public boolean methodIsStatic(Method m) {
3589  
    return (m.getModifiers() & Modifier.STATIC) != 0;
3590  
  }
3591  
3592  
  static public boolean argumentCompatibleWithType(Object arg, Class type) {
3593  
    return arg == null ? !type.isPrimitive() : isInstanceX(type, arg);
3594  
  }
3595  
3596  
  static public void arraycopy(Object[] a, Object[] b) {
3597  
    if (a != null && b != null)
3598  
      arraycopy(a, 0, b, 0, min(a.length, b.length));
3599  
  }
3600  
3601  
  static public void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) {
3602  
    if (n != 0)
3603  
      System.arraycopy(src, srcPos, dest, destPos, n);
3604  
  }
3605  
3606  
  static public <A> A[] arrayOfType(Class<A> type, int n) {
3607  
    return makeArray(type, n);
3608  
  }
3609  
3610  
  static public <A> A[] arrayOfType(int n, Class<A> type) {
3611  
    return arrayOfType(type, n);
3612  
  }
3613  
3614  
  static public List<String> getClassNames(Collection l) {
3615  
    List<String> out = new ArrayList();
3616  
    if (l != null)
3617  
      for (Object o : l) out.add(o == null ? null : getClassName(o));
3618  
    return out;
3619  
  }
3620  
3621  
  static public CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() {
3622  
3623  
    public Object next() {
3624  
      throw fail();
3625  
    }
3626  
3627  
    public boolean hasNext() {
3628  
      return false;
3629  
    }
3630  
  };
3631  
3632  
  static public <A> CloseableIterableIterator<A> emptyCloseableIterableIterator() {
3633  
    return emptyCloseableIterableIterator_instance;
3634  
  }
3635  
3636  
  static public boolean ewic(String a, String b) {
3637  
    return endsWithIgnoreCase(a, b);
3638  
  }
3639  
3640  
  static public boolean ewic(String a, String b, Matches m) {
3641  
    return endsWithIgnoreCase(a, b, m);
3642  
  }
3643  
3644  
  static public CloseableIterableIterator<String> linesFromReader(Reader r) {
3645  
    final BufferedReader br = bufferedReader(r);
3646  
    return iteratorFromFunction_f0_autoCloseable(new F0<String>() {
3647  
3648  
      public String get() {
3649  
        try {
3650  
          return readLineFromReaderWithClose(br);
3651  
        } catch (Exception __e) {
3652  
          throw rethrow(__e);
3653  
        }
3654  
      }
3655  
3656  
      public String toString() {
3657  
        return "ret readLineFromReaderWithClose(br);";
3658  
      }
3659  
    }, _wrapIOCloseable(r));
3660  
  }
3661  
3662  
  static public BufferedReader utf8bufferedReader(InputStream in) {
3663  
    try {
3664  
      return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in));
3665  
    } catch (Exception __e) {
3666  
      throw rethrow(__e);
3667  
    }
3668  
  }
3669  
3670  
  static public BufferedReader utf8bufferedReader(File f) {
3671  
    try {
3672  
      return utf8bufferedReader(newFileInputStream(f));
3673  
    } catch (Exception __e) {
3674  
      throw rethrow(__e);
3675  
    }
3676  
  }
3677  
3678  
  static public GZIPInputStream newGZIPInputStream(File f) {
3679  
    return gzInputStream(f);
3680  
  }
3681  
3682  
  static public GZIPInputStream newGZIPInputStream(InputStream in) {
3683  
    return gzInputStream(in);
3684  
  }
3685  
3686  
  static public File newFile(File base, String... names) {
3687  
    for (String name : names) base = new File(base, name);
3688  
    return base;
3689  
  }
3690  
3691  
  static public File newFile(String name) {
3692  
    return name == null ? null : new File(name);
3693  
  }
3694  
3695  
  static public File newFile(String base, String... names) {
3696  
    return newFile(newFile(base), names);
3697  
  }
3698  
3699  
  static public int methodApplicabilityScore_onTypes(Method m, Class[] argTypes) {
3700  
    Class<?>[] types = m.getParameterTypes();
3701  
    if (types.length != argTypes.length)
3702  
      return Integer.MAX_VALUE;
3703  
    int score = 0;
3704  
    for (int i = 0; i < types.length; i++) {
3705  
      Class a = argTypes[i];
3706  
      Class c = types[i];
3707  
      if (c == a) {
3708  
      } else if (isSubclassOf(a, c))
3709  
        ++score;
3710  
      else
3711  
        return Integer.MAX_VALUE;
3712  
    }
3713  
    return score;
3714  
  }
3715  
3716  
  static public <A, B> List<A> keysSortedByValue(Map<A, B> map) {
3717  
    return keysSortedByValues(map);
3718  
  }
3719  
3720  
  static public Class<?> _getClass(String name) {
3721  
    try {
3722  
      return Class.forName(name);
3723  
    } catch (ClassNotFoundException e) {
3724  
      return null;
3725  
    }
3726  
  }
3727  
3728  
  static public Class _getClass(Object o) {
3729  
    return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
3730  
  }
3731  
3732  
  static public Class _getClass(Object realm, String name) {
3733  
    try {
3734  
      return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
3735  
    } catch (ClassNotFoundException e) {
3736  
      return null;
3737  
    }
3738  
  }
3739  
3740  
  static public List<String> javaTok_noMLS(String s) {
3741  
    ArrayList<String> tok = new ArrayList();
3742  
    int l = s == null ? 0 : s.length();
3743  
    int i = 0, n = 0;
3744  
    while (i < l) {
3745  
      int j = i;
3746  
      char c, d;
3747  
      while (j < l) {
3748  
        c = s.charAt(j);
3749  
        d = j + 1 >= l ? '\0' : s.charAt(j + 1);
3750  
        if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
3751  
          ++j;
3752  
        else if (c == '/' && d == '*') {
3753  
          do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
3754  
          j = Math.min(j + 2, l);
3755  
        } else if (c == '/' && d == '/') {
3756  
          do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
3757  
        } else
3758  
          break;
3759  
      }
3760  
      tok.add(javaTok_substringN(s, i, j));
3761  
      ++n;
3762  
      i = j;
3763  
      if (i >= l)
3764  
        break;
3765  
      c = s.charAt(i);
3766  
      d = i + 1 >= l ? '\0' : s.charAt(i + 1);
3767  
      if (c == '\'' || c == '"') {
3768  
        char opener = c;
3769  
        ++j;
3770  
        while (j < l) {
3771  
          int c2 = s.charAt(j);
3772  
          if (c2 == opener || c2 == '\n' && opener == '\'') {
3773  
            ++j;
3774  
            break;
3775  
          } else if (c2 == '\\' && j + 1 < l)
3776  
            j += 2;
3777  
          else
3778  
            ++j;
3779  
        }
3780  
      } else if (Character.isJavaIdentifierStart(c))
3781  
        do ++j; while (j < l && Character.isJavaIdentifierPart(s.charAt(j)));
3782  
      else if (Character.isDigit(c)) {
3783  
        do ++j; while (j < l && Character.isDigit(s.charAt(j)));
3784  
        if (j < l && s.charAt(j) == 'L')
3785  
          ++j;
3786  
      } else
3787  
        ++j;
3788  
      tok.add(javaTok_substringC(s, i, j));
3789  
      ++n;
3790  
      i = j;
3791  
    }
3792  
    if ((tok.size() % 2) == 0)
3793  
      tok.add("");
3794  
    return tok;
3795  
  }
3796  
3797  
  static public boolean isInteger(String s) {
3798  
    int n = l(s);
3799  
    if (n == 0)
3800  
      return false;
3801  
    int i = 0;
3802  
    if (s.charAt(0) == '-')
3803  
      if (++i >= n)
3804  
        return false;
3805  
    while (i < n) {
3806  
      char c = s.charAt(i);
3807  
      if (c < '0' || c > '9')
3808  
        return false;
3809  
      ++i;
3810  
    }
3811  
    return true;
3812  
  }
3813  
3814  
  static public int parseInt(String s) {
3815  
    return emptyString(s) ? 0 : Integer.parseInt(s);
3816  
  }
3817  
3818  
  static public int parseInt(char c) {
3819  
    return Integer.parseInt(str(c));
3820  
  }
3821  
3822  
  static public Map<String, String[]> javaTokForJFind_array_cache = synchronizedMRUCache(1000);
3823  
3824  
  static public String[] javaTokForJFind_array(String s) {
3825  
    String[] tok = javaTokForJFind_array_cache.get(s);
3826  
    if (tok == null)
3827  
      javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s))));
3828  
    return tok;
3829  
  }
3830  
3831  
  static public int findCodeTokens(List<String> tok, String... tokens) {
3832  
    return findCodeTokens(tok, 1, false, tokens);
3833  
  }
3834  
3835  
  static public int findCodeTokens(List<String> tok, boolean ignoreCase, String... tokens) {
3836  
    return findCodeTokens(tok, 1, ignoreCase, tokens);
3837  
  }
3838  
3839  
  static public int findCodeTokens(List<String> tok, int startIdx, boolean ignoreCase, String... tokens) {
3840  
    return findCodeTokens(tok, startIdx, ignoreCase, tokens, null);
3841  
  }
3842  
3843  
  static public HashSet<String> findCodeTokens_specials = lithashset("*", "<quoted>", "<id>", "<int>", "\\*");
3844  
3845  
  static public int findCodeTokens_bails, findCodeTokens_nonbails;
3846  
3847  
  static public interface findCodeTokens_Matcher {
3848  
3849  
    public boolean get(String token);
3850  
  }
3851  
3852  
  static public int findCodeTokens(List<String> tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) {
3853  
    int end = tok.size() - tokens.length * 2 + 2, nTokens = tokens.length;
3854  
    int i = startIdx | 1;
3855  
    String firstToken = tokens[0];
3856  
    if (!ignoreCase && !findCodeTokens_specials.contains(firstToken)) {
3857  
      while (i < end && !firstToken.equals(tok.get(i))) i += 2;
3858  
    }
3859  
    findCodeTokens_Matcher[] matchers = new findCodeTokens_Matcher[nTokens];
3860  
    for (int j = 0; j < nTokens; j++) {
3861  
      String p = tokens[j];
3862  
      findCodeTokens_Matcher matcher;
3863  
      if (p.equals("*"))
3864  
        matcher = t -> true;
3865  
      else if (p.equals("<quoted>"))
3866  
        matcher = t -> isQuoted(t);
3867  
      else if (p.equals("<id>"))
3868  
        matcher = t -> isIdentifier(t);
3869  
      else if (p.equals("<int>"))
3870  
        matcher = t -> isInteger(t);
3871  
      else if (p.equals("\\*"))
3872  
        matcher = t -> t.equals("*");
3873  
      else if (ignoreCase)
3874  
        matcher = t -> eqic(p, t);
3875  
      else
3876  
        matcher = t -> t.equals(p);
3877  
      matchers[j] = matcher;
3878  
    }
3879  
    outer: for (; i < end; i += 2) {
3880  
      for (int j = 0; j < nTokens; j++) if (!matchers[j].get(tok.get(i + j * 2)))
3881  
        continue outer;
3882  
      if (condition == null || checkTokCondition(condition, tok, i - 1))
3883  
        return i;
3884  
    }
3885  
    return -1;
3886  
  }
3887  
3888  
  static public String jreplaceExpandRefs(String s, List<String> tokref) {
3889  
    if (!contains(s, '$'))
3890  
      return s;
3891  
    List<String> tok = javaTok(s);
3892  
    for (int i = 1; i < l(tok); i += 2) {
3893  
      String t = tok.get(i);
3894  
      if (t.startsWith("$") && isInteger(t.substring(1))) {
3895  
        String x = tokref.get(-1 + parseInt(t.substring(1)) * 2);
3896  
        tok.set(i, x);
3897  
      } else if (t.equals("\\")) {
3898  
        tok.set(i, "");
3899  
        i += 2;
3900  
      }
3901  
    }
3902  
    return join(tok);
3903  
  }
3904  
3905  
  static public void clearAllTokens(List<String> tok) {
3906  
    for (int i = 0; i < tok.size(); i++) tok.set(i, "");
3907  
  }
3908  
3909  
  static public void clearAllTokens(List<String> tok, int i, int j) {
3910  
    for (; i < j; i++) tok.set(i, "");
3911  
  }
3912  
3913  
  static public List<String> reTok(List<String> tok) {
3914  
    replaceCollection(tok, javaTok(tok));
3915  
    return tok;
3916  
  }
3917  
3918  
  static public List<String> reTok(List<String> tok, int i) {
3919  
    return reTok(tok, i, i + 1);
3920  
  }
3921  
3922  
  static public List<String> reTok(List<String> tok, int i, int j) {
3923  
    i = max(i & ~1, 0);
3924  
    j = min(l(tok), j | 1);
3925  
    if (i >= j)
3926  
      return tok;
3927  
    List<String> t = javaTok(joinSubList(tok, i, j));
3928  
    replaceListPart(tok, i, j, t);
3929  
    return tok;
3930  
  }
3931  
3932  
  static public List<String> reTok(List<String> tok, IntRange r) {
3933  
    if (r != null)
3934  
      reTok(tok, r.start, r.end);
3935  
    return tok;
3936  
  }
3937  
3938  
  static public boolean domainIsUnder(String domain, String mainDomain) {
3939  
    return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain);
3940  
  }
3941  
3942  
  static public String theAGIBlueDomain() {
3943  
    return "agi.blue";
3944  
  }
3945  
3946  
  public static boolean isSnippetID(String s) {
3947  
    try {
3948  
      parseSnippetID(s);
3949  
      return true;
3950  
    } catch (RuntimeException e) {
3951  
      return false;
3952  
    }
3953  
  }
3954  
3955  
  public static long parseSnippetID(String snippetID) {
3956  
    long id = Long.parseLong(shortenSnippetID(snippetID));
3957  
    if (id == 0)
3958  
      throw fail("0 is not a snippet ID");
3959  
    return id;
3960  
  }
3961  
3962  
  static public int toInt(Object o) {
3963  
    if (o == null)
3964  
      return 0;
3965  
    if (o instanceof Number)
3966  
      return ((Number) o).intValue();
3967  
    if (o instanceof String)
3968  
      return parseInt(((String) o));
3969  
    if (o instanceof Boolean)
3970  
      return boolToInt(((Boolean) o));
3971  
    throw fail("woot not int: " + getClassName(o));
3972  
  }
3973  
3974  
  static public int toInt(long l) {
3975  
    if (l != (int) l)
3976  
      throw fail("Too large for int: " + l);
3977  
    return (int) l;
3978  
  }
3979  
3980  
  static public <A> List<A> newSubList(List<A> l, int startIndex, int endIndex) {
3981  
    return cloneList(subList(l, startIndex, endIndex));
3982  
  }
3983  
3984  
  static public <A> List<A> newSubList(List<A> l, int startIndex) {
3985  
    return cloneList(subList(l, startIndex));
3986  
  }
3987  
3988  
  static public Map synchroHashMap() {
3989  
    return Collections.synchronizedMap(new HashMap());
3990  
  }
3991  
3992  
  static public boolean isInstanceX(Class type, Object arg) {
3993  
    if (type == boolean.class)
3994  
      return arg instanceof Boolean;
3995  
    if (type == int.class)
3996  
      return arg instanceof Integer;
3997  
    if (type == long.class)
3998  
      return arg instanceof Long;
3999  
    if (type == float.class)
4000  
      return arg instanceof Float;
4001  
    if (type == short.class)
4002  
      return arg instanceof Short;
4003  
    if (type == char.class)
4004  
      return arg instanceof Character;
4005  
    if (type == byte.class)
4006  
      return arg instanceof Byte;
4007  
    if (type == double.class)
4008  
      return arg instanceof Double;
4009  
    return type.isInstance(arg);
4010  
  }
4011  
4012  
  static public <A> A[] makeArray(Class<A> type, int n) {
4013  
    return (A[]) Array.newInstance(type, n);
4014  
  }
4015  
4016  
  static public boolean endsWithIgnoreCase(String a, String b) {
4017  
    int la = l(a), lb = l(b);
4018  
    return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb);
4019  
  }
4020  
4021  
  static public boolean endsWithIgnoreCase(String a, String b, Matches m) {
4022  
    if (!endsWithIgnoreCase(a, b))
4023  
      return false;
4024  
    m.m = new String[] { substring(a, 0, l(a) - l(b)) };
4025  
    return true;
4026  
  }
4027  
4028  
  static public BufferedReader bufferedReader(Reader r) {
4029  
    return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r);
4030  
  }
4031  
4032  
  static public <A> CloseableIterableIterator<A> iteratorFromFunction_f0_autoCloseable(final F0<A> f, final AutoCloseable closeable) {
4033  
    class IFF2 extends CloseableIterableIterator<A> {
4034  
4035  
      public A a;
4036  
4037  
      public boolean done = false;
4038  
4039  
      public boolean hasNext() {
4040  
        getNext();
4041  
        return !done;
4042  
      }
4043  
4044  
      public A next() {
4045  
        getNext();
4046  
        if (done)
4047  
          throw fail();
4048  
        A _a = a;
4049  
        a = null;
4050  
        return _a;
4051  
      }
4052  
4053  
      public void getNext() {
4054  
        if (done || a != null)
4055  
          return;
4056  
        a = f.get();
4057  
        done = a == null;
4058  
      }
4059  
4060  
      public void close() throws Exception {
4061  
        if (closeable != null)
4062  
          closeable.close();
4063  
      }
4064  
    }
4065  
    ;
4066  
    return new IFF2();
4067  
  }
4068  
4069  
  static public String readLineFromReaderWithClose(BufferedReader r) {
4070  
    try {
4071  
      String s = r.readLine();
4072  
      if (s == null)
4073  
        r.close();
4074  
      return s;
4075  
    } catch (Exception __e) {
4076  
      throw rethrow(__e);
4077  
    }
4078  
  }
4079  
4080  
  static public AutoCloseable _wrapIOCloseable(final AutoCloseable c) {
4081  
    return c == null ? null : new AutoCloseable() {
4082  
4083  
      public String toString() {
4084  
        return "c.close();\r\n    _registerIO(c, null, false);";
4085  
      }
4086  
4087  
      public void close() throws Exception {
4088  
        c.close();
4089  
        _registerIO(c, null, false);
4090  
      }
4091  
    };
4092  
  }
4093  
4094  
  static public <A> A _registerIOWrap(A wrapper, Object wrapped) {
4095  
    return wrapper;
4096  
  }
4097  
4098  
  static public FileInputStream newFileInputStream(File path) throws IOException {
4099  
    return newFileInputStream(path.getPath());
4100  
  }
4101  
4102  
  static public FileInputStream newFileInputStream(String path) throws IOException {
4103  
    FileInputStream f = new FileInputStream(path);
4104  
    _registerIO(f, path, true);
4105  
    return f;
4106  
  }
4107  
4108  
  static public int gzInputStream_defaultBufferSize = 65536;
4109  
4110  
  static public GZIPInputStream gzInputStream(File f) {
4111  
    try {
4112  
      return gzInputStream(new FileInputStream(f));
4113  
    } catch (Exception __e) {
4114  
      throw rethrow(__e);
4115  
    }
4116  
  }
4117  
4118  
  static public GZIPInputStream gzInputStream(File f, int bufferSize) {
4119  
    try {
4120  
      return gzInputStream(new FileInputStream(f), bufferSize);
4121  
    } catch (Exception __e) {
4122  
      throw rethrow(__e);
4123  
    }
4124  
  }
4125  
4126  
  static public GZIPInputStream gzInputStream(InputStream in) {
4127  
    return gzInputStream(in, gzInputStream_defaultBufferSize);
4128  
  }
4129  
4130  
  static public GZIPInputStream gzInputStream(InputStream in, int bufferSize) {
4131  
    try {
4132  
      return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in);
4133  
    } catch (Exception __e) {
4134  
      throw rethrow(__e);
4135  
    }
4136  
  }
4137  
4138  
  static public boolean isSubclassOf(Class a, Class b) {
4139  
    return isSubclass(a, b);
4140  
  }
4141  
4142  
  static public <A, B> List<A> keysSortedByValues(final Map<A, B> map) {
4143  
    List<A> l = new ArrayList(map.keySet());
4144  
    sort(l, mapComparator(map));
4145  
    return l;
4146  
  }
4147  
4148  
  static public Class<?> getClass(String name) {
4149  
    try {
4150  
      return Class.forName(name);
4151  
    } catch (ClassNotFoundException e) {
4152  
      return null;
4153  
    }
4154  
  }
4155  
4156  
  static public Class getClass(Object o) {
4157  
    return o instanceof Class ? (Class) o : o.getClass();
4158  
  }
4159  
4160  
  static public Class getClass(Object realm, String name) {
4161  
    try {
4162  
      try {
4163  
        return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
4164  
      } catch (ClassNotFoundException e) {
4165  
        return null;
4166  
      }
4167  
    } catch (Exception __e) {
4168  
      throw rethrow(__e);
4169  
    }
4170  
  }
4171  
4172  
  static public String classNameToVM(String name) {
4173  
    return name.replace(".", "$");
4174  
  }
4175  
4176  
  static public boolean emptyString(String s) {
4177  
    return s == null || s.length() == 0;
4178  
  }
4179  
4180  
  static public String[] codeTokensAsStringArray(List<String> tok) {
4181  
    int n = max(0, (l(tok) - 1) / 2);
4182  
    String[] out = new String[n];
4183  
    for (int i = 0; i < n; i++) out[i] = tok.get(i * 2 + 1);
4184  
    return out;
4185  
  }
4186  
4187  
  static public int jfind(String s, String in) {
4188  
    return jfind(javaTok(s), in);
4189  
  }
4190  
4191  
  static public int jfind(List<String> tok, String in) {
4192  
    return jfind(tok, 1, in);
4193  
  }
4194  
4195  
  static public int jfind(List<String> tok, int startIdx, String in) {
4196  
    return jfind(tok, startIdx, in, null);
4197  
  }
4198  
4199  
  static public int jfind(List<String> tok, String in, Object condition) {
4200  
    return jfind(tok, 1, in, condition);
4201  
  }
4202  
4203  
  static public int jfind(List<String> tok, int startIdx, String in, Object condition) {
4204  
    return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
4205  
  }
4206  
4207  
  static public int jfind(List<String> tok, List<String> tokin) {
4208  
    return jfind(tok, 1, tokin);
4209  
  }
4210  
4211  
  static public int jfind(List<String> tok, int startIdx, List<String> tokin) {
4212  
    return jfind(tok, startIdx, tokin, null);
4213  
  }
4214  
4215  
  static public int jfind(List<String> tok, int startIdx, String[] tokinC, Object condition) {
4216  
    return findCodeTokens(tok, startIdx, false, tokinC, condition);
4217  
  }
4218  
4219  
  static public int jfind(List<String> tok, int startIdx, List<String> tokin, Object condition) {
4220  
    return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
4221  
  }
4222  
4223  
  static public List<String> jfind_preprocess(List<String> tok) {
4224  
    for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
4225  
    replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
4226  
    return tok;
4227  
  }
4228  
4229  
  static public boolean eqic(String a, String b) {
4230  
    if ((a == null) != (b == null))
4231  
      return false;
4232  
    if (a == null)
4233  
      return true;
4234  
    return a.equalsIgnoreCase(b);
4235  
  }
4236  
4237  
  static public boolean eqic(char a, char b) {
4238  
    if (a == b)
4239  
      return true;
4240  
    char u1 = Character.toUpperCase(a);
4241  
    char u2 = Character.toUpperCase(b);
4242  
    if (u1 == u2)
4243  
      return true;
4244  
    return Character.toLowerCase(u1) == Character.toLowerCase(u2);
4245  
  }
4246  
4247  
  static public boolean checkTokCondition(Object condition, List<String> tok, int i) {
4248  
    if (condition instanceof TokCondition)
4249  
      return ((TokCondition) condition).get(tok, i);
4250  
    return checkCondition(condition, tok, i);
4251  
  }
4252  
4253  
  static public <A> void replaceCollection(Collection<A> dest, Collection<A> src) {
4254  
    if (dest == src)
4255  
      return;
4256  
    dest.clear();
4257  
    dest.addAll(src);
4258  
  }
4259  
4260  
  static public void replaceListPart(List l, int i, int j, List l2) {
4261  
    replaceSublist(l, i, j, l2);
4262  
  }
4263  
4264  
  static public String shortenSnippetID(String snippetID) {
4265  
    if (snippetID.startsWith("#"))
4266  
      snippetID = snippetID.substring(1);
4267  
    String httpBlaBla = "http://tinybrain.de/";
4268  
    if (snippetID.startsWith(httpBlaBla))
4269  
      snippetID = snippetID.substring(httpBlaBla.length());
4270  
    return "" + parseLong(snippetID);
4271  
  }
4272  
4273  
  static public int boolToInt(boolean b) {
4274  
    return b ? 1 : 0;
4275  
  }
4276  
4277  
  static public boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) {
4278  
    return a != null && a.regionMatches(true, offsetA, b, offsetB, len);
4279  
  }
4280  
4281  
  static public void _registerIO(Object object, String path, boolean opened) {
4282  
  }
4283  
4284  
  static public boolean isSubclass(Class a, Class b) {
4285  
    return a != null && b != null && b.isAssignableFrom(a);
4286  
  }
4287  
4288  
  static public <T> void sort(T[] a, Comparator<? super T> c) {
4289  
    Arrays.sort(a, c);
4290  
  }
4291  
4292  
  static public <T> void sort(T[] a) {
4293  
    Arrays.sort(a);
4294  
  }
4295  
4296  
  static public void sort(int[] a) {
4297  
    if (a != null)
4298  
      Arrays.sort(a);
4299  
  }
4300  
4301  
  static public <T> void sort(List<T> a, Comparator<? super T> c) {
4302  
    Collections.sort(a, c);
4303  
  }
4304  
4305  
  static public void sort(List a) {
4306  
    Collections.sort(a);
4307  
  }
4308  
4309  
  static public <A, B> Comparator<A> mapComparator(final Map<A, B> map) {
4310  
    return new Comparator<A>() {
4311  
4312  
      public int compare(A a, A b) {
4313  
        return cmp(map.get(a), map.get(b));
4314  
      }
4315  
    };
4316  
  }
4317  
4318  
  static public <A> ArrayList<A> litlist(A... a) {
4319  
    ArrayList l = new ArrayList(a.length);
4320  
    for (A x : a) l.add(x);
4321  
    return l;
4322  
  }
4323  
4324  
  static public <A> List<A> replaceSublist(List<A> l, List<A> x, List<A> y) {
4325  
    if (x == null)
4326  
      return l;
4327  
    int i = 0;
4328  
    while (true) {
4329  
      i = indexOfSubList(l, x, i);
4330  
      if (i < 0)
4331  
        break;
4332  
      replaceSublist(l, i, i + l(x), y);
4333  
      i += l(y);
4334  
    }
4335  
    return l;
4336  
  }
4337  
4338  
  static public <A> List<A> replaceSublist(List<A> l, int fromIndex, int toIndex, List<A> y) {
4339  
    int n = y.size(), toIndex_new = fromIndex + n;
4340  
    if (toIndex_new < toIndex) {
4341  
      removeSubList(l, toIndex_new, toIndex);
4342  
      copyListPart(y, 0, l, fromIndex, n);
4343  
    } else {
4344  
      copyListPart(y, 0, l, fromIndex, toIndex - fromIndex);
4345  
      if (toIndex_new > toIndex)
4346  
        l.addAll(toIndex, subList(y, toIndex - fromIndex));
4347  
    }
4348  
    return l;
4349  
  }
4350  
4351  
  static public <A> List<A> replaceSublist(List<A> l, IntRange r, List<A> y) {
4352  
    return replaceSublist(l, r.start, r.end, y);
4353  
  }
4354  
4355  
  static public String asString(Object o) {
4356  
    return o == null ? null : o.toString();
4357  
  }
4358  
4359  
  static public boolean checkCondition(Object condition, Object... args) {
4360  
    return isTrue(callF(condition, args));
4361  
  }
4362  
4363  
  static public <A> boolean checkCondition(IF1<A, Boolean> condition, A arg) {
4364  
    return isTrue(callF(condition, arg));
4365  
  }
4366  
4367  
  static public long parseLong(String s) {
4368  
    if (empty(s))
4369  
      return 0;
4370  
    return Long.parseLong(dropSuffix("L", s));
4371  
  }
4372  
4373  
  static public long parseLong(Object s) {
4374  
    return Long.parseLong((String) s);
4375  
  }
4376  
4377  
  static public int cmp(Number a, Number b) {
4378  
    return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue());
4379  
  }
4380  
4381  
  static public int cmp(double a, double b) {
4382  
    return a < b ? -1 : a == b ? 0 : 1;
4383  
  }
4384  
4385  
  static public int cmp(Object a, Object b) {
4386  
    if (a == null)
4387  
      return b == null ? 0 : -1;
4388  
    if (b == null)
4389  
      return 1;
4390  
    return ((Comparable) a).compareTo(b);
4391  
  }
4392  
4393  
  static public <A, B extends A> void copyListPart(List<B> a, int i1, List<A> b, int i2, int n) {
4394  
    if (a == null || b == null)
4395  
      return;
4396  
    for (int i = 0; i < n; i++) b.set(i2 + i, a.get(i1 + i));
4397  
  }
4398  
4399  
  static public String dropSuffix(String suffix, String s) {
4400  
    return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s;
4401  
  }
4402  
4403  
  final static public class _MethodCache {
4404  
4405  
    final public Class c;
4406  
4407  
    final public HashMap<String, List<Method>> cache = new HashMap();
4408  
4409  
    public _MethodCache(Class c) {
4410  
      this.c = c;
4411  
      _init();
4412  
    }
4413  
4414  
    public void _init() {
4415  
      Class _c = c;
4416  
      while (_c != null) {
4417  
        for (Method m : _c.getDeclaredMethods()) if (!isAbstract(m) && !reflection_isForbiddenMethod(m))
4418  
          multiMapPut(cache, m.getName(), makeAccessible(m));
4419  
        _c = _c.getSuperclass();
4420  
      }
4421  
      for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m))
4422  
        multiMapPut(cache, m.getName(), makeAccessible(m));
4423  
    }
4424  
4425  
    public Method findMethod(String method, Object[] args) {
4426  
      try {
4427  
        List<Method> m = cache.get(method);
4428  
        if (m == null)
4429  
          return null;
4430  
        int n = m.size();
4431  
        for (int i = 0; i < n; i++) {
4432  
          Method me = m.get(i);
4433  
          if (call_checkArgs(me, args, false))
4434  
            return me;
4435  
        }
4436  
        return null;
4437  
      } catch (Exception __e) {
4438  
        throw rethrow(__e);
4439  
      }
4440  
    }
4441  
4442  
    public Method findStaticMethod(String method, Object[] args) {
4443  
      try {
4444  
        List<Method> m = cache.get(method);
4445  
        if (m == null)
4446  
          return null;
4447  
        int n = m.size();
4448  
        for (int i = 0; i < n; i++) {
4449  
          Method me = m.get(i);
4450  
          if (isStaticMethod(me) && call_checkArgs(me, args, false))
4451  
            return me;
4452  
        }
4453  
        return null;
4454  
      } catch (Exception __e) {
4455  
        throw rethrow(__e);
4456  
      }
4457  
    }
4458  
  }
4459  
4460  
  static public class MRUCache<A, B> extends LinkedHashMap<A, B> {
4461  
4462  
    public int maxSize = 10;
4463  
4464  
    public MRUCache() {
4465  
    }
4466  
4467  
    public MRUCache(int maxSize) {
4468  
      this.maxSize = maxSize;
4469  
    }
4470  
4471  
    public boolean removeEldestEntry(Map.Entry eldest) {
4472  
      return size() > maxSize;
4473  
    }
4474  
4475  
    public Object _serialize() {
4476  
      return ll(maxSize, cloneLinkedHashMap(this));
4477  
    }
4478  
4479  
    static public MRUCache _deserialize(List l) {
4480  
      MRUCache m = new MRUCache();
4481  
      m.maxSize = (int) first(l);
4482  
      m.putAll((LinkedHashMap) second(l));
4483  
      return m;
4484  
    }
4485  
  }
4486  
4487  
  static abstract public class CloseableIterableIterator<A> extends IterableIterator<A> implements AutoCloseable {
4488  
4489  
    public void close() throws Exception {
4490  
    }
4491  
  }
4492  
4493  
  static public interface IFieldsToList {
4494  
4495  
    public Object[] _fieldsToList();
4496  
  }
4497  
4498  
  static public interface IF2<A, B, C> {
4499  
4500  
    public C get(A a, B b);
4501  
  }
4502  
4503  
  static public interface Steppable {
4504  
4505  
    public boolean step();
4506  
  }
4507  
4508  
  static abstract public class TokCondition {
4509  
4510  
    abstract public boolean get(List<String> tok, int i);
4511  
  }
4512  
4513  
  static abstract public class IterableIterator<A> implements Iterator<A>, Iterable<A> {
4514  
4515  
    public Iterator<A> iterator() {
4516  
      return this;
4517  
    }
4518  
4519  
    public void remove() {
4520  
      unsupportedOperation();
4521  
    }
4522  
  }
4523  
4524  
  static public class TransformersOnObjects<B> implements Steppable {
4525  
4526  
    public AllOnAll_probabilistic<F1, B> allOnAll = new AllOnAll_probabilistic();
4527  
4528  
    public Set<B> bs = new HashSet();
4529  
4530  
    public MultiSetMap<B, Object> trails = new MultiSetMap();
4531  
4532  
    public Map<Object, IF2> backTransformers = new HashMap();
4533  
4534  
    public Map<Object, Double> probabilities = new HashMap();
4535  
4536  
    transient public boolean verboseAddObject = true;
4537  
4538  
    transient public ThreadLocal<Double> currentProbability = new ThreadLocal();
4539  
4540  
    static public class TransformationTrail implements IFieldsToList {
4541  
4542  
      static final public String _fieldOrder = "transformer argument";
4543  
4544  
      public Object transformer;
4545  
4546  
      public Object argument;
4547  
4548  
      public TransformationTrail() {
4549  
      }
4550  
4551  
      public TransformationTrail(Object transformer, Object argument) {
4552  
        this.argument = argument;
4553  
        this.transformer = transformer;
4554  
      }
4555  
4556  
      public boolean equals(Object o) {
4557  
        if (!(o instanceof TransformationTrail))
4558  
          return false;
4559  
        TransformationTrail x = (TransformationTrail) o;
4560  
        return eq(transformer, x.transformer) && eq(argument, x.argument);
4561  
      }
4562  
4563  
      public int hashCode() {
4564  
        int h = 632501341;
4565  
        h = boostHashCombine(h, _hashCode(transformer));
4566  
        h = boostHashCombine(h, _hashCode(argument));
4567  
        return h;
4568  
      }
4569  
4570  
      public Object[] _fieldsToList() {
4571  
        return new Object[] { transformer, argument };
4572  
      }
4573  
4574  
      public String toString() {
4575  
        return squareBracket(str(transformer)) + " on " + squareBracket(str(argument));
4576  
      }
4577  
    }
4578  
4579  
    public boolean autoUnpackIterables = true;
4580  
4581  
    public boolean autoTrails = true;
4582  
4583  
    public boolean allowMultipleTrails = true;
4584  
4585  
    public AllOnAllOperation<F1, B> op = new AllOnAllOperation<>(allOnAll, (a, b) -> {
4586  
      if (!functionCallableOn_nonSynthetic(a, b))
4587  
        return;
4588  
      AutoCloseable __1 = tempSetTL(currentProbability, getProbability(a) * getProbability(b));
4589  
      try {
4590  
        Object out = callFOpt(a, b);
4591  
        Object trail = autoTrails ? makeTrailForTransformerApplication(a, b) : null;
4592  
        if (out == null)
4593  
          return;
4594  
        if (out instanceof WithProbability) {
4595  
          lowerCurrentProbability(((WithProbability) out).probability);
4596  
          out = ((WithProbability) out).get();
4597  
          if (out == null)
4598  
            return;
4599  
        }
4600  
        if (autoUnpackIterables && out instanceof Iterable)
4601  
          for (Object x : (Iterable) out) addObject((B) x, trail);
4602  
        else
4603  
          addObject((B) out, trail);
4604  
      } finally {
4605  
        _close(__1);
4606  
      }
4607  
    });
4608  
4609  
    public TransformersOnObjects() {
4610  
      allOnAll.probabilityForPair = (a, b) -> getProbability(a) * getProbability(b);
4611  
    }
4612  
4613  
    public boolean add(B b) {
4614  
      return addObject(b);
4615  
    }
4616  
4617  
    public boolean addObject(B b) {
4618  
      if (!addIfNotNull(bs, b))
4619  
        return false;
4620  
      double prob = or(currentProbability.get(), 1.0);
4621  
      setProbability(b, prob);
4622  
      if (verboseAddObject)
4623  
        print("Added with " + new WithProbability(prob, sfu(b)));
4624  
      allOnAll.addB(b);
4625  
      return true;
4626  
    }
4627  
4628  
    public void addObject(B b, Object trail) {
4629  
      if (b == null)
4630  
        return;
4631  
      add(b);
4632  
      if (trail != null && (allowMultipleTrails || !trails.containsKey(b)))
4633  
        trails.put(b, trail);
4634  
    }
4635  
4636  
    public void addTransformer(F1 f) {
4637  
      allOnAll.addA(f);
4638  
    }
4639  
4640  
    public void addTransformer(F1 f, F1 backTransformer) {
4641  
      addTransformer(f, backTransformer == null ? null : new IF2() {
4642  
4643  
        public Object get(Object in, Object out) {
4644  
          return callFIfActuallyCallable(backTransformer, out);
4645  
        }
4646  
4647  
        public String toString() {
4648  
          return str(backTransformer);
4649  
        }
4650  
      });
4651  
    }
4652  
4653  
    public <A, C> void addTransformer(F1<A, C> f, IF2<A, C, Object> backTransformer) {
4654  
      addTransformer(f);
4655  
      mapPut(backTransformers, f, backTransformer);
4656  
    }
4657  
4658  
    public void addTransformer(F2 f) {
4659  
      addTransformer(new F1<Object, Object>() {
4660  
4661  
        public Object get(Object a) {
4662  
          try {
4663  
            addTransformer(new F1<Object, Object>() {
4664  
4665  
              public Object get(Object b) {
4666  
                try {
4667  
                  return callableOn_nonSynthetic(f, "get", a, b) ? f.get(a, b) : null;
4668  
                } catch (Exception __e) {
4669  
                  throw rethrow(__e);
4670  
                }
4671  
              }
4672  
4673  
              public String toString() {
4674  
                return "callableOn_nonSynthetic(f, \"get\", a, b) ? f.get(a, b) : null";
4675  
              }
4676  
            });
4677  
            return null;
4678  
          } catch (Exception __e) {
4679  
            throw rethrow(__e);
4680  
          }
4681  
        }
4682  
4683  
        public String toString() {
4684  
          return "addTransformer(func(O b) {\r\n        callableOn_nonSynthetic(f, \"get\", a, b) ?...";
4685  
        }
4686  
      });
4687  
    }
4688  
4689  
    public boolean step() {
4690  
      return op.step();
4691  
    }
4692  
4693  
    public List<B> getObjects() {
4694  
      return allOnAll.getBs();
4695  
    }
4696  
4697  
    public Object makeTrailForTransformerApplication(Object transformer, B argument) {
4698  
      return new TransformationTrail(transformer, argument);
4699  
    }
4700  
4701  
    public void printWithTrails() {
4702  
      pnlMap(getObjects(), b -> {
4703  
        Set _trails = trails.get(b);
4704  
        return sfu(b) + (empty(_trails) ? "" : " [" + nTrails(_trails) + ": " + joinWithComma(_trails) + "]");
4705  
      });
4706  
    }
4707  
4708  
    public Collection<TransformationTrail> getTrails(B b) {
4709  
      return instancesOf(TransformationTrail.class, trails.get(b));
4710  
    }
4711  
4712  
    public Collection<TransformationTrail> getTrailsBy(B b, Object transformer) {
4713  
      return filter(getTrails(b), t -> eq(((TransformationTrail) t).transformer, transformer));
4714  
    }
4715  
4716  
    public TransformationTrail getTrailBy(B b, Object transformer) {
4717  
      return firstThat(getTrails(b), t -> eq(((TransformationTrail) t).transformer, transformer));
4718  
    }
4719  
4720  
    public IF2 getBackTransformer(Object transformer) {
4721  
      return backTransformers.get(transformer);
4722  
    }
4723  
4724  
    public void printTransformers() {
4725  
      pnl(allOnAll.getAs());
4726  
    }
4727  
4728  
    public double getProbability(Object o) {
4729  
      return or(probabilities.get(o), 1.0);
4730  
    }
4731  
4732  
    public <A> A setProbability(A o, double p) {
4733  
      if (o == null)
4734  
        return null;
4735  
      Double pOld = probabilities.get(p);
4736  
      if (pOld != null) {
4737  
        if (p == 1.0)
4738  
          probabilities.remove(o);
4739  
        else if (pOld.doubleValue() != p)
4740  
          probabilities.put(o, p);
4741  
      } else if (p != 1.0)
4742  
        probabilities.put(o, p);
4743  
      return o;
4744  
    }
4745  
4746  
    public void lowerCurrentProbability(double p) {
4747  
      currentProbability.set(currentProbability.get() * p);
4748  
    }
4749  
  }
4750  
4751  
  static public class WithProbability<A> extends Var<A> {
4752  
4753  
    public double probability;
4754  
4755  
    public WithProbability() {
4756  
    }
4757  
4758  
    public WithProbability(double probability, A a) {
4759  
      super(a);
4760  
      this.probability = probability;
4761  
    }
4762  
4763  
    public String toString() {
4764  
      return "p=" + formatDouble_noLeadingZero(probability, 2) + ": " + str(get());
4765  
    }
4766  
  }
4767  
4768  
  static public class Pair<A, B> implements Comparable<Pair<A, B>> {
4769  
4770  
    public A a;
4771  
4772  
    public B b;
4773  
4774  
    public Pair() {
4775  
    }
4776  
4777  
    public Pair(A a, B b) {
4778  
      this.b = b;
4779  
      this.a = a;
4780  
    }
4781  
4782  
    public int hashCode() {
4783  
      return hashCodeFor(a) + 2 * hashCodeFor(b);
4784  
    }
4785  
4786  
    public boolean equals(Object o) {
4787  
      if (o == this)
4788  
        return true;
4789  
      if (!(o instanceof Pair))
4790  
        return false;
4791  
      Pair t = (Pair) o;
4792  
      return eq(a, t.a) && eq(b, t.b);
4793  
    }
4794  
4795  
    public String toString() {
4796  
      return "<" + a + ", " + b + ">";
4797  
    }
4798  
4799  
    public int compareTo(Pair<A, B> p) {
4800  
      if (p == null)
4801  
        return 1;
4802  
      int i = ((Comparable<A>) a).compareTo(p.a);
4803  
      if (i != 0)
4804  
        return i;
4805  
      return ((Comparable<B>) b).compareTo(p.b);
4806  
    }
4807  
  }
4808  
4809  
  static public class AllOnAll_probabilistic<A, B> implements Producer<Pair<A, B>> {
4810  
4811  
    public List<A> aList = new ArrayList();
4812  
4813  
    public List<B> bList = new ArrayList();
4814  
4815  
    public List<Pair<IntRange, IntRange>> todo = new LinkedList();
4816  
4817  
    public MultiSetMap<Double, Pair<A, B>> todo2 = multiSetMap_outerDescTreeMap_innerLinkedHashSet();
4818  
4819  
    transient public IF2<A, B, Double> probabilityForPair;
4820  
4821  
    public double probabilityForPair(A a, B b) {
4822  
      return probabilityForPair != null ? probabilityForPair.get(a, b) : probabilityForPair_base(a, b);
4823  
    }
4824  
4825  
    final public double probabilityForPair_fallback(IF2<A, B, Double> _f, A a, B b) {
4826  
      return _f != null ? _f.get(a, b) : probabilityForPair_base(a, b);
4827  
    }
4828  
4829  
    public double probabilityForPair_base(A a, B b) {
4830  
      return 1.0;
4831  
    }
4832  
4833  
    public void addA(A a) {
4834  
      newA(a);
4835  
    }
4836  
4837  
    public void addAIfNotNull(A a) {
4838  
      if (a != null)
4839  
        newA(a);
4840  
    }
4841  
4842  
    synchronized public void newA(A a) {
4843  
      add(aList, a);
4844  
      addPair(todo, intRange_last(aList), intRange(0, l(bList)));
4845  
    }
4846  
4847  
    synchronized public void newAs(Iterable<A> l) {
4848  
      for (A a : unnull(l)) newA(a);
4849  
    }
4850  
4851  
    public void addB(B b) {
4852  
      newB(b);
4853  
    }
4854  
4855  
    public void addBIfNotNull(B b) {
4856  
      if (b != null)
4857  
        newB(b);
4858  
    }
4859  
4860  
    synchronized public void newB(B b) {
4861  
      add(bList, b);
4862  
      addPair(todo, intRange(0, l(aList)), intRange_last(bList));
4863  
    }
4864  
4865  
    synchronized public void newBs(Iterable<B> l) {
4866  
      for (B b : unnull(l)) newB(b);
4867  
    }
4868  
4869  
    public synchronized Pair<A, B> next() {
4870  
      Pair<IntRange, IntRange> p;
4871  
      while ((p = popFirst(todo)) != null) for (A a : subList(aList, p.a)) for (B b : subList(bList, p.b)) addAPair(a, b, probabilityForPair(a, b));
4872  
      return popFirstValueFromMultiSetMap(todo2);
4873  
    }
4874  
4875  
    final public void addAPair(A a, B b, double probability) {
4876  
      if (probability > 0)
4877  
        todo2.put(probability, pair(a, b));
4878  
    }
4879  
4880  
    synchronized public List cloneBList() {
4881  
      return clonedList(bList);
4882  
    }
4883  
4884  
    public List<A> getAs() {
4885  
      return aList;
4886  
    }
4887  
4888  
    public List<B> getBs() {
4889  
      return bList;
4890  
    }
4891  
  }
4892  
4893  
  static public class MultiSetMap<A, B> {
4894  
4895  
    public Map<A, Set<B>> data = new HashMap<A, Set<B>>();
4896  
4897  
    public int size;
4898  
4899  
    public MultiSetMap() {
4900  
    }
4901  
4902  
    public MultiSetMap(boolean useTreeMap) {
4903  
      if (useTreeMap)
4904  
        data = new TreeMap();
4905  
    }
4906  
4907  
    public MultiSetMap(MultiSetMap<A, B> map) {
4908  
      putAll(map);
4909  
    }
4910  
4911  
    public MultiSetMap(Map<A, Set<B>> data) {
4912  
      this.data = data;
4913  
    }
4914  
4915  
    public void put(A key, B value) {
4916  
      synchronized (data) {
4917  
        Set<B> set = data.get(key);
4918  
        if (set == null)
4919  
          data.put(key, set = _makeEmptySet());
4920  
        set.add(value);
4921  
        ++size;
4922  
      }
4923  
    }
4924  
4925  
    public void add(A key, B value) {
4926  
      put(key, value);
4927  
    }
4928  
4929  
    public void addAll(A key, Collection<B> values) {
4930  
      synchronized (data) {
4931  
        putAll(key, values);
4932  
      }
4933  
    }
4934  
4935  
    public void addAllIfNotThere(A key, Collection<B> values) {
4936  
      synchronized (data) {
4937  
        for (B value : values) setPut(key, value);
4938  
      }
4939  
    }
4940  
4941  
    public void setPut(A key, B value) {
4942  
      synchronized (data) {
4943  
        if (!containsPair(key, value))
4944  
          put(key, value);
4945  
      }
4946  
    }
4947  
4948  
    public boolean containsPair(A key, B value) {
4949  
      synchronized (data) {
4950  
        return get(key).contains(value);
4951  
      }
4952  
    }
4953  
4954  
    public void putAll(A key, Collection<B> values) {
4955  
      synchronized (data) {
4956  
        for (B value : values) put(key, value);
4957  
      }
4958  
    }
4959  
4960  
    public void removeAll(A key, Collection<B> values) {
4961  
      synchronized (data) {
4962  
        for (B value : values) remove(key, value);
4963  
      }
4964  
    }
4965  
4966  
    public Set<B> get(A key) {
4967  
      synchronized (data) {
4968  
        Set<B> set = data.get(key);
4969  
        return set == null ? Collections.<B>emptySet() : set;
4970  
      }
4971  
    }
4972  
4973  
    public Set<B> getActual(A key) {
4974  
      synchronized (data) {
4975  
        Set<B> set = data.get(key);
4976  
        if (set == null)
4977  
          data.put(key, set = _makeEmptySet());
4978  
        return set;
4979  
      }
4980  
    }
4981  
4982  
    public void clean(A key) {
4983  
      synchronized (data) {
4984  
        Set<B> list = data.get(key);
4985  
        if (list != null && list.isEmpty())
4986  
          data.remove(key);
4987  
      }
4988  
    }
4989  
4990  
    public Set<A> keySet() {
4991  
      synchronized (data) {
4992  
        return data.keySet();
4993  
      }
4994  
    }
4995  
4996  
    public Set<A> keys() {
4997  
      synchronized (data) {
4998  
        return data.keySet();
4999  
      }
5000  
    }
5001  
5002  
    public void remove(A key) {
5003  
      synchronized (data) {
5004  
        size -= l(data.get(key));
5005  
        data.remove(key);
5006  
      }
5007  
    }
5008  
5009  
    public void remove(A key, B value) {
5010  
      synchronized (data) {
5011  
        Set<B> set = data.get(key);
5012  
        if (set != null) {
5013  
          if (set.remove(value)) {
5014  
            --size;
5015  
            if (set.isEmpty())
5016  
              data.remove(key);
5017  
          }
5018  
        }
5019  
      }
5020  
    }
5021  
5022  
    public void clear() {
5023  
      synchronized (data) {
5024  
        data.clear();
5025  
        size = 0;
5026  
      }
5027  
    }
5028  
5029  
    public boolean containsKey(A key) {
5030  
      synchronized (data) {
5031  
        return data.containsKey(key);
5032  
      }
5033  
    }
5034  
5035  
    public B getFirst(A key) {
5036  
      synchronized (data) {
5037  
        return first(get(key));
5038  
      }
5039  
    }
5040  
5041  
    public void addAll(MultiSetMap<A, B> map) {
5042  
      putAll(map);
5043  
    }
5044  
5045  
    public void putAll(MultiSetMap<A, B> map) {
5046  
      synchronized (data) {
5047  
        for (A key : map.keySet()) putAll(key, map.get(key));
5048  
      }
5049  
    }
5050  
5051  
    public void putAll(Map<A, B> map) {
5052  
      synchronized (data) {
5053  
        if (map != null)
5054  
          for (Map.Entry<A, B> e : map.entrySet()) put(e.getKey(), e.getValue());
5055  
      }
5056  
    }
5057  
5058  
    public int keysSize() {
5059  
      synchronized (data) {
5060  
        return l(data);
5061  
      }
5062  
    }
5063  
5064  
    public int size() {
5065  
      synchronized (data) {
5066  
        return size;
5067  
      }
5068  
    }
5069  
5070  
    public int getSize(A key) {
5071  
      return l(data.get(key));
5072  
    }
5073  
5074  
    public Set<A> reverseGet(B b) {
5075  
      synchronized (data) {
5076  
        Set<A> l = new HashSet();
5077  
        for (A key : data.keySet()) if (data.get(key).contains(b))
5078  
          l.add(key);
5079  
        return l;
5080  
      }
5081  
    }
5082  
5083  
    public Map<A, Set<B>> asMap() {
5084  
      synchronized (data) {
5085  
        return cloneMap(data);
5086  
      }
5087  
    }
5088  
5089  
    public boolean isEmpty() {
5090  
      synchronized (data) {
5091  
        return data.isEmpty();
5092  
      }
5093  
    }
5094  
5095  
    public Set<B> _makeEmptySet() {
5096  
      return new HashSet();
5097  
    }
5098  
5099  
    public Collection<Set<B>> allLists() {
5100  
      synchronized (data) {
5101  
        return new HashSet(data.values());
5102  
      }
5103  
    }
5104  
5105  
    public List<B> allValues() {
5106  
      return concatLists(values(data));
5107  
    }
5108  
5109  
    public Object mutex() {
5110  
      return data;
5111  
    }
5112  
5113  
    public String toString() {
5114  
      return "mm" + str(data);
5115  
    }
5116  
5117  
    public Pair<A, B> firstEntry() {
5118  
      if (empty(data))
5119  
        return null;
5120  
      Map.Entry<A, Set<B>> entry = data.entrySet().iterator().next();
5121  
      return pair(entry.getKey(), first(entry.getValue()));
5122  
    }
5123  
  }
5124  
5125  
  static public class Var<A> implements IVar<A> {
5126  
5127  
    public Var() {
5128  
    }
5129  
5130  
    public Var(A v) {
5131  
      this.v = v;
5132  
    }
5133  
5134  
    public A v;
5135  
5136  
    public synchronized void set(A a) {
5137  
      if (v != a) {
5138  
        v = a;
5139  
        notifyAll();
5140  
      }
5141  
    }
5142  
5143  
    public synchronized A get() {
5144  
      return v;
5145  
    }
5146  
5147  
    public synchronized boolean has() {
5148  
      return v != null;
5149  
    }
5150  
5151  
    public synchronized void clear() {
5152  
      v = null;
5153  
    }
5154  
5155  
    public String toString() {
5156  
      return str(get());
5157  
    }
5158  
  }
5159  
5160  
  static abstract public class F2<A, B, C> {
5161  
5162  
    abstract public C get(A a, B b);
5163  
  }
5164  
5165  
  static public class AllOnAllOperation<A, B> implements Steppable {
5166  
5167  
    public Producer<Pair<A, B>> allOnAll;
5168  
5169  
    public AllOnAllOperation() {
5170  
    }
5171  
5172  
    public AllOnAllOperation(Producer<Pair<A, B>> allOnAll, IVF2<A, B> operation) {
5173  
      this.operation = operation;
5174  
      this.allOnAll = allOnAll;
5175  
    }
5176  
5177  
    transient public IVF2<A, B> operation;
5178  
5179  
    public void operation(A a, B b) {
5180  
      if (operation != null)
5181  
        operation.get(a, b);
5182  
      else
5183  
        operation_base(a, b);
5184  
    }
5185  
5186  
    final public void operation_fallback(IVF2<A, B> _f, A a, B b) {
5187  
      if (_f != null)
5188  
        _f.get(a, b);
5189  
      else
5190  
        operation_base(a, b);
5191  
    }
5192  
5193  
    public void operation_base(A a, B b) {
5194  
    }
5195  
5196  
    public boolean step() {
5197  
      Pair<A, B> p = allOnAll.next();
5198  
      if (p == null)
5199  
        return false;
5200  
      operation(p.a, p.b);
5201  
      return true;
5202  
    }
5203  
  }
5204  
5205  
  static public interface Producer<A> {
5206  
5207  
    public A next();
5208  
  }
5209  
5210  
  static public class IntRange {
5211  
5212  
    public int start, end;
5213  
5214  
    public IntRange() {
5215  
    }
5216  
5217  
    public IntRange(int start, int end) {
5218  
      this.end = end;
5219  
      this.start = start;
5220  
    }
5221  
5222  
    public boolean equals(Object o) {
5223  
      return stdEq2(this, o);
5224  
    }
5225  
5226  
    public int hashCode() {
5227  
      return stdHash2(this);
5228  
    }
5229  
5230  
    final public int length() {
5231  
      return end - start;
5232  
    }
5233  
5234  
    static public String _fieldOrder = "start end";
5235  
5236  
    public String toString() {
5237  
      return "[" + start + ";" + end + "]";
5238  
    }
5239  
  }
5240  
5241  
  static public interface IVF2<A, B> {
5242  
5243  
    public void get(A a, B b);
5244  
  }
5245  
5246  
  static public interface IVar<A> extends IF0<A> {
5247  
5248  
    public void set(A a);
5249  
5250  
    public A get();
5251  
5252  
    default public boolean has() {
5253  
      return get() != null;
5254  
    }
5255  
5256  
    default public void clear() {
5257  
      set(null);
5258  
    }
5259  
  }
5260  
5261  
  static public interface IF0<A> {
5262  
5263  
    public A get();
5264  
  }
5265  
5266  
  static public boolean isAbstract(Class c) {
5267  
    return (c.getModifiers() & Modifier.ABSTRACT) != 0;
5268  
  }
5269  
5270  
  static public boolean isAbstract(Method m) {
5271  
    return (m.getModifiers() & Modifier.ABSTRACT) != 0;
5272  
  }
5273  
5274  
  static public boolean reflection_isForbiddenMethod(Method m) {
5275  
    return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives");
5276  
  }
5277  
5278  
  static public <A, B> void multiMapPut(Map<A, List<B>> map, A a, B b) {
5279  
    List<B> l = map.get(a);
5280  
    if (l == null)
5281  
      map.put(a, l = new ArrayList());
5282  
    l.add(b);
5283  
  }
5284  
5285  
  static public Field makeAccessible(Field f) {
5286  
    try {
5287  
      f.setAccessible(true);
5288  
    } catch (Throwable e) {
5289  
      vmBus_send("makeAccessible_error", e, f);
5290  
    }
5291  
    return f;
5292  
  }
5293  
5294  
  static public Method makeAccessible(Method m) {
5295  
    try {
5296  
      m.setAccessible(true);
5297  
    } catch (Throwable e) {
5298  
      vmBus_send("makeAccessible_error", e, m);
5299  
    }
5300  
    return m;
5301  
  }
5302  
5303  
  static public Constructor makeAccessible(Constructor c) {
5304  
    try {
5305  
      c.setAccessible(true);
5306  
    } catch (Throwable e) {
5307  
      vmBus_send("makeAccessible_error", e, c);
5308  
    }
5309  
    return c;
5310  
  }
5311  
5312  
  static public Set<Class> allInterfacesImplementedBy(Class c) {
5313  
    if (c == null)
5314  
      return null;
5315  
    HashSet<Class> set = new HashSet();
5316  
    allInterfacesImplementedBy_find(c, set);
5317  
    return set;
5318  
  }
5319  
5320  
  static public void allInterfacesImplementedBy_find(Class c, Set<Class> set) {
5321  
    if (c.isInterface() && !set.add(c))
5322  
      return;
5323  
    do {
5324  
      for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set);
5325  
    } while ((c = c.getSuperclass()) != null);
5326  
  }
5327  
5328  
  static public Method findMethod(Object o, String method, Object... args) {
5329  
    return findMethod_cached(o, method, args);
5330  
  }
5331  
5332  
  static public boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) {
5333  
    Class<?>[] types = m.getParameterTypes();
5334  
    if (types.length != args.length) {
5335  
      if (debug)
5336  
        System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
5337  
      return false;
5338  
    }
5339  
    for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
5340  
      if (debug)
5341  
        System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
5342  
      return false;
5343  
    }
5344  
    return true;
5345  
  }
5346  
5347  
  static public boolean call_checkArgs(Method m, Object[] args, boolean debug) {
5348  
    Class<?>[] types = m.getParameterTypes();
5349  
    if (types.length != args.length) {
5350  
      if (debug)
5351  
        print("Bad parameter length: " + args.length + " vs " + types.length);
5352  
      return false;
5353  
    }
5354  
    for (int i = 0; i < types.length; i++) {
5355  
      Object arg = args[i];
5356  
      if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) {
5357  
        if (debug)
5358  
          print("Bad parameter " + i + ": " + arg + " vs " + types[i]);
5359  
        return false;
5360  
      }
5361  
    }
5362  
    return true;
5363  
  }
5364  
5365  
  static public Method findStaticMethod(Class c, String method, Object... args) {
5366  
    Class _c = c;
5367  
    while (c != null) {
5368  
      for (Method m : c.getDeclaredMethods()) {
5369  
        if (!m.getName().equals(method))
5370  
          continue;
5371  
        if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args))
5372  
          continue;
5373  
        return m;
5374  
      }
5375  
      c = c.getSuperclass();
5376  
    }
5377  
    return null;
5378  
  }
5379  
5380  
  static public boolean findStaticMethod_checkArgs(Method m, Object[] args) {
5381  
    Class<?>[] types = m.getParameterTypes();
5382  
    if (types.length != args.length)
5383  
      return false;
5384  
    for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i])))
5385  
      return false;
5386  
    return true;
5387  
  }
5388  
5389  
  static public <A, B> LinkedHashMap<A, B> cloneLinkedHashMap(Map<A, B> map) {
5390  
    return map == null ? new LinkedHashMap() : new LinkedHashMap(map);
5391  
  }
5392  
5393  
  static public UnsupportedOperationException unsupportedOperation() {
5394  
    throw new UnsupportedOperationException();
5395  
  }
5396  
5397  
  static public String squareBracket(String s) {
5398  
    return "[" + s + "]";
5399  
  }
5400  
5401  
  static public <A> AutoCloseable tempSetTL(ThreadLocal<A> tl, A a) {
5402  
    return tempSetThreadLocal(tl, a);
5403  
  }
5404  
5405  
  static public Object callFOpt(Object f, Object... args) {
5406  
    if (f == null)
5407  
      return null;
5408  
    if (f instanceof Runnable) {
5409  
      ((Runnable) f).run();
5410  
      return null;
5411  
    } else if (f instanceof String)
5412  
      return callOpt(mc(), (String) f, args);
5413  
    else
5414  
      return callOpt(f, "get", args);
5415  
  }
5416  
5417  
  static public <A> boolean addIfNotNull(Collection<A> l, A a) {
5418  
    return a != null && l != null & l.add(a);
5419  
  }
5420  
5421  
  static public <A> void addIfNotNull(MultiSet<A> ms, A a) {
5422  
    if (a != null && ms != null)
5423  
      ms.add(a);
5424  
  }
5425  
5426  
  static public void add(BitSet bs, int i) {
5427  
    bs.set(i);
5428  
  }
5429  
5430  
  static public <A> boolean add(Collection<A> c, A a) {
5431  
    return c != null && c.add(a);
5432  
  }
5433  
5434  
  static public void add(Container c, Component x) {
5435  
    addToContainer(c, x);
5436  
  }
5437  
5438  
  static public <A, B> void mapPut(Map<A, B> map, A key, B value) {
5439  
    if (map != null && key != null && value != null)
5440  
      map.put(key, value);
5441  
  }
5442  
5443  
  static public <A, B> void mapPut(Map<A, B> map, Pair<A, B> p) {
5444  
    if (map != null && p != null)
5445  
      map.put(p.a, p.b);
5446  
  }
5447  
5448  
  static public <A, B> List<B> pnlMap(IF1<A, B> f, Iterable<A> l) {
5449  
    return pnlMap(l, f);
5450  
  }
5451  
5452  
  static public <A, B> List<B> pnlMap(Iterable<A> l, IF1<A, B> f) {
5453  
    return pnl(map(l, f));
5454  
  }
5455  
5456  
  static public String nTrails(long n) {
5457  
    return n2(n, "trail");
5458  
  }
5459  
5460  
  static public String nTrails(Collection l) {
5461  
    return nTrails(l(l));
5462  
  }
5463  
5464  
  static public String nTrails(Map map) {
5465  
    return nTrails(l(map));
5466  
  }
5467  
5468  
  static public <A> List<A> filter(Iterable<A> c, Object pred) {
5469  
    if (pred instanceof F1)
5470  
      return filter(c, (F1<A, Boolean>) pred);
5471  
    List x = new ArrayList();
5472  
    if (c != null)
5473  
      for (Object o : c) if (isTrue(callF(pred, o)))
5474  
        x.add(o);
5475  
    return x;
5476  
  }
5477  
5478  
  static public List filter(Object pred, Iterable c) {
5479  
    return filter(c, pred);
5480  
  }
5481  
5482  
  static public <A, B extends A> List<B> filter(Iterable<B> c, F1<A, Boolean> pred) {
5483  
    List x = new ArrayList();
5484  
    if (c != null)
5485  
      for (B o : c) if (pred.get(o))
5486  
        x.add(o);
5487  
    return x;
5488  
  }
5489  
5490  
  static public <A, B extends A> List<B> filter(F1<A, Boolean> pred, Iterable<B> c) {
5491  
    return filter(c, pred);
5492  
  }
5493  
5494  
  static public <A, B extends A> List<B> filter(Iterable<B> c, IF1<A, Boolean> pred) {
5495  
    List x = new ArrayList();
5496  
    if (c != null)
5497  
      for (B o : c) if (pred.get(o))
5498  
        x.add(o);
5499  
    return x;
5500  
  }
5501  
5502  
  static public <A, B extends A> List<B> filter(B[] c, IF1<A, Boolean> pred) {
5503  
    List x = new ArrayList();
5504  
    if (c != null)
5505  
      for (B o : c) if (pred.get(o))
5506  
        x.add(o);
5507  
    return x;
5508  
  }
5509  
5510  
  static public <A, B extends A> List<B> filter(IF1<A, Boolean> pred, Iterable<B> c) {
5511  
    return filter(c, pred);
5512  
  }
5513  
5514  
  static public <A> A firstThat(Iterable<A> l, Object pred) {
5515  
    if (l != null)
5516  
      for (A a : l) if (checkCondition(pred, a))
5517  
        return a;
5518  
    return null;
5519  
  }
5520  
5521  
  static public <A> A firstThat(Iterable<A> l, IF1<A, Boolean> pred) {
5522  
    return firstThat(l, (Object) pred);
5523  
  }
5524  
5525  
  static public <A> A firstThat(IF1<A, Boolean> pred, Iterable<A> l) {
5526  
    return firstThat(l, pred);
5527  
  }
5528  
5529  
  static public String formatDouble_noLeadingZero(double d, int digits) {
5530  
    String format = digits <= 0 ? "0" : "#." + rep(digits, '#');
5531  
    return decimalFormatEnglish(format, d);
5532  
  }
5533  
5534  
  static public int hashCodeFor(Object a) {
5535  
    return a == null ? 0 : a.hashCode();
5536  
  }
5537  
5538  
  static public <A, B> MultiSetMap<A, B> multiSetMap_outerDescTreeMap_innerLinkedHashSet() {
5539  
    return new MultiSetMap<A, B>(descTreeMap()) {
5540  
5541  
      public Set<B> _makeEmptySet() {
5542  
        return new LinkedHashSet();
5543  
      }
5544  
    };
5545  
  }
5546  
5547  
  static public <A, B> void addPair(Collection<Pair<A, B>> c, A a, B b) {
5548  
    if (c != null)
5549  
      c.add(pair(a, b));
5550  
  }
5551  
5552  
  static public IntRange intRange_last(List l) {
5553  
    int n = l(l);
5554  
    return intRange(n - 1, n);
5555  
  }
5556  
5557  
  static public IntRange intRange(int start, int end) {
5558  
    return new IntRange(start, end);
5559  
  }
5560  
5561  
  static public <A> A popFirst(List<A> l) {
5562  
    if (empty(l))
5563  
      return null;
5564  
    A a = first(l);
5565  
    l.remove(0);
5566  
    return a;
5567  
  }
5568  
5569  
  static public <A> A popFirst(Collection<A> l) {
5570  
    if (empty(l))
5571  
      return null;
5572  
    A a = first(l);
5573  
    l.remove(a);
5574  
    return a;
5575  
  }
5576  
5577  
  static public <A> List<A> popFirst(int n, List<A> l) {
5578  
    List<A> part = cloneSubList(l, 0, n);
5579  
    removeSubList(l, 0, n);
5580  
    return part;
5581  
  }
5582  
5583  
  static public <A, B> B popFirstValueFromMultiSetMap(MultiSetMap<A, B> map) {
5584  
    if (map == null)
5585  
      return null;
5586  
    Pair<A, B> p = map.firstEntry();
5587  
    if (p == null)
5588  
      return null;
5589  
    map.remove(p.a, p.b);
5590  
    return p.b;
5591  
  }
5592  
5593  
  static public <A> ArrayList<A> clonedList(Iterable<A> l) {
5594  
    return cloneList(l);
5595  
  }
5596  
5597  
  static public <A> ArrayList<A> clonedList(Collection<A> l) {
5598  
    return cloneList(l);
5599  
  }
5600  
5601  
  static public <A, B> Map<A, B> putAll(Map<A, B> a, Map<? extends A, ? extends B> b) {
5602  
    if (a != null && b != null)
5603  
      a.putAll(b);
5604  
    return a;
5605  
  }
5606  
5607  
  static public <A, B> void put(Map<A, B> map, A a, B b) {
5608  
    if (map != null)
5609  
      map.put(a, b);
5610  
  }
5611  
5612  
  static public <A> void put(List<A> l, int i, A a) {
5613  
    if (l != null && i >= 0 && i < l(l))
5614  
      l.set(i, a);
5615  
  }
5616  
5617  
  static public <A> void remove(List<A> l, int i) {
5618  
    if (l != null && i >= 0 && i < l(l))
5619  
      l.remove(i);
5620  
  }
5621  
5622  
  static public <A> void remove(Collection<A> l, A a) {
5623  
    if (l != null)
5624  
      l.remove(a);
5625  
  }
5626  
5627  
  static public Set emptySet() {
5628  
    return new HashSet();
5629  
  }
5630  
5631  
  static public <A, B> Set<A> keySet(Map<A, B> map) {
5632  
    return map == null ? new HashSet() : map.keySet();
5633  
  }
5634  
5635  
  static public Set keySet(Object map) {
5636  
    return keys((Map) map);
5637  
  }
5638  
5639  
  static public <A> Set<A> keySet(MultiSet<A> ms) {
5640  
    return ms.keySet();
5641  
  }
5642  
5643  
  static public <A> A reverseGet(List<A> l, int idx) {
5644  
    if (l == null || idx < 0)
5645  
      return null;
5646  
    int n = l(l);
5647  
    return idx < n ? l.get(n - 1 - idx) : null;
5648  
  }
5649  
5650  
  static public <A, B> Map<A, B> cloneMap(Map<A, B> map) {
5651  
    if (map == null)
5652  
      return new HashMap();
5653  
    synchronized (map) {
5654  
      return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map);
5655  
    }
5656  
  }
5657  
5658  
  static public <A, B> List<B> cloneMap(Iterable<A> l, IF1<A, B> f) {
5659  
    List x = emptyList(l);
5660  
    if (l != null)
5661  
      for (A o : cloneList(l)) x.add(f.get(o));
5662  
    return x;
5663  
  }
5664  
5665  
  static public <A> List<A> concatLists(Collection<A>... lists) {
5666  
    List<A> l = new ArrayList();
5667  
    if (lists != null)
5668  
      for (Collection<A> list : lists) if (list != null)
5669  
        l.addAll(list);
5670  
    return l;
5671  
  }
5672  
5673  
  static public <A> List<A> concatLists(Collection<? extends Collection<A>> lists) {
5674  
    List<A> l = new ArrayList();
5675  
    if (lists != null)
5676  
      for (Collection<A> list : lists) if (list != null)
5677  
        l.addAll(list);
5678  
    return l;
5679  
  }
5680  
5681  
  static public <A, B> Collection<B> values(Map<A, B> map) {
5682  
    return map == null ? emptyList() : map.values();
5683  
  }
5684  
5685  
  static public Collection values(Object map) {
5686  
    return values((Map) map);
5687  
  }
5688  
5689  
  static public boolean stdEq2(Object a, Object b) {
5690  
    if (a == null)
5691  
      return b == null;
5692  
    if (b == null)
5693  
      return false;
5694  
    if (a.getClass() != b.getClass())
5695  
      return false;
5696  
    for (String field : allFields(a)) if (neq(getOpt(a, field), getOpt(b, field)))
5697  
      return false;
5698  
    return true;
5699  
  }
5700  
5701  
  static public int stdHash2(Object a) {
5702  
    if (a == null)
5703  
      return 0;
5704  
    return stdHash(a, toStringArray(allFields(a)));
5705  
  }
5706  
5707  
  static public <A> A set(A o, String field, Object value) {
5708  
    if (o == null)
5709  
      return null;
5710  
    if (o instanceof Class)
5711  
      set((Class) o, field, value);
5712  
    else
5713  
      try {
5714  
        Field f = set_findField(o.getClass(), field);
5715  
        makeAccessible(f);
5716  
        smartSet(f, o, value);
5717  
      } catch (Exception e) {
5718  
        throw new RuntimeException(e);
5719  
      }
5720  
    return o;
5721  
  }
5722  
5723  
  static public void set(Class c, String field, Object value) {
5724  
    if (c == null)
5725  
      return;
5726  
    try {
5727  
      Field f = set_findStaticField(c, field);
5728  
      makeAccessible(f);
5729  
      smartSet(f, null, value);
5730  
    } catch (Exception e) {
5731  
      throw new RuntimeException(e);
5732  
    }
5733  
  }
5734  
5735  
  static public Field set_findStaticField(Class<?> c, String field) {
5736  
    Class _c = c;
5737  
    do {
5738  
      for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
5739  
        return f;
5740  
      _c = _c.getSuperclass();
5741  
    } while (_c != null);
5742  
    throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
5743  
  }
5744  
5745  
  static public Field set_findField(Class<?> c, String field) {
5746  
    Class _c = c;
5747  
    do {
5748  
      for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
5749  
        return f;
5750  
      _c = _c.getSuperclass();
5751  
    } while (_c != null);
5752  
    throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
5753  
  }
5754  
5755  
  static public void vmBus_send(String msg, Object... args) {
5756  
    Object arg = vmBus_wrapArgs(args);
5757  
    pcallFAll(vm_busListeners_live(), msg, arg);
5758  
    pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
5759  
  }
5760  
5761  
  static public void vmBus_send(String msg) {
5762  
    vmBus_send(msg, (Object) null);
5763  
  }
5764  
5765  
  static public Method findMethod_cached(Object o, String method, Object... args) {
5766  
    try {
5767  
      if (o == null)
5768  
        return null;
5769  
      if (o instanceof Class) {
5770  
        _MethodCache cache = callOpt_getCache(((Class) o));
5771  
        List<Method> methods = cache.cache.get(method);
5772  
        if (methods != null)
5773  
          for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false))
5774  
            return m;
5775  
        return null;
5776  
      } else {
5777  
        _MethodCache cache = callOpt_getCache(o.getClass());
5778  
        List<Method> methods = cache.cache.get(method);
5779  
        if (methods != null)
5780  
          for (Method m : methods) if (findMethod_checkArgs(m, args, false))
5781  
            return m;
5782  
        return null;
5783  
      }
5784  
    } catch (Exception __e) {
5785  
      throw rethrow(__e);
5786  
    }
5787  
  }
5788  
5789  
  static public void addToContainer(final Container a, final Component b) {
5790  
    if (a != null && b != null) {
5791  
      swing(new Runnable() {
5792  
5793  
        public void run() {
5794  
          try {
5795  
            a.add(b);
5796  
          } catch (Exception __e) {
5797  
            throw rethrow(__e);
5798  
          }
5799  
        }
5800  
5801  
        public String toString() {
5802  
          return "a.add(b);";
5803  
        }
5804  
      });
5805  
    }
5806  
  }
5807  
5808  
  static public String rep(int n, char c) {
5809  
    return repeat(c, n);
5810  
  }
5811  
5812  
  static public String rep(char c, int n) {
5813  
    return repeat(c, n);
5814  
  }
5815  
5816  
  static public <A> List<A> rep(A a, int n) {
5817  
    return repeat(a, n);
5818  
  }
5819  
5820  
  static public <A> List<A> rep(int n, A a) {
5821  
    return repeat(n, a);
5822  
  }
5823  
5824  
  static public String decimalFormatEnglish(String format, double d) {
5825  
    return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)).format(d);
5826  
  }
5827  
5828  
  static public TreeMap descTreeMap() {
5829  
    return revTreeMap();
5830  
  }
5831  
5832  
  static public Set<String> allFields(Object o) {
5833  
    TreeSet<String> fields = new TreeSet();
5834  
    Class _c = _getClass(o);
5835  
    do {
5836  
      for (Field f : _c.getDeclaredFields()) fields.add(f.getName());
5837  
      _c = _c.getSuperclass();
5838  
    } while (_c != null);
5839  
    return fields;
5840  
  }
5841  
5842  
  static public int stdHash(Object a, String... fields) {
5843  
    if (a == null)
5844  
      return 0;
5845  
    int hash = getClassName(a).hashCode();
5846  
    for (String field : fields) hash = boostHashCombine(hash, hashCode(getOpt(a, field)));
5847  
    return hash;
5848  
  }
5849  
5850  
  static public String[] toStringArray(Collection<String> c) {
5851  
    String[] a = new String[l(c)];
5852  
    Iterator<String> it = c.iterator();
5853  
    for (int i = 0; i < l(a); i++) a[i] = it.next();
5854  
    return a;
5855  
  }
5856  
5857  
  static public String[] toStringArray(Object o) {
5858  
    if (o instanceof String[])
5859  
      return (String[]) o;
5860  
    else if (o instanceof Collection)
5861  
      return toStringArray((Collection<String>) o);
5862  
    else
5863  
      throw fail("Not a collection or array: " + getClassName(o));
5864  
  }
5865  
5866  
  static public void smartSet(Field f, Object o, Object value) throws Exception {
5867  
    try {
5868  
      f.set(o, value);
5869  
    } catch (Exception e) {
5870  
      Class type = f.getType();
5871  
      if (type == int.class && value instanceof Long)
5872  
        value = ((Long) value).intValue();
5873  
      if (type == LinkedHashMap.class && value instanceof Map) {
5874  
        f.set(o, asLinkedHashMap((Map) value));
5875  
        return;
5876  
      }
5877  
      try {
5878  
        if (f.getType() == Concept.Ref.class) {
5879  
          f.set(o, ((Concept) o).new Ref((Concept) value));
5880  
          return;
5881  
        }
5882  
        if (o instanceof Concept.Ref) {
5883  
          f.set(o, ((Concept.Ref) o).get());
5884  
          return;
5885  
        }
5886  
      } catch (Throwable _e) {
5887  
      }
5888  
      throw e;
5889  
    }
5890  
  }
5891  
5892  
  static public Object vmBus_wrapArgs(Object... args) {
5893  
    return empty(args) ? null : l(args) == 1 ? args[0] : args;
5894  
  }
5895  
5896  
  static public void pcallFAll(Collection l, Object... args) {
5897  
    if (l != null)
5898  
      for (Object f : cloneList(l)) pcallF(f, args);
5899  
  }
5900  
5901  
  static public void pcallFAll(Iterator it, Object... args) {
5902  
    while (it.hasNext()) pcallF(it.next(), args);
5903  
  }
5904  
5905  
  static public Set vm_busListeners_live_cache;
5906  
5907  
  static public Set vm_busListeners_live() {
5908  
    if (vm_busListeners_live_cache == null)
5909  
      vm_busListeners_live_cache = vm_busListeners_live_load();
5910  
    return vm_busListeners_live_cache;
5911  
  }
5912  
5913  
  static public Set vm_busListeners_live_load() {
5914  
    return vm_generalIdentityHashSet("busListeners");
5915  
  }
5916  
5917  
  static public Map<String, Set> vm_busListenersByMessage_live_cache;
5918  
5919  
  static public Map<String, Set> vm_busListenersByMessage_live() {
5920  
    if (vm_busListenersByMessage_live_cache == null)
5921  
      vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
5922  
    return vm_busListenersByMessage_live_cache;
5923  
  }
5924  
5925  
  static public Map<String, Set> vm_busListenersByMessage_live_load() {
5926  
    return vm_generalHashMap("busListenersByMessage");
5927  
  }
5928  
5929  
  static public Object swing(Object f) {
5930  
    return swingAndWait(f);
5931  
  }
5932  
5933  
  static public <A> A swing(F0<A> f) {
5934  
    return (A) swingAndWait(f);
5935  
  }
5936  
5937  
  static public <A> A swing(IF0<A> f) {
5938  
    return (A) swingAndWait(f);
5939  
  }
5940  
5941  
  static public String repeat(char c, int n) {
5942  
    n = Math.max(n, 0);
5943  
    char[] chars = new char[n];
5944  
    for (int i = 0; i < n; i++) chars[i] = c;
5945  
    return new String(chars);
5946  
  }
5947  
5948  
  static public <A> List<A> repeat(A a, int n) {
5949  
    n = Math.max(n, 0);
5950  
    List<A> l = new ArrayList(n);
5951  
    for (int i = 0; i < n; i++) l.add(a);
5952  
    return l;
5953  
  }
5954  
5955  
  static public <A> List<A> repeat(int n, A a) {
5956  
    return repeat(a, n);
5957  
  }
5958  
5959  
  static public TreeMap revTreeMap() {
5960  
    return new TreeMap(reverseComparator());
5961  
  }
5962  
5963  
  static public int hashCode(Object a) {
5964  
    return a == null ? 0 : a.hashCode();
5965  
  }
5966  
5967  
  static public <A, B> LinkedHashMap<A, B> asLinkedHashMap(Map<A, B> map) {
5968  
    if (map instanceof LinkedHashMap)
5969  
      return (LinkedHashMap) map;
5970  
    LinkedHashMap<A, B> m = new LinkedHashMap();
5971  
    if (map != null)
5972  
      synchronized (collectionMutex(map)) {
5973  
        m.putAll(map);
5974  
      }
5975  
    return m;
5976  
  }
5977  
5978  
  static public Object pcallF(Object f, Object... args) {
5979  
    return pcallFunction(f, args);
5980  
  }
5981  
5982  
  static public <A> A pcallF(F0<A> f) {
5983  
    try {
5984  
      return f == null ? null : f.get();
5985  
    } catch (Throwable __e) {
5986  
      return null;
5987  
    }
5988  
  }
5989  
5990  
  static public <A, B> B pcallF(F1<A, B> f, A a) {
5991  
    try {
5992  
      return f == null ? null : f.get(a);
5993  
    } catch (Throwable __e) {
5994  
      return null;
5995  
    }
5996  
  }
5997  
5998  
  static public <A> void pcallF(VF1<A> f, A a) {
5999  
    try {
6000  
      if (f != null)
6001  
        f.get(a);
6002  
    } catch (Throwable __e) {
6003  
      _handleException(__e);
6004  
    }
6005  
  }
6006  
6007  
  static public void swingAndWait(Runnable r) {
6008  
    try {
6009  
      if (isAWTThread())
6010  
        r.run();
6011  
      else
6012  
        EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
6013  
    } catch (Exception __e) {
6014  
      throw rethrow(__e);
6015  
    }
6016  
  }
6017  
6018  
  static public Object swingAndWait(final Object f) {
6019  
    if (isAWTThread())
6020  
      return callF(f);
6021  
    else {
6022  
      final Var result = new Var();
6023  
      swingAndWait(new Runnable() {
6024  
6025  
        public void run() {
6026  
          try {
6027  
            result.set(callF(f));
6028  
          } catch (Exception __e) {
6029  
            throw rethrow(__e);
6030  
          }
6031  
        }
6032  
6033  
        public String toString() {
6034  
          return "result.set(callF(f));";
6035  
        }
6036  
      });
6037  
      return result.get();
6038  
    }
6039  
  }
6040  
6041  
  static public <A> Comparator<A> reverseComparator(Comparator<A> c) {
6042  
    return (a, b) -> c.compare(b, a);
6043  
  }
6044  
6045  
  static public <A> Comparator<A> reverseComparator() {
6046  
    return (a, b) -> cmp(b, a);
6047  
  }
6048  
6049  
  static public Object pcallFunction(Object f, Object... args) {
6050  
    try {
6051  
      return callFunction(f, args);
6052  
    } catch (Throwable __e) {
6053  
      _handleException(__e);
6054  
    }
6055  
    return null;
6056  
  }
6057  
6058  
  static public Runnable addThreadInfoToRunnable(final Object r) {
6059  
    final Object info = _threadInfo();
6060  
    return info == null ? asRunnable(r) : new Runnable() {
6061  
6062  
      public void run() {
6063  
        try {
6064  
          _inheritThreadInfo(info);
6065  
          callF(r);
6066  
        } catch (Exception __e) {
6067  
          throw rethrow(__e);
6068  
        }
6069  
      }
6070  
6071  
      public String toString() {
6072  
        return "_inheritThreadInfo(info); callF(r);";
6073  
      }
6074  
    };
6075  
  }
6076  
6077  
  static public Object callFunction(Object f, Object... args) {
6078  
    return callF(f, args);
6079  
  }
6080  
6081  
  static public Runnable asRunnable(Object o) {
6082  
    return toRunnable(o);
6083  
  }
6084  
6085  
  static public void _inheritThreadInfo(Object info) {
6086  
    _threadInheritInfo(info);
6087  
  }
6088  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 7 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv

No comments. add comment

Snippet ID: #1028472
Snippet name: Older version of #1028445, not fully working either (working transpilation is probably older than this)
Eternal ID of this version: #1028472/2
Text MD5: ebe175cae46bf78ebb864e7c3f9e6bc9
Transpilation MD5: 5f451b4d0a104578541e464b729f56dc
Author: stefan
Category: javax / a.i.
Type: JavaX source code (Dynamic Module)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-06-20 23:43:43
Source code size: 170316 bytes / 6088 lines
Pitched / IR pitched: No / No
Views / Downloads: 208 / 255
Version history: 1 change(s)
Referenced in: [show references]