text:
package org.apache.sysds.runtime.io;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.sysds.conf.ConfigurationManager;
import org.apache.sysds.hops.OptimizerUtils;
import org.apache.sysds.runtime.DMLRuntimeException;
import org.apache.sysds.runtime.data.SparseRowVector;
import org.apache.sysds.runtime.matrix.data.MatrixBlock;
import org.apache.sysds.runtime.util.CommonThreadPool;

public class ReaderTextLIBSVMParallel extends MatrixReader {
	private static FileFormatPropertiesLIBSVM _props;
	private int _numThreads = 1;
	private SplitOffsetInfos _offsets = null;

	public ReaderTextLIBSVMParallel(FileFormatPropertiesLIBSVM props) {
		_numThreads = OptimizerUtils.getParallelTextReadParallelism();
		_props = props;
	}

	@Override
	public MatrixBlock readMatrixFromHDFS(String fname, long rlen, long clen,
			int blen, long estnnz)
		throws IOException, DMLRuntimeException
	{
		// prepare file access
		JobConf job = new JobConf(ConfigurationManager.getCachedJobConf());
		Path path = new Path(fname);
		FileSystem fs = IOUtilFunctions.getFileSystem(path, job);

		FileInputFormat.addInputPath(job, path);
		TextInputFormat informat = new TextInputFormat();
		informat.configure(job);

		InputSplit[] splits = informat.getSplits(job, _numThreads);
		splits = IOUtilFunctions.sortInputSplits(splits);

		// check existence and non-empty file
		checkValidInputFile(fs, path);

		// allocate output matrix block
		// First Read Pass (count rows/cols, determine offsets, allocate matrix block)
		MatrixBlock ret = computeLIBSVMSizeAndCreateOutputMatrixBlock(splits, path, job, rlen, clen, estnnz);
		rlen = ret.getNumRows();
		clen = ret.getNumColumns();

		// Second Read Pass (read, parse strings, append to matrix block)
		readLIBSVMMatrixFromHDFS(splits, path, job, ret, rlen, clen, blen);

		//post-processing (representation-specific, change of sparse/dense block representation)
		// - nnz explicitly maintained in parallel for the individual splits
		ret.examSparsity();

		// sanity check for parallel row count (since determined internally)
		if (rlen >= 0 && rlen != ret.getNumRows())
			throw new DMLRuntimeException("Read matrix inconsistent with given meta data: "
					+ "expected nrow="+ rlen + ", real nrow=" + ret.getNumRows());

		return ret;
	}

	@Override
	public MatrixBlock readMatrixFromInputStream(InputStream is, long rlen, long clen, int blen, long estnnz)
		throws IOException, DMLRuntimeException
	{
		//not implemented yet, fallback to sequential reader
		return new ReaderTextLIBSVM(_props).readMatrixFromInputStream(is, rlen, clen, blen, estnnz);
	}

	private void readLIBSVMMatrixFromHDFS(InputSplit[] splits, Path path, JobConf job,
			MatrixBlock dest, long rlen, long clen, int blen)
		throws IOException
	{
		FileInputFormat.addInputPath(job, path);
		TextInputFormat informat = new TextInputFormat();
		informat.configure(job);

		ExecutorService pool = CommonThreadPool.get(_numThreads);

		try
		{
			// create read tasks for all splits
			ArrayList<LIBSVMReadTask> tasks = new ArrayList<>();
			int splitCount = 0;
			for (InputSplit split : splits) {
				tasks.add( new LIBSVMReadTask(split, _offsets, informat, job, dest, rlen, clen, splitCount++) );
			}
			pool.invokeAll(tasks);
			pool.shutdown();

			// check return codes and aggregate nnz
			long lnnz = 0;
			for (LIBSVMReadTask rt : tasks) {
				lnnz += rt.getPartialNnz();
				if (!rt.getReturnCode()) {
					Exception err = rt.getException();
					throw new IOException("Read task for libsvm input failed: "+ err.toString(), err);
				}
			}
			dest.setNonZeros(lnnz);
		}
		catch (Exception e) {
			throw new IOException("Threadpool issue, while parallel read.", e);
		}
	}

	private MatrixBlock computeLIBSVMSizeAndCreateOutputMatrixBlock(InputSplit[] splits, Path path,
			JobConf job, long rlen, long clen, long estnnz)
		throws IOException, DMLRuntimeException
	{
		int nrow = 0;
		int ncol = (int) clen;

		FileInputFormat.addInputPath(job, path);
		TextInputFormat informat = new TextInputFormat();
		informat.configure(job);

		// count rows in parallel per split
		try
		{
			ExecutorService pool = CommonThreadPool.get(_numThreads);
			ArrayList<CountRowsTask> tasks = new ArrayList<>();
			for (InputSplit split : splits) {
				tasks.add(new CountRowsTask(split, informat, job));
			}
			pool.invokeAll(tasks);
			pool.shutdown();

			// collect row counts for offset computation
			// early error notify in case not all tasks successful
			_offsets = new SplitOffsetInfos(tasks.size());
			for (CountRowsTask rt : tasks) {
				if (!rt.getReturnCode())
					throw new IOException("Count task for libsvm input failed: "+ rt.getErrMsg());
				_offsets.setOffsetPerSplit(tasks.indexOf(rt), nrow);
				_offsets.setLenghtPerSplit(tasks.indexOf(rt), rt.getRowCount());
				nrow = nrow + rt.getRowCount();
			}
		}
		catch (Exception e) {
			throw new IOException("Threadpool Error " + e.getMessage(), e);
		}

		//robustness for wrong dimensions which are already compiled into the plan
		if( (rlen != -1 && nrow != rlen) || (clen != -1 && ncol != clen) ) {
			String msg = "Read matrix dimensions differ from meta data: ["+nrow+"x"+ncol+"] vs. ["+rlen+"x"+clen+"].";
			if( rlen < nrow || clen < ncol ) {
				//a) specified matrix dimensions too small
				throw new DMLRuntimeException(msg);
			}
			else {
				//b) specified matrix dimensions too large -> padding and warning
				LOG.warn(msg);
				nrow = (int) rlen;
				ncol = (int) clen;
			}
		}

		// allocate target matrix block based on given size;
		// need to allocate sparse as well since lock-free insert into target
		long estnnz2 = (estnnz < 0) ? (long)nrow * ncol : estnnz;
		return createOutputMatrixBlock(nrow, ncol, nrow, estnnz2, true, true);
	}

	private static class SplitOffsetInfos {
		// offset & length info per split
		private int[] offsetPerSplit = null;
		private int[] lenghtPerSplit = null;

		public SplitOffsetInfos(int numSplits) {
			lenghtPerSplit = new int[numSplits];
			offsetPerSplit = new int[numSplits];
		}

		public int getLenghtPerSplit(int split) {
			return lenghtPerSplit[split];
		}

		public void setLenghtPerSplit(int split, int r) {
			lenghtPerSplit[split] = r;
		}

		public int getOffsetPerSplit(int split) {
			return offsetPerSplit[split];
		}

		public void setOffsetPerSplit(int split, int o) {
			offsetPerSplit[split] = o;
		}
	}

	private static class CountRowsTask implements Callable<Object>
	{
		private InputSplit _split = null;
		private TextInputFormat _informat = null;
		private JobConf _job = null;
		private boolean _rc = true;
		private String _errMsg = null;
		private int _nrows = -1;

		public CountRowsTask(InputSplit split, TextInputFormat informat, JobConf job) {
			_split = split;
			_informat = informat;
			_job = job;
			_nrows = 0;
		}

		public boolean getReturnCode() {
			return _rc;
		}

		public int getRowCount() {
			return _nrows;
		}

		public String getErrMsg() {
			return _errMsg;
		}

		@Override
		public Object call()
			throws Exception
		{
			RecordReader<LongWritable, Text> reader = _informat.getRecordReader(_split, _job, Reporter.NULL);
			LongWritable key = new LongWritable();
			Text oneLine = new Text();

			try {
				// count rows from the first row
				while (reader.next(key, oneLine)) {
					_nrows++;
				}
			}
			catch (Exception e) {
				_rc = false;
				_errMsg = "RecordReader error libsvm format. split: "+ _split.toString() + e.getMessage();
				throw new IOException(_errMsg);
			}
			finally {
				IOUtilFunctions.closeSilently(reader);
			}

			return null;
		}
	}

	private static class LIBSVMReadTask implements Callable<Object>
	{
		private InputSplit _split = null;
		private SplitOffsetInfos _splitoffsets = null;
		private TextInputFormat _informat = null;
		private JobConf _job = null;
		private MatrixBlock _dest = null;
		private long _clen = -1;
		private int _splitCount = 0;

		private boolean _rc = true;
		private Exception _exception = null;
		private long _nnz;

		public LIBSVMReadTask(InputSplit split, SplitOffsetInfos offsets,
				TextInputFormat informat, JobConf job, MatrixBlock dest,
				long rlen, long clen, int splitCount)
		{
			_split = split;
			_splitoffsets = offsets;
			_informat = informat;
			_job = job;
			_dest = dest;
			_clen = clen;
			_rc = true;
			_splitCount = splitCount;
		}

		public boolean getReturnCode() {
			return _rc;
		}

		public Exception getException() {
			return _exception;
		}

		public long getPartialNnz() {
			return _nnz;
		}

		@Override
		public Object call()
			throws Exception
		{
			long lnnz = 0;

			try
			{
				RecordReader<LongWritable, Text> reader = _informat.getRecordReader(_split, _job, Reporter.NULL);
				LongWritable key = new LongWritable();
				Text value = new Text();
				SparseRowVector vect = new SparseRowVector(1024);

				int row = _splitoffsets.getOffsetPerSplit(_splitCount);

				try {
					while (reader.next(key, value)) { // foreach line
						String rowStr = value.toString().trim();
						lnnz += ReaderTextLIBSVM
							.parseLibsvmRow(rowStr, vect, (int) _clen, _props.getDelim(), _props.getIndexDelim());
						_dest.appendRow(row, vect);
						row++;
					}

					// sanity checks (number of rows)
					if (row != (_splitoffsets.getOffsetPerSplit(_splitCount) + _splitoffsets.getLenghtPerSplit(_splitCount)) ) {
						throw new IOException(
							"Incorrect number of rows (" + row + ") found in delimited file (" + (_splitoffsets
								.getOffsetPerSplit(_splitCount) + _splitoffsets
								.getLenghtPerSplit(_splitCount)) + "): " + value);
					}
				}
				finally {
					IOUtilFunctions.closeSilently(reader);
				}
			}
			catch (Exception ex) {
				// central error handling (return code, message)
				_rc = false;
				_exception = ex;
			}

			//post processing
			_nnz = lnnz;
			return null;
		}
	}
}


text:
package game;

import entities.Bullet;
import entities.Explosion;
import entities.Player;
import entities.enemy.Asteroid;
import entities.enemy.BigAsteroid;
import entities.enemy.Enemy;
import entities.enemy.Saucer;
import graphics.Background;
import graphics.Layer;
import java.util.HashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.newdawn.slick.*;
import org.newdawn.slick.font.effects.ColorEffect;
import org.newdawn.slick.font.effects.OutlineEffect;

/**
 * Main class for game, keeps track of viewport and game objects
 * @author Rasmus Larsson
 */
public class AceOfSpace extends BasicGame {
    private int gameTime;
    private CopyOnWriteArrayList<Enemy> enemies;
    private CopyOnWriteArrayList<Explosion> explosions;
    private Background background;
    private Music music;
    private Player player;
    private State state;
    private HashMap<String,UnicodeFont> fonts;

    public AceOfSpace() throws SlickException {
        super("Ace of Space");

        background = new Background();
    }

    public Background getBackground() {
        return background;
    }

    public CopyOnWriteArrayList<Enemy> getEnemies() {
        return enemies;
    }

    public CopyOnWriteArrayList<Explosion> getExplosions() {
        return explosions;
    }

