text:
/**
 * Helper to get all selected Items and return Array
 */
function getSelectedItems() {
    var aItems = [];
    $('.dashboardlisting input:checked').each(function () {
        if ($(this).parents('tr').attr('id')) {
            aItems.push($(this).parents('tr').attr('id').substr(5));
        }
    });
    console.log('getSelectedItems: ' + aItems);
    return aItems;
}

// basic form validation before submit, adapted from
// http://www.sitepoint.com/html5-forms-javascript-constraint-validation-api/
// =========================================================

// basic legacy validation checking
function LegacyValidation(field) {
    var
        valid = true,
        val = field.value,
        type = field.getAttribute("type"),
        chkbox = type === "checkbox" || type === "radio",
        required = field.getAttribute("required"),
        minlength = field.getAttribute("minlength"),
        maxlength = field.getAttribute("maxlength"),
        pattern = field.getAttribute("pattern");

    // disabled fields should not be validated
    if (field.disabled) {
        return valid;
    }

    /* jshint -W126 */

    // value required?
    valid = valid && (!required ||
        (chkbox && field.checked) ||
        (!chkbox && val !== "")
    );

    // minlength or maxlength set?
    valid = valid && (chkbox || (
        (!minlength || val.length >= minlength) &&
        (!maxlength || val.length <= maxlength)
    ));

    /* jshint +W126 */

    // test pattern
    if (valid && pattern) {
        pattern = new RegExp('^(?:'+pattern+')$');
        valid = pattern.test(val);
    }

    return valid;
}

