text:
let events = require('events');
// create eventEmitter Object
let eventEmitter = new events.EventEmitter();

// create eventHandler
let connectHandler = connected = () => {
	console.log('connect successfully');

	// trigger data_received event
	eventEmitter.emit('data_received');
};

// bind connection eventHandler
eventEmitter.on('connection', connectHandler);

// use anonymous function to bind data_received event
eventEmitter.on('data_received', () => {
	console.log('received data successfully');
});

// trigger connection event
eventEmitter.emit('connection');

console.log('the program is end\n');


text:
<?php

namespace Modules\Recipe\Sidebar;

use Maatwebsite\Sidebar\Group;
use Maatwebsite\Sidebar\Item;
use Maatwebsite\Sidebar\Menu;
use Modules\Core\Contracts\Authentication;

class SidebarExtender implements \Maatwebsite\Sidebar\SidebarExtender
{
    /**
     * @var Authentication
     */
    protected $auth;

    /**
     * @param Authentication $auth
     *
     * @internal param Guard $guard
     */
    public function __construct(Authentication $auth)
    {
        $this->auth = $auth;
    }

    /**
     * @param Menu $menu
     *
     * @return Menu
     */
    public function extendWith(Menu $menu)
    {
        $menu->group(trans('core::sidebar.content'), function (Group $group) {
            $group->item('Recipe', function (Item $item) {
                $item->icon('fa fa-copy');
                $item->weight(10);
                $item->authorize(
                    $this->auth->hasAccess('recipe.recipes.index')
                );
                $item->item(trans('recipe::recipes.title.recipes'), function (Item $item) {
                    $item->icon('fa fa-copy');
                    $item->weight(0);
                    $item->append('admin.recipe.recipe.create');
                    $item->route('admin.recipe.recipe.index');
                    $item->authorize(
                        $this->auth->hasAccess('recipe.recipes.index')
                    );
                });
            });
        });

        return $menu;
    }
}

redpajama_set_name: RedPajamaGithub


text:
PDOStatement::BindParam for binary types with empty strings and non-empty ones
--DESCRIPTION--
PDOStatement::BindParam for binary types with empty strings and non-empty ones
Related to GitHub PR 865 - verify that the same binary data can be reused rather
than flushed after the first use
--SKIPIF--
<?php require('skipif_mid-refactor.inc'); ?>
--FILE--
<?php
require_once("MsCommon_mid-refactor.inc");