    public UnicodeFont getFont(String index) {
        return fonts.get(index);
    }

    public int getGameTime() {
        return gameTime;
    }

    public Music getMusic() {
        return music;
    }

    public Player getPlayer() {
        return player;
    }

    public State getState() {
        return state;
    }

    /**
     * Resets the game state and initiates game variables
     * @param gc
     * @throws SlickException
     */
    @Override
    public void init(GameContainer gc) throws SlickException {
        getBackground().addLayer(new Layer("graphics/bg.png", 0.05f));
        getBackground().addLayer(new Layer("graphics/stars.png", 0.08f));
        setMusic(new Music("music/DefconZero.ogg"));
        getMusic().loop();

        HashMap<String, UnicodeFont> fonts = new HashMap<>();

        fonts.put("small", new UnicodeFont("graphics/apache.ttf", 32, false, false));
        fonts.put("large", new UnicodeFont("graphics/apache.ttf", 84, false, false));

        for (UnicodeFont font : fonts.values()) {
            font.addAsciiGlyphs();
            font.getEffects().add(new ColorEffect(java.awt.Color.white));
            font.getEffects().add(new OutlineEffect(font.getSpaceWidth() / 8, java.awt.Color.gray));
            font.loadGlyphs();
        }

        setFonts(fonts);
        gc.setDefaultFont(fonts.get("small"));
        gc.setShowFPS(false);

        startNewGame(gc);
    }

    /**
     * Method used for default game state, called on every logic update
     * @param gc
     * @param delta
     * @throws SlickException
     */
    public void play(GameContainer gc, int delta) throws SlickException {
        getPlayer().incrementScore(delta / 100f);
        setGameTime(getGameTime() + delta);

        if (Math.random() < 0.05) {
            enemies.add(new Asteroid(gc));
        }

        if (Math.random() < 0.01) {
            enemies.add(new BigAsteroid(gc));
        }

        if (getGameTime() > 10000 && Math.random() < 0.005) {
            getEnemies().add(new Saucer(gc));
        }

        for (Enemy e : enemies) {
            e.update(gc, delta, player);

            if (e.outsideOfScreen(gc)) {
                getEnemies().remove(e);
            }

            for (Bullet b : player.getBullets()) {
                if (e.intersects(b)) {
                    getPlayer().incrementScore(e.getScore());
                    getEnemies().remove(e);
                    getPlayer().getBullets().remove(b);
                    getExplosions().add(new Explosion(b.getX(), b.getY(), 100));

                    Sound sound = new Sound("sound/explosion.wav");

                    sound.play();

                    if (e instanceof BigAsteroid) {
                        enemies.add(new Asteroid(gc, e.getX(), e.getY(), -2));
                        enemies.add(new Asteroid(gc, e.getX(), e.getY(), 0));
                        enemies.add(new Asteroid(gc, e.getX(), e.getY(), 2));
                    }
                }
            }

            if (e.intersects(player)) {
                Sound sound = new Sound("sound/gameOver.wav");

                sound.play();
                setState(State.GAME_OVER);
            }
        }

        for (Explosion ex : getExplosions()) {
            ex.update(gc, delta);

            if (ex.getTime() < 0) {
                getExplosions().remove(ex);
            }
        }

        if (gc.getInput().isKeyPressed(Input.KEY_SPACE)) {
            getMusic().pause();
            setState(State.PAUSED);
        }

        if (!gc.hasFocus()) {
            setState(State.FROZEN);
        }

        getPlayer().update(gc, delta);
        getBackground().update(gc, delta);
    }

    /**
     * Renders viewport, agnostic to game state except for Game Over
     * @param gc
     * @param g
     * @throws SlickException
     */
    @Override
    public void render(GameContainer gc, Graphics g) throws SlickException {
        getBackground().render(gc, g);

        for (Enemy e : enemies) {
            e.render(gc, g);
        }

        for (Explosion e : explosions) {
            e.render(gc, g);
        }

        getPlayer().render(gc, g);

        String infoText = "Score: " + getPlayer().getScore();
        getFont("small").drawString(10, 10, infoText);

        switch (state) {
            case GAME_OVER:
                String title = "Game Over";
                String subtitle = "Press space to restart";

                getFont("large").drawString(
                        gc.getWidth() / 2 - getFont("large").getWidth(title) / 2,
                        gc.getHeight() / 2 - 60,
                        title
                    );

                getFont("small").drawString(
                        gc.getWidth() / 2 - getFont("small").getWidth(subtitle) / 2,
                        gc.getHeight() / 2 + 20,
                        subtitle
                    );

                break;
        }
    }

    public void startNewGame(GameContainer gc) throws SlickException {
        setEnemies(new CopyOnWriteArrayList<Enemy>());
        setExplosions(new CopyOnWriteArrayList<Explosion>());
        setPlayer(new Player(gc));
        setGameTime(0);
        setState(State.PLAYING);
    }

    public void setEnemies(CopyOnWriteArrayList<Enemy> enemies) {
        this.enemies = enemies;
    }

    public void setExplosions(CopyOnWriteArrayList<Explosion> explosions) {
        this.explosions = explosions;
    }

    public void setFonts(HashMap<String, UnicodeFont> fonts) {
        this.fonts = fonts;
    }

    public void setGameTime(int gameTime) {
        this.gameTime = gameTime;
    }

    public void setMusic(Music music) {
        this.music = music;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }

    public void setState(State state) {
        this.state = state;
    }

    /**
     * Main logic update method, executes different game states
     * @param gc
     * @param delta
     * @throws SlickException
     */
    @Override
    public void update(GameContainer gc, int delta) throws SlickException {
        if (gc.getInput().isKeyDown(Input.KEY_F)) {
            gc.setFullscreen(!gc.isFullscreen());
        }

        switch (state) {
            case GAME_OVER:
                if (gc.getInput().isKeyPressed(Input.KEY_SPACE)) {
                    startNewGame(gc);
                }

                break;
            case PAUSED:
                if (gc.getInput().isKeyPressed(Input.KEY_SPACE)) {
                    getMusic().resume();
                    setState(State.PLAYING);
                }

                break;
            case PLAYING:
                play(gc, delta);

                break;
            case MENU:
                break;
            case FROZEN:
                if (gc.hasFocus()) {
                    setState(State.PLAYING);
                }

                break;
        }
    }