function validateContent(form) {

    var formLength = form.elements.length,
        f, field, formvalid = true;

    // loop all fields
    for (f = 0; f < formLength; f++) {
        field = form.elements[f];

        if (field.nodeName !== "INPUT" && field.nodeName !== "TEXTAREA" && field.nodeName !== "SELECT") {
            continue;
        }

		if (field.nodeName === "INPUT"){
			// trim input values
			field.value = field.value.trim();
		}

        // is native browser validation available?
        if (typeof field.willValidate !== "undefined") {
            // native validation available
            if (field.nodeName === "INPUT" && field.type !== field.getAttribute("type")) {
                // input type not supported! Use legacy JavaScript validation
                field.setCustomValidity(LegacyValidation(field) ? "" : "error");
            }
            // native browser check
            field.checkValidity();
        }
        else {
            // native validation not available
            field.validity = field.validity || {};
            // set to result of validation function
            field.validity.valid = LegacyValidation(field);

            // if "invalid" events are required, trigger it here

        }

        var noticeID = field.id + '-notice';

        // first, remove any existing old notices
        $('#'+noticeID).remove();

        if (field.validity.valid) {

            // remove error styles and messages
            $(field).removeClass('error');
        }
        else {
            // style field, show error, etc.
            $(field).addClass('error');

            var msg = $(field).data('errortext') || 'The '+field.name+' field is required or needs to match a pattern';

            $('
' +
              '<button class="close" data-dismiss="alert">×</button>' + msg + '
')
                .hide()
                .insertAfter('.page-header')
                .slideDown('fast');

            // form is invalid
            formvalid = false;
        }
    }

    return formvalid;
}

// =========================================================


text:
module Tamber
  module APIOperations
    module Retrieve
      def retrieve(params={})
        response = request(:get, url+"/retrieve", params)
        Util.convert_to_tamber_object(response)
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.furnaghan.home.policy.store.file;

import com.furnaghan.home.policy.store.ScriptStore;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.io.ByteSource;
import com.google.common.io.CharSource;
import com.google.common.io.Files;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;

import static com.google.common.base.Preconditions.checkArgument;

public class FileScriptStore extends ScriptStore {

    private final File path;

    public FileScriptStore(final File path) {
        this.path = path;
        checkArgument(path.isDirectory() || path.mkdirs(), "Unable to create directory: " + path.getAbsolutePath());
    }

    @Override
    protected Optional<ByteSource> open(final String name) {
        final File file = new File(path, name);
        return file.exists() ? Optional.of(Files.asByteSource(file)) :
                Optional.<ByteSource>absent();
    }

    @Override
    public void save(final String name, final CharSource source) {
        final File file = new File(path, name);
        try (final Reader reader = source.openStream()) {
            Files.asCharSink(file, StandardCharsets.UTF_8).writeFrom(reader);
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
}


text:
package org.apache.commons.net.ftp.parser;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.TimeZone;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilters;
import org.apache.commons.net.ftp.FTPListParseEngine;
import org.junit.Test;

/**
 * Attempt comparison of LIST and MLSD listings
 *
 * TODO - needs some work.
 */
public class MLSDComparison {

    private final Comparator<FTPFile> cmp = (o1, o2) -> {
        final String n1 = o1.getName();
        final String n2 = o2.getName();
        return n1.compareTo(n2);
    };

    /**
     * Compare two instances to see if they are the same, ignoring any uninitialized fields.
     *
     * @param a first instance
     * @param b second instance
     * @return true if the initialized fields are the same
     * @since 3.0
     */
    public boolean areEquivalent(final FTPFile a, final FTPFile b) {
        return a.getName().equals(b.getName()) && areSame(a.getSize(), b.getSize(), -1L) &&
//            areSame(a.getUser(), b.getUser()) &&
//            areSame(a.getGroup(), b.getGroup()) &&
                areSame(a.getTimestamp(), b.getTimestamp()) &&
//            areSame(a.getType(), b.getType(), UNKNOWN_TYPE) &&
//            areSame(a.getHardLinkCount(), b.getHardLinkCount(), 0) &&
//            areSame(a._permissions, b._permissions)
                true;
    }

    private boolean areSame(final Calendar a, final Calendar b) {
        return a == null || b == null || areSameDateTime(a, b);
    }

    private boolean areSame(final long a, final long b, final long d) {
        return a == d || b == d || a == b;
    }

    // compare permissions: default is all false, but that is also a possible
    // state, so this may miss some differences
//    private boolean areSame(boolean[][] a, boolean[][] b) {
//        return isDefault(a) || isDefault(b) || Arrays.deepEquals(a, b);
//    }

    // Is the array in its default state?
//    private boolean isDefault(boolean[][] a) {
//        for(boolean[] r : a){
//            for(boolean rc : r){
//                if (rc) { // not default
//                    return false;
//                }
//            }
//        }
//        return true;
//    }

    private boolean areSameDateTime(final Calendar a, final Calendar b) {
        final TimeZone UTC = TimeZone.getTimeZone("UTC");
        final Calendar ac = Calendar.getInstance(UTC);
        ac.setTime(a.getTime());
        final Calendar bc = Calendar.getInstance(UTC);
        bc.setTime(b.getTime());
        return isSameDay(ac, bc) && isSameTime(ac, bc);
    }

    private void compareSortedLists(final FTPFile[] lst, final FTPFile[] mlst) {
        Arrays.sort(lst, cmp);
        Arrays.sort(mlst, cmp);
        FTPFile first, second;
        final int firstl = lst.length;
        final int secondl = mlst.length;
        int one = 0, two = 0;
        first = lst[one++];
        second = mlst[two++];
        int cmp;
        while (one < firstl || two < secondl) {
//            String fs1 = first.toFormattedString();
//            String fs2 = second.toFormattedString();
            final String rl1 = first.getRawListing();
            final String rl2 = second.getRawListing();
            cmp = first.getName().compareTo(second.getName());
            if (cmp == 0) {
                if (first.getName().endsWith("HEADER.html")) {
                    cmp = 0;
                }
                if (!areEquivalent(first, second)) {
//                    System.out.println(rl1);
//                    System.out.println(fs1);
                    final long tdiff = first.getTimestamp().getTimeInMillis() - second.getTimestamp().getTimeInMillis();
                    System.out.println("Minutes diff " + tdiff / (1000 * 60));
//                    System.out.println(fs2);
//                    System.out.println(rl2);
//                    System.out.println();
//                    fail();
                }
                if (one < firstl) {
                    first = lst[one++];
                }
                if (two < secondl) {
                    second = mlst[two++];
                }
            } else if (cmp < 0) {
                if (!first.getName().startsWith(".")) { // skip hidden files
                    System.out.println("1: " + rl1);
                }
                if (one < firstl) {
                    first = lst[one++];
                }
            } else {
                System.out.println("2: " + rl2);
                if (two < secondl) {
                    second = mlst[two++];
                }
            }
        }
    }

    private boolean isSameDay(final Calendar a, final Calendar b) {
        final int ad = a.get(Calendar.DAY_OF_MONTH);
        final int bd = b.get(Calendar.DAY_OF_MONTH);
        return a.get(Calendar.YEAR) == b.get(Calendar.YEAR) && a.get(Calendar.MONTH) == b.get(Calendar.MONTH) && ad == bd;
    }

    private boolean isSameTime(final Calendar a, final Calendar b) {
        final int ah = a.get(Calendar.HOUR_OF_DAY);
        final int bh = b.get(Calendar.HOUR_OF_DAY);
        final int am = a.get(Calendar.MINUTE);
        final int bm = b.get(Calendar.MINUTE);
        final int as = a.get(Calendar.SECOND);
        final int bs = b.get(Calendar.SECOND);
        return (ah == 0 && am == 0 && as == 0) || (bh == 0 && bm == 0 && bs == 0) || (ah == bh && am == bm) // ignore seconds
        ;
    }

    @Test
    public void testFile() throws Exception {
        final File path = new File(DownloadListings.DOWNLOAD_DIR);
        final FilenameFilter filter = (dir, name) -> name.endsWith("_mlsd.txt");
        final File[] files = path.listFiles(filter);
        if (files != null) {
            for (final File mlsd : files) {
                System.out.println(mlsd);
                FTPListParseEngine engine = new FTPListParseEngine(MLSxEntryParser.getInstance());
                try (final InputStream is = new FileInputStream(mlsd)) {
                    engine.readServerList(is, FTP.DEFAULT_CONTROL_ENCODING);
                }
                final FTPFile[] mlsds = engine.getFiles(FTPFileFilters.ALL);
                final File listFile = new File(mlsd.getParentFile(), mlsd.getName().replace("_mlsd", "_list"));
                try (final InputStream inputStream = new FileInputStream(listFile)) {
                    final FTPClientConfig cfg = new FTPClientConfig();
                    cfg.setServerTimeZoneId("GMT");
                    final UnixFTPEntryParser parser = new UnixFTPEntryParser(cfg);
                    engine = new FTPListParseEngine(parser);
                    engine.readServerList(inputStream, FTP.DEFAULT_CONTROL_ENCODING);
                    final FTPFile[] lists = engine.getFiles(FTPFileFilters.ALL);
                    compareSortedLists(mlsds, lists);
                }
            }
        }
    }

//    private boolean areSame(int a, int b, int d) {
//        return a == d || b == d || a == b;
//    }
//
//    private boolean areSame(String a, String b) {
//        return a.length() == 0 || b.length() == 0 || a.equals(b);
//    }
}


text:
package org.apache.ignite.internal.processors.query.h2;

import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.io.*;
import org.apache.ignite.cache.query.annotations.*;
import org.apache.ignite.internal.*;
import org.apache.ignite.internal.processors.cache.*;
import org.apache.ignite.internal.processors.cache.query.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.testframework.*;

import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

/**
 *
 */
public class GridH2IndexingGeoSelfTest extends GridCacheAbstractSelfTest {
    /** */
    private static final int CNT = 100;

    /** */
    private static final long DUR = 60000L;

    /** {@inheritDoc} */
    @Override protected int gridCount() {
        return 3;
    }

    /** {@inheritDoc} */
    @Override protected long getTestTimeout() {
        return DUR * 3;
    }

    /** {@inheritDoc} */
    @Override protected Class<?>[] indexedTypes() {
        return new Class<?>[]{
            Integer.class, EnemyCamp.class
        };
    }

    /**
     * @throws Exception If failed.
     */
    @SuppressWarnings("unchecked")
    public void testGeo() throws Exception {
        GridCache<Integer, EnemyCamp> cache = ((IgniteKernal)grid(0)).cache(null);

        WKTReader r = new WKTReader();

        cache.put(0, new EnemyCamp(r.read("POINT(25 75)"), "A"));
        cache.put(1, new EnemyCamp(r.read("POINT(70 70)"), "B"));
        cache.put(2, new EnemyCamp(r.read("POINT(70 30)"), "C"));
        cache.put(3, new EnemyCamp(r.read("POINT(75 25)"), "D"));

        CacheQuery<Map.Entry<Integer, EnemyCamp>> qry = cache.queries().createSqlQuery(EnemyCamp.class,
            "coords && ?");

        Collection<Map.Entry<Integer, EnemyCamp>> res = qry.execute(r.read("POLYGON((5 70, 5 80, 30 80, 30 70, 5 70))"))
            .get();

        checkPoints(res, "A");

        res = qry.execute(r.read("POLYGON((10 5, 10 35, 70 30, 75 25, 10 5))")).get();

        checkPoints(res, "C", "D");

        // Move B to the first polygon.
        cache.put(1, new EnemyCamp(r.read("POINT(20 75)"), "B"));

        res = qry.execute(r.read("POLYGON((5 70, 5 80, 30 80, 30 70, 5 70))")).get();

        checkPoints(res, "A", "B");

        // Move B to the second polygon.
        cache.put(1, new EnemyCamp(r.read("POINT(30 30)"), "B"));

        res = qry.execute(r.read("POLYGON((10 5, 10 35, 70 30, 75 25, 10 5))")).get();

        checkPoints(res, "B", "C", "D");

        // Remove B.
        cache.remove(1);

        res = qry.execute(r.read("POLYGON((5 70, 5 80, 30 80, 30 70, 5 70))")).get();

        checkPoints(res, "A");

        res = qry.execute(r.read("POLYGON((10 5, 10 35, 70 30, 75 25, 10 5))")).get();

        checkPoints(res, "C", "D");

        // Check explaint request.
        assertTrue(F.first(cache.queries().createSqlFieldsQuery("explain select * from EnemyCamp " +
            "where coords && 'POINT(25 75)'").execute().get()).get(0).toString().contains("coords_idx"));
    }

    /**
     * @throws Exception If failed.
     */
    @SuppressWarnings("unchecked")
    public void testGeoMultithreaded() throws Exception {
        final GridCache<Integer, EnemyCamp> cache1 = ((IgniteKernal)grid(0)).cache(null);
        final GridCache<Integer, EnemyCamp> cache2 = ((IgniteKernal)grid(1)).cache(null);
        final GridCache<Integer, EnemyCamp> cache3 = ((IgniteKernal)grid(2)).cache(null);

        final String[] points = new String[CNT];

        WKTReader r = new WKTReader();

        ThreadLocalRandom rnd = ThreadLocalRandom.current();

        for (int idx = 0; idx < CNT; idx++) {
            int x = rnd.nextInt(1, 100);
            int y = rnd.nextInt(1, 100);

            cache1.put(idx, new EnemyCamp(r.read("POINT(" + x + " " + y + ")"), Integer.toString(idx)));

            points[idx] = Integer.toString(idx);
        }

        Thread.sleep(200);

        final AtomicBoolean stop = new AtomicBoolean();
        final AtomicReference<Exception> err = new AtomicReference<>();

        IgniteInternalFuture<?> putFut = GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {
            @Override public Void call() throws Exception {
                WKTReader r = new WKTReader();

                ThreadLocalRandom rnd = ThreadLocalRandom.current();

                while (!stop.get()) {
                    int cacheIdx = rnd.nextInt(0, 3);

                    GridCache<Integer, EnemyCamp> cache = cacheIdx == 0 ? cache1 : cacheIdx == 1 ? cache2 : cache3;

                    int idx = rnd.nextInt(CNT);
                    int x = rnd.nextInt(1, 100);
                    int y = rnd.nextInt(1, 100);

                    cache.put(idx, new EnemyCamp(r.read("POINT(" + x + " " + y + ")"), Integer.toString(idx)));

                    U.sleep(50);
                }

                return null;
            }
        }, Runtime.getRuntime().availableProcessors(), "put-thread");

        IgniteInternalFuture<?> qryFut = GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {
            @Override public Void call() throws Exception {
                WKTReader r = new WKTReader();

                ThreadLocalRandom rnd = ThreadLocalRandom.current();

                while (!stop.get()) {
                    try {
                        int cacheIdx = rnd.nextInt(0, 3);

                        GridCache<Integer, EnemyCamp> cache = cacheIdx == 0 ? cache1 : cacheIdx == 1 ? cache2 : cache3;

                        CacheQuery<Map.Entry<Integer, EnemyCamp>> qry = cache.queries().createSqlQuery(
                            EnemyCamp.class, "coords && ?");

                        Collection<Map.Entry<Integer, EnemyCamp>> res = qry.execute(
                            r.read("POLYGON((0 0, 0 100, 100 100, 100 0, 0 0))")).get();

                        checkPoints(res, points);

                        U.sleep(5);
                    }
                    catch (Exception e) {
                        err.set(e);

                        stop.set(true);

                        break;
                    }
                }

                return null;
            }
        }, 4, "qry-thread");

        U.sleep(60000L);

        stop.set(true);

        putFut.get();
        qryFut.get();

        Exception err0 = err.get();

        if (err0 != null)
            throw err0;
    }

    /**
     * Check whether result contains all required points.
     *
     * @param res Result.
     * @param points Expected points.
     */
    private void checkPoints( Collection<Map.Entry<Integer, EnemyCamp>> res, String... points) {
        Set<String> set = new HashSet<>(Arrays.asList(points));

        assertEquals(set.size(), res.size());

        for (Map.Entry<Integer, EnemyCamp> e : res)
            assertTrue(set.remove(e.getValue().name));
    }

    /**
     *
     */
    private static class EnemyCamp implements Serializable {
        /** */
        @QuerySqlField(index = true)
        private Geometry coords;

        /** */
        @QuerySqlField
        private String name;

        /**
         * @param coords Coordinates.
         * @param name Name.
         */
        private EnemyCamp(Geometry coords, String name) {
            this.coords = coords;
            this.name = name;
        }
    }
}


text:
package jumpingalien.part3.internal;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.stream.Collectors;

import jumpingalien.common.game.IActionHandler;
import jumpingalien.common.game.JumpingAlienGame;
import jumpingalien.common.game.WorldInfoProvider;
import jumpingalien.common.sprites.ImageSprite;
import jumpingalien.common.sprites.JumpingAlienSprites;
import jumpingalien.model.Buzam;
import jumpingalien.model.Mazub;
import jumpingalien.model.Plant;
import jumpingalien.model.Program;
import jumpingalien.model.School;
import jumpingalien.model.Shark;
import jumpingalien.model.Slime;
import jumpingalien.model.World;
import jumpingalien.part2.internal.AlienInfoProvider2;
import jumpingalien.part2.internal.ObjectInfoProvider;
import jumpingalien.part2.internal.Part2WorldInfoProvider;
import jumpingalien.part2.internal.tmxfile.TMXFileReader;
import jumpingalien.part2.internal.tmxfile.data.ImageTile;
import jumpingalien.part2.internal.tmxfile.data.ImageTile.TileType;
import jumpingalien.part2.internal.tmxfile.data.Layer;
import jumpingalien.part2.internal.tmxfile.data.Map;
import jumpingalien.part2.internal.tmxfile.data.MapObject;
import jumpingalien.part3.facade.IFacadePart3;
import jumpingalien.part3.programs.ParseOutcome;
import jumpingalien.util.Sprite;
import ogp.framework.messages.Message;
import ogp.framework.messages.MessageType;
import ogp.framework.util.GUIUtils;

public class JumpingAlienGamePart3 extends JumpingAlienGame {

	private static final String ATTR_BUZAM_INITIAL_Y = "initialBuzamY";
	private static final String ATTR_BUZAM_INITIAL_X = "initialBuzamX";
	private Mazub alien;
	private Buzam buzam;
	private World world;

	private Map map;

	private int tileSize;
	private final ObjectInfoProvider objectInfoProvider;
	private String currentMap;

	private final Random random;

	public JumpingAlienGamePart3(Part3Options options, IFacadePart3 facade) {
		super(options, facade);
		this.random = new Random(options.getRandomSeed());
		this.objectInfoProvider = createObjectInfoProvider();
		this.evilTwinProvider = createEvilTwinInfoProvider();
	}

	@Override
	public void restart() {
		this.world = null;
		this.alien = null;

		super.restart();
	}

	@Override
	public IFacadePart3 getFacade() {
		return (IFacadePart3) super.getFacade();
	}

	@Override
	public Part3Options getOptions() {
		return (Part3Options) super.getOptions();
	}

	private boolean readLevelFile(String filename) {
		try {
			TMXFileReader reader = new TMXFileReader("levels/");

			map = reader.read(filename);

			if (map.getTileSizeY() != map.getTileSizeX()) {
				throw new IllegalArgumentException(
						"Can only work with square tile sizes");
			}

			if (map.getLayer("Terrain") == null) {
				throw new IllegalArgumentException(
						"The map must have a layer called 'Terrain'");
			}

			tileSize = map.getTileSizeY();
		} catch (Throwable e) {
			addMessage(new Message(MessageType.ERROR, "Error while reading "
					+ filename + ": " + e.getMessage()));
			return false;
		}

		return true;
	}

	@Override
	public void load() {
	}

	public int[] getWorldSize() {
		return new int[] { map.getPixelWidth(), map.getPixelHeight() };
	}

	@Override
	protected void createModel() {

		setWorld(getFacade().createWorld(tileSize, map.getNbTilesX(),
				map.getNbTilesY(), getVisibleScreenWidth(),
				getVisibleScreenHeight(), map.getTargetTileX(),
				map.getTargetTileY()));

		setTileTypes();

		addGameObjects();

		addBuzam();

		addMazub();

		// no more object creations or tile changes after starting
		getFacade().startGame(getWorld());
	}

	private void addGameObjects() {
		for (MapObject obj : map.getObjects()) {
			addObject(obj);
		}
	}

	private void addMazub() {
		setAlien(getFacade().createMazub(map.getInitialPositionX(),
				map.getInitialPositionY(), JumpingAlienSprites.ALIEN_SPRITESET));

		getFacade().setMazub(getWorld(), getAlien());
	}

	private void addBuzam() {
		if (!map.hasAttribute(ATTR_BUZAM_INITIAL_X) || !map.hasAttribute(ATTR_BUZAM_INITIAL_Y)) {
			return;
		}
		int buzamX = Integer.parseInt(map.getAttribute(ATTR_BUZAM_INITIAL_X));
		int buzamY = Integer.parseInt(map.getAttribute(ATTR_BUZAM_INITIAL_Y));
		Optional<Program> program = parseProgram(Resources.BUZAM_PROGRAM_FILENAME);
		if (program.isPresent() && random.nextBoolean()) {
			buzam = getFacade().createBuzamWithProgram(buzamX, buzamY,
					Resources.BUZAM_SPRITESET, program.get());
		} else {
			buzam = getFacade().createBuzam(buzamX, buzamY,
					Resources.BUZAM_SPRITESET);
		}

		getFacade().addBuzam(getWorld(), buzam);
	}

	@SuppressWarnings("unchecked")
	private Optional<Program> parseProgram(String filename) {
		try {
			InputStream is = GUIUtils.openResource(filename);
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String text = br.lines().collect(Collectors.joining("\n"));
			ParseOutcome<?> outcome = getFacade().parse(text);
			if (outcome.isSuccess()) {
				return Optional.ofNullable((Program) outcome.getResult());
			} else {
				System.out.println("Errors while parsing programs '" + filename
						+ "':");
				for (String error : (List<String>) outcome.getResult()) {
					System.out.println(error);
				}
			}
		} catch (IOException e) {
			System.out.println("Error while opening '" + filename + "': "
					+ e.getMessage());
			e.printStackTrace();
		}
		return Optional.empty();
	}

	private void setTileTypes() {
		Layer terrainLayer = map.getLayer("Terrain");

		for (int tileY = 0; tileY < map.getNbTilesY(); tileY++) {
			for (int tileX = 0; tileX < map.getNbTilesX(); tileX++) {
				ImageTile tile = terrainLayer.getTile(tileX, tileY);
				if (tile != null) {
					getFacade().setGeologicalFeature(getWorld(), tileX, tileY,
							tile.getType().getValue());
				} else {
					getFacade().setGeologicalFeature(getWorld(), tileX, tileY,
							TileType.AIR.getValue());
				}
			}
		}
	}

	private void addObject(MapObject obj) {
		switch (obj.getTile().getOSIndependentFilename()) {
		case Resources.PLANT_LEFT_FILENAME: {
			addPlant(obj);
			break;
		}
		case Resources.SHARK_LEFT_FILENAME:
		case Resources.SHARK_LEFT2_FILENAME:
		case Resources.SHARK_DEAD_FILENAME: {
			addShark(obj);
			break;
		}
		case Resources.SLIME_LEFT_FILENAME:
		case Resources.SLIME_LEFT2_FILENAME:
		case Resources.SLIME_DEAD_FILENAME: {
			addSlime(obj);
			break;
		}
		default:
			System.out
					.println("ERROR while loading level: don't know how to deal with object "
							+ obj);
			break;
		}
	}

	private void addPlant(MapObject obj) {
		Optional<Program> program = parseProgram(Resources.PLANT_PROGRAM_FILENAME);
		if (program.isPresent() && random.nextBoolean()) {
			getFacade().addPlant(
					getWorld(),
					getFacade().createPlantWithProgram(
							obj.getX(),
							obj.getY(),
							new Sprite[] { Resources.PLANT_SPRITE_LEFT,
									Resources.PLANT_SPRITE_RIGHT },
							program.get()));
		} else {
			getFacade().addPlant(
					getWorld(),
					getFacade().createPlant(
							obj.getX(),
							obj.getY(),
							new Sprite[] { Resources.PLANT_SPRITE_LEFT,
									Resources.PLANT_SPRITE_RIGHT }));
		}
	}

	private void addShark(MapObject obj) {
		Optional<Program> program = parseProgram(Resources.SHARK_PROGRAM_FILENAME);
		if (program.isPresent() && random.nextBoolean()) {
			getFacade().addShark(
					getWorld(),
					getFacade().createSharkWithProgram(
							obj.getX(),
							obj.getY(),
							new Sprite[] { Resources.SHARK_SPRITE_LEFT,
									Resources.SHARK_SPRITE_RIGHT },
							program.get()));
		} else {
			getFacade().addShark(
					getWorld(),
					getFacade().createShark(
							obj.getX(),
							obj.getY(),
							new Sprite[] { Resources.SHARK_SPRITE_LEFT,
									Resources.SHARK_SPRITE_RIGHT }));
		}
	}

	private void addSlime(MapObject obj) {
		Optional<Program> program = parseProgram(Resources.SLIME_PROGRAM_FILENAME);
		int school = obj.getIntAttribute("school").orElse(0);
		if (program.isPresent() && random.nextBoolean()) {
			getFacade().addSlime(
					getWorld(),
					getFacade().createSlimeWithProgram(
							obj.getX(),
							obj.getY(),
							new Sprite[] { Resources.SLIME_SPRITE_LEFT,
									Resources.SLIME_SPRITE_RIGHT },
							getSlimeSchool(school), program.get()));
		} else {
			getFacade().addSlime(
					getWorld(),
					getFacade().createSlime(
							obj.getX(),
							obj.getY(),
							new Sprite[] { Resources.SLIME_SPRITE_LEFT,
									Resources.SLIME_SPRITE_RIGHT },
							getSlimeSchool(school)));
		}
	}

	private java.util.Map<Integer, School> schools = new HashMap<Integer, School>();

	private final AlienInfoProvider2<Buzam> evilTwinProvider;

	private School getSlimeSchool(int nb) {
		return schools.computeIfAbsent(nb, i -> getFacade().createSchool());
	}

	public Map getMap() {
		return map;
	}

	private void setAlien(Mazub alien) {
		if (this.alien != null) {
			throw new IllegalStateException("Mazub already created!");
		}
		this.alien = alien;
	}

	private void setWorld(World world) {
		if (this.world != null) {
			throw new IllegalStateException("World already created!");
		}
		this.world = world;
	}

	Mazub getAlien() {
		return alien;
	}

	private World getWorld() {
		return world;
	}

	@Override
	protected void advanceTime(double dt) {
		getFacade().advanceTime(getWorld(), dt);
		if (getFacade().isGameOver(getWorld())) {
			stop();
		}
	}

	@Override
	protected IActionHandler createActionHandler() {
		return new Part3ActionHandler(this);
	}

	@Override
	public AlienInfoProvider2<Mazub> getAlienInfoProvider() {
		return (AlienInfoProvider2<Mazub>) super.getAlienInfoProvider();
	}

	@Override
	protected AlienInfoProvider2<Mazub> createAlienInfoProvider() {
		return new AlienInfoProvider2<Mazub>() {

			@Override
			public Mazub getAlien() {
				return alien;
			}

			@Override
			public Optional<int[]> getAlienXY() {
				return catchErrorGet(() -> getFacade().getLocation(getAlien()));
			}

			@Override
			public Optional<double[]> getAlienVelocity() {
				return catchErrorGet(() -> getFacade().getVelocity(getAlien()));
			}

			@Override
			public Optional<double[]> getAlienAcceleration() {
				return catchErrorGet(() -> getFacade().getAcceleration(
						getAlien()));
			}

			@Override
			public Optional<int[]> getAlienSize() {
				return catchErrorGet(() -> getFacade().getSize(getAlien()));
			}

			@Override
			public Optional<Sprite> getPlayerSprite() {
				return catchErrorGet(() -> getFacade().getCurrentSprite(
						getAlien()));
			}

			@Override
			public Optional<Integer> getAlienHealth() {
				return catchErrorGet(() -> getFacade().getNbHitPoints(
						getAlien()));
			}

			@Override
			public Optional<Boolean> isImmune() {
				return catchErrorGet(() -> getFacade().isImmune(getAlien()));
			}
		};
	}

	protected AlienInfoProvider2<Buzam> createEvilTwinInfoProvider() {
		return new AlienInfoProvider2<Buzam>() {

			@Override
			public Buzam getAlien() {
				return buzam;
			}

			@Override
			public Optional<int[]> getAlienXY() {
				return catchErrorGet(() -> getFacade().getLocation(getAlien()));
			}

			@Override
			public Optional<double[]> getAlienVelocity() {
				return catchErrorGet(() -> getFacade().getVelocity(getAlien()));
			}

			@Override
			public Optional<double[]> getAlienAcceleration() {
				return catchErrorGet(() -> getFacade().getAcceleration(
						getAlien()));
			}

			@Override
			public Optional<int[]> getAlienSize() {
				return catchErrorGet(() -> getFacade().getSize(getAlien()));
			}

			@Override
			public Optional<Sprite> getPlayerSprite() {
				return catchErrorGet(() -> getFacade().getCurrentSprite(
						getAlien()));
			}

			@Override
			public Optional<Integer> getAlienHealth() {
				return catchErrorGet(() -> getFacade().getNbHitPoints(
						getAlien()));
			}

			@Override
			public Optional<Boolean> isImmune() {
				return Optional.of(false); // don't require this
			}
		};
	}

	@Override
	protected WorldInfoProvider createWorldInfoProvider() {
		return new Part2WorldInfoProvider() {

			@Override
			public Optional<int[]> getVisibleWindow() {
				return catchErrorGet(() -> getFacade().getVisibleWindow(
						getWorld()));
			}

			@Override
			public Optional<int[][]> getTilesIn(int left, int bottom,
					int right, int top) {
				return catchErrorGet(() -> getFacade().getTilePositionsIn(
						world, left, bottom, right, top));
			}

			@Override
			public Optional<TileType> getGeologicalFeature(int bottomLeftX,
					int bottomLeftY) {
				return catchErrorGet(() -> TileType.fromValue(getFacade()
						.getGeologicalFeature(getWorld(), bottomLeftX,
								bottomLeftY)));
			}

			@Override
			public Optional<int[]> getBottomLeftPixelOfTile(int tileX, int tileY) {
				return catchErrorGet(() -> getFacade()
						.getBottomLeftPixelOfTile(world, tileX, tileY));
			}

			@Override
			public Optional<int[]> getWorldSize() {
				return catchErrorGet(() -> getFacade().getWorldSizeInPixels(
						getWorld()));
			}

			@Override
			public int getTileLength() {
				return catchErrorGet(
						() -> getFacade().getTileLength(getWorld())).orElse(
						tileSize);
			}

			@Override
			public Optional<Boolean> isGameOver() {
				return catchErrorGet(() -> getFacade().isGameOver(getWorld()));
			}

			@Override
			public Optional<Boolean> didPlayerWin() {
				return catchErrorGet(() -> getFacade().didPlayerWin(getWorld()));
			}

		};
	}

	@Override
	public Part2WorldInfoProvider getWorldInfoProvider() {
		return (Part2WorldInfoProvider) super.getWorldInfoProvider();
	}

	public String[] getAvailableMaps() {
		return new File("levels").list((file, name) -> name.endsWith(".tmx"));
	}

	public boolean setMapFile(String currentMap) {
		this.currentMap = currentMap;
		return readLevelFile(currentMap);
	}

	protected ObjectInfoProvider createObjectInfoProvider() {
		return new ObjectInfoProvider() {

			@Override
			public Collection<Slime> getSlimes() {
				Collection<Slime> result = getFacade().getSlimes(world);
				if (result == null) {
					result = Collections.emptyList();
				}
				return result;
			}

			@Override
			public Optional<int[]> getLocation(Slime slime) {
				return Optional.of(getFacade().getLocation(slime));
			}

			@Override
			public Collection<Shark> getSharks() {
				Collection<Shark> result = getFacade().getSharks(world);
				if (result == null) {
					result = Collections.emptyList();
				}
				return result;
			}

			@Override
			public Optional<int[]> getLocation(Shark shark) {
				return Optional.of(getFacade().getLocation(shark));
			}

			@Override
			public Collection<Plant> getPlants() {
				Collection<Plant> result = getFacade().getPlants(world);
				if (result == null) {
					result = Collections.emptyList();
				}
				return result;
			}

			@Override
			public Optional<int[]> getLocation(Plant plant) {
				return Optional.of(getFacade().getLocation(plant));
			}

			@Override
			public Optional<ImageSprite> getCurrentSprite(Plant plant) {
				return Optional.of((ImageSprite) getFacade().getCurrentSprite(
						plant));
			}

			@Override
			public Optional<ImageSprite> getCurrentSprite(Shark shark) {
				return Optional.of((ImageSprite) getFacade().getCurrentSprite(
						shark));
			}

			@Override
			public Optional<ImageSprite> getCurrentSprite(Slime slime) {
				return Optional.of((ImageSprite) getFacade().getCurrentSprite(
						slime));
			}

			@Override
			public Optional<School> getSchool(Slime slime) {
				return catchErrorGet(() -> getFacade().getSchool(slime));
			}

		};
	}

	public ObjectInfoProvider getObjectInfoProvider() {
		return objectInfoProvider;
	}

	public String getMapFile() {
		return currentMap;
	}

	public AlienInfoProvider2<Buzam> getEvilTwinInfoProvider() {
		return evilTwinProvider;
	}
}


text:
using RestSharp;
using System.Collections.Generic;
using System;
using System.Linq;

namespace QBankApi.Model
{
    public class PropertyResponse
    {
        /// <summary>
        /// When the Property was created.
        /// </summary>
        public DateTime Created { get; set; }

        /// <summary>
        /// The identifier of the User who created the Property.
        /// </summary>
        public int? CreatedBy { get; set; }

        /// <summary>
        /// When the Property was updated.
        /// </summary>
        public DateTime Updated { get; set; }

        /// <summary>
        /// Which user who updated the Property.
        /// </summary>
        public int? UpdatedBy { get; set; }

        /// <summary>
        /// Whether the Property is deleted.
        /// </summary>
        public bool? Deleted { get; set; }

        /// <summary>
        /// Whether the Property has been modified since constructed.
        /// </summary>
        public bool? Dirty { get; set; }

        /// <summary>
        /// The PropertyType describing this Property.
        /// </summary>
        public PropertyType PropertyType { get; set; }

        /// <summary>
        /// The value of the Property.
        /// </summary>
        public object Value { get; set; }

        public T GetValue<T>()
        {
            if (Type.GetTypeCode(typeof(T)) == TypeCode.DateTime)
            {
                return (T) (object) Convert.ToDateTime(Value);
            }

            if (Value is T)
                return (T) Value;
            else
                return default(T);
        }

        public List<T> GetValueArray<T>()
        {
            List<T> list = null;
            var array = Value as JsonArray;
            if (array == null)
            {
                var typedValue = GetValue<T>();
                if (typedValue != null)
                    list = new List<T>()
                    {
                        typedValue
                    };
            }
            else
            {
                list = new List<T>(from Dictionary<string, object> value in array
                    where value["value"] is T
                    select (T) value["value"]);
            }
            return list ?? new List<T>();
        }
    }
}


text:
Command listener for innocently trolling your friends.

Made in a day, mostly as a joke.

Allows you to start a listener on a victim's machine that will poll a webserver for a shell command. Fun for triggering text-to-speech on your friend's machine. Like a poor man's netcat only unidirectional and wont get picked up by anti-virus.


text:
//===--- PassManager.cpp - Swift Pass Manager -----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "sil-passmanager"

#include "swift/SILOptimizer/PassManager/PassManager.h"
#include "swift/AST/SILOptimizerRequests.h"
#include "swift/Demangling/Demangle.h"
#include "swift/SIL/ApplySite.h"
#include "swift/SIL/SILBridgingUtils.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SILOptimizer/Analysis/AliasAnalysis.h"
#include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h"
#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h"
#include "swift/SILOptimizer/Analysis/FunctionOrder.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/OptimizerBridging.h"
#include "swift/SILOptimizer/PassManager/PrettyStackTrace.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/OptimizerStatsUtils.h"
#include "swift/SILOptimizer/Utils/StackNesting.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Chrono.h"

using namespace swift;

llvm::cl::opt<bool> SILPrintAll(
    "sil-print-all", llvm::cl::init(false),
    llvm::cl::desc("Print SIL after each pass"));

llvm::cl::opt<bool> SILPrintPassName(
    "sil-print-pass-name", llvm::cl::init(false),
    llvm::cl::desc("Print the name of each SIL pass before it runs"));

llvm::cl::opt<bool> SILPrintPassTime(
    "sil-print-pass-time", llvm::cl::init(false),
    llvm::cl::desc("Print the execution time of each SIL pass"));

llvm::cl::opt<bool> SILPrintLast(
    "sil-print-last", llvm::cl::init(false),
    llvm::cl::desc("Print the last optimized function before and after the last pass"));

llvm::cl::opt<std::string> SILNumOptPassesToRun(
    "sil-opt-pass-count", llvm::cl::init(""),
    llvm::cl::desc("Stop optimizing after <N> passes or <N>.<M> passes/sub-passes"));

llvm::cl::opt<std::string> SILBreakOnFun(
    "sil-break-on-function", llvm::cl::init(""),
    llvm::cl::desc(
        "Break before running each function pass on a particular function"));

llvm::cl::opt<std::string> SILBreakOnPass(
    "sil-break-on-pass", llvm::cl::init(""),
    llvm::cl::desc("Break before running a particular function pass"));

llvm::cl::list<std::string>
    SILPrintFunction("sil-print-function", llvm::cl::CommaSeparated,
                    llvm::cl::desc("Only print out the sil for this function"));

llvm::cl::opt<std::string>
    SILPrintFunctions("sil-print-functions", llvm::cl::init(""),
                     llvm::cl::desc("Only print out the sil for the functions "
                                    "whose name contains this substring"));

llvm::cl::list<std::string>
    SILPrintBefore("sil-print-before", llvm::cl::CommaSeparated,
                   llvm::cl::desc("Print out the sil before passes which "
                                  "contain a string from this list."));

llvm::cl::list<std::string>
    SILPrintAfter("sil-print-after", llvm::cl::CommaSeparated,
                  llvm::cl::desc("Print out the sil after passes which contain "
                                 "a string from this list."));

llvm::cl::list<std::string>
    SILPrintAround("sil-print-around", llvm::cl::CommaSeparated,
                   llvm::cl::desc("Print out the sil before and after passes "
                                  "which contain a string from this list"));

llvm::cl::list<std::string>
    SILDisablePass("sil-disable-pass", llvm::cl::CommaSeparated,
                     llvm::cl::desc("Disable passes "
                                    "which contain a string from this list"));
llvm::cl::list<std::string> SILDisablePassOnlyFun(
    "sil-disable-pass-only-function", llvm::cl::CommaSeparated,
    llvm::cl::desc("Apply -sil-disable-pass only on this function"));

llvm::cl::list<std::string> SILVerifyBeforePass(
    "sil-verify-before-pass", llvm::cl::CommaSeparated,
    llvm::cl::desc("Verify the module/analyses before we run "
                   "a pass from this list"));

llvm::cl::list<std::string> SILVerifyAroundPass(
    "sil-verify-around-pass", llvm::cl::CommaSeparated,
    llvm::cl::desc("Verify the module/analyses before/after we run "
                   "a pass from this list"));

llvm::cl::list<std::string>
    SILVerifyAfterPass("sil-verify-after-pass", llvm::cl::CommaSeparated,
                       llvm::cl::desc("Verify the module/analyses after we run "
                                      "a pass from this list"));

llvm::cl::list<std::string> SILForceVerifyAroundPass(
    "sil-verify-force-analysis-around-pass", llvm::cl::CommaSeparated,
    llvm::cl::desc("For the given passes, precompute analyses before the pass "
                   "and verify analyses after the pass"));

llvm::cl::opt<bool> SILVerifyWithoutInvalidation(
    "sil-verify-without-invalidation", llvm::cl::init(false),
    llvm::cl::desc("Verify after passes even if the pass has not invalidated"));

llvm::cl::opt<bool> SILDisableSkippingPasses(
    "sil-disable-skipping-passes", llvm::cl::init(false),
    llvm::cl::desc("Do not skip passes even if nothing was changed"));

llvm::cl::opt<bool> SILForceVerifyAll(
    "sil-verify-force-analysis", llvm::cl::init(false),
    llvm::cl::desc("For all passes, precompute analyses before the pass and "
                   "verify analyses after the pass"));

static llvm::ManagedStatic<std::vector<unsigned>> DebugPassNumbers;

namespace {

struct DebugOnlyPassNumberOpt {
  void operator=(const std::string &Val) const {
    if (Val.empty())
      return;
    SmallVector<StringRef, 8> dbgPassNumbers;
    StringRef(Val).split(dbgPassNumbers, ',', -1, false);
    for (auto dbgPassNumber : dbgPassNumbers) {
      int PassNumber;
      if (dbgPassNumber.getAsInteger(10, PassNumber) || PassNumber < 0)
        llvm_unreachable("The pass number should be an integer number >= 0");
      DebugPassNumbers->push_back(static_cast<unsigned>(PassNumber));
    }
  }
};

} // end anonymous namespace

static DebugOnlyPassNumberOpt DebugOnlyPassNumberOptLoc;

static llvm::cl::opt<DebugOnlyPassNumberOpt, true,
                     llvm::cl::parser<std::string>>
    DebugOnly("debug-only-pass-number",
              llvm::cl::desc("Enable a specific type of debug output (comma "
                             "separated list pass numbers)"),
              llvm::cl::Hidden, llvm::cl::ZeroOrMore,
              llvm::cl::value_desc("pass number"),
              llvm::cl::location(DebugOnlyPassNumberOptLoc),
              llvm::cl::ValueRequired);

bool isFunctionSelectedForPrinting(SILFunction *F) {
  if (!SILPrintFunction.empty() && SILPrintFunction.end() ==
      std::find(SILPrintFunction.begin(), SILPrintFunction.end(), F->getName()))
    return false;

  if (!F->getName().contains(SILPrintFunctions))
    return false;

  return true;
}

static bool functionSelectionEmpty() {
  return SILPrintFunction.empty() && SILPrintFunctions.empty();
}

bool SILPassManager::doPrintBefore(SILTransform *T, SILFunction *F) {
  if (NumPassesRun == maxNumPassesToRun - 1 && SILPrintLast &&
      maxNumSubpassesToRun == UINT_MAX && !isMandatory)
    return true;

  if (F && !isFunctionSelectedForPrinting(F))
    return false;

  auto MatchFun = [&](const std::string &Str) -> bool {
    return T->getTag().contains(Str) || T->getID().contains(Str);
  };

  if (SILPrintBefore.end() !=
      std::find_if(SILPrintBefore.begin(), SILPrintBefore.end(), MatchFun))
    return true;
  if (!SILPrintBefore.empty())
    return false;

  if (SILPrintAround.end() !=
      std::find_if(SILPrintAround.begin(), SILPrintAround.end(), MatchFun))
    return true;
  if (!SILPrintAround.empty())
    return false;

  return false;
}

bool SILPassManager::doPrintAfter(SILTransform *T, SILFunction *F, bool PassChangedSIL) {
  if (NumPassesRun == maxNumPassesToRun - 1 && SILPrintLast && !isMandatory)
    return true;

  if (F && !isFunctionSelectedForPrinting(F))
    return false;

  auto MatchFun = [&](const std::string &Str) -> bool {
    return T->getTag().contains(Str) || T->getID().contains(Str);
  };

  if (SILPrintAfter.end() !=
      std::find_if(SILPrintAfter.begin(), SILPrintAfter.end(), MatchFun))
    return true;
  if (!SILPrintAfter.empty())
    return false;

  if (SILPrintAround.end() !=
      std::find_if(SILPrintAround.begin(), SILPrintAround.end(), MatchFun))
    return true;
  if (!SILPrintAround.empty())
    return false;

  return PassChangedSIL && (SILPrintAll || !functionSelectionEmpty());
}

static void printModule(SILModule *Mod, bool EmitVerboseSIL) {
  if (functionSelectionEmpty()) {
    Mod->dump();
    return;
  }
  for (auto &F : *Mod) {
    if (isFunctionSelectedForPrinting(&F))
      F.dump(EmitVerboseSIL);
  }
}

class DebugPrintEnabler {
#ifndef NDEBUG
  bool OldDebugFlag;
#endif
public:
  DebugPrintEnabler(unsigned PassNumber) {
#ifndef NDEBUG
    OldDebugFlag = llvm::DebugFlag;
    if (llvm::DebugFlag)
      return;
    if (DebugPassNumbers->empty())
      return;
    // Enable debug printing if the pass number matches
    // one of the pass numbers provided as a command line option.
    for (auto DebugPassNumber : *DebugPassNumbers) {
      if (DebugPassNumber == PassNumber) {
        llvm::DebugFlag = true;
        return;
      }
    }
#endif
  }

  ~DebugPrintEnabler() {
#ifndef NDEBUG
    llvm::DebugFlag = OldDebugFlag;
#endif
  }
};

//===----------------------------------------------------------------------===//
//                 Serialization Notification Implementation
//===----------------------------------------------------------------------===//

namespace {

class PassManagerDeserializationNotificationHandler final
    : public DeserializationNotificationHandler {
  NullablePtr<SILPassManager> pm;

public:
  PassManagerDeserializationNotificationHandler(SILPassManager *pm) : pm(pm) {}
  ~PassManagerDeserializationNotificationHandler() override = default;

  StringRef getName() const override {
    return "PassManagerDeserializationNotificationHandler";
  }

  /// Observe that we deserialized a function declaration.
  void didDeserialize(ModuleDecl *mod, SILFunction *fn) override {
    pm.get()->notifyAnalysisOfFunction(fn);
  }
};

} // end anonymous namespace

evaluator::SideEffect ExecuteSILPipelineRequest::evaluate(
    Evaluator &evaluator, SILPipelineExecutionDescriptor desc) const {
  SILPassManager PM(desc.SM, desc.IsMandatory, desc.IRMod);
  PM.executePassPipelinePlan(desc.Plan);
  return std::make_tuple<>();
}

void swift::executePassPipelinePlan(SILModule *SM,
                                    const SILPassPipelinePlan &plan,
                                    bool isMandatory,
                                    irgen::IRGenModule *IRMod) {
  auto &evaluator = SM->getASTContext().evaluator;
  SILPipelineExecutionDescriptor desc{SM, plan, isMandatory, IRMod};
  (void)llvm::cantFail(evaluator(ExecuteSILPipelineRequest{desc}));
}

SILPassManager::SILPassManager(SILModule *M, bool isMandatory,
                               irgen::IRGenModule *IRMod)
    : Mod(M), IRMod(IRMod),
      swiftPassInvocation(this),
      isMandatory(isMandatory), deserializationNotificationHandler(nullptr) {
#define ANALYSIS(NAME) \
  Analyses.push_back(create##NAME##Analysis(Mod));
#include "swift/SILOptimizer/Analysis/Analysis.def"

  if (!SILNumOptPassesToRun.empty()) {
    StringRef countsStr = SILNumOptPassesToRun;
    bool validFormat = true;
    if (countsStr.consumeInteger(10, maxNumPassesToRun))
      validFormat = false;
    if (countsStr.startswith(".")) {
      countsStr = countsStr.drop_front(1);
      if (countsStr.consumeInteger(10, maxNumSubpassesToRun))
        validFormat = false;
    }
    if (!validFormat || !countsStr.empty()) {
      llvm::errs() << "error: wrong format of -sil-opt-pass-count option\n";
      exit(1);
    }
  }

  for (SILAnalysis *A : Analyses) {
    A->initialize(this);
  }

  std::unique_ptr<DeserializationNotificationHandler> handler(
      new PassManagerDeserializationNotificationHandler(this));
  deserializationNotificationHandler = handler.get();
  M->registerDeserializationNotificationHandler(std::move(handler));
}

bool SILPassManager::continueTransforming() {
  if (isMandatory)
    return true;
  return NumPassesRun < maxNumPassesToRun;
}

bool SILPassManager::continueWithNextSubpassRun(SILInstruction *forInst,
                                                SILFunction *function,
                                                SILTransform *trans) {
  if (isMandatory)
    return true;
  if (NumPassesRun != maxNumPassesToRun - 1)
    return true;

  unsigned subPass = numSubpassesRun++;

  if (subPass == maxNumSubpassesToRun - 1 && SILPrintLast) {
    dumpPassInfo("*** SIL function before ", trans, function);
    if (forInst) {
      llvm::dbgs() << "  *** sub-pass " << subPass << " for " << *forInst;
    }
    function->dump(getOptions().EmitVerboseSIL);
  }
  return subPass < maxNumSubpassesToRun;
}

bool SILPassManager::analysesUnlocked() {
  for (auto *A : Analyses)
    if (A->isLocked())
      return false;

  return true;
}

// Test the function and pass names we're given against the debug
// options that force us to break prior to a given pass and/or on a
// given function.
static bool breakBeforeRunning(StringRef fnName, SILFunctionTransform *SFT) {
  if (SILBreakOnFun.empty() && SILBreakOnPass.empty())
    return false;

  if (SILBreakOnFun.empty()
      && (SFT->getID() == SILBreakOnPass || SFT->getTag() == SILBreakOnPass))
    return true;

  if (SILBreakOnPass.empty() && fnName == SILBreakOnFun)
    return true;

  return fnName == SILBreakOnFun
    && (SFT->getID() == SILBreakOnPass || SFT->getTag() == SILBreakOnPass);
}

void SILPassManager::dumpPassInfo(const char *Title, SILTransform *Tr,
                                  SILFunction *F, int passIdx) {
  llvm::dbgs() << "  " << Title << " #" << NumPassesRun
               << ", stage " << StageName << ", pass";
  if (passIdx >= 0)
    llvm::dbgs() << ' ' << passIdx;
  llvm::dbgs() << ": " << Tr->getID() << " (" << Tr->getTag() << ")";
  if (F)
    llvm::dbgs() << ", Function: " << F->getName();
  llvm::dbgs() << '\n';
}

void SILPassManager::dumpPassInfo(const char *Title, unsigned TransIdx,
                                  SILFunction *F) {
  dumpPassInfo(Title, Transformations[TransIdx], F, (int)TransIdx);
}

bool SILPassManager::isMandatoryFunctionPass(SILFunctionTransform *sft) {
  return isMandatory ||
         sft->getPassKind() ==
             PassKind::NonTransparentFunctionOwnershipModelEliminator ||
         sft->getPassKind() == PassKind::OwnershipModelEliminator;
}

static bool isDisabled(SILTransform *T, SILFunction *F = nullptr) {
  if (SILDisablePass.empty())
    return false;

  if (SILPassManager::isPassDisabled(T->getTag()) ||
      SILPassManager::isPassDisabled(T->getID())) {
    if (F && !SILPassManager::disablePassesForFunction(F))
      return false;
    return true;
  }
  return false;
}

bool SILPassManager::isPassDisabled(StringRef passName) {
  for (const std::string &namePattern : SILDisablePass) {
    if (passName.contains(namePattern))
      return true;
  }
  return false;
}

bool SILPassManager::disablePassesForFunction(SILFunction *function) {
  if (SILDisablePassOnlyFun.empty())
    return true;

  return std::find(SILDisablePassOnlyFun.begin(), SILDisablePassOnlyFun.end(),
                   function->getName()) != SILDisablePassOnlyFun.end();
}

void SILPassManager::runPassOnFunction(unsigned TransIdx, SILFunction *F) {

  assert(analysesUnlocked() && "Expected all analyses to be unlocked!");

  auto *SFT = cast<SILFunctionTransform>(Transformations[TransIdx]);

  if (!F->shouldOptimize() && !isMandatoryFunctionPass(SFT)) {
    return;
  }

  SFT->injectPassManager(this);
  SFT->injectFunction(F);

  PrettyStackTraceSILFunctionTransform X(SFT, NumPassesRun);
  DebugPrintEnabler DebugPrint(NumPassesRun);

  // If nothing changed since the last run of this pass, we can skip this
  // pass if it is not mandatory
  CompletedPasses &completedPasses = CompletedPassesMap[F];
  if (!isMandatoryFunctionPass(SFT) &&
      completedPasses.test((size_t)SFT->getPassKind()) &&
      !SILDisableSkippingPasses) {
    if (SILPrintPassName)
      dumpPassInfo("(Skip)", TransIdx, F);
    return;
  }

  if (isDisabled(SFT, F)) {
    if (SILPrintPassName)
      dumpPassInfo("(Disabled)", TransIdx, F);
    return;
  }

  updateSILModuleStatsBeforeTransform(F->getModule(), SFT, *this, NumPassesRun);

  CurrentPassHasInvalidated = false;
  numSubpassesRun = 0;

  auto MatchFun = [&](const std::string &Str) -> bool {
    return SFT->getTag().contains(Str) || SFT->getID().contains(Str);
  };
  if ((SILVerifyBeforePass.end() != std::find_if(SILVerifyBeforePass.begin(),
                                                 SILVerifyBeforePass.end(),
                                                 MatchFun)) ||
      (SILVerifyAroundPass.end() != std::find_if(SILVerifyAroundPass.begin(),
                                                 SILVerifyAroundPass.end(),
                                                 MatchFun))) {
    F->verify();
    verifyAnalyses();
  }

  if (SILPrintPassName)
    dumpPassInfo("Run", TransIdx, F);

  if (doPrintBefore(SFT, F)) {
    dumpPassInfo("*** SIL function before ", TransIdx);
    F->dump(getOptions().EmitVerboseSIL);
  }

  llvm::sys::TimePoint<> StartTime = std::chrono::system_clock::now();
  if (breakBeforeRunning(F->getName(), SFT))
    LLVM_BUILTIN_DEBUGTRAP;
  if (SILForceVerifyAll ||
      SILForceVerifyAroundPass.end() !=
          std::find_if(SILForceVerifyAroundPass.begin(),
                       SILForceVerifyAroundPass.end(), MatchFun)) {
    forcePrecomputeAnalyses(F);
  }

  assert(changeNotifications == SILAnalysis::InvalidationKind::Nothing
         && "change notifications not cleared");

  swiftPassInvocation.startFunctionPassRun(F);

  // Run it!
  SFT->run();

  if (changeNotifications != SILAnalysis::InvalidationKind::Nothing) {
    invalidateAnalysis(F, changeNotifications);
    changeNotifications = SILAnalysis::InvalidationKind::Nothing;
  }
  swiftPassInvocation.finishedFunctionPassRun();

  if (SILForceVerifyAll ||
      SILForceVerifyAroundPass.end() !=
          std::find_if(SILForceVerifyAroundPass.begin(),
                       SILForceVerifyAroundPass.end(), MatchFun)) {
    verifyAnalyses(F);
  }
  assert(analysesUnlocked() && "Expected all analyses to be unlocked!");
  Mod->flushDeletedInsts();

  auto Delta = (std::chrono::system_clock::now() - StartTime).count();
  if (SILPrintPassTime) {
    llvm::dbgs() << Delta << " (" << SFT->getID() << "," << F->getName()
                 << ")\n";
  }

  // If this pass invalidated anything, print and verify.
  if (doPrintAfter(SFT, F, CurrentPassHasInvalidated)) {
    dumpPassInfo("*** SIL function after ", TransIdx);
    F->dump(getOptions().EmitVerboseSIL);
  }

  updateSILModuleStatsAfterTransform(F->getModule(), SFT, *this, NumPassesRun,
                                     Delta);

  // Remember if this pass didn't change anything.
  if (!CurrentPassHasInvalidated)
    completedPasses.set((size_t)SFT->getPassKind());

  if (getOptions().VerifyAll &&
      (CurrentPassHasInvalidated || SILVerifyWithoutInvalidation)) {
    F->verify();
    verifyAnalyses(F);
  } else {
    if ((SILVerifyAfterPass.end() != std::find_if(SILVerifyAfterPass.begin(),
                                                  SILVerifyAfterPass.end(),
                                                  MatchFun)) ||
        (SILVerifyAroundPass.end() != std::find_if(SILVerifyAroundPass.begin(),
                                                   SILVerifyAroundPass.end(),
                                                   MatchFun))) {
      F->verify();
      verifyAnalyses();
    }
  }

  ++NumPassesRun;
}

void SILPassManager::
runFunctionPasses(unsigned FromTransIdx, unsigned ToTransIdx) {
  if (ToTransIdx <= FromTransIdx)
    return;

  BasicCalleeAnalysis *BCA = getAnalysis<BasicCalleeAnalysis>();
  BottomUpFunctionOrder BottomUpOrder(*Mod, BCA);
  auto BottomUpFunctions = BottomUpOrder.getFunctions();

  assert(FunctionWorklist.empty() && "Expected empty function worklist!");

  FunctionWorklist.reserve(BottomUpFunctions.size());
  for (auto I = BottomUpFunctions.rbegin(), E = BottomUpFunctions.rend();
       I != E; ++I) {
    auto &F = **I;

    // Only include functions that are definitions, and which have not
    // been intentionally excluded from optimization.
    if (F.isDefinition())
      FunctionWorklist.push_back(*I);
  }

  DerivationLevels.clear();

  // The maximum number of times the pass pipeline can be restarted for a
  // function. This is used to ensure we are not going into an infinite loop in
  // cases where (for example) we have recursive type-based specialization
  // happening.
  const unsigned MaxNumRestarts = 20;

  if (SILPrintPassName)
    llvm::dbgs() << "Start function passes at stage: " << StageName << "\n";

  // Run all transforms for all functions, starting at the tail of the worklist.
  while (!FunctionWorklist.empty() && continueTransforming()) {
    unsigned TailIdx = FunctionWorklist.size() - 1;
    unsigned PipelineIdx = FunctionWorklist[TailIdx].PipelineIdx;
    SILFunction *F = FunctionWorklist[TailIdx].F;

    if (PipelineIdx >= (ToTransIdx - FromTransIdx)) {
      // All passes did already run for the function. Pop it off the worklist.
      FunctionWorklist.pop_back();
      continue;
    }
    assert(!shouldRestartPipeline() &&
        "Did not expect function pipeline set up to restart from beginning!");

    runPassOnFunction(FromTransIdx + PipelineIdx, F);

    // Note: Don't get entry reference prior to runPassOnFunction().
    // A pass can push a new function to the worklist which may cause a
    // reallocation of the buffer and that would invalidate the reference.
    WorklistEntry &Entry = FunctionWorklist[TailIdx];
    if (shouldRestartPipeline() && Entry.NumRestarts < MaxNumRestarts) {
      ++Entry.NumRestarts;
      Entry.PipelineIdx = 0;
    } else {
      ++Entry.PipelineIdx;
    }
    clearRestartPipeline();
  }
}

void SILPassManager::runModulePass(unsigned TransIdx) {
  auto *SMT = cast<SILModuleTransform>(Transformations[TransIdx]);
  if (isDisabled(SMT))
    return;

  const SILOptions &Options = getOptions();

  SMT->injectPassManager(this);
  SMT->injectModule(Mod);

  PrettyStackTraceSILModuleTransform X(SMT, NumPassesRun);
  DebugPrintEnabler DebugPrint(NumPassesRun);

  updateSILModuleStatsBeforeTransform(*Mod, SMT, *this, NumPassesRun);

  CurrentPassHasInvalidated = false;
  numSubpassesRun = 0;

  if (SILPrintPassName)
    dumpPassInfo("Run module pass", TransIdx);

  if (doPrintBefore(SMT, nullptr)) {
    dumpPassInfo("*** SIL module before", TransIdx);
    printModule(Mod, Options.EmitVerboseSIL);
  }

  auto MatchFun = [&](const std::string &Str) -> bool {
    return SMT->getTag().contains(Str) || SMT->getID().contains(Str);
  };
  if ((SILVerifyBeforePass.end() != std::find_if(SILVerifyBeforePass.begin(),
                                                 SILVerifyBeforePass.end(),
                                                 MatchFun)) ||
      (SILVerifyAroundPass.end() != std::find_if(SILVerifyAroundPass.begin(),
                                                 SILVerifyAroundPass.end(),
                                                 MatchFun))) {
    Mod->verify();
    verifyAnalyses();
  }

  llvm::sys::TimePoint<> StartTime = std::chrono::system_clock::now();
  assert(analysesUnlocked() && "Expected all analyses to be unlocked!");
  SMT->run();
  assert(analysesUnlocked() && "Expected all analyses to be unlocked!");
  Mod->flushDeletedInsts();

  auto Delta = (std::chrono::system_clock::now() - StartTime).count();
  if (SILPrintPassTime) {
    llvm::dbgs() << Delta << " (" << SMT->getID() << ",Module)\n";
  }

  // If this pass invalidated anything, print and verify.
  if (doPrintAfter(SMT, nullptr, CurrentPassHasInvalidated)) {
    dumpPassInfo("*** SIL module after", TransIdx);
    printModule(Mod, Options.EmitVerboseSIL);
  }

  updateSILModuleStatsAfterTransform(*Mod, SMT, *this, NumPassesRun, Delta);

  if (Options.VerifyAll &&
      (CurrentPassHasInvalidated || !SILVerifyWithoutInvalidation)) {
    Mod->verify();
    verifyAnalyses();
  } else {
    if ((SILVerifyAfterPass.end() != std::find_if(SILVerifyAfterPass.begin(),
                                                  SILVerifyAfterPass.end(),
                                                  MatchFun)) ||
        (SILVerifyAroundPass.end() != std::find_if(SILVerifyAroundPass.begin(),
                                                   SILVerifyAroundPass.end(),
                                                   MatchFun))) {
      Mod->verify();
      verifyAnalyses();
    }
  }
}

void SILPassManager::verifyAnalyses() const {
  if (Mod->getOptions().VerifyNone)
    return;

  for (auto *A : Analyses) {
    A->verify();
  }
}

void SILPassManager::verifyAnalyses(SILFunction *F) const {
  if (Mod->getOptions().VerifyNone)
    return;

  for (auto *A : Analyses) {
    A->verify(F);
  }
}

void SILPassManager::executePassPipelinePlan(const SILPassPipelinePlan &Plan) {
  for (const SILPassPipeline &Pipeline : Plan.getPipelines()) {
    setStageName(Pipeline.Name);
    resetAndRemoveTransformations();
    for (PassKind Kind : Plan.getPipelinePasses(Pipeline)) {
      addPass(Kind);
      assert(!Pipeline.isFunctionPassPipeline
             || isa<SILFunctionTransform>(Transformations.back()));
    }
    execute();
  }
}

void SILPassManager::execute() {
  const SILOptions &Options = getOptions();

  LLVM_DEBUG(llvm::dbgs() << "*** Optimizing the module (" << StageName
                          << ") *** \n");
  if (SILPrintAll) {
    llvm::dbgs() << "*** SIL module before "  << StageName << " ***\n";
    printModule(Mod, Options.EmitVerboseSIL);
  }

  // Run the transforms by alternating between function transforms and
  // module transforms. We'll queue up all the function transforms
  // that we see in a row and then run the entire group of transforms
  // on each function in turn. Then we move on to running the next set
  // of consecutive module transforms.
  unsigned Idx = 0, NumTransforms = Transformations.size();

  while (Idx < NumTransforms && continueTransforming()) {
    SILTransform *Tr = Transformations[Idx];
    assert((isa<SILFunctionTransform>(Tr) || isa<SILModuleTransform>(Tr)) &&
           "Unexpected pass kind!");
    (void)Tr;

    unsigned FirstFuncTrans = Idx;
    while (Idx < NumTransforms && isa<SILFunctionTransform>(Transformations[Idx]))
      ++Idx;

    runFunctionPasses(FirstFuncTrans, Idx);

    while (Idx < NumTransforms && isa<SILModuleTransform>(Transformations[Idx])
           && continueTransforming()) {
      runModulePass(Idx);

      ++Idx;
      ++NumPassesRun;
    }
  }
}

/// D'tor.
SILPassManager::~SILPassManager() {
  // Before we do anything further, verify the module and our analyses. These
  // are natural points with which to verify.
  //
  // TODO: We currently do not verify the module here since the verifier asserts
  // in the normal build. This should be enabled and those problems resolved
  // either by changing the verifier or treating those asserts as signs of a
  // bug.
  for (auto *A : Analyses) {
    // We use verify full instead of just verify to ensure that passes that want
    // to run more expensive verification after a pass manager is destroyed
    // properly trigger.
    //
    // NOTE: verifyFull() has a default implementation that just calls
    // verify(). So functionally, there is no difference here.
    A->verifyFull();
  }

  // Remove our deserialization notification handler.
  Mod->removeDeserializationNotificationHandler(
      deserializationNotificationHandler);

  // Free all transformations.
  for (auto *T : Transformations)
    delete T;

  // delete the analysis.
  for (auto *A : Analyses) {
    assert(!A->isLocked() &&
           "Deleting a locked analysis. Did we forget to unlock ?");
    delete A;
  }
}

void SILPassManager::notifyOfNewFunction(SILFunction *F, SILTransform *T) {
  if (doPrintAfter(T, F, /*PassChangedSIL*/ true)) {
    dumpPassInfo("*** New SIL function in ", T, F);
    F->dump(getOptions().EmitVerboseSIL);
  }
}

void SILPassManager::addFunctionToWorklist(SILFunction *F,
                                           SILFunction *DerivedFrom) {
  assert(F && F->isDefinition() && (isMandatory || F->shouldOptimize()) &&
         "Expected optimizable function definition!");

  constexpr int MaxDeriveLevels = 10;

  int NewLevel = 1;
  if (DerivedFrom) {
    if (!functionSelectionEmpty() && isFunctionSelectedForPrinting(F)) {
      llvm::dbgs() << F->getName() << " was derived from "
                   << DerivedFrom->getName() << "\n";
    }
    // When SILVerifyAll is enabled, individual functions are verified after
    // function passes are run upon them. This means that any functions created
    // by a function pass will not be verified after the pass runs. Thus
    // specialization errors that cause the verifier to trip will be
    // misattributed to the first pass that makes a change to the specialized
    // function. This is very misleading and increases triage time.
    //
    // As a result, when SILVerifyAll is enabled, we always verify newly
    // specialized functions as they are added to the worklist.
    //
    // TODO: Currently, all specialized functions are added to the function
    // worklist in this manner. This is all well and good, but we should really
    // add support for verifying that all specialized functions are added via
    // this function to the pass manager to ensure that we perform this
    // verification.
    if (getOptions().VerifyAll) {
      F->verify();
    }

    NewLevel = DerivationLevels[DerivedFrom] + 1;
    // Limit the number of derivations, i.e. don't allow that a pass specializes
    // a specialized function which is itself a specialized function, and so on.
    if (NewLevel >= MaxDeriveLevels)
      return;
  }
  int &StoredLevel = DerivationLevels[F];

  // Only allow a function to be pushed on the worklist a single time
  // (not counting the initial population of the worklist with the bottom-up
  // function order).
  if (StoredLevel > 0)
    return;

  StoredLevel = NewLevel;
  FunctionWorklist.push_back(F);
}

void SILPassManager::restartWithCurrentFunction(SILTransform *T) {
  assert(isa<SILFunctionTransform>(T) &&
         "Can only restart the pipeline from function passes");
  RestartPipeline = true;
}

/// Reset the state of the pass manager and remove all transformation
/// owned by the pass manager. Analysis passes will be kept.
void SILPassManager::resetAndRemoveTransformations() {
  for (auto *T : Transformations)
    delete T;

  Transformations.clear();
}

void SILPassManager::setStageName(llvm::StringRef NextStage) {
  StageName = NextStage.str();
}

StringRef SILPassManager::getStageName() const {
  return StageName;
}

const SILOptions &SILPassManager::getOptions() const {
  return Mod->getOptions();
}

namespace {
enum class IRGenPasses : uint8_t {
#define PASS(ID, TAG, NAME)
#define IRGEN_PASS(ID, TAG, NAME) ID,
#include "swift/SILOptimizer/PassManager/Passes.def"
};
} // end anonymous namespace

void SILPassManager::addPass(PassKind Kind) {
  assert(unsigned(PassKind::AllPasses_Last) >= unsigned(Kind) &&
         "Invalid pass kind");
  switch (Kind) {
#define PASS(ID, TAG, NAME)                                                    \
  case PassKind::ID: {                                                         \
    SILTransform *T = swift::create##ID();                                     \
    T->setPassKind(PassKind::ID);                                              \
    Transformations.push_back(T);                                              \
    break;                                                                     \
  }
#define IRGEN_PASS(ID, TAG, NAME)                                              \
  case PassKind::ID: {                                                         \
    auto &ctx = Mod->getASTContext();                                          \
    auto irPasses = ctx.getIRGenSILTransforms();                               \
    SILTransform *T = irPasses[static_cast<unsigned>(IRGenPasses::ID)]();      \
    assert(T && "Missing IRGen pass?");                                        \
    T->setPassKind(PassKind::ID);                                              \
    Transformations.push_back(T);                                              \
    break;                                                                     \
  }
#include "swift/SILOptimizer/PassManager/Passes.def"
  case PassKind::invalidPassKind:
    llvm_unreachable("invalid pass kind");
  }
}

void SILPassManager::addPassForName(StringRef Name) {
  PassKind P = llvm::StringSwitch<PassKind>(Name)
#define PASS(ID, TAG, NAME) .Case(#ID, PassKind::ID)
#include "swift/SILOptimizer/PassManager/Passes.def"
  ;
  addPass(P);
}

//===----------------------------------------------------------------------===//
//                          View Call-Graph Implementation
//===----------------------------------------------------------------------===//

#ifndef NDEBUG

namespace {

  /// An explicit graph data structure for the call graph.
  /// Used for viewing the callgraph as dot file with llvm::ViewGraph.
  struct CallGraph {

    struct Node;

    struct Edge {
      FullApplySite FAS;
      Node *Child;
      bool Incomplete;
    };

    struct Node {
      SILFunction *F;
      CallGraph *CG;
      int NumCallSites = 0;
      SmallVector<Edge, 8> Children;
    };

    struct child_iterator
        : public std::iterator<std::random_access_iterator_tag, Node *,
                               ptrdiff_t> {
      SmallVectorImpl<Edge>::iterator baseIter;

      child_iterator(SmallVectorImpl<Edge>::iterator baseIter) :
      baseIter(baseIter)
      { }

      child_iterator &operator++() { baseIter++; return *this; }
      child_iterator operator++(int) {
        auto tmp = *this;
        ++baseIter;
        return tmp;
      }
      Node *operator*() const { return baseIter->Child; }
      bool operator==(const child_iterator &RHS) const {
        return baseIter == RHS.baseIter;
      }
      bool operator!=(const child_iterator &RHS) const {
        return baseIter != RHS.baseIter;
      }
      difference_type operator-(const child_iterator &RHS) const {
        return baseIter - RHS.baseIter;
      }
    };

    CallGraph(SILModule *M, BasicCalleeAnalysis *BCA);

    std::vector<Node> Nodes;

    /// The SILValue IDs which are printed as edge source labels.
    llvm::DenseMap<const SILNode *, unsigned> InstToIDMap;

    typedef std::vector<Node>::iterator iterator;
  };

  CallGraph::CallGraph(SILModule *M, BasicCalleeAnalysis *BCA) {
    Nodes.resize(M->getFunctionList().size());
    llvm::DenseMap<SILFunction *, Node *> NodeMap;
    int idx = 0;
    for (SILFunction &F : *M) {
      Node &Nd = Nodes[idx++];
      Nd.F = &F;
      Nd.CG = this;
      NodeMap[&F] = &Nd;

      F.numberValues(InstToIDMap);
    }

    for (Node &Nd : Nodes) {
      for (SILBasicBlock &BB : *Nd.F) {
        for (SILInstruction &I : BB) {
          if (FullApplySite FAS = FullApplySite::isa(&I)) {
            auto CList = BCA->getCalleeList(FAS);
            for (SILFunction *Callee : CList) {
              Node *CalleeNode = NodeMap[Callee];
              Nd.Children.push_back({FAS, CalleeNode,CList.isIncomplete()});
            }
          }
        }
      }
    }
  }

} // end anonymous namespace

namespace llvm {

  /// Wraps a dot node label string to multiple lines. The \p NumEdgeLabels
  /// gives an estimate on the minimum width of the node shape.
  static void wrap(std::string &Str, int NumEdgeLabels) {
    unsigned ColNum = 0;
    unsigned LastSpace = 0;
    unsigned MaxColumns = std::max(60, NumEdgeLabels * 8);
    for (unsigned i = 0; i != Str.length(); ++i) {
      if (ColNum == MaxColumns) {
        if (!LastSpace)
          LastSpace = i;
        Str.insert(LastSpace + 1, "\\l");
        ColNum = i - LastSpace - 1;
        LastSpace = 0;
      } else
        ++ColNum;
      if (Str[i] == ' ' || Str[i] == '.')
        LastSpace = i;
    }
  }

  /// CallGraph GraphTraits specialization so the CallGraph can be
  /// iterable by generic graph iterators.
  template <> struct GraphTraits<CallGraph::Node *> {
    typedef CallGraph::child_iterator ChildIteratorType;
    typedef CallGraph::Node *NodeRef;

    static NodeRef getEntryNode(NodeRef N) { return N; }
    static inline ChildIteratorType child_begin(NodeRef N) {
      return N->Children.begin();
    }
    static inline ChildIteratorType child_end(NodeRef N) {
      return N->Children.end();
    }
  };

  template <> struct GraphTraits<CallGraph *>
  : public GraphTraits<CallGraph::Node *> {
    typedef CallGraph *GraphType;
    typedef CallGraph::Node *NodeRef;

    static NodeRef getEntryNode(GraphType F) { return nullptr; }

    typedef pointer_iterator<CallGraph::iterator> nodes_iterator;
    static nodes_iterator nodes_begin(GraphType CG) {
      return nodes_iterator(CG->Nodes.begin());
    }
    static nodes_iterator nodes_end(GraphType CG) {
      return nodes_iterator(CG->Nodes.end());
    }
    static unsigned size(GraphType CG) { return CG->Nodes.size(); }
  };

  /// This is everything the llvm::GraphWriter needs to write the call graph in
  /// a dot file.
  template <>
  struct DOTGraphTraits<CallGraph *> : public DefaultDOTGraphTraits {

    DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}

    std::string getNodeLabel(const CallGraph::Node *Node,
                             const CallGraph *Graph) {
      std::string Label = Node->F->getName().str();
      wrap(Label, Node->NumCallSites);
      return Label;
    }

    std::string getNodeDescription(const CallGraph::Node *Node,
                                   const CallGraph *Graph) {
      std::string Label = Demangle::
      demangleSymbolAsString(Node->F->getName());
      wrap(Label, Node->NumCallSites);
      return Label;
    }

    static std::string getEdgeSourceLabel(const CallGraph::Node *Node,
                                          CallGraph::child_iterator I) {
      std::string Label;
      raw_string_ostream O(Label);
      SILInstruction *Inst = I.baseIter->FAS.getInstruction();
      O << '%' << Node->CG->InstToIDMap[Inst->asSILNode()];
      return Label;
    }

    static std::string getEdgeAttributes(const CallGraph::Node *Node,
                                         CallGraph::child_iterator I,
                                         const CallGraph *Graph) {
      CallGraph::Edge *Edge = I.baseIter;
      if (Edge->Incomplete)
        return "color=\"red\"";
      return "";
    }
  };
} // namespace llvm
#endif

void SILPassManager::viewCallGraph() {
  /// When asserts are disabled, this should be a NoOp.
#ifndef NDEBUG
  CallGraph OCG(getModule(), getAnalysis<BasicCalleeAnalysis>());
  llvm::ViewGraph(&OCG, "callgraph");
#endif
}

//===----------------------------------------------------------------------===//
//                           SwiftPassInvocation
//===----------------------------------------------------------------------===//

static_assert(BridgedSlabCapacity == FixedSizeSlab::capacity,
              "wrong bridged slab capacity");

FixedSizeSlab *SwiftPassInvocation::allocSlab(FixedSizeSlab *afterSlab) {
  FixedSizeSlab *slab = passManager->getModule()->allocSlab();
  if (afterSlab) {
    allocatedSlabs.insert(std::next(afterSlab->getIterator()), *slab);
  } else {
    allocatedSlabs.push_back(*slab);
  }
  return slab;
}

FixedSizeSlab *SwiftPassInvocation::freeSlab(FixedSizeSlab *slab) {
  FixedSizeSlab *prev = nullptr;
  assert(!allocatedSlabs.empty());
  if (&allocatedSlabs.front() != slab)
    prev = &*std::prev(slab->getIterator());

  allocatedSlabs.remove(*slab);
  passManager->getModule()->freeSlab(slab);
  return prev;
}

BasicBlockSet *SwiftPassInvocation::allocBlockSet() {
  assert(numBlockSetsAllocated < BlockSetCapacity - 1 &&
         "too many BasicBlockSets allocated");

  auto *storage = (BasicBlockSet *)blockSetStorage + numBlockSetsAllocated;
  BasicBlockSet *set = new (storage) BasicBlockSet(function);
  aliveBlockSets[numBlockSetsAllocated] = true;
  ++numBlockSetsAllocated;
  return set;
}

void SwiftPassInvocation::freeBlockSet(BasicBlockSet *set) {
  int idx = set - (BasicBlockSet *)blockSetStorage;
  assert(idx >= 0 && idx < numBlockSetsAllocated);
  assert(aliveBlockSets[idx] && "double free of BasicBlockSet");
  aliveBlockSets[idx] = false;

  while (numBlockSetsAllocated > 0 && !aliveBlockSets[numBlockSetsAllocated - 1]) {
    auto *set = (BasicBlockSet *)blockSetStorage + numBlockSetsAllocated - 1;
    set->~BasicBlockSet();
    --numBlockSetsAllocated;
  }
}

void SwiftPassInvocation::startFunctionPassRun(SILFunction *function) {
  assert(!this->function && "a pass is already running");
  this->function = function;
}

void SwiftPassInvocation::startInstructionPassRun(SILInstruction *inst) {
  assert(inst->getFunction() == function &&
         "running instruction pass on wrong function");
}

void SwiftPassInvocation::finishedFunctionPassRun() {
  endPassRunChecks();
  assert(function && "not running a pass");
  function = nullptr;
}

void SwiftPassInvocation::finishedInstructionPassRun() {
  endPassRunChecks();
}

void SwiftPassInvocation::endPassRunChecks() {
  assert(allocatedSlabs.empty() && "StackList is leaking slabs");
  assert(numBlockSetsAllocated == 0 && "Not all BasicBlockSets deallocated");
}

//===----------------------------------------------------------------------===//
//                            Swift Bridging
//===----------------------------------------------------------------------===//

inline SwiftPassInvocation *castToPassInvocation(BridgedPassContext ctxt) {
  return const_cast<SwiftPassInvocation *>(
    static_cast<const SwiftPassInvocation *>(ctxt.opaqueCtxt));
}

inline FixedSizeSlab *castToSlab(BridgedSlab slab) {
  if (slab.data)
    return static_cast<FixedSizeSlab *>((FixedSizeSlabPayload *)slab.data);
  return nullptr;
}

inline BridgedSlab toBridgedSlab(FixedSizeSlab *slab) {
  if (slab) {
    FixedSizeSlabPayload *payload = slab;
    assert((void *)payload == slab->dataFor<void>());
    return {payload};
  }
  return {nullptr};
}

inline BasicBlockSet *castToBlockSet(BridgedBasicBlockSet blockSet) {
  return static_cast<BasicBlockSet *>(blockSet.bbs);
}

BridgedSlab PassContext_getNextSlab(BridgedSlab slab) {
  return toBridgedSlab(&*std::next(castToSlab(slab)->getIterator()));
}

BridgedSlab PassContext_getPreviousSlab(BridgedSlab slab) {
  return toBridgedSlab(&*std::prev(castToSlab(slab)->getIterator()));
}

BridgedSlab PassContext_allocSlab(BridgedPassContext passContext,
                                  BridgedSlab afterSlab) {
  auto *inv = castToPassInvocation(passContext);
  return toBridgedSlab(inv->allocSlab(castToSlab(afterSlab)));
}

BridgedSlab PassContext_freeSlab(BridgedPassContext passContext,
                                 BridgedSlab slab) {
  auto *inv = castToPassInvocation(passContext);
  return toBridgedSlab(inv->freeSlab(castToSlab(slab)));
}

void PassContext_notifyChanges(BridgedPassContext passContext,
                               enum ChangeNotificationKind changeKind) {
  SwiftPassInvocation *inv = castToPassInvocation(passContext);
  switch (changeKind) {
  case instructionsChanged:
    inv->notifyChanges(SILAnalysis::InvalidationKind::Instructions);
    break;
  case callsChanged:
    inv->notifyChanges(SILAnalysis::InvalidationKind::CallsAndInstructions);
    break;
  case branchesChanged:
    inv->notifyChanges(SILAnalysis::InvalidationKind::BranchesAndInstructions);
    break;
  }
}

void PassContext_eraseInstruction(BridgedPassContext passContext,
                                  BridgedInstruction inst) {
  castToPassInvocation(passContext)->eraseInstruction(castToInst(inst));
}

void PassContext_fixStackNesting(BridgedPassContext passContext,
                                 BridgedFunction function) {
  switch (StackNesting::fixNesting(castToFunction(function))) {
    case StackNesting::Changes::None:
      break;
    case StackNesting::Changes::Instructions:
      PassContext_notifyChanges(passContext, instructionsChanged);
      break;
    case StackNesting::Changes::CFG:
      PassContext_notifyChanges(passContext, branchesChanged);
      break;
  }
}

BridgedAliasAnalysis PassContext_getAliasAnalysis(BridgedPassContext context) {
  SwiftPassInvocation *invocation = castToPassInvocation(context);
  SILPassManager *pm = invocation->getPassManager();
  return {pm->getAnalysis<AliasAnalysis>(invocation->getFunction())};
}

BridgedCalleeAnalysis
PassContext_getCalleeAnalysis(BridgedPassContext context) {
  SILPassManager *pm = castToPassInvocation(context)->getPassManager();
  return {pm->getAnalysis<BasicCalleeAnalysis>()};
}

BridgedDeadEndBlocksAnalysis
PassContext_getDeadEndBlocksAnalysis(BridgedPassContext context) {
  SwiftPassInvocation *invocation = castToPassInvocation(context);
  SILPassManager *pm = invocation->getPassManager();
  return {pm->getAnalysis<DeadEndBlocksAnalysis>(invocation->getFunction())};
}

BridgedDomTree PassContext_getDomTree(BridgedPassContext context) {
  SwiftPassInvocation *invocation = castToPassInvocation(context);
  SILPassManager *pm = invocation->getPassManager();
  return {pm->getAnalysis<DominanceAnalysis>(invocation->getFunction())};
}

SwiftInt DominatorTree_dominates(BridgedDomTree domTree,
                                 BridgedBasicBlock dominating,
                                 BridgedBasicBlock dominated) {
  DominanceInfo *di = static_cast<DominanceInfo *>(domTree.dt);
  return di->dominates(castToBasicBlock(dominating), castToBasicBlock(dominated)) ? 1 : 0;
}

BridgedPostDomTree PassContext_getPostDomTree(BridgedPassContext context) {
  SwiftPassInvocation *invocation = castToPassInvocation(context);
  SILPassManager *pm = invocation->getPassManager();
  return {pm->getAnalysis<PostDominanceAnalysis>(invocation->getFunction())};
}

SwiftInt PostDominatorTree_postDominates(BridgedPostDomTree pdomTree,
                                         BridgedBasicBlock dominating,
                                         BridgedBasicBlock dominated) {
  auto *pdi = static_cast<PostDominanceInfo *>(pdomTree.pdt);
  return pdi->dominates(castToBasicBlock(dominating), castToBasicBlock(dominated)) ? 1 : 0;
}

BridgedBasicBlockSet PassContext_allocBasicBlockSet(BridgedPassContext context) {
  return {castToPassInvocation(context)->allocBlockSet()};
}

void PassContext_freeBasicBlockSet(BridgedPassContext context,
                                   BridgedBasicBlockSet set) {
  castToPassInvocation(context)->freeBlockSet(castToBlockSet(set));
}

SwiftInt BasicBlockSet_contains(BridgedBasicBlockSet set, BridgedBasicBlock block) {
  return castToBlockSet(set)->contains(castToBasicBlock(block)) ? 1 : 0;
}

void BasicBlockSet_insert(BridgedBasicBlockSet set, BridgedBasicBlock block) {
  castToBlockSet(set)->insert(castToBasicBlock(block));
}

void BasicBlockSet_erase(BridgedBasicBlockSet set, BridgedBasicBlock block) {
  castToBlockSet(set)->erase(castToBasicBlock(block));
}

BridgedFunction BasicBlockSet_getFunction(BridgedBasicBlockSet set) {
  return {castToBlockSet(set)->getFunction()};
}

void AllocRefInstBase_setIsStackAllocatable(BridgedInstruction arb) {
  castToInst<AllocRefInstBase>(arb)->setStackAllocatable();
}

BridgedSubstitutionMap
PassContext_getContextSubstitutionMap(BridgedPassContext context,
                                      BridgedType bridgedType) {
  auto type = castToSILType(bridgedType);
  auto *ntd = type.getASTType()->getAnyNominal();
  auto *pm = castToPassInvocation(context)->getPassManager();
  auto *m = pm->getModule()->getSwiftModule();

  return {type.getASTType()->getContextSubstitutionMap(m, ntd).getOpaqueValue()};
}


text:
import {
  ComponentsProps,
  ComponentsOverrides,
  ComponentsVariants,
  Theme as MuiTheme,
} from '@mui/material/styles';

type Theme = Omit<MuiTheme, 'components'>;

// shut off automatic exporting for the `Theme` above
export {};

export interface LabComponents {
  MuiLoadingButton?: {
    defaultProps?: ComponentsProps['MuiLoadingButton'];
    styleOverrides?: ComponentsOverrides<Theme>['MuiLoadingButton'];
    variants?: ComponentsVariants['MuiLoadingButton'];
  };
  MuiTabList?: {
    defaultProps?: ComponentsProps['MuiTabList'];
    styleOverrides?: ComponentsOverrides<Theme>['MuiTabList'];
    variants?: ComponentsVariants['MuiTabList'];
  };
  MuiTabPanel?: {
    defaultProps?: ComponentsProps['MuiTabPanel'];
    styleOverrides?: ComponentsOverrides<Theme>['MuiTabPanel'];
    variants?: ComponentsVariants['MuiTabPanel'];
  };
  MuiTimeline?: {
    defaultProps?: ComponentsProps['MuiTimeline'];
    styleOverrides?: ComponentsOverrides<Theme>['MuiTimeline'];
    variants?: ComponentsVariants['MuiTimeline'];
  };
  MuiTimelineConnector?: {
    defaultProps?: ComponentsProps['MuiTimelineConnector'];
    styleOverrides?: ComponentsOverrides<Theme>['MuiTimelineConnector'];
    variants?: ComponentsVariants['MuiTimelineConnector'];
  };
  MuiTimelineContent?: {
    defaultProps?: ComponentsProps['MuiTimelineContent'];
    styleOverrides?: ComponentsOverrides<Theme>['MuiTimelineContent'];
    variants?: ComponentsVariants['MuiTimelineContent'];
  };
  MuiTimelineDot?: {
    defaultProps?: ComponentsProps['MuiTimelineDot'];
    styleOverrides?: ComponentsOverrides<Theme>['MuiTimelineDot'];
    variants?: ComponentsVariants['MuiTimelineDot'];
  };
  MuiTimelineItem?: {
    defaultProps?: ComponentsProps['MuiTimelineItem'];
    styleOverrides?: ComponentsOverrides<Theme>['MuiTimelineItem'];
    variants?: ComponentsVariants['MuiTimelineItem'];
  };
  MuiTimelineOppositeContent?: {
    defaultProps?: ComponentsProps['MuiTimelineOppositeContent'];
    styleOverrides?: ComponentsOverrides<Theme>['MuiTimelineOppositeContent'];
    variants?: ComponentsVariants['MuiTimelineOppositeContent'];
  };
  MuiTimelineSeparator?: {
    defaultProps?: ComponentsProps['MuiTimelineSeparator'];
    styleOverrides?: ComponentsOverrides<Theme>['MuiTimelineSeparator'];
    variants?: ComponentsVariants['MuiTimelineSeparator'];
  };
  MuiTreeItem?: {
    defaultProps?: ComponentsProps['MuiTreeItem'];
    styleOverrides?: ComponentsOverrides<Theme>['MuiTreeItem'];
    variants?: ComponentsVariants['MuiTreeItem'];
  };
  MuiTreeView?: {
    defaultProps?: ComponentsProps['MuiTreeView'];
    styleOverrides?: ComponentsOverrides<Theme>['MuiTreeView'];
    variants?: ComponentsVariants['MuiTreeView'];
  };
}

declare module '@mui/material/styles' {
  interface Components extends LabComponents {}
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>
  <link href="https://fonts.googleapis.com/css?family=Arimo" rel="stylesheet">
  <link rel="stylesheet" href="css/styles.css">


text:
var expect = require('chai').expect;
require('./../dist/dig').init();

describe('dig.js - obtrusive', function () {
  it('should return the value for an existing key', function () {
    var value = 'something';
    var here = {
      is: {
        a: {
          nested: value
        }
      }
    };

    expect(here.dig('is', 'a', 'nested')).to.equal(value);
  });

  it('should return null for a non-existant key', function () {
    var here = {};

    expect(here.dig('is', 'a', 'fake', 'key')).to.equal(null);
  });
})