try {
    $conn = connect();
    $tableName = "pdoEmptyBinary";
    $size = 6;

    $colMetaArr = array(new ColumnMeta("binary($size)", "BinaryCol"),
                        new ColumnMeta("varbinary($size)", "VarBinaryCol"),
                        new ColumnMeta("varbinary(max)", "VarBinaryMaxCol"));
    createTable($conn, $tableName, $colMetaArr);

    // Insert two rows, first empty strings and the second not empty
    $inputs = array('', 'ABC');

    $bin = fopen('php://memory', 'a');
    fwrite($bin, $inputs[0]);                   // an empty string will be 0x in hex
    rewind($bin);

    $query = "INSERT INTO $tableName VALUES(?, ?, ?)";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(1, $bin, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
    $stmt->bindParam(2, $bin, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
    $stmt->bindParam(3, $bin, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);

    $stmt->execute();
    fclose($bin);

    $bin2 = fopen('php://memory', 'a');
    fwrite($bin2, $inputs[1]);                  // 'ABC' will be 0x414243 in hex
    rewind($bin2);

    $stmt->bindParam(1, $bin2, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
    $stmt->bindParam(2, $bin2, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
    $stmt->bindParam(3, $bin2, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);

    $stmt->execute();
    fclose($bin2);

    // Verify the data by fetching and comparing against the inputs
    $query = "SELECT * FROM $tableName";
    $stmt = $conn->query($query);
    $rowset = $stmt->fetchAll();

    for ($i = 0; $i < 2; $i++) {
        for ($j = 0; $j < 3; $j++) {
            $str = $rowset[$i][$j];
            $len = strlen($str);
            $failed = false;

            if ($j == 0) {
                // binary fields have fixed size, unlike varbinary ones
                if ($len !== $size || trim($str) !== $inputs[$i]) {
                    $failed = true;
                }
            } else {
                if ($len !== strlen($inputs[$i]) || $str !== $inputs[$i]) {
                    $failed = true;
                }
            }

            if ($failed) {
                $row = $i + 1;
                $col = $j + 1;
                echo "Unexpected value returned from row $row and column $col: \n";
                var_dump($str);
            }
        }
    }

    dropTable($conn, $tableName);
    unset($stmt);
    unset($conn);

    echo "Done\n";
} catch (PDOException $e) {
    var_dump($e);
    exit;
}
?>
--EXPECT--
Done


text:
require 'spec_helper'

describe SettingsHelper do
end


text:
/*
  RandomExponentialDistribution.java

  (P)2000-2001 Laurentiu Cristofor
*/

/*

laur.rand - A Java package for random number generators and other
random methods
Copyright (C) 2002  Laurentiu Cristofor

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA

The laur.rand package was written by Laurentiu Cristofor (laur@cs.umb.edu).

*/

package laur.rand;

import java.util.Random;

/**

   A generator of random numbers with exponential distribution.

   @version 1.0
   @author Laurentiu Cristofor

 */
public class RandomExponentialDistribution
{
  private Random rand;
  private double mean;

  /**
   * Create a new generator of random numbers
   * with exponential distribution of mean 1.
   */
  public RandomExponentialDistribution()
  {
    this(1.0, new Random());
  }

  /**
   * Create a new generator of random numbers
   * with exponential distribution of specified mean.
   *
   * @param mean   the mean of the exponential distribution
   */
  public RandomExponentialDistribution(double mean)
  {
    this(mean, new Random());
  }

  /**
   * Create a new generator of random numbers with exponential
   * distribution of specified mean that will use randgen
   * as its source of random numbers.
   *
   * @param mean   the mean of the exponential distribution
   * @param randgen   a Random object to be used by the generator.
   */
  public RandomExponentialDistribution(double mean, Random randgen)
  {
    this.mean = mean;
    rand = randgen;
  }

  /**
   * Return a random number with exponential distribution.
   */
  public double nextDouble()
  {
    double val;

    do
      val = rand.nextDouble();
    while (val == 0.0);

    return mean * (-Math.log(val));
  }

  /**
   * sample usage and testing
   */
  public static void main(String[] args)
  {
    RandomExponentialDistribution exponential
      = new RandomExponentialDistribution(10);

    for (int i = 0; i <= 10; i++)
      System.out.println(exponential.nextDouble());
  }
}


text:
package evaluator

import (
	"fmt"
	"net"

	"github.com/sirupsen/logrus"
	"google.golang.org/grpc"

	"open-match.dev/open-match/pkg/pb"

	utilTesting "open-match.dev/open-match/internal/util/testing"

	"open-match.dev/open-match/examples/scale/scenarios"
)

var (
	logger = logrus.WithFields(logrus.Fields{
		"app":       "openmatch",
		"component": "scale.evaluator",
	})
)

// Run triggers execution of an evaluator.
func Run() {
	activeScenario := scenarios.ActiveScenario

	server := grpc.NewServer(utilTesting.NewGRPCServerOptions(logger)...)
	pb.RegisterEvaluatorServer(server, activeScenario.Evaluator)
	ln, err := net.Listen("tcp", fmt.Sprintf(":%d", 50508))
	if err != nil {
		logger.WithFields(logrus.Fields{
			"error": err.Error(),
			"port":  50508,
		}).Fatal("net.Listen() error")
	}

	logger.WithFields(logrus.Fields{
		"port": 50508,
	}).Info("TCP net listener initialized")

	logger.Info("Serving gRPC endpoint")
	err = server.Serve(ln)
	if err != nil {
		logger.WithFields(logrus.Fields{
			"error": err.Error(),
		}).Fatal("gRPC serve() error")
	}
}


text:
require 'nark/emitter'

module Nark
  class NullEmitter < Nark::Emitter
    def emit(collection_name, data, timestamp = nil); end

    def emit_bulk(data_hash); end
  end
end


text:
package hprose.exam.client;

import java.sql.Date;

public class User {
    private String name;
    private Sex sex;
    private Date birthday;
    private int age;
    private boolean married;

    public User() {
    }

    public User(String name, Sex sex, Date birthday, int age, boolean married) {
        this.name = name;
        this.sex = sex;
        this.birthday = birthday;
        this.age = age;
        this.married = married;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Sex getSex() {
        return sex;
    }

    public void setSex(Sex sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isMarried() {
        return married;
    }

    public void setMarried(boolean married) {
        this.married = married;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   tcp_accept.h
 * Author: admin
 *
 * Created on 2017年3月7日, 上午11:25
 */

#ifndef TCP_ACCEPT_H
#define TCP_ACCEPT_H
#include "svr_define.h"
#include "iplayer.h"
#include "net_package.h"
#include "epoll_svr.h"
namespace easynet{
//监听服务器
    class EPOLLSvr;
    using EPOLLSvrPtr = std::shared_ptr<EPOLLSvr>;
    class TCPAccept : public IPlayer
    {
        public:
            TCPAccept(int32_t port, EPOLLSvrPtr s);
            bool Listen(bool reuse = true);
            virtual void OnNetMessage();
            ~TCPAccept();

            virtual void SetHandler(On_Accept_Handler h);
        private:
            On_Accept_Handler accept_handler_;  //接收事件后的回调函数
            EPOLLSvrPtr svr_;                    //epoll svr

    };
    using TCPAcceptPtr = std::shared_ptr<TCPAccept>;

}

#endif /* TCP_ACCEPT_H */


text:
package cloud.cluster.sim.utilities.dto;

public class SimulationSettings {
    private int taskTimeout = 5;
    private long startVmDelay = 45;
    private long stopVmDelay = 15;
    private int vmCreationTimeout = 60;
    private int vmTerminationTimeout = 25;
    private int lowUtilisationThreshold = 50;
    private int upUtilisationThreshold = 70;
    private int lowThresholdExceedSuccessionLimit = 21;
    private int upThresholdExceedSuccessionLimit = 11;
    private long opsForVm = 100;
    private int mttr = 120;
    private String pathToTraces = "traces";
    private String regexForTracesName = "trimmed";

    public SimulationSettings() {
    }

    public SimulationSettings(int taskTimeout, long startVmDelay, long stopVmDelay, int vmCreationTimeout, int vmTerminationTimeout, int lowUtilisationThreshold, int upUtilisationThreshold, int lowThresholdExceedSuccessionLimit, int upThresholdExceedSuccessionLimit, long opsForVm, int mttr, String pathToTraces, String regexForTracesName) {
        this.taskTimeout = taskTimeout;
        this.startVmDelay = startVmDelay;
        this.stopVmDelay = stopVmDelay;
        this.vmCreationTimeout = vmCreationTimeout;
        this.vmTerminationTimeout = vmTerminationTimeout;
        this.lowUtilisationThreshold = lowUtilisationThreshold;
        this.upUtilisationThreshold = upUtilisationThreshold;
        this.lowThresholdExceedSuccessionLimit = lowThresholdExceedSuccessionLimit;
        this.upThresholdExceedSuccessionLimit = upThresholdExceedSuccessionLimit;
        this.opsForVm = opsForVm;
        this.mttr = mttr;
        this.pathToTraces = pathToTraces;
        this.regexForTracesName = regexForTracesName;
    }

    public int getTaskTimeout() {
        return taskTimeout;
    }

    public void setTaskTimeout(int taskTimeout) {
        this.taskTimeout = taskTimeout;
    }

    public long getStartVmDelay() {
        return startVmDelay;
    }

    public void setStartVmDelay(long startVmDelay) {
        this.startVmDelay = startVmDelay;
    }

    public long getStopVmDelay() {
        return stopVmDelay;
    }

    public void setStopVmDelay(long stopVmDelay) {
        this.stopVmDelay = stopVmDelay;
    }

    public int getVmCreationTimeout() {
        return vmCreationTimeout;
    }

    public void setVmCreationTimeout(int vmCreationTimeout) {
        this.vmCreationTimeout = vmCreationTimeout;
    }

    public int getVmTerminationTimeout() {
        return vmTerminationTimeout;
    }

    public void setVmTerminationTimeout(int vmTerminationTimeout) {
        this.vmTerminationTimeout = vmTerminationTimeout;
    }

    public int getLowUtilisationThreshold() {
        return lowUtilisationThreshold;
    }

    public void setLowUtilisationThreshold(int lowUtilisationThreshold) {
        this.lowUtilisationThreshold = lowUtilisationThreshold;
    }

    public int getUpUtilisationThreshold() {
        return upUtilisationThreshold;
    }

    public void setUpUtilisationThreshold(int upUtilisationThreshold) {
        this.upUtilisationThreshold = upUtilisationThreshold;
    }

    public int getLowThresholdExceedSuccessionLimit() {
        return lowThresholdExceedSuccessionLimit;
    }

    public void setLowThresholdExceedSuccessionLimit(int lowThresholdExceedSuccessionLimit) {
        this.lowThresholdExceedSuccessionLimit = lowThresholdExceedSuccessionLimit;
    }

    public int getUpThresholdExceedSuccessionLimit() {
        return upThresholdExceedSuccessionLimit;
    }

    public void setUpThresholdExceedSuccessionLimit(int upThresholdExceedSuccessionLimit) {
        this.upThresholdExceedSuccessionLimit = upThresholdExceedSuccessionLimit;
    }

    public long getOpsForVm() {
        return opsForVm;
    }

    public void setOpsForVm(long opsForVm) {
        this.opsForVm = opsForVm;
    }

    public int getMttr() {
        return mttr;
    }

    public void setMttr(int mttr) {
        this.mttr = mttr;
    }

    public String getPathToTraces() {
        return pathToTraces;
    }

    public void setPathToTraces(String pathToTraces) {
        this.pathToTraces = pathToTraces;
    }

    public String getRegexForTracesName() {
        return regexForTracesName;
    }

    public void setRegexForTracesName(String regexForTracesName) {
        this.regexForTracesName = regexForTracesName;
    }

}


text:
var gameScale = 50;

// text constants
var GAME_WIN_TEXT = "You won!  Hit SPACE to play the next level or ESC for the level selection menu.";
var GOLDEN_COG_TEXT = "You earned a golden cog!";
var SILVER_COG_TEXT = "You earned a silver cog!";
var GAME_LOSS_TEXT = "You lost.  Hit SPACE to restart, or ESC to select a new level.";
var TEXT_BOX_X_MARGIN = 6;
var TEXT_BOX_Y_MARGIN = 6;
var SECONDS_BETWEEN_TICKS = 1 / 60;
var useFixedPhysicsTick = true;

Game.subclasses(Screen);

// class Game extends Screen
function Game() {
	this.camera = new Camera();
	this.fps = 0;
	this.fixedPhysicsTick = 0;

	this.isDone = false;
	this.onWin = null;

	// whether this game is the last level in the menu, this will be updated by main.js when the menu loads
	this.lastLevel = false;

	gameState = new GameState();
}

Game.prototype.resize = function(w, h) {
	this.width = w;
	this.height = h;
	this.camera = new Camera(gameState.playerA, gameState.playerB, w / gameScale, h / gameScale);
};

Game.prototype.tick = function(seconds) {
	// when the screen isn't split, standing at the original spawn point:
	// * Triple Threat
	//	 - variable physics tick: 30 FPS
	//	 - fixed physics tick: 25 FPS
	// * Cube
	//	 - variable physics tick: 35 FPS
	//	 - fixed physics tick: 30 FPS
	// * Coordinated Panic
	//	 - variable physics tick: 55 FPS
	//	 - fixed physics tick: 50 FPS
	// overall, a fixed physics tick provides about 5 FPS drop but fixes a lot of
	// gameplay issues (measurements above approximate but within about +/-1)

	if (useFixedPhysicsTick) {
		// fixed physics tick
		var count = 0;
		this.fixedPhysicsTick += seconds;
		while (++count <= 3 && this.fixedPhysicsTick >= 0) {
			this.fixedPhysicsTick -= SECONDS_BETWEEN_TICKS;
			gameState.tick(SECONDS_BETWEEN_TICKS);
			Particle.tick(SECONDS_BETWEEN_TICKS);
		}
	} else {
		// variable physics tick
		gameState.tick(seconds);
		Particle.tick(seconds);
	}

	// smooth the fps a bit
	this.fps = lerp(this.fps, 1 / seconds, 0.05);

	// handle winning the game
	if (!this.isDone && gameState.gameStatus != GAME_IN_PLAY) {
		this.isDone = true;
		if (gameState.gameStatus == GAME_WON && this.onWin) {
			this.onWin();
		}
	}
};

Game.prototype.render = function(c, center, width, height, backgroundCache) {
	var halfWidth = width / 2;
	var halfHeight = height / 2;
	var xmin = center.x - halfWidth;
	var ymin = center.y - halfHeight;
	var xmax = center.x + halfWidth;
	var ymax = center.y + halfHeight;
	c.save();
	c.translate(-center.x, -center.y);

	// draw the background, backgroundCache is an optional argument
	if (backgroundCache) {
		backgroundCache.draw(c, xmin, ymin, xmax, ymax);
	} else {
		gameState.world.draw(c, xmin, ymin, xmax, ymax);
	}

	gameState.draw(c, xmin, ymin, xmax, ymax);
	Particle.draw(c);
	c.restore();
};

// Draw a text box, takes in an array of lines
function drawTextBox(c, textArray, xCenter, yCenter, textSize) {
	var numLines = textArray.length;
	if (numLines < 1) return;

	// Calculate the height of all lines and the widest line's width
	c.font = textSize + 'px Arial, sans-serif';
	var lineHeight = textSize + 2;
	var textHeight = lineHeight * numLines;
	var textWidth = -1;
	for (var i = 0; i < numLines; ++i) {
		var currWidth = c.measureText(textArray[i]).width;
		if (textWidth < currWidth) {
			textWidth = currWidth;
		}
	}

	// Draw the box
	c.fillStyle = '#BFBFBF';
	c.strokeStyle = '#7F7F7F';
	c.lineWidth = 1;
	var xLeft = xCenter - textWidth / 2 - TEXT_BOX_X_MARGIN;
	var yBottom = yCenter - textHeight / 2 - TEXT_BOX_Y_MARGIN;
	c.fillRect(xLeft, yBottom, textWidth + TEXT_BOX_X_MARGIN * 2, textHeight + TEXT_BOX_Y_MARGIN * 2);
	c.strokeRect(xLeft, yBottom, textWidth + TEXT_BOX_X_MARGIN * 2, textHeight + TEXT_BOX_Y_MARGIN * 2);

	// Draw the text
	c.fillStyle = 'black';
	c.textAlign = 'center';
	// yCurr starts at the top, so subtract half of height of box
	var yCurr = yCenter + 4 - (numLines - 1) * lineHeight / 2;
	for (var i = 0; i < numLines; ++i) {
		c.fillText(textArray[i], xCenter, yCurr);
		yCurr += lineHeight;
	}
}

Game.prototype.draw = function(c) {
	if (!useBackgroundCache) {
		// clear the background
		c.fillStyle = '#BFBFBF';
		c.fillRect(0, 0, this.width, this.height);
	}

	// draw the game
	c.save();
	c.translate(this.width / 2, this.height / 2);
	c.scale(gameScale, -gameScale);
	c.lineWidth = 1 / gameScale;
	this.camera.draw(c, this);
	c.restore();

	if (gameState.gameStatus === GAME_WON) {
		// draw winning text
		c.save();
		var gameWinText = (this.lastLevel ? "Congratulations, you beat the last level in this set!	Press SPACE or ESC to return to the level selection menu." : GAME_WIN_TEXT);
		var cogsCollectedText = "Cogs Collected: " + gameState.stats[STAT_COGS_COLLECTED] + "/" + gameState.stats[STAT_NUM_COGS];
		drawTextBox(c, [gameWinText, "", cogsCollectedText], this.width / 2, this.height / 2, 14);
		c.restore();
	} else if (gameState.gameStatus === GAME_LOST) {
		// draw losing text
		c.save();
		drawTextBox(c, [GAME_LOSS_TEXT], this.width / 2, this.height / 2, 14);
		c.restore();
	}

	// draw the fps counter
	c.font = '10px Arial, sans-serif';
	c.fillStyle = 'black';
	var text = this.fps.toFixed(0) + ' FPS';
	c.fillText(text, this.width - 5 - c.measureText(text).width, this.height - 5);
};

Game.prototype.keyDown = function(e) {
	var keyCode = e.which;
	var action = Keys.fromKeyCode(keyCode);
	if (action != null) {
		if (action.indexOf('a-') == 0) gameState.playerA[action.substr(2)] = true;
		else if (action.indexOf('b-') == 0) gameState.playerB[action.substr(2)] = true;
		else gameState[action] = true;
		e.preventDefault();
		e.stopPropagation();
	}
};

Game.prototype.keyUp = function(e) {
	var keyCode = e.which;
	var action = Keys.fromKeyCode(keyCode);
	if (action != null) {
		if (action.indexOf('a-') == 0) gameState.playerA[action.substr(2)] = false;
		else if (action.indexOf('b-') == 0) gameState.playerB[action.substr(2)] = false;
		else gameState[action] = false;
		e.preventDefault();
		e.stopPropagation();
	}
};


text:
<?php

include "Photo.class.php";
include "PhotoGallery.class.php";
include "Object.class.php";
include "Gallery.class.php";


text:
<Record>
<Term>Efegatran</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Protease Inhibitor</ParentTerm>
<ParentTerm>Anticoagulant Agent</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Anticoagulant Agent/Efegatran Sulfate</ClassificationPath>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Anticoagulant Agent/Efegatran,/NCIThesaurus/Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Enzyme Inhibitor/Protease Inhibitor/Efegatran</ClassificationPath>
<BroaderTerm>Efegatran Sulfate</BroaderTerm>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Enzyme Inhibitor</BroaderTerm>
<BroaderTerm>NCIThesaurus</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Efegatran</BroaderTerm>
<BroaderTerm>Adjuvant</BroaderTerm>
<BroaderTerm>Protease Inhibitor</BroaderTerm>
<BroaderTerm>Anticoagulant Agent</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<BroaderTerm>Efegatran,</BroaderTerm>
<Synonym>EFEGATRAN</Synonym>
<Synonym>Efegatran Sulfate</Synonym>
<Synonym>Efegatran</Synonym>
<Synonym>EFEGATRAN SULFATE</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
package org.apache.flink.runtime.util;

import org.junit.Test;

import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import static org.apache.flink.util.Preconditions.checkNotNull;

public class EvictingBoundedListTest {

	@Test
	public void testAddGet() {
		int insertSize = 17;
		int boundSize = 5;
		Integer defaultElement = 4711;

		EvictingBoundedList<Integer> list = new EvictingBoundedList<>(boundSize, defaultElement);
		assertTrue(list.isEmpty());

		for (int i = 0; i < insertSize; ++i) {
			list.add(i);
		}

		assertEquals(17, list.size());

		for (int i = 0; i < insertSize; ++i) {
			int exp = i < (insertSize - boundSize) ? defaultElement : i;
			int act = list.get(i);
			assertEquals(exp, act);
		}
	}

	@Test
	public void testSet() {
		int insertSize = 17;
		int boundSize = 5;
		Integer defaultElement = 4711;
		List<Integer> reference = new ArrayList<>(insertSize);
		EvictingBoundedList<Integer> list = new EvictingBoundedList<>(boundSize, defaultElement);
		for (int i = 0; i < insertSize; ++i) {
			reference.add(i);
			list.add(i);
		}

		assertEquals(reference.size(), list.size());

		list.set(0, 123);
		list.set(insertSize - boundSize - 1, 123);

		list.set(insertSize - boundSize, 42);
		reference.set(insertSize - boundSize, 42);
		list.set(13, 43);
		reference.set(13, 43);
		list.set(16, 44);
		reference.set(16, 44);

		try {
			list.set(insertSize, 23);
			fail("Illegal index in set not detected.");
		} catch (IllegalArgumentException ignored) {

		}

		for (int i = 0; i < insertSize; ++i) {
			int exp = i < (insertSize - boundSize) ? defaultElement : reference.get(i);
			int act = list.get(i);
			assertEquals(exp, act);
		}

		assertEquals(reference.size(), list.size());
	}

	@Test
	public void testClear() {
		int insertSize = 17;
		int boundSize = 5;
		Integer defaultElement = 4711;

		EvictingBoundedList<Integer> list = new EvictingBoundedList<>(boundSize, defaultElement);
		for (int i = 0; i < insertSize; ++i) {
			list.add(i);
		}

		list.clear();

		assertEquals(0, list.size());
		assertTrue(list.isEmpty());

		try {
			list.get(0);
			fail();
		} catch (IndexOutOfBoundsException ignore) {
		}
	}

	@Test
	public void testIterator() {
		int insertSize = 17;
		int boundSize = 5;
		Integer defaultElement = 4711;

		EvictingBoundedList<Integer> list = new EvictingBoundedList<>(boundSize, defaultElement);
		assertTrue(list.isEmpty());

		for (int i = 0; i < insertSize; ++i) {
			list.add(i);
		}

		Iterator<Integer> iterator = list.iterator();

		for (int i = 0; i < insertSize; ++i) {
			assertTrue(iterator.hasNext());
			int exp = i < (insertSize - boundSize) ? defaultElement : i;
			int act = iterator.next();
			assertEquals(exp, act);
		}

		assertFalse(iterator.hasNext());

		try {
			iterator.next();
			fail("Next on exhausted iterator did not trigger exception.");
		} catch (NoSuchElementException ignored) {

		}

		iterator = list.iterator();
		assertTrue(iterator.hasNext());
		iterator.next();
		list.add(123);
		assertTrue(iterator.hasNext());
		try {
			iterator.next();
			fail("Concurrent modification not detected.");
		} catch (ConcurrentModificationException ignored) {

		}
	}

	@Test
	public void testMapWithHalfFullList() {
		final Object[] originals = { new Object(), new Object(), new Object() };
		final Object defaultValue = new Object();

		final EvictingBoundedList<Object> original = new EvictingBoundedList<>(5, defaultValue);
		for (Object o : originals) {
			original.add(o);
		}

		final EvictingBoundedList<TransformedObject> transformed = original.map(new Mapper());

		assertEquals(original.size(), transformed.size());
		assertEquals(original.getSizeLimit(), transformed.getSizeLimit());
		assertEquals(defaultValue, transformed.getDefaultElement().original);

		int i = 0;
		for (TransformedObject to : transformed) {
			assertEquals(originals[i++], to.original);
		}

		try {
			transformed.get(originals.length);
			fail("should have failed with an exception");
		} catch (IndexOutOfBoundsException e) {
			// expected
		}
	}

	@Test
	public void testMapWithEvictedElements() {
		final Object[] originals = { new Object(), new Object(), new Object(), new Object(), new Object() };
		final Object defaultValue = new Object();

		final EvictingBoundedList<Object> original = new EvictingBoundedList<>(2, defaultValue);
		for (Object o : originals) {
			original.add(o);
		}

		final EvictingBoundedList<TransformedObject> transformed = original.map(new Mapper());

		assertEquals(originals.length, transformed.size());
		assertEquals(original.size(), transformed.size());
		assertEquals(original.getSizeLimit(), transformed.getSizeLimit());
		assertEquals(defaultValue, transformed.getDefaultElement().original);

		for (int i = 0; i < originals.length; i++) {
			if (i < originals.length - transformed.getSizeLimit()) {
				assertEquals(transformed.getDefaultElement(), transformed.get(i));
			} else {
				assertEquals(originals[i], transformed.get(i).original);
			}
		}

		try {
			transformed.get(originals.length);
			fail("should have failed with an exception");
		} catch (IndexOutOfBoundsException e) {
			// expected
		}
	}

	@Test
	public void testMapWithNullDefault() {
		final EvictingBoundedList<Object> original = new EvictingBoundedList<>(5, null);
		final EvictingBoundedList<TransformedObject> transformed = original.map(new Mapper());

		assertEquals(original.size(), transformed.size());
		assertNull(transformed.getDefaultElement());
	}

	// ------------------------------------------------------------------------

	private static final class TransformedObject {

		final Object original;

		TransformedObject(Object original) {
			this.original = checkNotNull(original);
		}
	}

	// ------------------------------------------------------------------------

	private static final class Mapper implements EvictingBoundedList.Function<Object, TransformedObject> {

		@Override
		public TransformedObject apply(Object value) {
			return new TransformedObject(value);
		}
	}
}


text:
import {
    combineLatest as observableCombineLatest,
    empty as observableEmpty,
    merge as observableMerge,
    from as observableFrom,
    Observable,
} from "rxjs";

import {
    distinctUntilChanged,
    filter,
    first,
    map,
    mergeMap,
    publishReplay,
    refCount,
    share,
    skipWhile,
    startWith,
    switchMap,
    tap,
} from "rxjs/operators";

import { TagCreator } from "./TagCreator";
import { TagDOMRenderer } from "./TagDOMRenderer";
import { TagScene } from "./TagScene";
import { TagMode } from "./TagMode";
import { TagSet } from "./TagSet";
import { Geometry } from "./geometry/Geometry";
import { PointsGeometry } from "./geometry/PointsGeometry";
import { CreateHandlerBase } from "./handlers/CreateHandlerBase";
import { CreatePointHandler } from "./handlers/CreatePointHandler";
import { CreatePointsHandler } from "./handlers/CreatePointsHandler";
import { CreatePolygonHandler } from "./handlers/CreatePolygonHandler";
import { CreateRectHandler } from "./handlers/CreateRectHandler";
import { CreateRectDragHandler } from "./handlers/CreateRectDragHandler";
import { EditVertexHandler } from "./handlers/EditVertexHandler";
import { Tag } from "./tag/Tag";
import { RenderTag } from "./tag/RenderTag";
import { CreateTag } from "./tag/CreateTag";

import { Component } from "../Component";
import { TagConfiguration } from "../interfaces/TagConfiguration";

import { Transform } from "../../geo/Transform";
import { ViewportCoords } from "../../geo/ViewportCoords";
import { Navigator } from "../../viewer/Navigator";
import { RenderPass } from "../../render/RenderPass";
import { RenderCamera } from "../../render/RenderCamera";
import { GLRenderHash } from "../../render/interfaces/IGLRenderHash";
import { ViewportSize } from "../../render/interfaces/ViewportSize";
import { VirtualNodeHash } from "../../render/interfaces/VirtualNodeHash";
import { AnimationFrame } from "../../state/interfaces/AnimationFrame";
import { Container } from "../../viewer/Container";
import { ISpriteAtlas } from "../../viewer/interfaces/ISpriteAtlas";
import { ComponentEventType } from "../events/ComponentEventType";
import { ComponentTagModeEvent } from "../events/ComponentTagModeEvent";
import { ComponentGeometryEvent } from "../events/ComponentGeometryEvent";
import { ComponentStateEvent } from "../events/ComponentStateEvent";
import { ComponentName } from "../ComponentName";

/**
 * @class TagComponent
 *
 * @classdesc Component for showing and editing tags with different
 * geometries composed from 2D basic image coordinates (see the
 * {@link Viewer} class documentation for more information about coordinate
 * systems).
 *
 * The `add` method is used for adding new tags or replacing
 * tags already in the set. Tags are removed by id.
 *
 * If a tag already in the set has the same
 * id as one of the tags added, the old tag will be removed and
 * the added tag will take its place.
 *
 * The tag component mode can be set to either be non interactive or
 * to be in creating mode of a certain geometry type.
 *
 * The tag properties can be updated at any time and the change will
 * be visibile immediately.
 *
 * Tags are only relevant to a single image because they are based on
 * 2D basic image coordinates. Tags related to a certain image should
 * be removed when the viewer is moved to another image.
 *
 * To retrive and use the tag component
 *
 * @example
 * ```js
 * var viewer = new Viewer({ component: { tag: true } }, ...);
 *
 * var tagComponent = viewer.getComponent("tag");
 * ```
 */
export class TagComponent extends Component<TagConfiguration> {
    /** @inheritdoc */
    public static componentName: ComponentName = "tag";

    private _tagDomRenderer: TagDOMRenderer;
    private _tagScene: TagScene;
    private _tagSet: TagSet;
    private _tagCreator: TagCreator;
    private _viewportCoords: ViewportCoords;

    private _renderTags$: Observable<RenderTag<Tag>[]>;
    private _tagChanged$: Observable<Tag>;
    private _renderTagGLChanged$: Observable<RenderTag<Tag>>;
    private _createGeometryChanged$: Observable<CreateTag<Geometry>>;
    private _createGLObjectsChanged$: Observable<CreateTag<Geometry>>;

    private _creatingConfiguration$: Observable<TagConfiguration>;

    private _createHandlers: {
        [K in keyof typeof TagMode]: CreateHandlerBase;
    };
    private _editVertexHandler: EditVertexHandler;

    /** @ignore */
    constructor(
        name: string,
        container: Container,
        navigator: Navigator) {
        super(name, container, navigator);

        this._tagDomRenderer = new TagDOMRenderer();
        this._tagScene = new TagScene();
        this._tagSet = new TagSet();
        this._tagCreator = new TagCreator(this, navigator);
        this._viewportCoords = new ViewportCoords();

        this._createHandlers = {
            "CreatePoint":
                new CreatePointHandler(
                    this,
                    container,
                    navigator,
                    this._viewportCoords,
                    this._tagCreator),
            "CreatePoints":
                new CreatePointsHandler(
                    this,
                    container,
                    navigator,
                    this._viewportCoords,
                    this._tagCreator),
            "CreatePolygon":
                new CreatePolygonHandler(
                    this,
                    container,
                    navigator,
                    this._viewportCoords,
                    this._tagCreator),
            "CreateRect":
                new CreateRectHandler(
                    this,
                    container,
                    navigator,
                    this._viewportCoords,
                    this._tagCreator),
            "CreateRectDrag":
                new CreateRectDragHandler(
                    this,
                    container,
                    navigator,
                    this._viewportCoords,
                    this._tagCreator),
            "Default": undefined,
        };

        this._editVertexHandler =
            new EditVertexHandler(
                this,
                container,
                navigator,
                this._viewportCoords,
                this._tagSet);

        this._renderTags$ = this._tagSet.changed$.pipe(
            map(
                (tagSet: TagSet): RenderTag<Tag>[] => {
                    const tags: RenderTag<Tag>[] = tagSet.getAll();

                    // ensure that tags are always rendered in the same order
                    // to avoid hover tracking problems on first resize.
                    tags.sort(
                        (t1: RenderTag<Tag>, t2: RenderTag<Tag>): number => {
                            const id1: string = t1.tag.id;
                            const id2: string = t2.tag.id;

                            if (id1 < id2) {
                                return -1;
                            }

                            if (id1 > id2) {
                                return 1;
                            }

                            return 0;
                        });

                    return tags;
                }),
            share());

        this._tagChanged$ = this._renderTags$.pipe(
            switchMap(
                (tags: RenderTag<Tag>[]): Observable<Tag> => {
                    return observableFrom(tags).pipe(
                        mergeMap(
                            (tag: RenderTag<Tag>): Observable<Tag> => {
                                return observableMerge(
                                    tag.tag.changed$,
                                    tag.tag.geometryChanged$);
                            }));
                }),
            share());

        this._renderTagGLChanged$ = this._renderTags$.pipe(
            switchMap(
                (tags: RenderTag<Tag>[]): Observable<RenderTag<Tag>> => {
                    return observableFrom(tags).pipe(
                        mergeMap(
                            (tag: RenderTag<Tag>): Observable<RenderTag<Tag>> => {
                                return tag.glObjectsChanged$;
                            }));
                }),
            share());

        this._createGeometryChanged$ = this._tagCreator.tag$.pipe(
            switchMap(
                (tag: CreateTag<Geometry>): Observable<CreateTag<Geometry>> => {
                    return tag != null ?
                        tag.geometryChanged$ :
                        observableEmpty();
                }),
            share());

        this._createGLObjectsChanged$ = this._tagCreator.tag$.pipe(
            switchMap(
                (tag: CreateTag<Geometry>): Observable<CreateTag<Geometry>> => {
                    return tag != null ?
                        tag.glObjectsChanged$ :
                        observableEmpty();
                }),
            share());

        this._creatingConfiguration$ = this._configuration$.pipe(
            distinctUntilChanged(
                (c1: TagConfiguration, c2: TagConfiguration): boolean => {
                    return c1.mode === c2.mode;
                },
                (configuration: TagConfiguration): TagConfiguration => {
                    return {
                        createColor: configuration.createColor,
                        mode: configuration.mode,
                    };
                }),
            publishReplay(1),
            refCount());

        this._creatingConfiguration$
            .subscribe(
                (configuration: TagConfiguration): void => {
                    const type: ComponentEventType = "tagmode";
                    const event: ComponentTagModeEvent = {
                        mode: configuration.mode,
                        target: this,
                        type,
                    };
                    this.fire(type, event);
                });
    }

    /**
     * Add tags to the tag set or replace tags in the tag set.
     *
     * @description If a tag already in the set has the same
     * id as one of the tags added, the old tag will be removed
     * the added tag will take its place.
     *
     * @param {Array<Tag>} tags - Tags to add.
     *
     * @example
     * ```js
     * tagComponent.add([tag1, tag2]);
     * ```
     */
    public add(tags: Tag[]): void {
        if (this._activated) {
            this._navigator.stateService.currentTransform$.pipe(
                first())
                .subscribe(
                    (transform: Transform): void => {
                        this._tagSet.add(tags, transform);

                        const renderTags: RenderTag<Tag>[] = tags
                            .map(
                                (tag: Tag): RenderTag<Tag> => {
                                    return this._tagSet.get(tag.id);
                                });

                        this._tagScene.add(renderTags);
                    });
        } else {
            this._tagSet.addDeactivated(tags);
        }
    }

    /**
     * Calculate the smallest rectangle containing all the points
     * in the points geometry.
     *
     * @description The result may be different depending on if the
     * current image is an spherical or not. If the
     * current image is an spherical the rectangle may
     * wrap the horizontal border of the image.
     *
     * @returns {Promise<Array<number>>} Promise to the rectangle
     * on the format specified for the {@link RectGeometry} in basic
     * coordinates.
     */
    public calculateRect(geometry: PointsGeometry): Promise<number[]> {
        return new Promise<number[]>((resolve: (value: number[]) => void, reject: (reason: Error) => void): void => {
            this._navigator.stateService.currentTransform$.pipe(
                first(),
                map(
                    (transform: Transform): number[] => {
                        return geometry.getRect2d(transform);
                    }))
                .subscribe(
                    (rect: number[]): void => {
                        resolve(rect);
                    },
                    (error: Error): void => {
                        reject(error);
                    });
        });
    }

    /**
     * Force the creation of a geometry programatically using its
     * current vertices.
     *
     * @description The method only has an effect when the tag
     * mode is either of the following modes:
     *
     * {@link TagMode.CreatePoints}
     * {@link TagMode.CreatePolygon}
     * {@link TagMode.CreateRect}
     * {@link TagMode.CreateRectDrag}
     *
     * In the case of points or polygon creation, only the created
     * vertices are used, i.e. the mouse position is disregarded.
     *
     * In the case of rectangle creation the position of the mouse
     * at the time of the method call is used as one of the vertices
     * defining the rectangle.
     *
     * @fires geometrycreate
     *
     * @example
     * ```js
     * tagComponent.on("geometrycreate", function(geometry) {
     *     console.log(geometry);
     * });
     *
     * tagComponent.create();
     * ```
     */
    public create(): void {
        this._tagCreator.replayedTag$.pipe(
            first(),
            filter(
                (tag: CreateTag<Geometry>): boolean => {
                    return !!tag;
                }))
            .subscribe(
                (tag: CreateTag<Geometry>): void => {
                    tag.create();
                });
    }

    /**
     * Change the current tag mode.
     *
     * @description Change the tag mode to one of the create modes for creating new geometries.
     *
     * @param {TagMode} mode - New tag mode.
     *
     * @fires tagmode
     *
     * @example
     * ```js
     * tagComponent.changeMode(TagMode.CreateRect);
     * ```
     */
    public changeMode(mode: TagMode): void {
        this.configure({ mode: mode });
    }

    public fire(
        type: "geometrycreate",
        event: ComponentGeometryEvent)
        : void;
    public fire(
        type: "tagmode",
        event: ComponentTagModeEvent)
        : void;
    /** @ignore */
    public fire(
        type:
            | "tagcreateend"
            | "tagcreatestart"
            | "tags",
        event: ComponentStateEvent)
        : void;
    public fire<T>(
        type: ComponentEventType,
        event: T)
        : void {
        super.fire(type, event);
    }

    /**
     * Returns the tag in the tag set with the specified id, or
     * undefined if the id matches no tag.
     *
     * @param {string} tagId - Id of the tag.
     *
     * @example
     * ```js
     * var tag = tagComponent.get("tagId");
     * ```
     */
    public get(tagId: string): Tag {
        if (this._activated) {
            const renderTag: RenderTag<Tag> = this._tagSet.get(tagId);
            return renderTag !== undefined ? renderTag.tag : undefined;
        } else {
            return this._tagSet.getDeactivated(tagId);
        }
    }

    /**
     * Returns an array of all tags.
     *
     * @example
     * ```js
     * var tags = tagComponent.getAll();
     * ```
     */
    public getAll(): Tag[] {
        if (this.activated) {
            return this._tagSet
                .getAll()
                .map(
                    (renderTag: RenderTag<Tag>): Tag => {
                        return renderTag.tag;
                    });
        } else {
            return this._tagSet.getAllDeactivated();
        }
    }

    /**
     * Returns an array of tag ids for tags that contain the specified point.
     *
     * @description The pixel point must lie inside the polygon or rectangle
     * of an added tag for the tag id to be returned. Tag ids for
     * tags that do not have a fill will also be returned if the point is inside
     * the geometry of the tag. Tags with point geometries can not be retrieved.
     *
     * No tag ids will be returned for polygons rendered in cropped spherical or
     * rectangles rendered in spherical.
     *
     * Notice that the pixelPoint argument requires x, y coordinates from pixel space.
     *
     * With this function, you can use the coordinates provided by mouse
     * events to get information out of the tag component.
     *
     * If no tag at exist the pixel point, an empty array will be returned.
     *
     * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
     * @returns {Promise<Array<string>>} Promise to the ids of the tags that
     * contain the specified pixel point.
     *
     * @example
     * ```js
     * tagComponent.getTagIdsAt([100, 100])
     *     .then((tagIds) => { console.log(tagIds); });
     * ```
     */
    public getTagIdsAt(pixelPoint: number[]): Promise<string[]> {
        return new Promise<string[]>((resolve: (value: string[]) => void, reject: (reason: Error) => void): void => {
            this._container.renderService.renderCamera$.pipe(
                first(),
                map(
                    (render: RenderCamera): string[] => {
                        const viewport: number[] = this._viewportCoords
                            .canvasToViewport(
                                pixelPoint[0],
                                pixelPoint[1],
                                this._container.container);

                        const ids: string[] = this._tagScene.intersectObjects(viewport, render.perspective);

                        return ids;
                    }))
                .subscribe(
                    (ids: string[]): void => {
                        resolve(ids);
                    },
                    (error: Error): void => {
                        reject(error);
                    });
        });
    }

    /**
     * Check if a tag exist in the tag set.
     *
     * @param {string} tagId - Id of the tag.
     *
     * @example
     * ```js
     * var tagExists = tagComponent.has("tagId");
     * ```
     */
    public has(tagId: string): boolean {
        return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId);
    }

    public off(
        type: "geometrycreate",
        handler: (event: ComponentGeometryEvent) => void)
        : void;
    public off(
        type: "tagmode",
        handler: (event: ComponentTagModeEvent) => void)
        : void;
    public off(
        type:
            | "tagcreateend"
            | "tagcreatestart"
            | "tags",
        handler: (event: ComponentStateEvent) => void)
        : void;
    public off<T>(
        type: ComponentEventType,
        handler: (event: T) => void)
        : void {
        super.off(type, handler);
    }

    /**
     * Event fired when a geometry has been created.
     *
     * @event geometrycreated
     * @example
     * ```js
     * // Initialize the viewer
     * var viewer = new Viewer({ // viewer options });
     * var component = viewer.getComponent('<component-name>');
     * // Set an event listener
     * component.on('geometrycreated', function() {
     *   console.log("A geometrycreated event has occurred.");
     * });
     * ```
     */
    public on(
        type: "geometrycreate",
        handler: (event: ComponentGeometryEvent) => void)
        : void;
    /**
     * Event fired when an interaction to create a geometry ends.
     *
     * @description A create interaction can by a geometry being created
     * or by the creation being aborted.
     *
     * @event tagcreateend
     * @example
     * ```js
     * // Initialize the viewer
     * var viewer = new Viewer({ // viewer options });
     * var component = viewer.getComponent('<component-name>');
     * // Set an event listener
     * component.on('tagcreateend', function() {
     *   console.log("A tagcreateend event has occurred.");
     * });
     * ```
     */
    public on(
        type: "tagcreateend",
        handler: (event: ComponentStateEvent) => void)
        : void;
    /**
     * Event fired when an interaction to create a geometry starts.
     *
     * @description A create interaction starts when the first vertex
     * is created in the geometry.
     *
     * @event tagcreatestart
     * @example
     * ```js
     * // Initialize the viewer
     * var viewer = new Viewer({ // viewer options });
     * var component = viewer.getComponent('<component-name>');
     * // Set an event listener
     * component.on('tagcreatestart', function() {
     *   console.log("A tagcreatestart event has occurred.");
     * });
     * ```
     */
    public on(
        type: "tagcreatestart",
        handler: (event: ComponentStateEvent) => void)
        : void;
    /**
     * Event fired when the create mode is changed.
     *
     * @event tagmode
     * @example
     * ```js
     * // Initialize the viewer
     * var viewer = new Viewer({ // viewer options });
     * var component = viewer.getComponent('<component-name>');
     * // Set an event listener
     * component.on('tagmode', function() {
     *   console.log("A tagmode event has occurred.");
     * });
     * ```
     */
    public on(
        type: "tagmode",
        handler: (event: ComponentTagModeEvent) => void)
        : void;
    /**
     * Event fired when the tags collection has changed.
     *
     * @event tags
     * @example
     * ```js
     * // Initialize the viewer
     * var viewer = new Viewer({ // viewer options });
     * var component = viewer.getComponent('<component-name>');
     * // Set an event listener
     * component.on('tags', function() {
     *   console.log("A tags event has occurred.");
     * });
     * ```
     */
    public on(
        type: "tags",
        handler: (event: ComponentStateEvent) => void)
        : void;
    public on<T>(
        type: ComponentEventType,
        handler: (event: T) => void)
        : void {
        super.on(type, handler);
    }

    /**
     * Remove tags with the specified ids from the tag set.
     *
     * @param {Array<string>} tagIds - Ids for tags to remove.
     *
     * @example
     * ```js
     * tagComponent.remove(["id-1", "id-2"]);
     * ```
     */
    public remove(tagIds: string[]): void {
        if (this._activated) {
            this._tagSet.remove(tagIds);
            this._tagScene.remove(tagIds);
        } else {
            this._tagSet.removeDeactivated(tagIds);
        }
    }

    /**
     * Remove all tags from the tag set.
     *
     * @example
     * ```js
     * tagComponent.removeAll();
     * ```
     */
    public removeAll(): void {
        if (this._activated) {
            this._tagSet.removeAll();
            this._tagScene.removeAll();
        } else {
            this._tagSet.removeAllDeactivated();
        }
    }

    protected _activate(): void {
        this._editVertexHandler.enable();

        const handlerGeometryCreated$ =
            observableFrom(<(keyof typeof TagMode)[]>Object.keys(this._createHandlers)).pipe(
                map(
                    (key: keyof typeof TagMode): CreateHandlerBase => {
                        return this._createHandlers[key];
                    }),
                filter(
                    (handler: CreateHandlerBase): boolean => {
                        return !!handler;
                    }),
                mergeMap(
                    (handler: CreateHandlerBase): Observable<Geometry> => {
                        return handler.geometryCreated$;
                    }),
                share());

        const subs = this._subscriptions;

        subs.push(handlerGeometryCreated$
            .subscribe(
                (geometry: Geometry): void => {
                    const type: ComponentEventType = "geometrycreate";
                    const event: ComponentGeometryEvent = {
                        geometry,
                        target: this,
                        type,
                    };
                    this.fire(type, event);
                }));

        subs.push(this._tagCreator.tag$.pipe(
            skipWhile(
                (tag: CreateTag<Geometry>): boolean => {
                    return tag == null;
                }),
            distinctUntilChanged())
            .subscribe(
                (tag: CreateTag<Geometry>): void => {
                    const type: ComponentEventType = tag != null ?
                        "tagcreatestart" :
                        "tagcreateend";
                    const event: ComponentStateEvent = {
                        target: this,
                        type,
                    };
                    this.fire(type, event);
                }));

        subs.push(handlerGeometryCreated$
            .subscribe(
                (): void => {
                    this.changeMode(TagMode.Default);
                }));

        subs.push(this._creatingConfiguration$
            .subscribe(
                (configuration: TagConfiguration): void => {
                    this._disableCreateHandlers();

                    const mode: keyof typeof TagMode = <keyof typeof TagMode>TagMode[configuration.mode];
                    const handler: CreateHandlerBase = this._createHandlers[mode];
                    if (!!handler) {
                        handler.enable();
                    }
                }));

        subs.push(this._renderTags$
            .subscribe(
                (): void => {
                    const type: ComponentEventType = "tags";
                    const event: ComponentStateEvent = {
                        target: this,
                        type,
                    };
                    this.fire(type, event);
                }));

        subs.push(this._tagCreator.tag$.pipe(
            switchMap(
                (tag: CreateTag<Geometry>): Observable<void> => {
                    return tag != null ?
                        tag.aborted$.pipe(
                            map((): void => { return null; })) :
                        observableEmpty();
                }))
            .subscribe((): void => { this.changeMode(TagMode.Default); }));

        subs.push(this._tagCreator.tag$
            .subscribe(
                (tag: CreateTag<Geometry>): void => {
                    if (this._tagScene.hasCreateTag()) {
                        this._tagScene.removeCreateTag();
                    }

                    if (tag != null) {
                        this._tagScene.addCreateTag(tag);
                    }
                }));

        subs.push(this._createGLObjectsChanged$
            .subscribe(
                (tag: CreateTag<Geometry>): void => {
                    this._tagScene.updateCreateTagObjects(tag);
                }));

        subs.push(this._renderTagGLChanged$
            .subscribe(
                (tag: RenderTag<Tag>): void => {
                    this._tagScene.updateObjects(tag);
                }));

        subs.push(this._tagChanged$
            .subscribe(
                (): void => {
                    this._tagScene.update();
                }));

        subs.push(observableCombineLatest(
            this._renderTags$.pipe(
                startWith([]),
                tap(
                    (): void => {
                        this._container.domRenderer.render$.next({
                            name: this._name,
                            vNode: this._tagDomRenderer.clear(),
                        });
                    })),
            this._container.renderService.renderCamera$,
            this._container.spriteService.spriteAtlas$,
            this._container.renderService.size$,
            this._tagChanged$.pipe(startWith(null)),
            observableMerge(
                this._tagCreator.tag$,
                this._createGeometryChanged$).pipe(startWith(null))).pipe(
                    map(
                        ([renderTags, rc, atlas, size, , ct]:
                            [RenderTag<Tag>[], RenderCamera, ISpriteAtlas, ViewportSize, Tag, CreateTag<Geometry>]):
                            VirtualNodeHash => {
                            return {
                                name: this._name,
                                vNode: this._tagDomRenderer.render(renderTags, ct, atlas, rc.perspective, size),
                            };
                        }))
            .subscribe(this._container.domRenderer.render$));

        subs.push(this._navigator.stateService.currentState$.pipe(
            map(
                (frame: AnimationFrame): GLRenderHash => {
                    const tagScene: TagScene = this._tagScene;

                    return {
                        name: this._name,
                        renderer: {
                            frameId: frame.id,
                            needsRender: tagScene.needsRender,
                            render: tagScene.render.bind(tagScene),
                            pass: RenderPass.Opaque,
                        },
                    };
                }))
            .subscribe(this._container.glRenderer.render$));

        this._navigator.stateService.currentTransform$.pipe(
            first())
            .subscribe(
                (transform: Transform): void => {
                    this._tagSet.activate(transform);
                    this._tagScene.add(this._tagSet.getAll());
                });

    }

    protected _deactivate(): void {
        this._editVertexHandler.disable();
        this._disableCreateHandlers();

        this._tagScene.clear();
        this._tagSet.deactivate();

        this._tagCreator.delete$.next(null);

        this._subscriptions.unsubscribe();

        this._container.container.classList.remove("component-tag-create");
    }

    protected _getDefaultConfiguration(): TagConfiguration {
        return {
            createColor: 0xFFFFFF,
            indicatePointsCompleter: true,
            mode: TagMode.Default,
        };
    }

    private _disableCreateHandlers(): void {
        const createHandlers: {
            [K in keyof typeof TagMode]:
            CreateHandlerBase
        } = this._createHandlers;

        for (const key in createHandlers) {
            if (!createHandlers.hasOwnProperty(key)) {
                continue;
            }
            const handler =
                createHandlers[<keyof typeof TagMode>key];
            if (!!handler) {
                handler.disable();
            }
        }
    }
}


text:
#pragma once
#include <aws/elasticloadbalancingv2/ElasticLoadBalancingv2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace ElasticLoadBalancingv2
{
namespace Model
{
  enum class TargetHealthStateEnum
  {
    NOT_SET,
    initial,
    healthy,
    unhealthy,
    unused,
    draining
  };

namespace TargetHealthStateEnumMapper
{
AWS_ELASTICLOADBALANCINGV2_API TargetHealthStateEnum GetTargetHealthStateEnumForName(const Aws::String& name);

AWS_ELASTICLOADBALANCINGV2_API Aws::String GetNameForTargetHealthStateEnum(TargetHealthStateEnum value);
} // namespace TargetHealthStateEnumMapper
} // namespace Model
} // namespace ElasticLoadBalancingv2
} // namespace Aws


text:
template<int> struct A
{
  static int i;
};

template<int N> int A<N>::i(decltype (A::i));	// { dg-error "member function|must be an expression" }


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mem. N. Y. bot. Gdn 28(1): 192 (1976)

#### Original name
Phellinus griseoporus D.A. Reid, 1976

### Remarks
null


text:
CREATE TABLE lowelabArkinOperonScore (
    name varchar(255) not null,	# operon name
    gene1 varchar(255) not null,	# name of gene1
    gene2 varchar(255) not null,	# name og gene2
    prob float not null,	# probability of operon
    gnMinus float not null,	# gene neighbor score
              #Indices
    INDEX(name),
    PRIMARY KEY(name, gene1, gene2)
);


text:
CKEDITOR.plugins.setLang( 'energineimage', 'en', {
	toolbar: 'Insert image from the energine media library',
	title: 'Insert image from the energine media library'
});


text:
<?php

namespace Recca0120\Terminal;

use Exception;
use Illuminate\Contracts\Console\Kernel as KernelContract;
use Illuminate\Contracts\Queue\Queue;
use Illuminate\Foundation\Console\QueuedCommand;
use Illuminate\Support\Arr;
use Recca0120\Terminal\Application as Artisan;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class Kernel implements KernelContract
{
    /**
     * The Artisan application instance.
     *
     * @var \Illuminate\Console\Application
     */
    protected $artisan;

    /**
     * $config.
     *
     * @var array
     */
    protected $config;

    /**
     * The Artisan commands provided by the application.
     *
     * @var array
     */
    protected $commands = [];

    /**
     * Create a new console kernel instance.
     *
     * @param Application $artisan
     * @param array $config
     */
    public function __construct(Artisan $artisan, $config = [])
    {
        $this->artisan = $artisan;
        $this->config = Arr::except(array_merge([
            'username' => 'LARAVEL', 'hostname' => php_uname('n'), 'os' => PHP_OS,
        ], $config), ['enabled', 'whitelists', 'route', 'commands']);
    }

    /**
     * getConfig.
     *
     * @return array
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * Bootstrap the application for artisan commands.
     *
     * @return void
     */
    public function bootstrap()
    {
    }

    /**
     * Handle an incoming console command.
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     * @throws Exception
     */
    public function handle($input, $output = null)
    {
        $this->bootstrap();

        return $this->artisan->run($input, $output);
    }

    /**
     * Run an Artisan console command by name.
     *
     * @param string $command
     * @param array $parameters
     * @param OutputInterface $outputBuffer
     * @return int
     * @throws Exception
     */
    public function call($command, array $parameters = [], $outputBuffer = null)
    {
        $this->bootstrap();

        return $this->artisan->call($command, $parameters, $outputBuffer);
    }

    /**
     * Queue an Artisan console command by name.
     *
     * @param string $command
     * @param array $parameters
     * @return void
     */
    public function queue($command, array $parameters = [])
    {
        $this->bootstrap();

        if (class_exists(QueuedCommand::class)) {
            return QueuedCommand::dispatch(func_get_args());
        }

        $app = $this->artisan->getLaravel();
        $app[Queue::class]->push(
            'Illuminate\Foundation\Console\QueuedJob',
            func_get_args()
        );
    }

    /**
     * Get all of the commands registered with the console.
     *
     * @return array
     */
    public function all()
    {
        $this->bootstrap();

        return $this->artisan->all();
    }

    /**
     * Get the output for the last run command.
     *
     * @return string
     */
    public function output()
    {
        $this->bootstrap();

        return $this->artisan->output();
    }

    /**
     * Terminate the application.
     *
     * @param InputInterface $input
     * @param int $status
     * @return void
     */
    public function terminate($input, $status)
    {
        $this->bootstrap();
        $this->artisan->terminate();
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Brouze | Search Tutors</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/search-page.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                    Toggle navigation

                </button>

Study That Shit

                    <form class="navbar-form" role="search">

                            <input type="text" class="form-control" placeholder="Search Tutors" name="srch-term" id="srch-term">

                                <button class="btn btn-default" type="submit"></button>

                    </form>

                        Hi Buttface

Profile

Saved Tutors

Sign Out

Results

Results go in here

Filter:

                    <form>

                            Subject:
                            <input type="text" class="form-control" id="subject">

                            Teacher:
                            <input type="text" class="form-control" id="teacher">

                            Minimum Price:
                            <input type="text" class="form-control" id="minprcie">

                            Maximum Price:
                            <input type="text" class="form-control" id="maxprice">

                    </form>

Copyright 2015 - YAAAS Labs


text:
require_dependency "chatty/application_controller"

class Chatty::ChatsController < Chatty::ApplicationController
  before_action :set_chat, only: [:show, :edit, :update, :destroy, :messages, :handle, :close]

  def index
    @ransack_params = params[:q] || {}
    @ransack = Chatty::Chat.ransack(@ransack_params.clone)
    @chats = @ransack.result.order(:id).reverse_order
  end

  def show
    respond_to do |format|
      format.json { render(json: {chat: @chat.json}) }
      format.html { render :show }
    end
  end

  def new
    @chat = Chatty::Chat.new
  end

  def edit
  end

  def create
    @chat = Chatty::Chat.new(chat_params)

    if @chat.save
      redirect_to @chat, notice: 'Chat was successfully created.'
    else
      render action: 'new'
    end
  end

  def update
    if @chat.update(chat_params)
      redirect_to @chat, notice: 'Chat was successfully updated.'
    else
      render action: 'edit'
    end
  end

  def destroy
    @chat.destroy
    redirect_to chats_url, notice: 'Chat was successfully destroyed.'
  end

  def messages
    @messages = @chat.messages
    render partial: "messages", layout: false
  end

  def handle
    @chat.handle!
    @chat.create_activity key: "chatty/chat.handled", owner: current_user
    redirect_to chat_path(@chat)
  end

  def close
    @chat.close
    @chat.create_activity key: "chatty/chat.closed", owner: current_user
    redirect_to chat_path(@chat)
  end

private

  def set_chat
    @chat = Chatty::Chat.find(params[:id])
    authorize! action_name.to_sym, @chat
  end

  def chat_params
    params.require(:chat).permit(:user_type, :user_id, :resource_type, :resource_id)
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Linnaea 5: 532, tab. 11:4 (1830)

#### Original name
Anthina subulata Fr.

### Remarks
null


text:
//
//  RefreshTableView.h
//  DJXRefresh
//
//  Created by Founderbn on 14-7-18.
//  Copyright (c) 2014年 Umeng 董剑雄. All rights reserved.
//

#import <UIKit/UIKit.h>

typedef enum{
    UMNomalStatus = 0,//正常状态
    UMPullingStatus = 1,//拉动状态
    UMPreLoadStatus = 2,//达到松手即可加载的状态
    UMLoadingStatus = 3,//正在加载状态
    UMNoMoredStatus = 4,//已是最后一页的状态
} UMLoadStatus;

@class UMComRefreshView;

@interface UMComRefreshView : UIView

@property (nonatomic,retain) UILabel *dateLable;//显示上次刷新时间

@property (nonatomic,retain) UILabel *statusLable;//显示状态信息

@property (nonatomic,retain) UIImageView *indicateImageView;//显示图片箭头图片

@property (nonatomic,retain) UIActivityIndicatorView *activityIndicatorView;//透明指示器

@property (nonatomic,assign) UMLoadStatus  loadStatus;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic,assign) CGFloat beginPullHeight;/*达到松手即可刷新的高度 默认为65.0f*/

@property (nonatomic, assign) UIEdgeInsets scrollViewOriginalInset;

@property (nonatomic, assign) CGFloat pullingPercent;

@property (nonatomic, copy) NSString * (^noticeForLoadStatusBlock)(UMLoadStatus loadStatus);

@property (nonatomic, copy) void(^loadingBlock)();

+ (UMComRefreshView *)refreshControllViewWithScrollView:(UIScrollView *)scrollView block:(void(^)())block;

- (NSString *)noticeForLoadStatus:(UMLoadStatus)loadStatus;

- (void)endLoading;
- (void)noMoreData;

- (void)resetSubViews;

- (void)scrollViewDidChangeOffset:(NSDictionary *)change;

- (void)setRotation:(NSInteger)rotation animated:(BOOL)animated;

@end

@interface UMComHeadView : UMComRefreshView

@end

@interface UMComFootView : UMComRefreshView

@property (nonatomic, assign) BOOL haveNextPage;

@end


text:
### BEGIN INIT INFO
#Provides:          piping
#Required-Start:    $remote_fs $syslog
#Required-Stop:     $remote_fs $syslog
#Default-Start:     2 3 4 5
#Default-Stop:      0 1 6
#Short-Description: Script pings hosts and present it on unicornhat
#Description:
### END INIT INFO

# Change the next 3 lines to suit where you install your script and what you want to call it
DIR=/usr/local/bin/piping
DAEMON=$DIR/piping.py
DAEMON_NAME=piping

# Add any command line options for your daemon here
DAEMON_OPTS=""

# This next line determines what user the script runs as.
# Root generally not recommended but necessary if you are using the Raspberry Pi GPIO from Python.
DAEMON_USER=root

# The process ID of the script when it runs is stored here:
PIDFILE=/var/run/$DAEMON_NAME.pid

. /lib/lsb/init-functions

do_start () {
    log_daemon_msg "Starting system $DAEMON_NAME daemon"
    start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON -- $DAEMON_OPTS
    log_end_msg $?
}
do_stop () {
    log_daemon_msg "Stopping system $DAEMON_NAME daemon"
    sudo python $DIR/clearunicorn.py
    start-stop-daemon --stop --pidfile $PIDFILE --retry 10
    log_end_msg $?
}

case "$1" in

    start|stop)
        do_${1}
        ;;

    restart|reload|force-reload)
        do_stop
        do_start
        ;;

    status)
        status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $?
        ;;
    *)
        echo "Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}"
        exit 1
        ;;

esac
exit 0