    public static void main(String[] args) throws SlickException {
        AppGameContainer app = new AppGameContainer(new AceOfSpace());

        app.setDisplayMode(800, 600, false);
        app.setMinimumLogicUpdateInterval(10);
        app.setMaximumLogicUpdateInterval(30);
        app.start();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package config

import "github.com/btracey/su2tools/config/common"

// This file is autogenerated using github.com/btracey/su2tools/config_writer/parser/write_options_structs.go based on the output from parse_config.py

// Options is a struct containing all of the possible options in SU^2
type Options struct {
	// Adjoint type
	RegimeType common.Enum
	// Write extra output
	ExtraOutput bool
	// Physical governing equations
	PhysicalProblem common.Enum
	// Mathematical problem
	MathProblem common.Enum
	// Specify turbulence model
	KindTurbModel common.Enum
	// Specify transition model
	KindTransModel common.Enum
	// Axisymmetric simulation
	Axisymmetric bool
	// Add the gravity force
	GravityForce bool
	// Perform a low fidelity simulation
	LowFidelitySimulation bool
	// Restart solution from native solution file
	RestartSol bool
	// Write a tecplot file for each partition
	VisualizePart bool
	// Marker(s) of the surface in the surface flow solution file
	MarkerPlotting string
	// Marker(s) of the surface where evaluate the non-dimensional coefficients
	MarkerMonitoring string
	// Marker(s) of the surface where objective function (design problem) will be evaluated
	MarkerDesigning string
	// Euler wall boundary marker(s)
	MarkerEuler string
	// Far-field boundary marker(s)
	MarkerFar string
	// Symmetry boundary condition
	MarkerSym string
	// Symmetry boundary condition
	MarkerPressure string
	// Near-Field boundary condition
	MarkerNearfield string
	// Zone interface boundary marker(s)
	MarkerInterface string
	// Dirichlet boundary marker(s)
	MarkerDirichlet string
	// Neumann boundary marker(s)
	MarkerNeumann string
	// poisson dirichlet boundary marker(s)
	ElecDirichlet string
	// poisson neumann boundary marker(s)
	ElecNeumann string
	// Custom boundary marker(s)
	MarkerCustom string
	// No description
	MarkerPeriodic string
	// Inlet boundary type
	InletType common.Enum
	// No description
	MarkerInlet string
	// No description
	MarkerSupersonicInlet string
	// No description
	MarkerOutlet string
	// No description
	MarkerIsothermal string
	// No description
	MarkerHeatflux string
	// No description
	MarkerNacelleInflow string
	// Engine subsonic intake region
	SubsonicNacelleInflow bool
	// No description
	MarkerNacelleExhaust string
	// Displacement boundary marker(s)
	MarkerNormalDispl string
	// Load boundary marker(s)
	MarkerNormalLoad string
	// Flow load boundary marker(s)
	MarkerFlowload string
	// Damping factor for engine inlet condition
	DampNacelleInflow float64
	// Kind of grid adaptation
	KindAdapt common.Enum
	// Percentage of new elements (% of the original number of elements)
	NewElems float64
	// Scale factor for the dual volume
	DualvolPower float64
	// Use analytical definition for surfaces
	AnalyticalSurfdef common.Enum
	// Before each computation, implicitly smooth the nodal coordinates
	SmoothGeometry bool
	// Adapt the boundary elements
	AdaptBoundary bool
	// Divide rectangles into triangles
	DivideElements bool
	// Unsteady simulation
	UnsteadySimulation common.Enum
	// Unsteady farfield boundaries
	UnsteadyFarfield bool
	// Courant-Friedrichs-Lewy condition of the finest grid
	CflNumber float64
	// No description
	CflRamp []float64
	// Reduction factor of the CFL coefficient in the adjoint problem
	AdjCflReduction float64
	// Reduction factor of the CFL coefficient in the level set problem
	TurbCflReduction float64
	// Reduction factor of the CFL coefficient in the turbulent adjoint problem
	AdjturbCflReduction float64
	// Number of total iterations
	ExtIter float64
	// Runge-Kutta alpha coefficients
	RkAlphaCoeff string
	// Time Step for dual time stepping simulations (s)
	UnstTimestep float64
	// Total Physical Time for dual time stepping simulations (s)
	UnstTime float64
	// Unsteady Courant-Friedrichs-Lewy number of the finest grid
	UnstCflNumber float64
	// Number of internal iterations (dual time method)
	UnstIntIter float64
	// Integer number of periodic time instances for Time Spectral
	TimeInstances float64
	// Iteration number to begin unsteady restarts (dual time method)
	UnstRestartIter float64
	// Starting direct solver iteration for the unsteady adjoint
	UnstAdjointIter float64
	// Time discretization
	TimeDiscreFlow common.Enum
	// Time discretization
	TimeDiscreTne2 common.Enum
	// Time discretization
	TimeDiscreAdjtne2 common.Enum
	// Time discretization
	TimeDiscreAdjlevelset common.Enum
	// Time discretization
	TimeDiscreAdj common.Enum
	// Time discretization
	TimeDiscreLin common.Enum
	// Time discretization
	TimeDiscreTurb common.Enum
	// Time discretization
	TimeDiscreAdjturb common.Enum
	// Time discretization
	TimeDiscreWave common.Enum
	// Time discretization
	TimeDiscreFea common.Enum
	// Time discretization
	TimeDiscreHeat common.Enum
	// Time discretization
	TimeDiscrePoisson common.Enum
	// Linear solver for the implicit, mesh deformation, or discrete adjoint systems
	LinearSolver common.Enum
	// Preconditioner for the Krylov linear solvers
	LinearSolverPrec common.Enum
	// Minimum error threshold for the linear solver for the implicit formulation
	LinearSolverError float64
	// Maximum number of iterations of the linear solver for the implicit formulation
	LinearSolverIter float64
	// Relaxation of the linear solver for the implicit formulation
	LinearSolverRelax float64
	// Roe-Turkel preconditioning for low Mach number flows
	RoeTurkelPrec bool
	// Time Step for dual time stepping simulations (s)
	MinRoeTurkelPrec float64
	// Time Step for dual time stepping simulations (s)
	MaxRoeTurkelPrec float64
	// Linear solver for the turbulent adjoint systems
	AdjturbLinSolver common.Enum
	// Preconditioner for the turbulent adjoint Krylov linear solvers
	AdjturbLinPrec common.Enum
	// Minimum error threshold for the turbulent adjoint linear solver for the implicit formulation
	AdjturbLinError float64
	// Maximum number of iterations of the turbulent adjoint linear solver for the implicit formulation
	AdjturbLinIter float64
	// Mesh motion for unsteady simulations
	GridMovement bool
	// Type of mesh motion
	GridMovementKind []string
	// Marker(s) of moving surfaces (MOVING_WALL or DEFORMING grid motion).
	MarkerMoving string
	// Mach number (non-dimensional, based on the mesh velocity and freestream vals.)
	MachMotion float64
	// Coordinates of the rigid motion origin
	MotionOriginX string
	// Coordinates of the rigid motion origin
	MotionOriginY string
	// Coordinates of the rigid motion origin
	MotionOriginZ string
	// Translational velocity vector (m/s) in the x, y, & z directions (RIGID_MOTION only)
	TranslationRateX string
	// Translational velocity vector (m/s) in the x, y, & z directions (RIGID_MOTION only)
	TranslationRateY string
	// Translational velocity vector (m/s) in the x, y, & z directions (RIGID_MOTION only)
	TranslationRateZ string
	// Angular velocity vector (rad/s) about x, y, & z axes (RIGID_MOTION only)
	RotationRateX string
	// Angular velocity vector (rad/s) about x, y, & z axes (RIGID_MOTION only)
	RotationRateY string
	// Angular velocity vector (rad/s) about x, y, & z axes (RIGID_MOTION only)
	RotationRateZ string
	// Pitching angular freq. (rad/s) about x, y, & z axes (RIGID_MOTION only)
	PitchingOmegaX string
	// Pitching angular freq. (rad/s) about x, y, & z axes (RIGID_MOTION only)
	PitchingOmegaY string
	// Pitching angular freq. (rad/s) about x, y, & z axes (RIGID_MOTION only)
	PitchingOmegaZ string
	// Pitching amplitude (degrees) about x, y, & z axes (RIGID_MOTION only)
	PitchingAmplX string
	// Pitching amplitude (degrees) about x, y, & z axes (RIGID_MOTION only)
	PitchingAmplY string
	// Pitching amplitude (degrees) about x, y, & z axes (RIGID_MOTION only)
	PitchingAmplZ string
	// Pitching phase offset (degrees) about x, y, & z axes (RIGID_MOTION only)
	PitchingPhaseX string
	// Pitching phase offset (degrees) about x, y, & z axes (RIGID_MOTION only)
	PitchingPhaseY string
	// Pitching phase offset (degrees) about x, y, & z axes (RIGID_MOTION only)
	PitchingPhaseZ string
	// Plunging angular freq. (rad/s) in x, y, & z directions (RIGID_MOTION only)
	PlungingOmegaX string
	// Plunging angular freq. (rad/s) in x, y, & z directions (RIGID_MOTION only)
	PlungingOmegaY string
	// Plunging angular freq. (rad/s) in x, y, & z directions (RIGID_MOTION only)
	PlungingOmegaZ string
	// Plunging amplitude (m) in x, y, & z directions (RIGID_MOTION only)
	PlungingAmplX string
	// Plunging amplitude (m) in x, y, & z directions (RIGID_MOTION only)
	PlungingAmplY string
	// Plunging amplitude (m) in x, y, & z directions (RIGID_MOTION only)
	PlungingAmplZ string
	// Value to move motion origins (1 or 0)
	MoveMotionOrigin string
	//
	MotionFilename string
	// Uncoupled Aeroelastic Frequency Plunge.
	FreqPlungeAeroelastic float64
	// Uncoupled Aeroelastic Frequency Pitch.
	FreqPitchAeroelastic float64
	// Apply a wind gust
	WindGust bool
	// Type of gust
	GustType common.Enum
	// Gust wavelenght (meters)
	GustWavelength float64
	// Number of gust periods
	GustPeriods float64
	// Gust amplitude (m/s)
	GustAmpl float64
	// Time at which to begin the gust (sec)
	GustBeginTime float64
	// Location at which the gust begins (meters)
	GustBeginLoc float64
	// Direction of the gust X or Y dir
	GustDir common.Enum
	// Convergence criteria
	ConvCriteria common.Enum
	// Residual reduction (order of magnitude with respect to the initial value)
	ResidualReduction float64
	// Min value of the residual (log10 of the residual)
	ResidualMinval float64
	// Iteration number to begin convergence monitoring
	StartconvIter float64
	// Number of elements to apply the criteria
	CauchyElems float64
	// Epsilon to control the series convergence
	CauchyEps float64
	// Flow functional for the Cauchy criteria
	CauchyFuncFlow common.Enum
	// Adjoint functional for the Cauchy criteria
	CauchyFuncAdj common.Enum
	// Linearized functional for the Cauchy criteria
	CauchyFuncLin common.Enum
	// Epsilon for a full multigrid method evaluation
	FullmgCauchyEps float64
	// Full multi-grid
	Fullmg bool
	// Start up iterations using the fine grid only
	StartUpIter float64
	// Multi-grid Levels
	Mglevel float64
	// Multi-grid Cycle (0 = V cycle, 1 = W Cycle)
	Mgcycle float64
	// Multi-grid pre-smoothing level
	MgPreSmooth string
	// Multi-grid post-smoothing level
	MgPostSmooth string
	// Jacobi implicit smoothing of the correction
	MgCorrectionSmooth string
	// Damping factor for the residual restriction
	MgDampRestriction float64
	// Damping factor for the correction prolongation
	MgDampProlongation float64
	// CFL reduction factor on the coarse levels
	MgCflReduction float64
	// Maximum number of children in the agglomeration stage
	MaxChildren float64
	// Maximum length of an agglomerated element (relative to the domain)
	MaxDimension float64
	// Numerical method for spatial gradients
	NumMethodGrad common.Enum
	// Coefficient for the limiter
	LimiterCoeff float64
	// Coefficient for detecting the limit of the sharp edges
	SharpEdgesCoeff float64
	// No description
	ConvNumMethodFlow common.Enum
	// Viscous numerical method
	ViscNumMethodFlow common.Enum
	// Source term numerical method
	SourNumMethodFlow common.Enum
	// Slope limiter
	SlopeLimiterFlow common.Enum
	// 1st, 2nd and 4th order artificial dissipation coefficients
	AdCoeffFlow []float64
	// No description
	ConvNumMethodAdj common.Enum
	// Viscous numerical method
	ViscNumMethodAdj common.Enum
	// Source term numerical method
	SourNumMethodAdj common.Enum
	// Slope limiter
	SlopeLimiterAdjflow common.Enum
	// 1st, 2nd and 4th order artificial dissipation coefficients
	AdCoeffAdj []float64
	// Slope limiter
	SlopeLimiterTurb common.Enum
	// Convective numerical method
	ConvNumMethodTurb common.Enum
	// Viscous numerical method
	ViscNumMethodTurb common.Enum
	// Source term numerical method
	SourNumMethodTurb common.Enum
	// Slope limiter
	SlopeLimiterAdjturb common.Enum
	// Convective numerical method
	ConvNumMethodAdjturb common.Enum
	// Viscous numerical method
	ViscNumMethodAdjturb common.Enum
	// Source term numerical method
	SourNumMethodAdjturb common.Enum
	// Convective numerical method
	ConvNumMethodLin common.Enum
	// Viscous numerical method
	ViscNumMethodLin common.Enum
	// Source term numerical method
	SourNumMethodLin common.Enum
	// 1st, 2nd and 4th order artificial dissipation coefficients
	AdCoeffLin []float64
	// Slope limiter
	SlopeLimiterAdjlevelset common.Enum
	// Convective numerical method
	ConvNumMethodAdjlevelset common.Enum
	// Viscous numerical method
	ViscNumMethodAdjlevelset common.Enum
	// Source term numerical method
	SourNumMethodAdjlevelset common.Enum
	// Convective numerical method
	ConvNumMethodTne2 common.Enum
	// Viscous numerical method
	ViscNumMethodTne2 common.Enum
	// Source term numerical method
	SourNumMethodTne2 common.Enum
	// Slope limiter
	SlopeLimiterTne2 common.Enum
	// 1st, 2nd and 4th order artificial dissipation coefficients
	AdCoeffTne2 []float64
	// Convective numerical method
	ConvNumMethodAdjtne2 common.Enum
	// Viscous numerical method
	ViscNumMethodAdjtne2 common.Enum
	// Source term numerical method
	SourNumMethodAdjtne2 common.Enum
	// Slope limiter
	SlopeLimiterAdjtne2 common.Enum
	// 1st, 2nd and 4th order artificial dissipation coefficients
	AdCoeffAdjtne2 []float64
	// Viscous numerical method
	ViscNumMethodWave common.Enum
	// Source term numerical method
	SourNumMethodWave common.Enum
	// Viscous numerical method
	ViscNumMethodPoisson common.Enum
	// Source term numerical method
	SourNumMethodPoisson common.Enum
	// Viscous numerical method
	ViscNumMethodFea common.Enum
	// Source term numerical method
	SourNumMethodFea common.Enum
	// Viscous numerical method
	ViscNumMethodHeat common.Enum
	// Source term numerical method
	SourNumMethodHeat common.Enum
	// Source term numerical method
	SourNumMethodTemplate common.Enum
	// Limit value for the adjoint variable
	AdjLimit float64
	// Adjoint problem boundary condition
	AdjObjfunc common.Enum
	// No description
	GeoSectionLimit []float64
	// Mode of the GDC code (analysis, or gradient)
	GeoMode common.Enum
	// Drag weight in sonic boom Objective Function (from 0.0 to 1.0)
	DragInSonicboom float64
	// Sensitivity smoothing
	SensSmoothing common.Enum
	// Continuous governing equation set
	ContinuousEqns common.Enum
	// Discrete governing equation set
	DiscreteEqns common.Enum
	// Adjoint frozen viscosity
	FrozenVisc bool
	//
	CteViscousDrag float64
	// Remove sharp edges from the sensitivity evaluation
	SensRemoveSharp bool
	// I/O
	OutputFormat common.Enum
	// Mesh input file format
	MeshFormat common.Enum
	// Convert a CGNS mesh to SU2 format
	CgnsToSu2 bool
	// Mesh input file
	MeshFilename string
	// Mesh output file
	MeshOutFilename string
	// Output file convergence history (w/o extension)
	ConvFilename string
	// Restart flow input file
	SolutionFlowFilename string
	// Restart flow input file
	FarfieldFilename string
	// Restart linear flow input file
	SolutionLinFilename string
	// Restart adjoint input file
	SolutionAdjFilename string
	// Output file restart flow
	RestartFlowFilename string
	// Output file linear flow
	RestartLinFilename string
	// Output file restart adjoint
	RestartAdjFilename string
	// Output file restart wave
	RestartWaveFilename string
	// Output file flow (w/o extension) variables
	VolumeFlowFilename string
	// Output file structure (w/o extension) variables
	VolumeStructureFilename string
	// Output file structure (w/o extension) variables
	SurfaceStructureFilename string
	// Output file structure (w/o extension) variables
	SurfaceWaveFilename string
	// Output file structure (w/o extension) variables
	SurfaceHeatFilename string
	// Output file wave (w/o extension) variables
	VolumeWaveFilename string
	// Output file wave (w/o extension) variables
	VolumeHeatFilename string
	// Output file adj. wave (w/o extension) variables
	VolumeAdjwaveFilename string
	// Output file adjoint (w/o extension) variables
	VolumeAdjFilename string
	// Output file linear (w/o extension) variables
	VolumeLinFilename string
	// Output objective function gradient
	GradObjfuncFilename string
	// Output objective function
	ValueObjfuncFilename string
	// Output file surface flow coefficient (w/o extension)
	SurfaceFlowFilename string
	// Output file surface adjoint coefficient (w/o extension)
	SurfaceAdjFilename string
	// Output file surface linear coefficient (w/o extension)
	SurfaceLinFilename string
	// Writing solution file frequency
	WrtSolFreq float64
	// Writing solution file frequency
	WrtSolFreqDualtime float64
	// Writing convergence history frequency
	WrtConFreq float64
	// Writing convergence history frequency for the dual time
	WrtConFreqDualtime float64
	// Write a volume solution file
	WrtVolSol bool
	// Write a surface solution file
	WrtSrfSol bool
	// Write a surface CSV solution file
	WrtCsvSol bool
	// Write a restart solution file
	WrtRestart bool
	// Output residual info to solution/restart file
	WrtResiduals bool
	// Output the rind layers in the solution files
	WrtHalo bool
	// Output sectional forces for specified markers.
	WrtSectionalForces bool
	// Evaluate equivalent area on the Near-Field
	EquivArea bool
	// Integration limits of the equivalent area ( xmin, xmax, Dist_NearField )
	EaIntLimit []float64
	// Specific gas constant (287.87 J/kg*K (air), only for compressible flows)
	GasConstant float64
	// Ratio of specific heats (1.4 (air), only for compressible flows)
	GammaValue float64
	// Reynolds number (non-dimensional, based on the free-stream values)
	ReynoldsNumber float64
	// Reynolds length (1 m by default)
	ReynoldsLength float64
	// Laminar Prandtl number (0.72 (air), only for compressible flows)
	PrandtlLam float64
	// Turbulent Prandtl number (0.9 (air), only for compressible flows)
	PrandtlTurb float64
	// Value of the Bulk Modulus
	BulkModulus float64
	// Artifical compressibility factor
	ArtcompFactor float64
	// Mach number (non-dimensional, based on the free-stream values)
	MachNumber float64
	// No description
	MixtureMolarMass float64
	// Free-stream pressure (101325.0 N/m^2 by default)
	FreestreamPressure float64
	// Free-stream density (1.2886 Kg/m^3 (air), 998.2 Kg/m^3 (water))
	FreestreamDensity float64
	// Free-stream temperature (273.15 K by default)
	FreestreamTemperature float64
	// Free-stream vibrational-electronic temperature (273.15 K by default)
	FreestreamTemperatureVe float64
	// Free-stream velocity (m/s)
	FreestreamVelocity []float64
	// Free-stream viscosity (1.853E-5 Ns/m^2 (air), 0.798E-3 Ns/m^2 (water))
	FreestreamViscosity float64
	//
	FreestreamIntermittency float64
	//
	FreestreamTurbulenceintensity float64
	//
	FreestreamNuFactor float64
	//
	FreestreamTurb2lamviscratio float64
	// Side-slip angle (degrees, only for compressible flows)
	SideslipAngle float64
	// Angle of attack (degrees, only for compressible flows)
	Aoa float64
	// X Reference origin for moment computation
	RefOriginMomentX string
	// Y Reference origin for moment computation
	RefOriginMomentY string
	// Z Reference origin for moment computation
	RefOriginMomentZ string
	// Reference area for force coefficients (0 implies automatic calculation)
	RefArea float64
	// Reference length for pitching, rolling, and yawing non-dimensional moment
	RefLengthMoment float64
	// Reference element length for computing the slope limiter epsilon
	RefElemLength float64
	// Reference coefficient for detecting sharp edges
	RefSharpEdges float64
	// Reference pressure (1.0 N/m^2 by default, only for compressible flows)
	RefPressure float64
	// Reference temperature (1.0 K by default, only for compressible flows)
	RefTemperature float64
	// Reference density (1.0 Kg/m^3 by default, only for compressible flows)
	RefDensity float64
	// Reference velocity (incompressible only)
	RefVelocity float64
	// Reference viscosity (incompressible only)
	RefViscosity float64
	// Factor for converting the grid to meters
	ConvertToMeter float64
	// Write a new mesh converted to meters
	WriteConvertedMesh bool
	// Specify chemical model for multi-species simulations
	GasModel common.Enum
	//
	GasComposition string
	// Ratio of density for two phase problems
	RatioDensity float64
	// Ratio of viscosity for two phase problems
	RatioViscosity float64
	// Location of the freesurface (y or z coordinate)
	FreesurfaceZero float64
	// Free surface depth surface (x or y coordinate)
	FreesurfaceDepth float64
	// Thickness of the interface in a free surface problem
	FreesurfaceThickness float64
	// Free surface damping coefficient
	FreesurfaceDampingCoeff float64
	// Free surface damping length (times the baseline wave)
	FreesurfaceDampingLength float64
	// Location of the free surface outlet surface (x or y coordinate)
	FreesurfaceOutlet float64
	// Kind of deformation
	DvKind []string
	// Marker of the surface to which we are going apply the shape deformation
	DvMarker string
	// New value of the shape deformation
	DvValue string
	// No description
	DvParam string
	// Hold the grid fixed in a region
	HoldGridFixed bool
	// Coordinates of the box where the grid will be deformed (Xmin, Ymin, Zmin, Xmax, Ymax, Zmax)
	HoldGridFixedCoord []float64
	// Visualize the deformation
	VisualizeDeformation bool
	// Number of iterations for FEA mesh deformation (surface deformation increments)
	GridDeformIter float64
	// No description
	CyclicPitch float64
	// No description
	CollectivePitch float64
	// Modulus of elasticity
	ElasticityModulus float64
	// Poisson ratio
	PoissonRatio float64
	// Material density
	MaterialDensity float64
	// Constant wave speed
	WaveSpeed float64
	// Thermal diffusivity constant
	ThermalDiffusivity float64
	// Location of the turb model itself
	MlTurbModelFile string
	// blah
	MlTurbModelFeatureset string
}


text:
using System;

namespace VacuumCleaner
{
#if WINDOWS || XBOX
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            using (VacuumCleanerMain game = new VacuumCleanerMain())
            {
                game.Run();
            }
        }
    }
#endif
}


text:
const CLI = require('../CLI');

function handleError(err) {
  console.log('Oops! Something went wrong.\n', err);
  process.exit(1);
}

process.on('uncaughtException', handleError);
process.on('unhandledRejection', handleError);

CLI.execute(process.argv).then(exitCode => {
  process.exitCode = exitCode;
});


text:
console.log('Service worker waking up! 😴 ');

self.addEventListener('install', event => {
  console.log('Service worker installed! 👍');
  skipWaiting();
});

self.addEventListener('activate', event => {
  console.log('Service worker activated! 😁');
});

self.addEventListener('fetch', event => {
  const path = event.request.url.split('http://localhost:8081')[1];
  console.log('Intercepted request for:', path);

  // if (path === '/images/sad.jpg') {
  //   console.log('Responding with tired.jpg instead of sad.jpg');
  //   event.respondWith(
  //     fetch('/images/tired.jpg')
  //   );
  // }

  event.respondWith(
    caches.open('my-cache').then(cache => {
      return cache.match(event.request)
        .then(response => {
          const fetchPromise = fetch(event.request)
            .then(networkResponse => {
              // clone the network response
              const responseToCache = networkResponse.clone();
              cache.put(event.request, responseToCache);
              return networkResponse;
            });
          return response || fetchPromise;
        });
    })
  );
});


text:
package pro.beam.minecraft.action.impl;

import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Player;

import pro.beam.interactive.net.packet.Protocol;
import pro.beam.minecraft.action.AbstractBukkitAction;

public class ChangeTimeAction extends AbstractBukkitAction {
    public ChangeTimeAction(Server server) {
        super(server);
    }

    @Override
    public void take(Protocol.Report report) {
        Player p = getPlayer();

        if (p == null) {
            return;
        }

        World w = p.getWorld();

        w.setTime(w.getTime() + 12000);

        StringBuffer buffer = new StringBuffer();
        buffer.append(ChatColor.GRAY);
        buffer.append(ChatColor.ITALIC);
        buffer.append("Changing Time Of Day!");

        getPlayer().sendMessage(buffer.toString());

    }
}


text:
namespace DotNetNuke.Modules.Reports.DataSources
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using Components;
    using global::DotNetNuke.Entities.Modules;
    using global::DotNetNuke.Modules.Reports.Converters;
    using global::DotNetNuke.Modules.Reports.Exceptions;

    /// <summary>
    ///     Base class for SQL-based Data Sources
    /// </summary>
    public abstract class SqlDataSourceBase : DataSourceBase
    {
        /// <summary>
        ///     Gets the key used to find the SQL Query in the Data Source Settings
        /// </summary>
        /// <value></value>
        /// <returns></returns>
        /// <remarks></remarks>
        protected virtual string QueryKey => ReportsConstants.SETTING_Query;

        public override DataView ExecuteReport(ReportInfo report,
                                               PortalModuleBase hostModule,
                                               IDictionary<string, object> inputParameters)
        {
            base.ExecuteReport(report, hostModule, inputParameters);

            // Load up the properties
            this.CurrentReport = report;
            this.HostModule = hostModule;
            this.Parameters = inputParameters;
            this.Converters = this.Converters;

            // Validate Query
            if (!report.DataSourceSettings.ContainsKey(this.QueryKey) ||
                string.IsNullOrEmpty(Convert.ToString(report.DataSourceSettings[this.QueryKey])))
            {
                if (ReferenceEquals(hostModule, null))
                {
                    return new DataView(new DataTable("QueryResults")); // Not hosted in a module, so fail silently
                }
                if (hostModule.UserInfo != null)
                {
                    if (hostModule.UserInfo.IsSuperUser)
                    {
                        throw new DataSourceNotConfiguredException(new LocalizedText("HostNoQuery.Error"),
                                                                   "There is no data source configured for this module, please configure one in the Module Settings page");
                    }
                    if (hostModule.IsEditable)
                    {
                        throw new DataSourceNotConfiguredException(new LocalizedText("AdminNoQuery.Error"),
                                                                   "There is no data source configured for this module, please contact your Host for assistance");
                    }
                }
                else
                {
                    throw new DataSourceNotConfiguredException(new LocalizedText("AnonNoQuery.Error"));
                }
            }

            // Execute the Query
            return this.ExecuteSQLReport();
        }

        /// <summary>
        ///     When overriden, executes the SQL-based report
        /// </summary>
        /// <returns>A <see cref="DataTable" /> containing the results</returns>
        /// <remarks>
        ///     The report, host module and input parameters can be accessed through
        ///     the <see cref="CurrentReport" />, <see cref="HostModule" />,
        ///     <see cref="Parameters" /> properties.
        /// </remarks>
        protected abstract DataView ExecuteSQLReport();

        /// <summary>
        ///     Validates that the specified setting exists AND has a non-empty value
        /// </summary>
        /// <param name="setting">The name of the setting to validate</param>
        /// <exception cref="RequiredSettingMissingException">
        ///     The setting was not found
        /// </exception>
        protected void ValidateRequiredReportSetting(string setting)
        {
            if (SettingsUtil.FieldIsNotSet(this.CurrentReport.DataSourceSettings, setting))
            {
                throw new RequiredSettingMissingException(setting, this.ExtensionContext);
            }
        }

        #region  Private Fields

        #endregion

        #region  Protected Properties

        protected ReportInfo CurrentReport { get; private set; }

        protected PortalModuleBase HostModule { get; private set; }

        protected IDictionary<string, object> Parameters { get; private set; }

        protected IDictionary<string, IList<ConverterInstanceInfo>> Converters { get; private set; }

        #endregion
    }
}


text:
> A UIViewController subclass a la UIImagePickerController for capturing multiple images in a single session.

[![Swift Version][swift-image]][swift-url]
[![Build Status][travis-image]][travis-url]
[![License][license-image]][license-url]
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/EZSwiftExtensions.svg)](https://img.shields.io/cocoapods/v/LFAlertController.svg)
[![Platform](https://img.shields.io/cocoapods/p/LFAlertController.svg?style=flat)](http://cocoapods.org/pods/LFAlertController)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)

One the limitations of UIImagePickerController is that you can't take multiple pictures in camera without dismissing and relaunching.
This implementation is a custom overlay on UIImagePickerController that lets you capture as many images as you desire.

<!--![](header.png)-->

## Features

- [x] Taking multiple images in a single session
- [x] Delegation pattern
- [x] Customizable

## Requirements

- iOS 9.0+
- Xcode 7.3+

## Installation

#### CocoaPods
You can use [CocoaPods](http://cocoapods.org/) to install `STCameraPicker` by adding it to your `Podfile`:

```ruby
platform :ios, '9.0'
use_frameworks!
pod 'STCameraPicker'
```

To get the full benefits import `STCameraPicker` wherever you import UIKit

``` swift
import UIKit
import STCameraPicker
```

<!--## Usage example

```objective-c
#import STCameraPicker
ez.detectScreenShot { () -> () in
    print("User took a screen shot")
}
```-->

## Contribute

We would love for you to contribute to **STCameraPicker**, check the ``LICENSE`` file for more info.

## Meta

Saeed Taheri – [@saeed_taheri](https://twitter.com/saeed_taheri) – saeed.taheri@gmail.com

Distributed under the MIT license. See ``LICENSE`` for more information.

[https://github.com/sdtaheri/STCameraPicker](https://github.com/sdtaheri/)

[swift-image]:https://img.shields.io/badge/swift-3.0-orange.svg
[swift-url]: https://swift.org/
[license-image]: https://img.shields.io/badge/License-MIT-blue.svg
[license-url]: LICENSE
[travis-image]: https://img.shields.io/travis/dbader/node-datadog-metrics/master.svg?style=flat-square
[travis-url]: https://travis-ci.org/dbader/node-datadog-metrics
[codebeat-image]: https://codebeat.co/badges/c19b47ea-2f9d-45df-8458-b2d952fe9dad
[codebeat-url]: https://codebeat.co/projects/github-com-vsouza-awesomeios-com


text:
import FileType = require('file-type');

declare function ImageType(buf: Buffer | Uint8Array): FileType.FileTypeResult | null;

export = ImageType;


text:
using System;

class ConvertFloatingPointToBinary
{
    public static string DoubleToBinaryString(double d)
    {
        return Convert.ToString(BitConverter.DoubleToInt64Bits(d), 2);
    }

    public static double BinaryStringToDouble(string s)
    {
        return BitConverter.Int64BitsToDouble(Convert.ToInt64(s, 2));
    }

    public static string SingleToBinaryString(float f)
    {
        byte[] b = BitConverter.GetBytes(f);
        int i = BitConverter.ToInt32(b, 0);
        return Convert.ToString(i, 2);
    }

    public static float BinaryStringToSingle(string s)
    {
        int i = Convert.ToInt32(s, 2);
        byte[] b = BitConverter.GetBytes(i);
        return BitConverter.ToSingle(b, 0);
    }

    static void Main()
    {
        double d1 = 1234.5678;
        string ds = DoubleToBinaryString(d1);
        double d2 = BinaryStringToDouble(ds);

        float f1 = 654.321f;
        string fs = SingleToBinaryString(f1);
        float f2 = BinaryStringToSingle(fs);
    }
}


text:
Android animator of view's height whether it is an item of RecyclerView or ListView or any regular view.

Key intents of that library are:

1. Fast (no layout steps, no onLayout(), no onMeasure() calls)

2. Loosely coupled, lightweight, minimal dependencies and ability to use with low level API

3. Animate any view whether it is a recyclerview's item or regular view

## Usage
It's just 2 classes:

a. VerticalClipLayout - add it to your xml

Control height with VerticalClipLayout.setClipCoef(0..1)

Clicks and drawing will be adjusted to provided coefficient. So you don't click an invisible element or get weird visual when animating.

b. ExpandCollapseAnimator - use it if you need to make common list behaviour:

while 1 item expands, all the other collapses.

ExpandCollapseAnimator.add(int position, VerticalClipLayout view) - adds view to processing

ExpandCollapseAnimator.remove(int position) - remove (for example, when view gone offscreen)

ExpandCollapseAnimator.setExpanding(int position) - to start expanding that view, all the other will start (or continue) collapsing

## RecyclerView Demo
You can find example code in project "app". If you run it on android device, you'll see a list of cards with different gradients (to simply distinguish them). When you click and item, it is expanded. Try it out.

![image](RecyclerViewDemo.png)

* RecyclerViewFragment - example code of how to setup ExpandCollapseAnimator library for RecyclerView

* RecyclerViewAdapter - adapter with example of how you can change item height programmatically

## License
It's free to use as long as you give credit to author.

Copyright 2014 Tokarev Mikhail (also known as Deepscorn)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
from __future__ import unicode_literals

import hashlib
import logging
import operator
import os
import os.path
import sqlite3
import time
import uritools

from mopidy import local
from mopidy.local import translator  # FIXME: undocumented Mopidy API
from mopidy.models import Ref, SearchResult

from . import Extension, schema

DBNAME = 'library.db'

logger = logging.getLogger(__name__)

class SQLiteLibrary(local.Library):

    ROOT_PATH_URI = 'local:directory:'

    name = 'sqlite'

    def __init__(self, config):
        self._config = ext_config = config[Extension.ext_name]
        self._dbpath = os.path.join(Extension.get_data_dir(config), DBNAME)
        self._media_dir = config['local']['media_dir']
        self._directories = []
        for line in ext_config['directories']:
            name, uri = line.rsplit(None, 1)
            ref = Ref.directory(uri=uri, name=name)
            self._directories.append(ref)
        if ext_config['extract_images']:
            from .images import ImageDirectory
            self._images = ImageDirectory(config)
        else:
            self._images = None
        self._connection = None

    def load(self):
        with self._connect() as connection:
            version = schema.load(connection)
            logger.info('Using SQLite database schema v%s', version)
            return schema.count_tracks(connection)

    def lookup(self, uri):
        return schema.lookup(self._connect(), uri)

    def browse(self, uri):
        try:
            if uri == self.ROOT_DIRECTORY_URI:
                return self._directories
            elif uri.startswith(self.ROOT_PATH_URI):
                return self._browse_directory_path(uri)
            elif uri.startswith('local:directory'):
                return self._browse_directory(uri)
            elif uri.startswith('local:artist'):
                return self._browse_artist(uri)
            elif uri.startswith('local:album'):
                return self._browse_album(uri)
            else:
                raise ValueError('Invalid browse URI')
        except Exception as e:
            logger.error('Error browsing %s: %s', uri, e)
            return []

    def search(self, query=None, limit=100, offset=0, uris=None, exact=False):
        q = []
        for field, values in (query.items() if query else []):
            if isinstance(values, basestring):
                q.append((field, values))
            else:
                q.extend((field, value) for value in values)
        filters = [f for uri in uris or [] for f in self._filters(uri) if f]
        with self._connect() as c:
            tracks = schema.search_tracks(c, q, limit, offset, exact, filters)
        uri = uritools.uricompose('local', path='search', query=q)
        return SearchResult(uri=uri, tracks=tracks)

    def begin(self):
        return schema.tracks(self._connect())

    def add(self, track):
        try:
            track = self._validate_track(track)
            if self._images and track.album:
                uri = translator.local_track_uri_to_file_uri(
                    track.uri, self._media_dir
                )
                album = track.album.copy(images=self._images.scan(uri))
                track = track.copy(album=album)
            schema.insert_track(self._connect(), track)
        except Exception as e:
            logger.warn('Skipped %s: %s', track.uri, e)

    def remove(self, uri):
        schema.delete_track(self._connect(), uri)

    def flush(self):
        if not self._connection:
            return False
        self._connection.commit()
        return True

    def close(self):
        schema.cleanup(self._connection)
        if self._images:
            self._images.cleanup(schema.images(self._connection))
        self._connection.commit()
        self._connection.close()
        self._connection = None

    def clear(self):
        with self._connect() as connection:
            try:
                schema.clear(connection)
            except sqlite3.Error as e:
                logger.error('Error clearing SQLite database: %s', e)
                return False
        if self._images:
            try:
                self._images.clear()
            except Exception as e:
                logger.error('Error clearing image directory: %s', e)
                return False
        return True

    def _connect(self):
        if not self._connection:
            self._connection = sqlite3.connect(
                self._dbpath,
                factory=schema.Connection,
                timeout=self._config['timeout'],
                check_same_thread=False,
            )
        return self._connection

    def _browse_album(self, uri, order=('disc_no', 'track_no', 'name')):
        return schema.browse(self._connect(), Ref.TRACK, order, album=uri)

    def _browse_artist(self, uri):
        with self._connect() as c:
            albums = schema.browse(c, Ref.ALBUM, albumartist=uri)
            refs = schema.browse(c, artist=uri)
        uris, tracks = {ref.uri for ref in albums}, []
        for ref in refs:
            if ref.type == Ref.TRACK:
                tracks.append(ref)
            elif ref.type == Ref.ALBUM and ref.uri not in uris:
                uri = uritools.uricompose('local', None, 'directory', dict(
                    type=Ref.TRACK, album=ref.uri, artist=uri
                ))
                albums.append(Ref.directory(uri=uri, name=ref.name))
            else:
                logger.debug('Skipped SQLite browse result %s', ref.uri)
        albums.sort(key=operator.attrgetter('name'))
        return albums + tracks

    def _browse_directory(self, uri):
        query = dict(uritools.urisplit(str(uri)).getquerylist())
        type = query.pop('type', None)
        role = query.pop('role', None)
        # TODO: handle these in schema (generically)?
        if type == 'date':
            format = query.get('format', '%Y-%m-%d')
            return map(_dateref, schema.dates(self._connect(), format=format))
        if type == 'genre':
            return map(_genreref, schema.genres(self._connect()))
        if type == 'last_modified':
            return map(_lastmodifiedref,
                       ((7, 'Last 7 days'),
                       (30, 'Last month'),
                       (92, 'Last 3 months'),
                       (157, 'Last 6 months'),
                       (365, 'Last year'))
            )

        roles = role or ('artist', 'albumartist')

        refs = []
        for ref in schema.browse(self._connect(), type, role=roles, **query):
            if ref.type == Ref.TRACK or (not query and not role):
                # FIXME: artist refs not browsable via mpd
                if ref.type == Ref.ARTIST:
                    refs.append(ref.copy(type=Ref.DIRECTORY))
                else:
                    refs.append(ref)
            elif ref.type == Ref.ALBUM:
                uri = uritools.uricompose('local', None, 'directory', dict(
                    query, type=Ref.TRACK, album=ref.uri
                ))
                refs.append(Ref.directory(uri=uri, name=ref.name))
            elif ref.type == Ref.ARTIST:
                uri = uritools.uricompose('local', None, 'directory', dict(
                    query, **{role: ref.uri}
                ))
                refs.append(Ref.directory(uri=uri, name=ref.name))
            else:
                logger.warn('Unexpected SQLite browse result: %r', ref)
        return refs

    def _browse_directory_path(self, uri):
        root = uritools.urisplit(str(uri)).getpath().partition(':')[2]
        refs, tracks = [], []
        for name in sorted(os.listdir(os.path.join(self._media_dir, root))):
            path = os.path.join(root, name)
            if os.path.isdir(os.path.join(self._media_dir, path)):
                uri = translator.path_to_local_directory_uri(path)
                refs.append(Ref.directory(uri=uri, name=name))
            else:
                uri = translator.path_to_local_track_uri(path)
                tracks.append(Ref.track(uri=uri, name=name))
        with self._connect() as c:
            refs += [track for track in tracks if schema.exists(c, track.uri)]
        return refs

    def _validate_artist(self, artist):
        if not artist.name:
            raise ValueError('Empty artist name')
        uri = artist.uri or self._model_uri('artist', artist)
        return artist.copy(uri=uri)

    def _validate_album(self, album):
        if not album.name:
            raise ValueError('Empty album name')
        uri = album.uri or self._model_uri('album', album)
        artists = map(self._validate_artist, album.artists)
        return album.copy(uri=uri, artists=artists)

    def _validate_track(self, track):
        if not track.uri:
            raise ValueError('Empty track URI')
        if track.name:
            name = track.name
        else:
            path = translator.local_track_uri_to_path(track.uri, b'')
            name = os.path.basename(path).decode('utf-8')
        if track.album and track.album.name:
            album = self._validate_album(track.album)
        else:
            album = None
        return track.copy(
            name=name,
            album=album,
            artists=map(self._validate_artist, track.artists),
            composers=map(self._validate_artist, track.composers),
            performers=map(self._validate_artist, track.performers)
        )

    def _filters(self, uri):
        if not uri or uri in (self.ROOT_DIRECTORY_URI, self.ROOT_PATH_URI):
            return []
        elif uri.startswith(self.ROOT_PATH_URI):
            return [{'uri': uri.replace('directory', 'track', 1) + '/*'}]
        elif uri.startswith('local:directory'):
            return [dict(uritools.urisplit(uri).getquerylist())]
        elif uri.startswith('local:artist'):
            return [{'artist': uri}, {'albumartist': uri}]
        elif uri.startswith('local:album'):
            return [{'album': uri}]
        else:
            raise ValueError('Invalid search URI: %s', uri)

    def _model_uri(self, type, model):
        if model.musicbrainz_id and self._config['use_%s_mbid_uri' % type]:
            return 'local:%s:mbid:%s' % (type, model.musicbrainz_id)
        digest = hashlib.md5(str(model)).hexdigest()
        return 'local:%s:md5:%s' % (type, digest)

def _dateref(date):
    return Ref.directory(
        uri=uritools.uricompose('local', None, 'directory', {'date': date}),
        name=date
    )

def _genreref(genre):
    return Ref.directory(
        uri=uritools.uricompose('local', None, 'directory', {'genre': genre}),
        name=genre
    )

def _lastmodifiedref(option):
    timestamp = int(time.time()) - option[0] * 24*60*1000
    return Ref.directory(
        uri=uritools.uricompose('local', None, 'directory',
                                {'last_modified': timestamp}),
        name=option[1]
    )


text:
package org.springframework.cloud.dataflow.integration.test.tags;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.junit.jupiter.api.Tag;

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Tag(TagNames.MSSQL)
public @interface Mssql {
}


text:
using Quasar.Communication.Packets.Outgoing.Catalog;
using Quasar.HabboHotel.GameClients;
using Quasar.HabboHotel.Rooms.AI;
using Quasar.Communication.Packets.Incoming;

namespace Quasar.Communication.Packets.Incoming.Catalog
{
    public class GetSellablePetBreedsEvent : IPacketEvent
    {
        public void Parse(GameClient Session, ClientPacket Packet)
        {
            string Type = Packet.PopString();
            string PacketType = "";
            int PetId = QuasarEnvironment.GetGame().GetCatalog().GetPetRaceManager().GetPetId(Type, out PacketType);

            Session.SendMessage(new SellablePetBreedsComposer(PacketType, PetId, QuasarEnvironment.GetGame().GetCatalog().GetPetRaceManager().GetRacesForRaceId(PetId)));
        }
    }
}


text:
layout: post
categories:
- api
- rails
title: Using let in Controllers
---

`let` in rspec is one of my favorite features. The [decent_exposure](https://github.com/voxdolo/decent_exposure) is similar to `let`, but it ends up doing way more for you than I want it to. I have been doing mostly API work in Rails recently so it doesn't fit.

To fix this I ended up writing my own simple version of `let` to use in my controllers.

##### lib/let.rb
```ruby
def self.let(method, &block)
  define_method(method) do
    @lets ||= {}
    @lets[method] ||= instance_eval(&block)
  end
end
```

Since I ended up pasting this code in most of the projects I'm in, I ended up writing a gem [letter](https://github.com/oestrich/letter). It's simple to use.

##### app/controllers/application_controller.rb
```ruby
class ApplicationController
  extend Letter

  let(:current_user) { User.find(session[:user_id]) }
end
```

Currently this gem doesn't work if you have views. So a simple addition to make it work with views would be:

##### app/controllers/application_controller.rb
```ruby
class ApplicationController
  extend Letter

  def self.let(method, *args)
    super
    helper_method(method)
  end

  let(:current_user) { User.find(session[:user_id]) }
end
```


text:
#ifndef QPS_WORKER_H
#define QPS_WORKER_H

#include <memory>

namespace grpc {

class Server;

namespace testing {

class WorkerServiceImpl;

class QpsWorker {
 public:
  explicit QpsWorker(int driver_port, int server_port = 0);
  ~QpsWorker();

 private:
  std::unique_ptr<WorkerServiceImpl> impl_;
  std::unique_ptr<Server> server_;
};

}  // namespace testing
}  // namespace grpc

#endif


text:
package org.opensingular.requirement.module.spring.security.builder;

import org.opensingular.requirement.module.persistence.entity.FeaturePermissionEntity;
import org.opensingular.requirement.module.persistence.entity.FeaturePermissionEntityPK;
import org.opensingular.requirement.module.spring.security.SingularPermission;

import java.util.ArrayList;
import java.util.List;

public class PermissionBuilderEnd {

    private final List<String> actions;
    private final List<String> forms;
    private final List<String> flows;
    private final List<String> taskDefinitions;

    PermissionBuilderEnd(List<String> actions, List<String> forms, List<String> flows, List<String> taskDefinitions) {
        this.actions = actions;
        this.forms = forms;
        this.flows = flows;
        this.taskDefinitions = taskDefinitions;
    }

    @SuppressWarnings("squid:S134")
    public List<SingularPermission> list() {
        List<SingularPermission> permissions = new ArrayList<>();
        for (String action : actions) {
            for (String form : forms) {
                for (String flow : flows) {
                    for (String taskDefinition : taskDefinitions) {
                        permissions.add(new SingularPermission(action, form, flow, taskDefinition));
                    }
                }
            }
        }
        return permissions;
    }

    public List<FeaturePermissionEntity> listEntities(String moduleKey, String clientRoleId) {
        List<FeaturePermissionEntity> fpes = new ArrayList<>();
        for (SingularPermission singularPermission : list()) {
            fpes.add(new FeaturePermissionEntity(new FeaturePermissionEntityPK(singularPermission.getSingularId(), clientRoleId, moduleKey)));
        }
        return fpes;
    }
}


text:
/**
 * Provider that uses network configuration capability as a means of infrastructure configuration.
 */
package org.onosproject.provider.isis.cfg.impl;


text:
/* *
 * (c) 2010-2017 Sebastian Bochan
 *
 * License: www.highcharts.com/license
 */

'use strict';

import H from '../parts/Globals.js';
import '../parts/Utilities.js';
import '../parts/Options.js';
import derivedSeriesMixin from '../mixins/derived-series.js';

var correctFloat = H.correctFloat,
    seriesType = H.seriesType,
    merge = H.merge;

/**
 * The pareto series type.
 *
 * @private
 * @class
 * @name Highcharts.seriesTypes.pareto
 *
 * @augments Highcharts.Series
 */
seriesType('pareto', 'line'

    /**
 * A pareto diagram is a type of chart that contains both bars and a line graph,
 * where individual values are represented in descending order by bars, and the
 * cumulative total is represented by the line.
 *
 * @sample {highcharts} highcharts/demo/pareto/
 *         Pareto diagram
 *
 * @extends      plotOptions.line
 * @since        6.0.0
 * @product      highcharts
 * @excluding    allAreas, boostThreshold, borderColor, borderRadius,
 *               borderWidth, crisp, colorAxis, depth, data, edgeColor,
 *               edgeWidth, findNearestPointBy, gapSize, gapUnit, grouping,
 *               groupPadding, groupZPadding, maxPointWidth, keys,
 *               negativeColor, pointInterval, pointIntervalUnit, pointPadding,
 *               pointPlacement, pointRange, pointStart, pointWidth, shadow,
 *               step, softThreshold, stacking, threshold, zoneAxis, zones
 * @optionparent plotOptions.pareto
 */
    , {
    /**
     * Higher zIndex than column series to draw line above shapes.
     */
        zIndex: 3
    }, merge(derivedSeriesMixin, {
    /**
     * Calculate sum and return percent points.
     *
     * @private
     * @function Highcharts.Series#setDerivedData
     *
     * @return {Array<Array<number,number>>}
     *         Returns array of points [x,y]
     */
        setDerivedData: function () {
            if (this.baseSeries.yData.length > 1) {
                var xValues = this.baseSeries.xData,
                    yValues = this.baseSeries.yData,
                    sum = this.sumPointsPercents(yValues, xValues, null, true);

                this.setData(
                    this.sumPointsPercents(yValues, xValues, sum, false),
                    false
                );
            }
        },
        /**
     * Calculate y sum and each percent point.
     *
     * @private
     * @function Highcharts.Series#sumPointsPercents
     *
     * @param {Array<number>} yValues
     *        Y values
     *
     * @param {Array<number>} xValues
     *        X values
     *
     * @param {number} sum
     *        Sum of all y values
     *
     * @param {boolean} [isSum]
     *        Declares if calculate sum of all points
     *
     * @return {number|Array<number,number>}
     *         Returns sum of points or array of points [x,sum]
     */
        sumPointsPercents: function (yValues, xValues, sum, isSum) {
            var sumY = 0,
                sumPercent = 0,
                percentPoints = [],
                percentPoint;

            yValues.forEach(function (point, i) {
                if (point !== null) {
                    if (isSum) {
                        sumY += point;
                    } else {
                        percentPoint = (point / sum) * 100;
                        percentPoints.push([
                            xValues[i],
                            correctFloat(sumPercent + percentPoint)
                        ]);
                        sumPercent += percentPoint;
                    }
                }
            });

            return isSum ? sumY : percentPoints;
        }
    }));

/**
 * A `pareto` series. If the [type](#series.pareto.type) option is not
 * specified, it is inherited from [chart.type](#chart.type).
 *
 * @extends   series,plotOptions.pareto
 * @since     6.0.0
 * @product   highcharts
 * @excluding data, dataParser, dataURL
 * @apioption series.pareto
 */

/**
 * An integer identifying the index to use for the base series, or a string
 * representing the id of the series.
 *
 * @type      {number|string}
 * @default   undefined
 * @apioption series.pareto.baseSeries
 */

/**
 * An array of data points for the series. For the `pareto` series type,
 * points are calculated dynamically.
 *
 * @type      {Array<Array<number|string>|*>}
 * @extends   series.column.data
 * @since     6.0.0
 * @product   highcharts
 * @apioption series.pareto.data
 */


text:
import pandas as pd

class FilterEngine:
	def __init__(self):
		pass

	def filter_exclusive(self, input_file, output_file, label_exclusive_string):
		print "label_exclusive_string = ", label_exclusive_string
		if label_exclusive_string[0] != '[' and label_exclusive_string[-1] != ']':
			label_exclusive_list = [label_exclusive_string]
		else:
			label_exclusive_list = label_exclusive_string[1:-1].split(',')
			for label in label_exlusive_list:
				label = label.strip()
		df = pd.read_csv(input_file, header=0)
		df[~df['Class'].isin(label_exclusive_list)].to_csv(output_file)

	def filter_inclusive(self, input_file, output_file, label_inclusive_string):
		print "label_inclusive_string = ", label_inclusive_string
		if label_inclusive_string[0] != '[' and label_inclusive_string[-1] != ']':
			label_inclusive_list = [label_inclusive_string]
		else:
			label_inclusive_list = label_inclusive_string[1:-1].split(',')
			print "list = ", label_inclusive_list
			for label in label_inclusive_list:
				label = label.strip()
		df = pd.read_csv(input_file, header=0)
		df[df['Class'].isin(label_inclusive_list)].to_csv(output_file)


text:
import {Byte, newArray, utf8Encode} from '../util';
import {BigIntExponentiation} from './big_integer';

import * as i18n from './i18n_ast';

/**
 * Return the message id or compute it using the XLIFF1 digest.
 */
export function digest(message: i18n.Message): string {
  return message.id || computeDigest(message);
}

/**
 * Compute the message id using the XLIFF1 digest.
 */
export function computeDigest(message: i18n.Message): string {
  return sha1(serializeNodes(message.nodes).join('') + `[${message.meaning}]`);
}

/**
 * Return the message id or compute it using the XLIFF2/XMB/$localize digest.
 */
export function decimalDigest(message: i18n.Message): string {
  return message.id || computeDecimalDigest(message);
}

/**
 * Compute the message id using the XLIFF2/XMB/$localize digest.
 */
export function computeDecimalDigest(message: i18n.Message): string {
  const visitor = new _SerializerIgnoreIcuExpVisitor();
  const parts = message.nodes.map(a => a.visit(visitor, null));
  return computeMsgId(parts.join(''), message.meaning);
}

/**
 * Serialize the i18n ast to something xml-like in order to generate an UID.
 *
 * The visitor is also used in the i18n parser tests
 *
 * @internal
 */
class _SerializerVisitor implements i18n.Visitor {
  visitText(text: i18n.Text, context: any): any {
    return text.value;
  }

  visitContainer(container: i18n.Container, context: any): any {
    return `[${container.children.map(child => child.visit(this)).join(', ')}]`;
  }

  visitIcu(icu: i18n.Icu, context: any): any {
    const strCases =
        Object.keys(icu.cases).map((k: string) => `${k} {${icu.cases[k].visit(this)}}`);
    return `{${icu.expression}, ${icu.type}, ${strCases.join(', ')}}`;
  }

  visitTagPlaceholder(ph: i18n.TagPlaceholder, context: any): any {
    return ph.isVoid ?
        `<ph tag name="${ph.startName}"/>` :
        `<ph tag name="${ph.startName}">${
            ph.children.map(child => child.visit(this)).join(', ')}</ph name="${ph.closeName}">`;
  }

  visitPlaceholder(ph: i18n.Placeholder, context: any): any {
    return ph.value ? `<ph name="${ph.name}">${ph.value}</ph>` : `<ph name="${ph.name}"/>`;
  }

  visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): any {
    return `<ph icu name="${ph.name}">${ph.value.visit(this)}</ph>`;
  }
}

const serializerVisitor = new _SerializerVisitor();

export function serializeNodes(nodes: i18n.Node[]): string[] {
  return nodes.map(a => a.visit(serializerVisitor, null));
}

/**
 * Serialize the i18n ast to something xml-like in order to generate an UID.
 *
 * Ignore the ICU expressions so that message IDs stays identical if only the expression changes.
 *
 * @internal
 */
class _SerializerIgnoreIcuExpVisitor extends _SerializerVisitor {
  visitIcu(icu: i18n.Icu, context: any): any {
    let strCases = Object.keys(icu.cases).map((k: string) => `${k} {${icu.cases[k].visit(this)}}`);
    // Do not take the expression into account
    return `{${icu.type}, ${strCases.join(', ')}}`;
  }
}

/**
 * Compute the SHA1 of the given string
 *
 * see https://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
 *
 * WARNING: this function has not been designed not tested with security in mind.
 *          DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
 */
export function sha1(str: string): string {
  const utf8 = utf8Encode(str);
  const words32 = bytesToWords32(utf8, Endian.Big);
  const len = utf8.length * 8;

  const w = newArray(80);
  let a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476, e = 0xc3d2e1f0;

  words32[len >> 5] |= 0x80 << (24 - len % 32);
  words32[((len + 64 >> 9) << 4) + 15] = len;

  for (let i = 0; i < words32.length; i += 16) {
    const h0 = a, h1 = b, h2 = c, h3 = d, h4 = e;

    for (let j = 0; j < 80; j++) {
      if (j < 16) {
        w[j] = words32[i + j];
      } else {
        w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
      }

      const fkVal = fk(j, b, c, d);
      const f = fkVal[0];
      const k = fkVal[1];
      const temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
      e = d;
      d = c;
      c = rol32(b, 30);
      b = a;
      a = temp;
    }
    a = add32(a, h0);
    b = add32(b, h1);
    c = add32(c, h2);
    d = add32(d, h3);
    e = add32(e, h4);
  }

  return bytesToHexString(words32ToByteString([a, b, c, d, e]));
}

function fk(index: number, b: number, c: number, d: number): [number, number] {
  if (index < 20) {
    return [(b & c) | (~b & d), 0x5a827999];
  }

  if (index < 40) {
    return [b ^ c ^ d, 0x6ed9eba1];
  }

  if (index < 60) {
    return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
  }

  return [b ^ c ^ d, 0xca62c1d6];
}

/**
 * Compute the fingerprint of the given string
 *
 * The output is 64 bit number encoded as a decimal string
 *
 * based on:
 * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
 */
export function fingerprint(str: string): [number, number] {
  const utf8 = utf8Encode(str);

  let hi = hash32(utf8, 0);
  let lo = hash32(utf8, 102072);

  if (hi == 0 && (lo == 0 || lo == 1)) {
    hi = hi ^ 0x130f9bef;
    lo = lo ^ -0x6b5f56d8;
  }

  return [hi, lo];
}

export function computeMsgId(msg: string, meaning: string = ''): string {
  let msgFingerprint = fingerprint(msg);

  if (meaning) {
    const meaningFingerprint = fingerprint(meaning);
    msgFingerprint = add64(rol64(msgFingerprint, 1), meaningFingerprint);
  }

  const hi = msgFingerprint[0];
  const lo = msgFingerprint[1];

  return wordsToDecimalString(hi & 0x7fffffff, lo);
}

function hash32(bytes: Byte[], c: number): number {
  let a = 0x9e3779b9, b = 0x9e3779b9;
  let i: number;

  const len = bytes.length;

  for (i = 0; i + 12 <= len; i += 12) {
    a = add32(a, wordAt(bytes, i, Endian.Little));
    b = add32(b, wordAt(bytes, i + 4, Endian.Little));
    c = add32(c, wordAt(bytes, i + 8, Endian.Little));
    const res = mix(a, b, c);
    a = res[0], b = res[1], c = res[2];
  }

  a = add32(a, wordAt(bytes, i, Endian.Little));
  b = add32(b, wordAt(bytes, i + 4, Endian.Little));
  // the first byte of c is reserved for the length
  c = add32(c, len);
  c = add32(c, wordAt(bytes, i + 8, Endian.Little) << 8);

  return mix(a, b, c)[2];
}

// clang-format off
function mix(a: number, b: number, c: number): [number, number, number] {
  a = sub32(a, b); a = sub32(a, c); a ^= c >>> 13;
  b = sub32(b, c); b = sub32(b, a); b ^= a << 8;
  c = sub32(c, a); c = sub32(c, b); c ^= b >>> 13;
  a = sub32(a, b); a = sub32(a, c); a ^= c >>> 12;
  b = sub32(b, c); b = sub32(b, a); b ^= a << 16;
  c = sub32(c, a); c = sub32(c, b); c ^= b >>> 5;
  a = sub32(a, b); a = sub32(a, c); a ^= c >>> 3;
  b = sub32(b, c); b = sub32(b, a); b ^= a << 10;
  c = sub32(c, a); c = sub32(c, b); c ^= b >>> 15;
  return [a, b, c];
}
// clang-format on

// Utils

enum Endian {
  Little,
  Big,
}

function add32(a: number, b: number): number {
  return add32to64(a, b)[1];
}

function add32to64(a: number, b: number): [number, number] {
  const low = (a & 0xffff) + (b & 0xffff);
  const high = (a >>> 16) + (b >>> 16) + (low >>> 16);
  return [high >>> 16, (high << 16) | (low & 0xffff)];
}

function add64(a: [number, number], b: [number, number]): [number, number] {
  const ah = a[0], al = a[1];
  const bh = b[0], bl = b[1];
  const result = add32to64(al, bl);
  const carry = result[0];
  const l = result[1];
  const h = add32(add32(ah, bh), carry);
  return [h, l];
}

function sub32(a: number, b: number): number {
  const low = (a & 0xffff) - (b & 0xffff);
  const high = (a >> 16) - (b >> 16) + (low >> 16);
  return (high << 16) | (low & 0xffff);
}

// Rotate a 32b number left `count` position
function rol32(a: number, count: number): number {
  return (a << count) | (a >>> (32 - count));
}

// Rotate a 64b number left `count` position
function rol64(num: [number, number], count: number): [number, number] {
  const hi = num[0], lo = num[1];
  const h = (hi << count) | (lo >>> (32 - count));
  const l = (lo << count) | (hi >>> (32 - count));
  return [h, l];
}

function bytesToWords32(bytes: Byte[], endian: Endian): number[] {
  const size = (bytes.length + 3) >>> 2;
  const words32 = [];

  for (let i = 0; i < size; i++) {
    words32[i] = wordAt(bytes, i * 4, endian);
  }

  return words32;
}

function byteAt(bytes: Byte[], index: number): Byte {
  return index >= bytes.length ? 0 : bytes[index];
}

function wordAt(bytes: Byte[], index: number, endian: Endian): number {
  let word = 0;
  if (endian === Endian.Big) {
    for (let i = 0; i < 4; i++) {
      word += byteAt(bytes, index + i) << (24 - 8 * i);
    }
  } else {
    for (let i = 0; i < 4; i++) {
      word += byteAt(bytes, index + i) << 8 * i;
    }
  }
  return word;
}

function words32ToByteString(words32: number[]): Byte[] {
  return words32.reduce((bytes, word) => bytes.concat(word32ToByteString(word)), [] as Byte[]);
}

function word32ToByteString(word: number): Byte[] {
  let bytes: Byte[] = [];
  for (let i = 0; i < 4; i++) {
    bytes.push((word >>> 8 * (3 - i)) & 0xff);
  }
  return bytes;
}

function bytesToHexString(bytes: Byte[]): string {
  let hex: string = '';
  for (let i = 0; i < bytes.length; i++) {
    const b = byteAt(bytes, i);
    hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16);
  }
  return hex.toLowerCase();
}

/**
 * Create a shared exponentiation pool for base-256 computations. This shared pool provides memoized
 * power-of-256 results with memoized power-of-two computations for efficient multiplication.
 *
 * For our purposes, this can be safely stored as a global without memory concerns. The reason is
 * that we encode two words, so only need the 0th (for the low word) and 4th (for the high word)
 * exponent.
 */
const base256 = new BigIntExponentiation(256);

/**
 * Represents two 32-bit words as a single decimal number. This requires a big integer storage
 * model as JS numbers are not accurate enough to represent the 64-bit number.
 *
 * Based on https://www.danvk.org/hex2dec.html
 */
function wordsToDecimalString(hi: number, lo: number): string {
  // Encode the four bytes in lo in the lower digits of the decimal number.
  // Note: the multiplication results in lo itself but represented by a big integer using its
  // decimal digits.
  const decimal = base256.toThePowerOf(0).multiplyBy(lo);

  // Encode the four bytes in hi above the four lo bytes. lo is a maximum of (2^8)^4, which is why
  // this multiplication factor is applied.
  base256.toThePowerOf(4).multiplyByAndAddTo(hi, decimal);

  return decimal.toString();
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var FALLBACK_SCROLL_BAR_WIDTH = 15;
var Viewport = (function () {
    function Viewport(_terminal, _viewportElement, _scrollArea, _charMeasure) {
        var _this = this;
        this._terminal = _terminal;
        this._viewportElement = _viewportElement;
        this._scrollArea = _scrollArea;
        this._charMeasure = _charMeasure;
        this.scrollBarWidth = 0;
        this._currentRowHeight = 0;
        this._lastRecordedBufferLength = 0;
        this._lastRecordedViewportHeight = 0;
        this._lastRecordedBufferHeight = 0;
        this._wheelPartialScroll = 0;
        this.scrollBarWidth = (this._viewportElement.offsetWidth - this._scrollArea.offsetWidth) || FALLBACK_SCROLL_BAR_WIDTH;
        this._viewportElement.addEventListener('scroll', this._onScroll.bind(this));
        setTimeout(function () { return _this.syncScrollArea(); }, 0);
    }
    Viewport.prototype.onThemeChanged = function (colors) {
        this._viewportElement.style.backgroundColor = colors.background.css;
    };
    Viewport.prototype._refresh = function () {
        if (this._charMeasure.height > 0) {
            this._currentRowHeight = this._terminal.renderer.dimensions.scaledCellHeight / window.devicePixelRatio;
            this._lastRecordedViewportHeight = this._viewportElement.offsetHeight;
            var newBufferHeight = Math.round(this._currentRowHeight * this._lastRecordedBufferLength) + (this._lastRecordedViewportHeight - this._terminal.renderer.dimensions.canvasHeight);
            if (this._lastRecordedBufferHeight !== newBufferHeight) {
                this._lastRecordedBufferHeight = newBufferHeight;
                this._scrollArea.style.height = this._lastRecordedBufferHeight + 'px';
            }
        }
    };
    Viewport.prototype.syncScrollArea = function () {
        if (this._lastRecordedBufferLength !== this._terminal.buffer.lines.length) {
            this._lastRecordedBufferLength = this._terminal.buffer.lines.length;
            this._refresh();
        }
        else if (this._lastRecordedViewportHeight !== this._terminal.renderer.dimensions.canvasHeight) {
            this._refresh();
        }
        else {
            if (this._terminal.renderer.dimensions.scaledCellHeight / window.devicePixelRatio !== this._currentRowHeight) {
                this._refresh();
            }
        }
        var scrollTop = this._terminal.buffer.ydisp * this._currentRowHeight;
        if (this._viewportElement.scrollTop !== scrollTop) {
            this._viewportElement.scrollTop = scrollTop;
        }
    };
    Viewport.prototype._onScroll = function (ev) {
        if (!this._viewportElement.offsetParent) {
            return;
        }
        var newRow = Math.round(this._viewportElement.scrollTop / this._currentRowHeight);
        var diff = newRow - this._terminal.buffer.ydisp;
        this._terminal.scrollLines(diff, true);
    };
    Viewport.prototype.onWheel = function (ev) {
        var amount = this._getPixelsScrolled(ev);
        if (amount === 0) {
            return;
        }
        this._viewportElement.scrollTop += amount;
        ev.preventDefault();
    };
    Viewport.prototype._getPixelsScrolled = function (ev) {
        if (ev.deltaY === 0) {
            return 0;
        }
        var amount = ev.deltaY;
        if (ev.deltaMode === WheelEvent.DOM_DELTA_LINE) {
            amount *= this._currentRowHeight;
        }
        else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
            amount *= this._currentRowHeight * this._terminal.rows;
        }
        return amount;
    };
    Viewport.prototype.getLinesScrolled = function (ev) {
        if (ev.deltaY === 0) {
            return 0;
        }
        var amount = ev.deltaY;
        if (ev.deltaMode === WheelEvent.DOM_DELTA_PIXEL) {
            amount /= this._currentRowHeight + 0.0;
            this._wheelPartialScroll += amount;
            amount = Math.floor(Math.abs(this._wheelPartialScroll)) * (this._wheelPartialScroll > 0 ? 1 : -1);
            this._wheelPartialScroll %= 1;
        }
        else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
            amount *= this._terminal.rows;
        }
        return amount;
    };
    Viewport.prototype.onTouchStart = function (ev) {
        this._lastTouchY = ev.touches[0].pageY;
    };
    Viewport.prototype.onTouchMove = function (ev) {
        var deltaY = this._lastTouchY - ev.touches[0].pageY;
        this._lastTouchY = ev.touches[0].pageY;
        if (deltaY === 0) {
            return;
        }
        this._viewportElement.scrollTop += deltaY;
        ev.preventDefault();
    };
    return Viewport;
}());
exports.Viewport = Viewport;

//# sourceMappingURL=Viewport.js.map


text:
<?php

/**
 * Metadata lib of OneLogin PHP Toolkit
 *
 */

class OneLogin_Saml2_Metadata
{
    const TIME_VALID = 172800;  // 2 days
    const TIME_CACHED = 604800; // 1 week

    /**
     * Generates the metadata of the SP based on the settings
     *
     * @param string    $sp            The SP data
     * @param string    $authnsign     authnRequestsSigned attribute
     * @param string    $wsign         wantAssertionsSigned attribute
     * @param DateTime  $validUntil    Metadata's valid time
     * @param Timestamp $cacheDuration Duration of the cache in seconds
     * @param array     $contacts      Contacts info
     * @param array     $organization  Organization ingo
     *
     * @return string SAML Metadata XML
     */
    public static function builder($sp, $authnsign = false, $wsign = false, $validUntil = null, $cacheDuration = null, $contacts = array(), $organization = array())
    {

        $validUntilTime = null;
        if (isset($validUntil)) {
            $validUntilTime =  gmdate('Y-m-d\TH:i:s\Z', $validUntil);
        }

        $sls = '';
        if (isset($sp['singleLogoutService'])) {
            $sls = <<<SLS_TEMPLATE
        <md:SingleLogoutService Binding="{$sp['singleLogoutService']['binding']}"
                                     Location="{$sp['singleLogoutService']['url']}" />
SLS_TEMPLATE;
        }

        if ($authnsign) {
            $strAuthnsign = 'true';
        } else {
            $strAuthnsign = 'false';
        }

        if ($wsign) {
            $strWsign = 'true';
        } else {
            $strWsign = 'false';
        }

        $strOrganization = '';
        if (!empty($organization)) {
            $organizationInfo = array();
            foreach ($organization as $lang => $info) {
                $organizationInfo[] = <<<CONTACT
    <md:Organization>
       <md:OrganizationName xml:lang="{$lang}">{$info['name']}</md:OrganizationName>
       <md:OrganizationDisplayName xml:lang="{$lang}">{$info['displayname']}</md:OrganizationDisplayName>
       <md:OrganizationURL xml:lang="{$lang}">{$info['url']}</md:OrganizationURL>
    </md:Organization>
CONTACT;
            }
            $strOrganization = implode("\n", $organizationInfo);
        }

        $strContacts = '';
        if (!empty($contacts)) {
            $contactsInfo = array();
            foreach ($contacts as $type => $info) {
                $contactsInfo[] = <<<CONTACT
    <md:ContactPerson contactType="{$type}">
        <md:GivenName>{$info['givenName']}</md:GivenName>
        <md:EmailAddress>{$info['emailAddress']}</md:EmailAddress>
    </md:ContactPerson>
CONTACT;
            }
            $strContacts = implode("\n", $contactsInfo);
        }

        $extensions = '';
        if (isset($sp['uiInfo']))
        {
            $extensions = <<<EXTENSIONS
    <md:Extensions>
      <mdui:UIInfo xmlns:mdui="urn:oasis:names:tc:SAML:metadata:ui">
        <mdui:DisplayName xml:lang="en">{$sp['uiInfo']['displayName']}</mdui:DisplayName>
        <mdui:Logo height="64" width="100" xml:lang="en">{$sp['uiInfo']['logo']}</mdui:Logo>
      </mdui:UIInfo>
    </md:Extensions>
EXTENSIONS;
        }

        $validUntilString = "";
        $cacheDurationString = "";
        if ($validUntilTime) {
            $validUntilString = "validUntil=\"{$validUntilTime}\"";
        }
        if ($cacheDuration) {
            $cacheDurationString = "cacheDuration=\"PT{$cacheDuration}S\"";
        }

        $metadata = <<<METADATA_TEMPLATE
<?xml version="1.0"?>
<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
        {$validUntilString}
        {$cacheDurationString}
        entityID="{$sp['entityId']}">
    <md:SPSSODescriptor AuthnRequestsSigned="{$strAuthnsign}" WantAssertionsSigned="{$strWsign}" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
        <md:NameIDFormat>{$sp['NameIDFormat']}</md:NameIDFormat>
        <md:AssertionConsumerService Binding="{$sp['assertionConsumerService']['binding']}"
                                     Location="{$sp['assertionConsumerService']['url']}"
                                     index="1" />
{$sls}
{$extensions}
    </md:SPSSODescriptor>
{$strOrganization}
{$strContacts}
</md:EntityDescriptor>
METADATA_TEMPLATE;

        return $metadata;
    }

    /**
     * Signs the metadata with the key/cert provided
     *
     * @param string $metadata SAML Metadata XML
     * @param string $key      x509 key
     * @param string $cert     x509 cert
     *
     * @return string Signed Metadata
     */
    public static function signMetadata($metadata, $key, $cert)
    {
        return OneLogin_Saml2_Utils::addSign($metadata, $key, $cert);
    }

    /**
     * Adds the x509 descriptors (sign/encriptation) to the metadata
     * The same cert will be used for sign/encrypt
     *
     * @param string $metadata SAML Metadata XML
     * @param string $cert     x509 cert
     *
     * @return string Metadata with KeyDescriptors
     */
    public static function addX509KeyDescriptors($metadata, $cert)
    {
        $xml = new DOMDocument();
        try {
            $xml = OneLogin_Saml2_Utils::loadXML($xml, $metadata);
            if (!$xml) {
                throw new Exception('Error parsing metadata');
            }
        } catch (Exception $e) {
            throw new Exception('Error parsing metadata. '.$e->getMessage());
        }

        $formatedCert = OneLogin_Saml2_Utils::formatCert($cert, false);
        $x509Certificate = $xml->createElementNS(OneLogin_Saml2_Constants::NS_DS, 'X509Certificate', $formatedCert);

        $keyData = $xml->createElementNS(OneLogin_Saml2_Constants::NS_DS, 'ds:X509Data');
        $keyData->appendChild($x509Certificate);

        $keyInfo = $xml->createElementNS(OneLogin_Saml2_Constants::NS_DS, 'ds:KeyInfo');
        $keyInfo->appendChild($keyData);

        $keyDescriptor = $xml->createElementNS(OneLogin_Saml2_Constants::NS_MD, "md:KeyDescriptor");

        $SPSSODescriptor = $xml->getElementsByTagName('SPSSODescriptor')->item(0);
        $SPSSODescriptor->insertBefore($keyDescriptor->cloneNode(), $SPSSODescriptor->firstChild);
        $SPSSODescriptor->insertBefore($keyDescriptor->cloneNode(), $SPSSODescriptor->firstChild);

        $signing = $xml->getElementsByTagName('KeyDescriptor')->item(0);
        $signing->setAttribute('use', 'signing');

        $encryption = $xml->getElementsByTagName('KeyDescriptor')->item(1);
        $encryption->setAttribute('use', 'encryption');

        $signing->appendChild($keyInfo);
        $encryption->appendChild($keyInfo->cloneNode(true));

        return $xml->saveXML();
    }
}