text:
<!DOCTYPE HTML>
<meta name="timeout" content="long">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/utils.js"></script>
<script src="/common/dispatcher/dispatcher.js"></script>
<script src="resources/helper.sub.js"></script>
<script>
// When localStorage (`key1`) is modified when a page (`pageA`) is in BFCache,
// storage events should not be fired for the page after becoming active.
// https://github.com/whatwg/storage/issues/119#issuecomment-1115844532
promise_test(async t => {
  const pageA = new RemoteContext(token());
  const pageB = new RemoteContext(token());
  const pageC = new RemoteContext(token());

  const urlA = executorPath + pageA.context_id + '&events=pagehide,pageshow,load';
  const urlB = originCrossSite + executorPath + pageB.context_id;
  const urlC = executorPath + pageC.context_id + '&events=pagehide,pageshow,load';

  // localStorage key to set while pageA is in BFCache.
  const key1 = token();
  // localStorage key to set after pageA is restored from BFCache.
  const key2 = token();

  const startRecordingStorageEvent = (key1, key2) => {
    window.key1EventFired = new Promise(resolve => {
      window.addEventListener('storage', e => {
        if (e.key === key1) {
          recordEvent('storage1');
          resolve();
        }
      });
    });
    window.key2EventFired = new Promise(resolve => {
      window.addEventListener('storage', e => {
        if (e.key === key2) {
          recordEvent('storage2');
          resolve();
        }
      });
    });
  };

  window.open(urlA, '_blank', 'noopener');
  await pageA.execute_script(waitForPageShow);
  await pageA.execute_script(startRecordingStorageEvent, [key1, key2]);

  // Window C is an unrelated window kept open without navigation, to confirm
  // that storage events are fired as expected in non-BFCache-related scenario
  // and not blocked due to non-BFCache-related reasons.
  window.open(urlC, '_blank');
  await pageC.execute_script(waitForPageShow);
  await pageC.execute_script(startRecordingStorageEvent, [key1, key2]);

  // Navigate A to B.
  await pageA.execute_script((url) => {
    prepareNavigation(() => {
      location.href = url;
    });
  }, [urlB]);
  await pageB.execute_script(waitForPageShow);

  // Update `key1` while pageA is in BFCache.
  localStorage.setItem(key1, 'value');

  // Wait for a storage event is fired on PageC and a while,
  // to prevent race conditions between event processing
  // triggered by `setItem()` and the following operations.
  await pageC.execute_script(() => window.key1EventFired);
  await new Promise(resolve => t.step_timeout(resolve, 1000));

  // Back navigate to pageA, to be restored from BFCache.
  await pageB.execute_script(
    () => {
      prepareNavigation(() => { history.back(); });
    }
  );
  await pageA.execute_script(waitForPageShow);
  await assert_bfcached(pageA);

  // Update `key2` after pageA is restored from BFCache.
  localStorage.setItem(key2, 'value');

  // Wait for a storage event for `key2` is fired on PageA.
  await pageA.execute_script(() => window.key2EventFired);

  // Confirm that a storage event for `key1` is not fired on PageA.
  assert_array_equals(
    await pageA.execute_script(() => getRecordedEvents()),
    [
      'window.load',
      'window.pageshow',
      'window.pagehide.persisted',
      'window.pageshow.persisted',
      'storage2',
    ],
    'pageA should not receive storage events for updates while in BFCache');

}, 'Storage events should not be fired for BFCached pages after becoming active');
</script>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/DiscordWebhookConnector.iml" filepath="$PROJECT_DIR$/.idea/DiscordWebhookConnector.iml" />
    </modules>
  </component>
</project>

redpajama_set_name: RedPajamaGithub


text:
/*    */ package com.hundsun.network.gates.wulin.biz.dao.ibatis.baseset;
/*    */
/*    */ import com.hundsun.network.gates.luosi.common.base.BaseDAO;
/*    */ import com.hundsun.network.gates.wulin.biz.dao.baseset.SystemServicechargeSpecialDAO;
/*    */ import com.hundsun.network.gates.wulin.biz.domain.baseset.SystemServicechargeSpecial;
/*    */ import com.hundsun.network.gates.wulin.biz.domain.baseset.SystemServicechargeSpecialExt;
/*    */ import com.hundsun.network.melody.common.util.StringUtil;
/*    */ import java.util.List;
/*    */ import org.springframework.orm.ibatis.SqlMapClientTemplate;
/*    */ import org.springframework.stereotype.Repository;
/*    */
/*    */ @Repository("systemServicechargeSpecialDAO")
/*    */ public class SystemServicechargeSpecialDAOImpl extends BaseDAO
/*    */   implements SystemServicechargeSpecialDAO
/*    */ {
/*    */   public List<SystemServicechargeSpecialExt> selectChargeSpecialByCond(String userAccount, String proTypeCode, String tradingType, String haveAuctioneer, Long turnoverAmount)
/*    */   {
/* 25 */     SystemServicechargeSpecial sscs = new SystemServicechargeSpecial();
/* 26 */     if (StringUtil.isNotEmpty(userAccount)) {
/* 27 */       sscs.setUserAccount(userAccount);
/*    */     }
/* 29 */     if (StringUtil.isNotEmpty(proTypeCode)) {
/* 30 */       sscs.setProTypeCode(proTypeCode);
/*    */     }
/* 32 */     if (StringUtil.isNotEmpty(tradingType)) {
/* 33 */       sscs.setTradingType(tradingType);
/*    */     }
/* 35 */     if (StringUtil.isNotEmpty(haveAuctioneer)) {
/* 36 */       sscs.setHaveAuctioneer(haveAuctioneer);
/*    */     }
/* 38 */     if (null != turnoverAmount) {
/* 39 */       sscs.setTurnoverAmount(turnoverAmount);
/*    */     }
/* 41 */     return getSqlMapClientTemplate().queryForList("SYSTEM_SERVICECHARGE_SPECIAL.selectChargeSpecialByCond", sscs);
/*    */   }
/*    */
/*    */   public SystemServicechargeSpecial selectChargeSpecialSystem()
/*    */   {
/* 49 */     return (SystemServicechargeSpecial)getSqlMapClientTemplate().queryForObject("SYSTEM_SERVICECHARGE_SPECIAL.selectChargeSpecialSystem");
/*    */   }
/*    */ }

/* Location:           E:\__安装归档\linquan-20161112\deploy16\wulin\webroot\WEB-INF\classes\
 * Qualified Name:     com.hundsun.network.gates.wulin.biz.dao.ibatis.baseset.SystemServicechargeSpecialDAOImpl
 * JD-Core Version:    0.6.0
 */


text:
class Starbot
  class Conversation
    class << self
      attr_writer :bot, :wrappers, :name, :desc
      # Answers to questions that can be asked at any time during a Conversation
      def answers
        @answers ||= {}
      end # answers

      def bot
        @bot || raise("I don't know how to reach my bot")
      end # bot
      # Holds code to execute at the start and end or the conversation
      def wrappers
        @wrappers ||= {:before => {:all => [], :each => []}, :after => {:all => [], :each => []}}
      end # wrappers

      # Code to execute either at the start of the conversation or as each response is received
      # @param [Symbol] scope :all, or :each
      def before(scope, &blk)
        raise ArgumentError, "scope must be either :all, or :each" unless [:all, :each].include?(scope)
        wrappers[:before][scope].push(blk)
      end # before(scope, &blk)

      # Code to execute either at the end of the conversation or after each response is sent
      # @param [Symbol] scope :all, or :each
      def after(scope, &blk)
        raise ArgumentError, "scope must be either :all, or :each" unless [:all, :each].include?(scope)
        wrappers[:after][scope].push(blk)
      end # after(scope, &blk)
    end # << self

    attr_reader :events, :raw, :params, :opts, :bot
    attr_accessor :desc, :name

    def initialize(msg, *args)
      @raw            = msg
      @msg            = msg
      @opts           = args.last.is_a?(Hash) ? args.pop : {}
      @params         = args

      @answers        = []
      @level          = 0
      @bot            = self.class.bot
      @room           = msg.room
      @contact        = msg.contact
      @first_question = msg.txt
      # See #on
      @events         = {}
      # Listeners for specific rooms and contacts that are not in this conversation
      @listeners      = {}
      # An intercept for this specific conversation. It overrides any handlers defined
      # at any level of the conversation
      @intercept      = nil

      on(:no_answer) { end_conversation }
      on(:branch_end) { end_conversation }
      always_answer("go back") { go_back(2) }
      always_answer("help") do
        say(%Q{you started this conversation by asking, "#{@first_question}"} )
        say("At level #{@level - 1} I'll respond to:")
        say("·  " + answers(@level - 1).keys.join("\n·  "))
      end
      always_answer("end conversation") { end_conversation }

      self.class.wrappers[:before][:all].each { |wrapper| instance_eval(&wrapper) }
      register_with_router
    end # initialize(msg)

    # Any methods that are defined in Starbot are accessible in the Conversations through
    # this method_missing. If they are not available in the Starbot then the method call
    # will go to the superclass.
    def method_missing(meth, *args, &blk)
      if self.class.bot.respond_to?(meth)
        block_given? ? self.class.bot.send(meth, *args, &blk) : self.class.bot.send(meth, *args)
      else
        block_given? ? super(meth, *args, &blk) : super(meth, *args)
      end # self.class.bot.respond_to?(meth)
    end # method_missing(meth, *args, &blk)

    # Causes starbot to remember a fact.
    # A remembered fact can be recalled from any conversation and will
    # survive a restart of the bot.
    # @param [String, Symbol] key
    # @param [Object] value
    def remember(key, value)
      self.class.bot.remember(key, value)
    end # remember(key, value)
    def recal(key, dflt = nil)
      self.class.bot.recal(key, dflt)
    end # recal(key)
    def forget(key)
      self.class.bot.forget(key)
    end # forget(key)

    # Asks a question and yields the response (the next message)
    # @param [String] question
    def ask(question)
      say("#{question}") if question.is_a?(String)
      intercept_until do |resp|
        yield(resp)
        true
      end #  |txt, resp|
      nil
    end # ask(msg, question)

    # Asks for agreement to the given question. If the response is n[o], or y[es]
    # then false or true is yielded. If the response is not n[o], or y[es] then
    # asks the user to respond yes or no.
    # @param [String] question
    def agree?(question)
      (question[-1] == '?' ? question : "#{question}?").tap do |q|
        say(q)
      end #  |q|

      intercept_until do |msg|
        resp = msg.downcase
        if resp == 'y' || resp == 'yes'
          yield(true, msg)
          true
        elsif resp == 'n' || resp == 'no'
          yield(false, msg)
          true
        else
          say("please answer yes, or no")
          false
        end # resp == 'y' || resp == 'yes'
      end #  |txt, msg|
      nil
    end # agree?(msg, question)

    # Routes all messages from the given room (@room) and optional contact (@contact)
    # to the given block until the block returns true, or until the conversation ends.
    # @param [Room] rm (@room)
    # @param [Contact, nil] ctct (@contact)
    def listen_until(rm = @room, ctct = @contact, &blk)
      return unless block_given?
      @listeners["#{rm}:#{ctct}"] = blk
      if events[:conversation_end].nil?
        on(:conversation_end) { @listeners.each {|k,b| bot.stop_watching(*k.split(":"), &b) }}
      end # events[:conversation_end].nil?
      bot.watch_until(rm, ctct, &blk)
    end # listen_until(room = @room, contact = @contact)

    # Stop listening to the given room and contact. Use this method to cancel #listen_until
    # without ending the conversation.
    def stop_listening(rm = @room, ctct = @contact)
      return if @listeners["#{rm}:#{ctct}"].nil?
      bot.stop_watching(rm, ctct, &@listeners["#{rm}:#{ctct}"])
    end # stop_listening(rm = @room, ctct = @contact)

    # Returns the list of available answers at the current level
    def answers(lev = @level)
      @answers[lev] ||= {}
    end # answers

    # Creates an answer to a question that can be asked at any level of
    # the conversation. Any previously defined 'always answer' for the
    # given question will be overriden. Answers defiend by #answer at
    # any level that share the same 'question' will override the
    # 'always answer'
    # @param [String]
    def always_answer(question, &blk)
      self.class.answers[question] = blk
    end # always_answer(question, &blk)

    # Goes back up a level in the conversation
    def go_back(amt = 1)
      @level -= amt
      @level = 0 if @level < 0
      @answers = @answers[0..@level]
      @level
    end # go_back

    # Assigns a handler to a particular event. Currently supported events are:
    #  :branch_end - there are no more answers defined below the current answer
    #  :no_answer - the user asked a question that does not match any questions
    #               defined for this conversation.
    #  :conversation_end - the converstaion has ended
    def on(event, &blk)
      case event
      when :branch_end
        @events[:branch_end] = blk
      when :no_answer
        @events[:no_answer] = blk
      when :intercept_end
        @events[:intercept_end] = blk
      when :conversation_end
        @events[:conversation_end] = blk
      end # event
    end # on(event, &blk)

    # Signals the router that the conversation is over
    def end_conversation
      unless @ended
        self.class.wrappers[:after][:all].each { |wrapper| instance_eval(&wrapper) }
        instance_eval &@events[:conversation_end] unless @events[:conversation_end].nil?
        say("conversation, '#{@first_question}' is over.")
      end
      @ended = true
      true
    end # end_conversation

    # Signals that the convesation is not oever
    def continue_conversation
      false
    end # continue_conversation

    def register_with_router
      bot.watch_until(@room, @contact, &watch_proc)
      nil
    end # register_with_router
    def unregister_with_router
      bot.stop_watching(@room, @contact, &watch_proc)
      nil
    end # unregister_with_router

    def answer(question, &blk)
      return answers[question] unless block_given?
      answers[question] = blk
    end # answer(question, &blk)

    def say(msg)
      bot.sayto(@room || @contact, msg)
    end
    def sayto(addr, msg)
      bot.sayto(addr, msg)
    end
    def sayloud(msg)
      bot.sayloudto(@room || @contact, msg)
    end
    def sayloudto(addr, msg)
      bot.sayloudto(addr, msg)
    end

    # Access a previously defined helper
    # @param [Symbol] name
    def helper(name, *args)
      bot.helper(name, *args)
    end # helper(name, *args)

    def helpers
      bot.helpers
    end # helpers

    def log
      bot.log
    end # log

    # The number of seconds that the bot has been up for.
    def uptime
      bot.uptime
    end # uptime

    # Retrieve all contacts
    def contacts
      bot.contacts
    end # contacts

    # Find a contact by alias or id
    # @param [String] qry
    # @return [Contact, nil]
    # @todo look for contacts in the same room with an alias equivalent to qry
    #       then look for any contact with the alias
    def contact(qry = nil)
      return @contact if qry.nil?
      room.nil? ? bot.contact(qry) : bot.contact(qry, :room => room.id)
    end # contact(qry)

    # Retrieve all rooms
    def rooms
      bot.rooms
    end # rooms

    # Find's a room by alias or id
    # @param [String]
    # @return [Room, nil]
    def room(qry = nil)
      return @room if qry.nil?
      bot.room(qry)
    end # room(qry)

    def scheduled
      bot.scheduled
    end # scheduled

    def bot
      self.class.bot
    end # bot
    def wrappers
      self.class.wrappers
    end # wrappers

    # Causes the given block to intercept all incoming messages in this conversation until the
    # block returns true.
    def intercept_until(&blk)
      @intercept = blk
    end # watch_until(room, contact = nil)

  private

    def watch_proc
      @watch_proc ||= (Proc.new do |txt, msg|
        begin
          if !@intercept.nil?
            if @intercept.call(msg) == true
              @intercept = nil
              instance_eval(&events[:intercept_end]) if events[:intercept_end].respond_to?(:call)
            end # @intercept.call(msg) == true
          else
            m = msg.strip
            @msg = txt
            @raw = msg
            @params = []

            if answers[m]
              ans = answers[m]
            elsif (match = answers.keys.select{|q| q.is_a?(Regexp) }.find{|q| msg.match(q) })
              # obviously this is slow - we can keep track of regexes on reloads
              @params      = *msg.match(match).to_a[1..-1]
              ans = answers[match]
            elsif self.class.answers[m]
              ans = self.class.answers[m]
            elsif (match = self.class.answers.keys.select{|q| q.is_a?(Regexp) }.find{|q| msg.match(q) })
              @params      = *msg.match(match).to_a[1..-1]
              ans = answers[match]
            else
              ans = events[:no_answer]
              say("i couldn't find an answer to, '#{msg}'")
            end # @questions[m]

            @level += 1
            self.class.wrappers[:before][:each].each { |wrapper| instance_eval(&wrapper) }
            res = ans.is_a?(Proc) ? instance_eval(&ans) : nil
            if answers.empty?
              #@level -= 1
              instance_eval &events[:branch_end]
            end # answers.empty?

            if res.is_a?(String)
              say(res)
              res = false
            end # res.is_a?(String)

            self.class.wrappers[:after][:each].each { |wrapper| instance_eval(&wrapper) }
            res == true ? end_conversation : continue_conversation
          end # !@intercept.nil?
        rescue Exception => e
          say("I've encountered an error: \n#{e}\n  #{e.backtrace.join("\n  ")}")
        end # begin
      end) #  |txt, msg|
    end # watch_proc

  end # class::Conversation
end # class::Starbot


text:
import java.awt.Rectangle;
import java.util.ArrayList;

public class CloudNode {
	int centerX;
	int centerY;
	ArrayList<Rectangle> objects;
	CloudNode quadrantI;
	CloudNode quadrantII;
	CloudNode quadrantIII;
	CloudNode quadrantIV;

	public CloudNode(int xloc, int yloc) {
		centerX = xloc;
		centerY = yloc;
		objects = new ArrayList<>();
	}

	public void add(Rectangle obj) {
		// TODO: implement a quadtree for efficient collision detection
		objects.add(obj);
	}

	public boolean collisionDetection(Rectangle obj) {
		for (Rectangle o : objects) {
			if (o.intersects(obj) || o.contains(obj) || obj.contains(o)) {
				return true;
			}
		}
		return false;
	}
}


text:
{% extends "contracts/base.html" %}
{% load i18n %}

{% block title %}{{ contract.contract_description }}{% endblock %}
{% block content %}

{{ contract.description }}

                        {% trans "Description" %}:

                            {{ contract.contract_description }}

                        {% trans "Contractors" %}:
                        {% for contrator in contract.contractors.all %}
                            {% include "contracts/entity_inline.html" with entity=contrator %}
                        {% endfor %}

                        {% trans "Contracted" %}:
                        {% for contracted in contract.contracted.all %}
                            {% include "contracts/entity_inline.html" with entity=contracted %}
                        {% endfor %}

                        {% trans "Value" %}:
                        {% include "contracts/contract_list/colored_price.html" with price=contract.price %}

                        {% trans "Type" %}:
                        {{ contract.contract_type.name }}

                        {% trans "Date" %}:
                        {{contract.signing_date}} ({% trans "registered at"%}
                        {{contract.added_date}})

                        {% trans "Category" %}:
                        {% if contract.category %}
                            {% include "contracts/category_a.html" with category=contract.category %}
                        {% else %}
                            {% trans "No category assigned." %}
                        {% endif %}

                        {% trans "Location" %}:
                        {% include "inline_location.html" %}

                        {% trans "Official record" %}:

                            {{ contract.base_id }}

{% endblock %}


text:
package com.mvdb.platform;

import java.util.HashMap;
import java.util.Map;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import com.mvdb.etl.data.GenericDataRecord;
import com.mvdb.platform.data.MultiVersionRecord;

/**
 * Unit test for simple App.
 */
public class MultiVersionRecordTest extends TestCase
{
    /**
     * Create the test case
     *
     * @param testName
     *            name of the test case
     */
    public MultiVersionRecordTest(String testName)
    {
        super(testName);
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return new TestSuite(MultiVersionRecordTest.class);
    }

    public void testGenericDataRecord()
    {
        GenericDataRecord genericDataRecord1 = new GenericDataRecord();
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("f1", 10);
        map1.put("f2", 20);
        map1.put("f3", 30);
        map1.put("f4", 40);
        genericDataRecord1.setDataMap(map1);

        GenericDataRecord genericDataRecord2 = new GenericDataRecord();
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("f1", 11);
        map2.put("f2", 20);
        map2.put("f3", 31);
        map2.put("f4", 40);
        genericDataRecord2.setDataMap(map2);

        MultiVersionRecord multiVersionRecord = new MultiVersionRecord();
        // Begin Test for adding first record
        multiVersionRecord.addLatestVersion(genericDataRecord1);
        GenericDataRecord ultimateVersion = multiVersionRecord.getVersion(0);
        Map<String, Object> ultimateVersionMap = ultimateVersion.getDataMap();
        assertTrue(ultimateVersionMap.get("f1").equals(10));
        assertTrue(ultimateVersionMap.get("f2").equals(20));
        assertTrue(ultimateVersionMap.get("f3").equals(30));
        assertTrue(ultimateVersionMap.get("f4").equals(40));
        // End Test for adding first record

        // Begin Test for adding second record
        multiVersionRecord.addLatestVersion(genericDataRecord2);
        GenericDataRecord penultimateVersion = multiVersionRecord.getVersion(0);
        Map<String, Object> penultimateVersionMap = penultimateVersion.getDataMap();
        assertTrue(penultimateVersionMap.get("f1").equals(10));
        assertTrue(penultimateVersionMap.get("f2") == null);
        assertTrue(penultimateVersionMap.get("f3").equals(30));
        assertTrue(penultimateVersionMap.get("f4") == null);

        ultimateVersion = multiVersionRecord.getVersion(1);
        ultimateVersionMap = ultimateVersion.getDataMap();
        assertTrue(ultimateVersionMap.get("f1").equals(11));
        assertTrue(ultimateVersionMap.get("f2").equals(20));
        assertTrue(ultimateVersionMap.get("f3").equals(31));
        assertTrue(ultimateVersionMap.get("f4").equals(40));
        // End Test for adding second record

        assertTrue(true);
    }
}


text:
@interface ImageItemDescriptionTableViewCell : UITableViewCell

@property(nonatomic, copy) NSString* parameterNameText;
@property(nonatomic, copy) NSString* parameterValueText;

@end


text:
void setMainWindow(QMainWindow *window);
QMainWindow *getMainWindow();

#endif // INSTANCESETUP_H


text:
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
# echo ${SCRIPTDIR} # For debugging

BLACK='\033[0;30m'
BLUE='\033[0;34m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
RED='\033[0;31m'
PURPLE='\033[0;35m'
ORANGE='\033[0;33m' # or brown
LIGHTGRAY='\033[0;37m'
DARKGRAY='\033[1;30m'
LIGHTBLUE='\033[1;34m'
LIGHTGREEN='\033[1;32m'
LIGHTCYAN='\033[1;36m'
LIGHTRED='\033[1;31m'
LIGHTPURPLE='\033[1;35m'
YELLOW='\033[1;33m'
WHITE='\033[1;37m'
NC='\033[0m' # NoColor

printf "\n${YELLOW}[Installing/Updating Node Version Manager]${NC}\n"
if [ -e  ${HOME}/.nvm/nvm.sh ]
    then
    printf "${YELLOW}Deactivating existing Node Version Manager:${NC}\n"
    export NVM_DIR="${HOME}/.nvm"
    [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"  # This loads nvm
    nvm deactivate
fi

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash
export NVM_DIR="${HOME}/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"  # This loads nvm

printf "\n${YELLOW}[Initializing the required Node version]${NC}\n"
printf "${RED}This is the version I'm developing with now, so stick with it.${NC}\n"
source ${SCRIPTDIR}/setNodeVersion.sh
nvm install ${node_version}
nvm alias stable ${node_version}
nvm alias default ${node_version}

printf "\n${YELLOW}[Updating npm]${NC}\n"
npm update -g npm

printf "\n${YELLOW}[Grabbing dependencies for node packages]${NC}\n"
printf "\n${YELLOW}You will get some errors here, that is normal. As long as things work, it is OK.$NC\n"
cd
if ! (which forever > /dev/null)
    then
    npm install -g forever
fi
if ! (which log.io-harvester > /dev/null)
    then
    npm install -g https://github.com/pruge/Log.io
fi
if ! (which pm2 > /dev/null)
    then
    npm install -g pm2
fi
cd ${SCRIPTDIR}/../node
printf "\n${YELLOW}You will get some errors here, that is normal. As long as things work, it is OK.$NC\n"
npm install

cd ${SCRIPTDIR}/../website
npm install
npm run build

cd ${SCRIPTDIR}

# Install required Ubuntu packages
# All required Ubuntu packages have been moved to the Arlobot setup.sh file,
# in order to consolidate and avoid running apt-get twice.

if ! (which mjpg_streamer > /dev/null)
    then
    printf "\n${YELLOW}[Installing mjpg_streamer for Web Page camera viewing]${NC}\n"
    cd ${SCRIPTDIR}
    svn co https://svn.code.sf.net/p/mjpg-streamer/code mjpg-streamer
    cd mjpg-streamer/mjpg-streamer
    # https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=109352
    patch -p0 < ../../input_uvc_patch
    # sudo apt-get install libv4l-dev # Installed earlier, left here for documentation of why
    make USE_LIBV4L2=true clean all
    sudo make install
    # mjpg_streamer usage example:
    #mjpg_streamer -i "/usr/local/lib/input_uvc.so -d /dev/video0 -f 30 -r 640x480" -o "/usr/local/lib/output_http.so -p 58180 -w ${SCRIPTDIR}/mjpg-streamer/mjpg-streamer/www"
fi

if [ ! -d ${SCRIPTDIR}/meld ]
 then
 cd ${SCRIPTDIR}
 wget -q -N https://download.gnome.org/sources/meld/3.16/meld-3.16.1.tar.xz -O meld.tar.xz
 tar xf meld.tar.xz
 rm meld.tar.xz
 mv meld-3.16.1 meld
fi

printf "\n${YELLOW}[Enable non-root use of Bluetooth 4.0.]${NC}\n"
sudo setcap cap_net_raw+eip $(eval readlink -f `which node`)

if ! [ -f ${HOME}/Desktop/arlobot.desktop ]
    then
    printf "\n${YELLOW}[Creating Desktop Icon]${NC}\n"
    echo "[Desktop Entry]" > ${HOME}/Desktop/arlobot.desktop
    echo "Encoding=UTF-8" >> ${HOME}/Desktop/arlobot.desktop
    echo "Name=ArloBot" >> ${HOME}/Desktop/arlobot.desktop
    echo "GenericName=ArloBot" >> ${HOME}/Desktop/arlobot.desktop
    echo "Comment=Start the robot" >> ${HOME}/Desktop/arlobot.desktop
    if (which lxterminal)
        then
        echo "Exec=lxterminal --command \"${HOME}/catkin_ws/src/ArloBot/scripts/arlobotXwindows.sh\"" >> ${HOME}/Desktop/arlobot.desktop
    elif (which gnome-terminal)
        then
        echo "Exec=gnome-terminal --command \"${HOME}/catkin_ws/src/ArloBot/scripts/arlobotXwindows.sh\"" >> ${HOME}/Desktop/arlobot.desktop
    fi
    echo "Icon=${HOME}/catkin_ws/src/ArloBot/icon-70x70.png" >> ${HOME}/Desktop/arlobot.desktop
    echo "Type=Application" >> ${HOME}/Desktop/arlobot.desktop
    echo "Path=${HOME}/catkin_ws/src/ArloBot/scripts/" >> ${HOME}/Desktop/arlobot.desktop
    echo "Terminal=false" >> ${HOME}/Desktop/arlobot.desktop
    chmod +x ${HOME}/Desktop/arlobot.desktop
fi

if [ ! -d ${HOME}/.arlobot ]
    then
    printf "\n${YELLOW}[Setting up .arlobot folder]${NC}\n"
    printf "${GREEN}This holds personal data for your robot.${NC}\n"
    # We will use ~/.arlobot to store "private" data
    # That is data that doesn't need to be part of
    # the public github repo like user tokens,
    # sounds, and room maps and per robot settings
    mkdir ${HOME}/.arlobot
fi

ARLOHOME=${HOME}/.arlobot

if [ -e ${ARLOHOME}/personalDataForBehavior.json ]
    then
    node ${SCRIPTDIR}/../node/personalData.js
else
    printf "\n"
    cp ${SCRIPTDIR}/dotarlobot/personalDataForBehavior.json ${ARLOHOME}/
    printf "${GREEN}A brand new ${RED}~/.arlobot/personalDataForBehavior.json${GREEN} file has been created,${NC}\n"
    printf "${LIGHTPURPLE}Please edit this file to customize according to your robot!${NC}\n"
fi

if [ ! -d ${ARLOHOME}/rosmaps ]
    then
    mkdir ${ARLOHOME}/rosmaps
fi

if [ ! -d ${ARLOHOME}/sounds ]
    then
    mkdir ${ARLOHOME}/sounds
fi

if [ ! -d ${ARLOHOME}/status ]
    then
    mkdir ${ARLOHOME}/status
fi
sudo chmod -R 777 ${ARLOHOME}/status

if [ ! -d ${ARLOHOME}/status/doors ]
    then
    mkdir ${ARLOHOME}/status/doors
fi
sudo chmod -R 777 ${ARLOHOME}/status/doors

if ! [ -f /etc/udev/rules.d/99-libftdi.rules ]
    then
    printf "\n${YELLOW}[Adding required sudo rule to reset USB ports.]${NC}\n"
    sudo ${SCRIPTDIR}/addRuleForUSBRelayBoard.sh
    printf "${RED}You may have to reboot before the USB Relay board will function!${NC}\n"
fi

if ! (grep mbrola /etc/festival.scm>/dev/null)
    then
    sudo ${SCRIPTDIR}/updateFestivalDefaults.sh
fi

if ! (sudo -nl|grep resetUSB > /dev/null)
    then
    printf "\n${YELLOW}[Setting up required sudo entries.]${NC}\n"
    echo "${USER} ALL = NOPASSWD: ${SCRIPTDIR}/resetUSB.sh" >> /tmp/arlobot_sudoers
    chmod 0440 /tmp/arlobot_sudoers
    sudo chown root:root /tmp/arlobot_sudoers
    sudo mv /tmp/arlobot_sudoers /etc/sudoers.d/
    sudo chown root:root /etc/sudoers.d/arlobot_sudoers
fi

if [ "${USER}" == chrisl8 ]
    then
    if ! [ -d /home/robotStatusUser ]
        then
        printf "\n${YELLOW}[Adding robotStatusUser.]${NC}\n"
        printf "${GREEN}(This is NOT required for Arlobot, just a personal thing.)${NC}\n"
        sudo useradd -m robotStatusUser
        printf "${GREEN}Be sure to add your key to ~robotStatusUser/.ssh/authorized_keys${NC}\n"
        printf "${GREEN}for anyone who needs to use it!${NC}\n"
        printf "${RED}sudo su - robotStatusUser${NC}\n"
        printf "${RED}mkdir .ssh${NC}\n"
        printf "${RED}vim .ssh/authorized_keys${NC}\n"
        printf "${GREEN}(This is NOT required for Arlobot, just a personal thing.)${NC}\n"
    fi
    # For use with the paid text to speech engine I use
    #if ! (which aoss > /dev/null)
    #    then
    #    printf "\n${YELLOW}[Adding aoss for Text To Speech.]${NC}\n"
    #    sudo apt install -y alsa-oss
    #    printf "\n${GREEN}Don't for get to insatll Cepstral Voice!${NC}\n"
    #fi

    # Special notices for the developer himself to keep his stuff up to date!
    cd ${SCRIPTDIR}/../node
    printf "\n${RED}[Hey ${USER} please make sure the below items are up to date!]${NC}\n"
    printf "\n${GREEN}[Hey ${USER} please make sure the below items are up to date!]${NC}\n"
    printf "\n${PURPLE}[Hey ${USER} please make sure the below items are up to date!]${NC}\n"
    printf "${YELLOW}Does the current version of nvm we installed:${NC} "
    nvm --version
    printf "${YELLOW}Match the version on github:${NC} "
    wget -qO- https://github.com/creationix/nvm/blob/master/README.md|grep install.sh|grep wget|sed -e "s/
//"|sed "s/\//\\n/g"|grep ^v|head -1
    printf "\n${YELLOW}You are using this version of node:${NC} "
    node --version
    printf "${YELLOW}and this is the current stable version of node:${NC} "
    wget -qO- https://nodejs.org/en/download/|grep "Latest LTS Version:"|sed "s/<\/p>//g"|sed "s/
//"
    printf "\n${YELLOW}Checking for out of date global node modules:${NC}\n"
    npm outdated -g
    printf "${YELLOW}Checking for out of date package node modules:${NC}\n"
    printf "${YELLOW}in /node:${NC}\n"
    npm outdated
    printf "${YELLOW}in /website:${NC}\n"
    cd ${SCRIPTDIR}/../website
    npm outdated
    printf "${PURPLE}-------------------------------------------------------${NC}\n"
fi


text:
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

/* Tabulator v4.5.1 (c) Oliver Folkerd */

var Download = function Download(table) {
	this.table = table; //hold Tabulator object
	this.fields = {}; //hold filed multi dimension arrays
	this.columnsByIndex = []; //hold columns in their order in the table
	this.columnsByField = {}; //hold columns with lookup by field name
	this.config = {};
};

//trigger file download
Download.prototype.download = function (type, filename, options, active, interceptCallback) {
	var self = this,
	    downloadFunc = false;
	this.processConfig();

	function buildLink(data, mime) {
		if (interceptCallback) {
			if (interceptCallback === true) {
				self.triggerDownload(data, mime, type, filename, true);
			} else {
				interceptCallback(data);
			}
		} else {
			self.triggerDownload(data, mime, type, filename);
		}
	}

	if (typeof type == "function") {
		downloadFunc = type;
	} else {
		if (self.downloaders[type]) {
			downloadFunc = self.downloaders[type];
		} else {
			console.warn("Download Error - No such download type found: ", type);
		}
	}

	this.processColumns();

	if (downloadFunc) {
		downloadFunc.call(this, self.processDefinitions(), self.processData(active || "active"), options || {}, buildLink, this.config);
	}
};

Download.prototype.processConfig = function () {
	var config = { //download config
		columnGroups: true,
		rowGroups: true,
		columnCalcs: true
	};

	if (this.table.options.downloadConfig) {
		for (var key in this.table.options.downloadConfig) {
			config[key] = this.table.options.downloadConfig[key];
		}
	}

	if (config.rowGroups && this.table.options.groupBy && this.table.modExists("groupRows")) {
		this.config.rowGroups = true;
	}

	if (config.columnGroups && this.table.columnManager.columns.length != this.table.columnManager.columnsByIndex.length) {
		this.config.columnGroups = true;
	}

	if (config.columnCalcs && this.table.modExists("columnCalcs")) {
		this.config.columnCalcs = true;
	}
};

Download.prototype.processColumns = function () {
	var self = this;

	self.columnsByIndex = [];
	self.columnsByField = {};

	self.table.columnManager.columnsByIndex.forEach(function (column) {

		if (column.field && column.definition.download !== false && (column.visible || !column.visible && column.definition.download)) {
			self.columnsByIndex.push(column);
			self.columnsByField[column.field] = column;
		}
	});
};

Download.prototype.processDefinitions = function () {
	var self = this,
	    processedDefinitions = [];

	if (this.config.columnGroups) {
		self.table.columnManager.columns.forEach(function (column) {
			var colData = self.processColumnGroup(column);

			if (colData) {
				processedDefinitions.push(colData);
			}
		});
	} else {
		self.columnsByIndex.forEach(function (column) {
			if (column.download !== false) {
				//isolate definiton from defintion object
				processedDefinitions.push(self.processDefinition(column));
			}
		});
	}

	return processedDefinitions;
};

Download.prototype.processColumnGroup = function (column) {
	var _this = this;

	var subGroups = column.columns,
	    maxDepth = 0;
	var processedColumn = this.processDefinition(column);
	var groupData = {
		type: "group",
		title: processedColumn.title,
		depth: 1
	};

	if (subGroups.length) {
		groupData.subGroups = [];
		groupData.width = 0;

		subGroups.forEach(function (subGroup) {
			var subGroupData = _this.processColumnGroup(subGroup);

			if (subGroupData.depth > maxDepth) {
				maxDepth = subGroupData.depth;
			}

			if (subGroupData) {
				groupData.width += subGroupData.width;
				groupData.subGroups.push(subGroupData);
			}
		});

		groupData.depth += maxDepth;

		if (!groupData.width) {
			return false;
		}
	} else {
		if (column.field && column.definition.download !== false && (column.visible || !column.visible && column.definition.download)) {
			groupData.width = 1;
			groupData.definition = processedColumn;
		} else {
			return false;
		}
	}

	return groupData;
};

Download.prototype.processDefinition = function (column) {
	var def = {};

	for (var key in column.definition) {
		def[key] = column.definition[key];
	}

	if (typeof column.definition.downloadTitle != "undefined") {
		def.title = column.definition.downloadTitle;
	}

	return def;
};

Download.prototype.processData = function (active) {
	var _this2 = this;

	var self = this,
	    data = [],
	    groups = [],
	    rows = false,
	    calcs = {};

	if (this.config.rowGroups) {

		if (active == "visible") {

			rows = self.table.rowManager.getRows(active);

			rows.forEach(function (row) {
				if (row.type == "row") {
					var group = row.getGroup();

					if (groups.indexOf(group) === -1) {
						groups.push(group);
					}
				}
			});
		} else {
			groups = this.table.modules.groupRows.getGroups();
		}

		groups.forEach(function (group) {
			data.push(_this2.processGroupData(group, rows));
		});
	} else {
		data = self.table.rowManager.getData(active, "download");
	}

	if (this.config.columnCalcs) {
		calcs = this.table.getCalcResults();

		data = {
			calcs: calcs,
			data: data
		};
	}

	//bulk data processing
	if (typeof self.table.options.downloadDataFormatter == "function") {
		data = self.table.options.downloadDataFormatter(data);
	}

	return data;
};

Download.prototype.processGroupData = function (group, visRows) {
	var _this3 = this;

	var subGroups = group.getSubGroups();

	var groupData = {
		type: "group",
		key: group.key
	};

	if (subGroups.length) {
		groupData.subGroups = [];

		subGroups.forEach(function (subGroup) {
			groupData.subGroups.push(_this3.processGroupData(subGroup, visRows));
		});
	} else {
		if (visRows) {
			groupData.rows = [];

			group.rows.forEach(function (row) {
				if (visRows.indexOf(row) > -1) {
					groupData.rows.push(row.getData("download"));
				}
			});
		} else {
			groupData.rows = group.getData(true, "download");
		}
	}

	return groupData;
};

Download.prototype.triggerDownload = function (data, mime, type, filename, newTab) {
	var element = document.createElement('a'),
	    blob = new Blob([data], { type: mime }),
	    filename = filename || "Tabulator." + (typeof type === "function" ? "txt" : type);

	blob = this.table.options.downloadReady.call(this.table, data, blob);

	if (blob) {

		if (newTab) {
			window.open(window.URL.createObjectURL(blob));
		} else {
			if (navigator.msSaveOrOpenBlob) {
				navigator.msSaveOrOpenBlob(blob, filename);
			} else {
				element.setAttribute('href', window.URL.createObjectURL(blob));

				//set file title
				element.setAttribute('download', filename);

				//trigger download
				element.style.display = 'none';
				document.body.appendChild(element);
				element.click();

				//remove temporary link element
				document.body.removeChild(element);
			}
		}

		if (this.table.options.downloadComplete) {
			this.table.options.downloadComplete();
		}
	}
};

//nested field lookup
Download.prototype.getFieldValue = function (field, data) {
	var column = this.columnsByField[field];

	if (column) {
		return column.getFieldValue(data);
	}

	return false;
};

Download.prototype.commsReceived = function (table, action, data) {
	switch (action) {
		case "intercept":
			this.download(data.type, "", data.options, data.intercept);
			break;
	}
};

//downloaders
Download.prototype.downloaders = {
	csv: function csv(columns, data, options, setFileContents, config) {
		var self = this,
		    titles = [],
		    fields = [],
		    delimiter = options && options.delimiter ? options.delimiter : ",",
		    fileContents,
		    output;

		//build column headers
		function parseSimpleTitles() {
			columns.forEach(function (column) {
				titles.push('"' + String(column.title).split('"').join('""') + '"');
				fields.push(column.field);
			});
		}

		function parseColumnGroup(column, level) {
			if (column.subGroups) {
				column.subGroups.forEach(function (subGroup) {
					parseColumnGroup(subGroup, level + 1);
				});
			} else {
				titles.push('"' + String(column.title).split('"').join('""') + '"');
				fields.push(column.definition.field);
			}
		}

		if (config.columnGroups) {
			console.warn("Download Warning - CSV downloader cannot process column groups");

			columns.forEach(function (column) {
				parseColumnGroup(column, 0);
			});
		} else {
			parseSimpleTitles();
		}

		//generate header row
		fileContents = [titles.join(delimiter)];

		function parseRows(data) {
			//generate each row of the table
			data.forEach(function (row) {
				var rowData = [];

				fields.forEach(function (field) {
					var value = self.getFieldValue(field, row);

					switch (typeof value === "undefined" ? "undefined" : _typeof(value)) {
						case "object":
							value = JSON.stringify(value);
							break;

						case "undefined":
						case "null":
							value = "";
							break;

						default:
							value = value;
					}

					//escape quotation marks
					rowData.push('"' + String(value).split('"').join('""') + '"');
				});

				fileContents.push(rowData.join(delimiter));
			});
		}

		function parseGroup(group) {
			if (group.subGroups) {
				group.subGroups.forEach(function (subGroup) {
					parseGroup(subGroup);
				});
			} else {
				parseRows(group.rows);
			}
		}

		if (config.columnCalcs) {
			console.warn("Download Warning - CSV downloader cannot process column calculations");
			data = data.data;
		}

		if (config.rowGroups) {
			console.warn("Download Warning - CSV downloader cannot process row groups");

			data.forEach(function (group) {
				parseGroup(group);
			});
		} else {
			parseRows(data);
		}

		output = fileContents.join("\n");

		if (options.bom) {
			output = "\uFEFF" + output;
		}

		setFileContents(output, "text/csv");
	},

	json: function json(columns, data, options, setFileContents, config) {
		var fileContents;

		if (config.columnCalcs) {
			console.warn("Download Warning - CSV downloader cannot process column calculations");
			data = data.data;
		}

		fileContents = JSON.stringify(data, null, '\t');

		setFileContents(fileContents, "application/json");
	},

	pdf: function pdf(columns, data, options, setFileContents, config) {
		var self = this,
		    fields = [],
		    header = [],
		    body = [],
		    calcs = {},
		    headerDepth = 1,
		    table = "",
		    autoTableParams = {},
		    rowGroupStyles = options.rowGroupStyles || {
			fontStyle: "bold",
			fontSize: 12,
			cellPadding: 6,
			fillColor: 220
		},
		    rowCalcStyles = options.rowCalcStyles || {
			fontStyle: "bold",
			fontSize: 10,
			cellPadding: 4,
			fillColor: 232
		},
		    jsPDFParams = options.jsPDF || {},
		    title = options && options.title ? options.title : "";

		if (config.columnCalcs) {
			calcs = data.calcs;
			data = data.data;
		}

		if (!jsPDFParams.orientation) {
			jsPDFParams.orientation = options.orientation || "landscape";
		}

		if (!jsPDFParams.unit) {
			jsPDFParams.unit = "pt";
		}

		//build column headers
		function parseSimpleTitles() {
			columns.forEach(function (column) {
				if (column.field) {
					header.push(column.title || "");
					fields.push(column.field);
				}
			});

			header = [header];
		}

		function parseColumnGroup(column, level) {
			var colSpan = column.width,
			    rowSpan = 1,
			    col = {
				content: column.title || ""
			};

			if (column.subGroups) {
				column.subGroups.forEach(function (subGroup) {
					parseColumnGroup(subGroup, level + 1);
				});
				rowSpan = 1;
			} else {
				fields.push(column.definition.field);
				rowSpan = headerDepth - level;
			}

			col.rowSpan = rowSpan;
			// col.colSpan = colSpan;

			header[level].push(col);

			colSpan--;

			if (rowSpan > 1) {
				for (var i = level + 1; i < headerDepth; i++) {
					header[i].push("");
				}
			}

			for (var i = 0; i < colSpan; i++) {
				header[level].push("");
			}
		}

		if (config.columnGroups) {
			columns.forEach(function (column) {
				if (column.depth > headerDepth) {
					headerDepth = column.depth;
				}
			});

			for (var i = 0; i < headerDepth; i++) {
				header.push([]);
			}

			columns.forEach(function (column) {
				parseColumnGroup(column, 0);
			});
		} else {
			parseSimpleTitles();
		}

		function parseValue(value) {
			switch (typeof value === "undefined" ? "undefined" : _typeof(value)) {
				case "object":
					value = JSON.stringify(value);
					break;

				case "undefined":
				case "null":
					value = "";
					break;

				default:
					value = value;
			}

			return value;
		}

		function parseRows(data) {
			//build table rows
			data.forEach(function (row) {
				body.push(parseRow(row));
			});
		}

		function parseRow(row, styles) {
			var rowData = [];

			fields.forEach(function (field) {
				var value = self.getFieldValue(field, row);
				value = parseValue(value);

				if (styles) {
					rowData.push({
						content: value,
						styles: styles
					});
				} else {
					rowData.push(value);
				}
			});

			return rowData;
		}

		function parseGroup(group, calcObj) {
			var groupData = [];

			groupData.push({ content: parseValue(group.key), colSpan: fields.length, styles: rowGroupStyles });

			body.push(groupData);

			if (group.subGroups) {
				group.subGroups.forEach(function (subGroup) {
					parseGroup(subGroup, calcObj[group.key] ? calcObj[group.key].groups || {} : {});
				});
			} else {

				if (config.columnCalcs) {
					addCalcRow(calcObj, group.key, "top");
				}

				parseRows(group.rows);

				if (config.columnCalcs) {
					addCalcRow(calcObj, group.key, "bottom");
				}
			}
		}

		function addCalcRow(calcs, selector, pos) {
			var calcData = calcs[selector];

			if (calcData) {
				if (pos) {
					calcData = calcData[pos];
				}

				if (Object.keys(calcData).length) {
					body.push(parseRow(calcData, rowCalcStyles));
				}
			}
		}

		if (config.rowGroups) {
			data.forEach(function (group) {
				parseGroup(group, calcs);
			});
		} else {
			if (config.columnCalcs) {
				addCalcRow(calcs, "top");
			}

			parseRows(data);

			if (config.columnCalcs) {
				addCalcRow(calcs, "bottom");
			}
		}

		var doc = new jsPDF(jsPDFParams); //set document to landscape, better for most tables

		if (options && options.autoTable) {
			if (typeof options.autoTable === "function") {
				autoTableParams = options.autoTable(doc) || {};
			} else {
				autoTableParams = options.autoTable;
			}
		}

		if (title) {
			autoTableParams.addPageContent = function (data) {
				doc.text(title, 40, 30);
			};
		}

		autoTableParams.head = header;
		autoTableParams.body = body;

		doc.autoTable(autoTableParams);

		if (options && options.documentProcessing) {
			options.documentProcessing(doc);
		}

		setFileContents(doc.output("arraybuffer"), "application/pdf");
	},

	xlsx: function xlsx(columns, data, options, setFileContents, config) {
		var self = this,
		    sheetName = options.sheetName || "Sheet1",
		    workbook = XLSX.utils.book_new(),
		    calcs = {},
		    groupRowIndexs = [],
		    groupColumnIndexs = [],
		    calcRowIndexs = [],
		    output;

		workbook.SheetNames = [];
		workbook.Sheets = {};

		if (config.columnCalcs) {
			calcs = data.calcs;
			data = data.data;
		}

		function generateSheet() {
			var titles = [],
			    fields = [],
			    rows = [],
			    worksheet;

			//convert rows to worksheet
			function rowsToSheet() {
				var sheet = {};
				var range = { s: { c: 0, r: 0 }, e: { c: fields.length, r: rows.length } };

				XLSX.utils.sheet_add_aoa(sheet, rows);

				sheet['!ref'] = XLSX.utils.encode_range(range);

				var merges = generateMerges();

				if (merges.length) {
					sheet["!merges"] = merges;
				}

				return sheet;
			}

			function parseSimpleTitles() {
				//get field lists
				columns.forEach(function (column) {
					titles.push(column.title);
					fields.push(column.field);
				});

				rows.push(titles);
			}

			function parseColumnGroup(column, level) {

				if (typeof titles[level] === "undefined") {
					titles[level] = [];
				}

				if (typeof groupColumnIndexs[level] === "undefined") {
					groupColumnIndexs[level] = [];
				}

				if (column.width > 1) {

					groupColumnIndexs[level].push({
						type: "hoz",
						start: titles[level].length,
						end: titles[level].length + column.width - 1
					});
				}

				titles[level].push(column.title);

				if (column.subGroups) {
					column.subGroups.forEach(function (subGroup) {
						parseColumnGroup(subGroup, level + 1);
					});
				} else {
					fields.push(column.definition.field);
					padColumnTitles(fields.length - 1, level);

					groupColumnIndexs[level].push({
						type: "vert",
						start: fields.length - 1
					});
				}
			}

			function padColumnTitles() {
				var max = 0;

				titles.forEach(function (title) {
					var len = title.length;
					if (len > max) {
						max = len;
					}
				});

				titles.forEach(function (title) {
					var len = title.length;
					if (len < max) {
						for (var i = len; i < max; i++) {
							title.push("");
						}
					}
				});
			}

			if (config.columnGroups) {
				columns.forEach(function (column) {
					parseColumnGroup(column, 0);
				});

				titles.forEach(function (title) {
					rows.push(title);
				});
			} else {
				parseSimpleTitles();
			}

			function generateMerges() {
				var output = [];

				groupRowIndexs.forEach(function (index) {
					output.push({ s: { r: index, c: 0 }, e: { r: index, c: fields.length - 1 } });
				});

				groupColumnIndexs.forEach(function (merges, level) {
					merges.forEach(function (merge) {
						if (merge.type === "hoz") {
							output.push({ s: { r: level, c: merge.start }, e: { r: level, c: merge.end } });
						} else {
							if (level != titles.length - 1) {
								output.push({ s: { r: level, c: merge.start }, e: { r: titles.length - 1, c: merge.start } });
							}
						}
					});
				});

				return output;
			}

			//generate each row of the table
			function parseRows(data) {
				data.forEach(function (row) {
					rows.push(parseRow(row));
				});
			}

			function parseRow(row) {
				var rowData = [];

				fields.forEach(function (field) {
					var value = self.getFieldValue(field, row);
					rowData.push(!(value instanceof Date) && (typeof value === "undefined" ? "undefined" : _typeof(value)) === "object" ? JSON.stringify(value) : value);
				});

				return rowData;
			}

			function addCalcRow(calcs, selector, pos) {
				var calcData = calcs[selector];

				if (calcData) {
					if (pos) {
						calcData = calcData[pos];
					}

					if (Object.keys(calcData).length) {
						calcRowIndexs.push(rows.length);
						rows.push(parseRow(calcData));
					}
				}
			}

			function parseGroup(group, calcObj) {
				var groupData = [];

				groupData.push(group.key);

				groupRowIndexs.push(rows.length);

				rows.push(groupData);

				if (group.subGroups) {
					group.subGroups.forEach(function (subGroup) {
						parseGroup(subGroup, calcObj[group.key] ? calcObj[group.key].groups || {} : {});
					});
				} else {

					if (config.columnCalcs) {
						addCalcRow(calcObj, group.key, "top");
					}

					parseRows(group.rows);

					if (config.columnCalcs) {
						addCalcRow(calcObj, group.key, "bottom");
					}
				}
			}

			if (config.rowGroups) {
				data.forEach(function (group) {
					parseGroup(group, calcs);
				});
			} else {
				if (config.columnCalcs) {
					addCalcRow(calcs, "top");
				}

				parseRows(data);

				if (config.columnCalcs) {
					addCalcRow(calcs, "bottom");
				}
			}

			worksheet = rowsToSheet();

			return worksheet;
		}

		if (options.sheetOnly) {
			setFileContents(generateSheet());
			return;
		}

		if (options.sheets) {
			for (var sheet in options.sheets) {

				if (options.sheets[sheet] === true) {
					workbook.SheetNames.push(sheet);
					workbook.Sheets[sheet] = generateSheet();
				} else {

					workbook.SheetNames.push(sheet);

					this.table.modules.comms.send(options.sheets[sheet], "download", "intercept", {
						type: "xlsx",
						options: { sheetOnly: true },
						intercept: function intercept(data) {
							workbook.Sheets[sheet] = data;
						}
					});
				}
			}
		} else {
			workbook.SheetNames.push(sheetName);
			workbook.Sheets[sheetName] = generateSheet();
		}

		if (options.documentProcessing) {
			workbook = options.documentProcessing(workbook);
		}

		//convert workbook to binary array
		function s2ab(s) {
			var buf = new ArrayBuffer(s.length);
			var view = new Uint8Array(buf);
			for (var i = 0; i != s.length; ++i) {
				view[i] = s.charCodeAt(i) & 0xFF;
			}return buf;
		}

		output = XLSX.write(workbook, { bookType: 'xlsx', bookSST: true, type: 'binary' });

		setFileContents(s2ab(output), "application/octet-stream");
	},

	html: function html(columns, data, options, setFileContents, config) {
		if (this.table.modExists("htmlTableExport", true)) {
			setFileContents(this.table.modules.htmlTableExport.getHtml(true, options.style, config), "text/html");
		}
	}

};

Tabulator.prototype.registerModule("download", Download);


text:
var slideIndex = 1;
showSlides(slideIndex);

// Next/previous controls
function plusSlides(n) {
  showSlides(slideIndex += n);
}

// Thumbnail image controls
function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");
  var captionText = document.getElementById("caption");
  if (n > slides.length) { slideIndex = 1 }
  if (n < 1) { slideIndex = slides.length }
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex - 1].style.display = "block";
  dots[slideIndex - 1].className += " active";
  captionText.innerHTML = dots[slideIndex - 1].alt;
}

$(document).ready(function(){
  $('[data-toggle="tooltip"]').tooltip();
});

(function($) {

  // Add smooth scrolling to all links in navbar
  $(".navbar a,a.btn-appoint, .quick-info li a, .overlay-detail a, .back-to-top a").on('click', function(event) {

    var hash = this.hash;
    if (hash) {
      event.preventDefault();
      $('html, body').animate({
        scrollTop: $(hash).offset().top - 90
      }, 900, function() {
        window.location.hash = hash;
      });
    }

  });

  $(".navbar-collapse a").on('click', function() {
    $(".navbar-collapse.collapse").removeClass('in');
  });

  //jQuery to collapse the navbar on scroll
  $(window).scroll(function() {
    if ($(".navbar-default").offset().top - 90 > 50) {
      $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
      $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
  });

  // modals
  $('#myModal').on('shown.bs.modal', function () {
    $('#myInput').trigger('focus')
  });

  // gallery carousel
  $('.gallery').carousel({
    interval: 2000
  })

})(jQuery);


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>OnlyOnceErrorHandler Constructor (String)</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

OnlyOnceErrorHandler Constructor (String)

 Constructor

        [Visual Basic]

Overloads Public Sub New( _
   ByVal prefix As String _
)

        [C#]

public OnlyOnceErrorHandler(
   string prefix
);

Parameters

          prefix

The prefix to use for each message.

Remarks

 Initializes a new instance of the OnlyOnceErrorHandler class with the specified prefix.

See Also

OnlyOnceErrorHandler Class | log4net.Util Namespace | OnlyOnceErrorHandler Constructor Overload List

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text:
package au.gov.amsa.detection.behaviour;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.Date;

import org.junit.Test;

import com.google.common.base.Optional;

import au.gov.amsa.detection.behaviour.DetectionRuleBehaviour.DetectionRuleCraftProvider;
import au.gov.amsa.detection.model.Detection;
import au.gov.amsa.detection.model.DetectionRule;
import au.gov.amsa.detection.model.DetectionRule.Events.PositionInRegion;
import au.gov.amsa.detection.model.DetectionRuleCraft;
import au.gov.amsa.detection.model.MessageTemplate;

public class DetectionRuleBehaviourTest {

    @Test
    public void testDoesNotCreateDetectionIfTimeOutsideTimeRangeAndIsExclusiveOnUpperLimitOfTimeRange() {
        DetectionRule dr = mock(DetectionRule.class);
        PositionInRegion p = createPositionInRegionEvent().build();
        when(dr.getMustCross()).thenReturn(Boolean.FALSE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(10000));

        assertFalse(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> true, null));
    }

    @Test
    public void testDoesNotCreateDetectionIfTimeOutsideTimeRange() {
        DetectionRule dr = mock(DetectionRule.class);
        PositionInRegion p = createPositionInRegionEvent().build();
        when(dr.getMustCross()).thenReturn(Boolean.FALSE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(9000));
        assertFalse(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> true, null));
    }

    @Test
    public void testDoesNotCreateDetectionIfMustCrossAndHasNotBeenOutside() {
        DetectionRule dr = mock(DetectionRule.class);
        PositionInRegion p = createPositionInRegionEvent().build();
        when(dr.getMustCross()).thenReturn(Boolean.TRUE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(20000));
        assertFalse(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> true, null));
    }

    @Test
    public void testDoesNotCreateDetectionIfDoesNotMatchPattern() {
        DetectionRule dr = mock(DetectionRule.class);
        PositionInRegion p = createPositionInRegionEvent().build();
        when(dr.getMustCross()).thenReturn(Boolean.FALSE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(20000));
        assertFalse(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> false, null));
    }

    @Test
    public void testCreateDetectionIfNoPreviousDetection() {
        DetectionRule dr = mock(DetectionRule.class);
        PositionInRegion p = createPositionInRegionEvent().build();
        when(dr.getMustCross()).thenReturn(Boolean.FALSE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(20000));
        assertTrue(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> true,
                (cId, drId) -> Optional.absent()));
    }

    @Test
    public void testDoNotCreateDetectionIfLastDetectionPresentButPositionTimeIsBeforeLastDetectionReportTime() {
        DetectionRule dr = mock(DetectionRule.class);

        PositionInRegion p = createPositionInRegionEvent().build();
        when(dr.getMustCross()).thenReturn(Boolean.FALSE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(20000));
        Detection d = mock(Detection.class);
        // last detection report time is after position time for p
        when(d.getReportTime()).thenReturn(new Date(16000));
        DetectionRuleCraftProvider drcProvider = drc(d);
        assertFalse(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> true, drcProvider));
    }

    @Test
    public void testDoNotCreateDetectionIfLastDetectionPresentButPositionTimeIsEqualsLastDetectionReportTime() {
        DetectionRule dr = mock(DetectionRule.class);

        PositionInRegion p = createPositionInRegionEvent().build();
        when(dr.getMustCross()).thenReturn(Boolean.FALSE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(20000));
        Detection d = mock(Detection.class);
        // last detection report time is same as position time for p
        when(d.getReportTime()).thenReturn(new Date(10000));
        DetectionRuleCraftProvider drcProvider = drc(d);
        assertFalse(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> true, drcProvider));
    }

    private static DetectionRuleCraftProvider drc(Detection d) {
        DetectionRuleCraft drc = mock(DetectionRuleCraft.class);
        when(drc.getDetection_R12()).thenReturn(d);
        return (craftId, detectionRuleId) -> Optional.of(drc);
    }

    @Test
    public void testCreateDetectionIfLastDetectionCreationTimeBeforeForceUpdateTime() {
        DetectionRule dr = mock(DetectionRule.class);

        PositionInRegion p = createPositionInRegionEvent(6000, true).build();
        when(dr.getMustCross()).thenReturn(Boolean.TRUE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(20000));
        Detection d = mock(Detection.class);
        // last detection report time is before position time for p
        when(d.getReportTime()).thenReturn(new Date(5000));
        when(d.getCreatedTime()).thenReturn(new Date(6000));
        MessageTemplate template = mock(MessageTemplate.class);
        when(dr.getMessageTemplate_R8()).thenReturn(template);
        when(template.getStartTime()).thenReturn(new Date(0));
        when(template.getEndTime()).thenReturn(new Date(20000));
        when(template.getForceUpdateBeforeTime()).thenReturn(new Date(8000));
        DetectionRuleCraftProvider drcProvider = drc(d);
        assertTrue(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> true, drcProvider));
    }

    @Test
    public void testCreateDetectionIfLastDetectionCreationTimeAfterForceUpdateTimeAndIntervalSinceLastDetectionGreaterThanMinInterval() {
        DetectionRule dr = mock(DetectionRule.class);

        PositionInRegion p = createPositionInRegionEvent(6000, true).currentTime(new Date(9000))
                .build();
        when(dr.getMustCross()).thenReturn(Boolean.TRUE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(20000));
        when(dr.getMinIntervalSecs()).thenReturn(3);
        Detection d = mock(Detection.class);
        // last detection report time is before position time for p
        when(d.getReportTime()).thenReturn(new Date(5000));
        when(d.getCreatedTime()).thenReturn(new Date(6000));
        MessageTemplate template = mock(MessageTemplate.class);
        when(dr.getMessageTemplate_R8()).thenReturn(template);
        when(template.getStartTime()).thenReturn(new Date(0));
        when(template.getEndTime()).thenReturn(new Date(20000));
        when(template.getForceUpdateBeforeTime()).thenReturn(new Date(4000));
        DetectionRuleCraftProvider drcProvider = drc(d);
        assertTrue(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> true, drcProvider));
    }

    @Test
    public void testCreateDetectionIfLastDetectionCreationTimeAfterForceUpdateTimeAndIntervalSinceLastDetectionEqualToMinInterval() {
        DetectionRule dr = mock(DetectionRule.class);

        PositionInRegion p = createPositionInRegionEvent(6000, true).currentTime(new Date(10000))
                .build();
        when(dr.getMustCross()).thenReturn(Boolean.TRUE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(20000));
        when(dr.getMinIntervalSecs()).thenReturn(4);
        Detection d = mock(Detection.class);
        // last detection report time is before position time for p
        when(d.getReportTime()).thenReturn(new Date(5000));
        when(d.getCreatedTime()).thenReturn(new Date(6000));
        MessageTemplate template = mock(MessageTemplate.class);
        when(dr.getMessageTemplate_R8()).thenReturn(template);
        when(template.getStartTime()).thenReturn(new Date(0));
        when(template.getEndTime()).thenReturn(new Date(20000));
        when(template.getForceUpdateBeforeTime()).thenReturn(new Date(4000));
        DetectionRuleCraftProvider drcProvider = drc(d);
        assertTrue(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> true, drcProvider));
    }

    @Test
    public void testCreateDetectionIfLastDetectionCreationTimeAfterForceUpdateTimeAndIntervalSinceLastDetectionLessThanMinInterval() {
        DetectionRule dr = mock(DetectionRule.class);

        PositionInRegion p = createPositionInRegionEvent(6000, true).build();
        when(dr.getMustCross()).thenReturn(Boolean.TRUE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(20000));
        // big interval
        when(dr.getMinIntervalSecs()).thenReturn(30);
        when(dr.getMinIntervalSecsOut()).thenReturn(30);

        // last detection
        Detection d = mock(Detection.class);
        // last detection report time is before position time for p
        when(d.getReportTime()).thenReturn(new Date(5000));
        when(d.getCreatedTime()).thenReturn(new Date(6000));
        MessageTemplate template = mock(MessageTemplate.class);
        when(dr.getMessageTemplate_R8()).thenReturn(template);
        when(template.getStartTime()).thenReturn(new Date(0));
        when(template.getEndTime()).thenReturn(new Date(20000));
        when(template.getForceUpdateBeforeTime()).thenReturn(new Date(4000));
        DetectionRuleCraftProvider drcProvider = drc(d);
        assertFalse(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> true, drcProvider));
    }

    @Test
    public void testCreateDetectionIfLastDetectionCreationTimeAfterForceUpdateTimeAndIntervalSinceLastDetectionGreaterThanMinIntervalButIsEntranceAndBeenOutsideLongEnough() {
        DetectionRule dr = mock(DetectionRule.class);

        PositionInRegion p = createPositionInRegionEvent(6000, true).currentTime(new Date(9000))
                .lastExitTimeFromRegion(new Date(0)).lastTimeEntered(new Date(9000))
                .isEntrance(true).build();
        when(dr.getMustCross()).thenReturn(Boolean.TRUE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(20000));
        when(dr.getMinIntervalSecs()).thenReturn(30);
        when(dr.getMinIntervalSecsOut()).thenReturn(1);
        Detection d = mock(Detection.class);
        // last detection report time is before position time for p
        when(d.getReportTime()).thenReturn(new Date(5000));
        when(d.getCreatedTime()).thenReturn(new Date(6000));
        MessageTemplate template = mock(MessageTemplate.class);
        when(dr.getMessageTemplate_R8()).thenReturn(template);
        when(template.getStartTime()).thenReturn(new Date(0));
        when(template.getEndTime()).thenReturn(new Date(20000));
        when(template.getForceUpdateBeforeTime()).thenReturn(new Date(4000));
        DetectionRuleCraftProvider drcProvider = drc(d);
        assertTrue(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> true, drcProvider));
    }

    @Test
    public void testCreateDetectionIfLastDetectionCreationTimeAfterForceUpdateTimeAndIntervalSinceLastDetectionGreaterThanMinIntervalButIsEntranceAndNotBeenOutsideLongEnough() {
        DetectionRule dr = mock(DetectionRule.class);

        PositionInRegion p = createPositionInRegionEvent(6000, true).currentTime(new Date(9000))
                .lastExitTimeFromRegion(new Date(0)).lastTimeEntered(new Date(1000))
                .isEntrance(true).build();
        when(dr.getMustCross()).thenReturn(Boolean.TRUE);
        when(dr.getStartTime()).thenReturn(new Date(0));
        when(dr.getEndTime()).thenReturn(new Date(20000));
        when(dr.getMinIntervalSecs()).thenReturn(30);
        when(dr.getMinIntervalSecsOut()).thenReturn(2);
        Detection d = mock(Detection.class);
        // last detection report time is before position time for p
        when(d.getReportTime()).thenReturn(new Date(5000));
        when(d.getCreatedTime()).thenReturn(new Date(6000));
        MessageTemplate template = mock(MessageTemplate.class);
        when(dr.getMessageTemplate_R8()).thenReturn(template);
        when(template.getStartTime()).thenReturn(new Date(0));
        when(template.getEndTime()).thenReturn(new Date(20000));
        when(template.getForceUpdateBeforeTime()).thenReturn(new Date(4000));
        DetectionRuleCraftProvider drcProvider = drc(d);
        assertFalse(DetectionRuleBehaviour.shouldCreateDetection(dr, p, x -> true, drcProvider));
    }

    private PositionInRegion.Builder createPositionInRegionEventBuilder() {
        return DetectionRule.Events.PositionInRegion.builder().hasBeenOutsideRegion(false)
                .latitude(-10.0).longitude(135.0).lastExitTimeFromRegion(new Date(0))
                .lastTimeEntered(new Date(0)).time(new Date(10000)).craftID("abc").isEntrance(false)
                .altitudeMetres(0.0).currentTime(new Date(15000));
    }

    private PositionInRegion.Builder createPositionInRegionEvent(long currentTime,
            boolean hasBeenOutsideRegion) {
        return createPositionInRegionEventBuilder().currentTime(new Date(currentTime))
                .hasBeenOutsideRegion(hasBeenOutsideRegion);
    }

    private PositionInRegion.Builder createPositionInRegionEvent() {
        return createPositionInRegionEvent(15000, false);
    }

}


text:
<mvc:View
	controllerName="serializer.view.TestXml"
	xmlns="sap.m"
	xmlns:layout="sap.ui.layout"
	xmlns:mvc="sap.ui.core.mvc" >
	<layout:VerticalLayout
		id="thaPage">
		<Image
			src="http://www.sap.com/global/images/SAPLogo.gif"
			alt="alternative text for image">
		</Image>
		<mvc:HTMLView
			viewName="serializer.view.NestedHtmlView" />
		<Label
			id="label"
			text="Label">
		</Label>
		<Button
			id="button"
			text="Save">
		</Button>
	</layout:VerticalLayout>
</mvc:View>


text:
/* ----------------------------------------------------------------- */
/*           The Toolkit for Building Voice Interaction Systems      */
/*           "MMDAgent" developed by MMDAgent Project Team           */
/*           http://www.mmdagent.jp/                                 */
/* ----------------------------------------------------------------- */
/*                                                                   */
/*  Copyright (c) 2009-2012  Nagoya Institute of Technology          */
/*                           Department of Computer Science          */
/*                                                                   */
/* All rights reserved.                                              */
/*                                                                   */
/* Redistribution and use in source and binary forms, with or        */
/* without modification, are permitted provided that the following   */
/* conditions are met:                                               */
/*                                                                   */
/* - Redistributions of source code must retain the above copyright  */
/*   notice, this list of conditions and the following disclaimer.   */
/* - Redistributions in binary form must reproduce the above         */
/*   copyright notice, this list of conditions and the following     */
/*   disclaimer in the documentation and/or other materials provided */
/*   with the distribution.                                          */
/* - Neither the name of the MMDAgent project team nor the names of  */
/*   its contributors may be used to endorse or promote products     */
/*   derived from this software without specific prior written       */
/*   permission.                                                     */
/*                                                                   */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND            */
/* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,       */
/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF          */
/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE          */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS */
/* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          */
/* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED   */
/* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     */
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,   */
/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY    */
/* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           */
/* POSSIBILITY OF SUCH DAMAGE.                                       */
/* ----------------------------------------------------------------- */

/* headers */

#include "MMDFiles.h"

/* PMDModel::renderModel: render the model */
/* needs multi-texture function on OpenGL: */
/* texture unit 0: model texture */
/* texture unit 1: toon texture for toon shading */
/* texture unit 2: additional sphere map texture, if exist */
void PMDModel::renderModel()
{
   unsigned long i;
   float c[4];
   PMDMaterial *m;
   float modelAlpha;

   if (!m_vertexList) return;

#ifndef MMDFILES_CONVERTCOORDINATESYSTEM
   glPushMatrix();
   glScalef(1.0f, 1.0f, -1.0f); /* from left-hand to right-hand */
   glCullFace(GL_FRONT);
#endif /* !MMDFILES_CONVERTCOORDINATESYSTEM */

   /* activate texture unit 0 */
   glActiveTextureARB(GL_TEXTURE0_ARB);
   glClientActiveTextureARB(GL_TEXTURE0_ARB);

   /* set lists */
   glEnableClientState(GL_VERTEX_ARRAY);
   glEnableClientState(GL_NORMAL_ARRAY);
   glVertexPointer(3, GL_FLOAT, sizeof(btVector3), m_skinnedVertexList);
   glNormalPointer(GL_FLOAT, sizeof(btVector3), m_skinnedNormalList);
   /* set model texture coordinates to texture unit 0 */
   glClientActiveTextureARB(GL_TEXTURE0_ARB);
   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
   glTexCoordPointer(2, GL_FLOAT, 0, m_texCoordList);
   if (m_toon) {
      /* set toon texture coordinates to texture unit 1 */
      glActiveTextureARB(GL_TEXTURE1_ARB);
      glEnable(GL_TEXTURE_2D);
      glClientActiveTextureARB(GL_TEXTURE1_ARB);
      glEnableClientState(GL_TEXTURE_COORD_ARRAY);
      if (m_selfShadowDrawing)
         /* when drawing a shadow part in shadow mapping, force toon texture coordinates to (0, 0) */
         glTexCoordPointer(2, GL_FLOAT, 0, m_toonTexCoordListForShadowMap);
      else
         glTexCoordPointer(2, GL_FLOAT, 0, m_toonTexCoordList);
      glActiveTextureARB(GL_TEXTURE0_ARB);
      glClientActiveTextureARB(GL_TEXTURE0_ARB);
   }
   if (m_hasSingleSphereMap) {
      /* this model contains single sphere map texture */
      /* set texture coordinate generation for sphere map on texture unit 0 */
      glEnable(GL_TEXTURE_2D);
      glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
      glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
      glDisable(GL_TEXTURE_2D);
   }
   if (m_hasMultipleSphereMap) {
      /* this model contains additional sphere map texture */
      /* set texture coordinate generation for sphere map on texture unit 2 */
      glActiveTextureARB(GL_TEXTURE2_ARB);
      glEnable(GL_TEXTURE_2D);
      glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
      glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
      glDisable(GL_TEXTURE_2D);
      glActiveTextureARB(GL_TEXTURE0_ARB);
   }

   /* calculate alpha value, applying model global alpha */
   modelAlpha = m_globalAlpha;

   /* render per material */
   for (i = 0; i < m_numMaterial; i++) {
      m = &(m_material[m_materialRenderOrder[i]]);
      /* set colors */
      c[3] = m->getAlpha() * modelAlpha;
      if (c[3] > 0.99f) c[3] = 1.0f; /* clamp to 1.0 */
      if (m_toon) {
         /* use averaged color of diffuse and ambient for both */
         m->copyAvgcol(c);
         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, &(c[0]));
         m->copySpecular(c);
         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, &(c[0]));
      } else {
         /* use each color */
         m->copyDiffuse(c);
         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, &(c[0]));
         m->copyAmbient(c);
         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, &(c[0]));
         m->copySpecular(c);
         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, &(c[0]));
      }
      glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, m->getShiness());

      /* disable face culling for transparent materials */
      if (m->getAlpha() < 1.0f)
         glDisable(GL_CULL_FACE);
      else
         glEnable(GL_CULL_FACE);

      /* if using multiple texture units, set current unit to 0 */
      if (m_toon || m_hasMultipleSphereMap)
         glActiveTextureARB(GL_TEXTURE0_ARB);

      if (m->getTexture()) {
         /* bind model texture */
         glEnable(GL_TEXTURE_2D);
         glBindTexture(GL_TEXTURE_2D, m->getTexture()->getID());
         if (m_hasSingleSphereMap) {
            if (m->getTexture()->isSphereMap()) {
               /* this is sphere map */
               /* enable texture coordinate generation */
               if (m->getTexture()->isSphereMapAdd())
                  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);
               glEnable(GL_TEXTURE_GEN_S);
               glEnable(GL_TEXTURE_GEN_T);
            } else {
               /* disable generation */
               glDisable(GL_TEXTURE_GEN_S);
               glDisable(GL_TEXTURE_GEN_T);
            }
         }
      } else {
         glDisable(GL_TEXTURE_2D);
      }

      if (m_toon) {
         /* set toon texture for texture unit 1 */
         glActiveTextureARB(GL_TEXTURE1_ARB);
         glBindTexture(GL_TEXTURE_2D, m_toonTextureID[m->getToonID()]);
         /* set GL_CLAMP_TO_EDGE for toon texture to avoid texture interpolation at edge */
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
      }

      if (m_hasMultipleSphereMap) {
         if (m->getAdditionalTexture()) {
            /* this material has additional sphere map texture, bind it at texture unit 2 */
            glActiveTextureARB(GL_TEXTURE2_ARB);
            glEnable(GL_TEXTURE_2D);
            if (m->getAdditionalTexture()->isSphereMapAdd())
               glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);
            else
               glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
            glBindTexture(GL_TEXTURE_2D, m->getAdditionalTexture()->getID());
            glEnable(GL_TEXTURE_GEN_S);
            glEnable(GL_TEXTURE_GEN_T);
         } else {
            /* disable generation */
            glActiveTextureARB(GL_TEXTURE2_ARB);
            glDisable(GL_TEXTURE_2D);
         }
      }

      /* draw elements */
      glDrawElements(GL_TRIANGLES, m->getNumSurface(), GL_UNSIGNED_SHORT, m->getSurfaceList());

      /* reset some parameters */
      if (m->getTexture() && m->getTexture()->isSphereMap() && m->getTexture()->isSphereMapAdd()) {
         if (m_toon)
            glActiveTextureARB(GL_TEXTURE0_ARB);
         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
      }
   }

   glDisableClientState(GL_VERTEX_ARRAY);
   glDisableClientState(GL_NORMAL_ARRAY);
   if (m_toon) {
      glClientActiveTextureARB(GL_TEXTURE0_ARB);
      glDisableClientState(GL_TEXTURE_COORD_ARRAY);
      if (m_hasSingleSphereMap) {
         glActiveTextureARB(GL_TEXTURE0_ARB);
         glDisable(GL_TEXTURE_GEN_S);
         glDisable(GL_TEXTURE_GEN_T);
      }
      glClientActiveTextureARB(GL_TEXTURE1_ARB);
      glDisableClientState(GL_TEXTURE_COORD_ARRAY);
      if (m_hasMultipleSphereMap) {
         glActiveTextureARB(GL_TEXTURE2_ARB);
         glDisable(GL_TEXTURE_GEN_S);
         glDisable(GL_TEXTURE_GEN_T);
      }
      glActiveTextureARB(GL_TEXTURE0_ARB);
   } else {
      glDisableClientState(GL_TEXTURE_COORD_ARRAY);
      if (m_hasSingleSphereMap) {
         glDisable(GL_TEXTURE_GEN_S);
         glDisable(GL_TEXTURE_GEN_T);
      }
      if (m_hasMultipleSphereMap) {
         glActiveTextureARB(GL_TEXTURE2_ARB);
         glDisable(GL_TEXTURE_GEN_S);
         glDisable(GL_TEXTURE_GEN_T);
         glActiveTextureARB(GL_TEXTURE0_ARB);
      }
   }

   if (m_hasSingleSphereMap || m_hasMultipleSphereMap) {
      glDisable(GL_TEXTURE_GEN_S);
      glDisable(GL_TEXTURE_GEN_T);
   }
   if (m_toon) {
      glActiveTextureARB(GL_TEXTURE1_ARB);
      glDisable(GL_TEXTURE_2D);
   }
   if (m_hasMultipleSphereMap) {
      glActiveTextureARB(GL_TEXTURE2_ARB);
      glDisable(GL_TEXTURE_2D);
   }
   glActiveTextureARB(GL_TEXTURE0_ARB);
   glClientActiveTextureARB(GL_TEXTURE0_ARB);

   glDisable(GL_TEXTURE_2D);
   glEnable(GL_CULL_FACE);
#ifndef MMDFILES_CONVERTCOORDINATESYSTEM
   glCullFace(GL_BACK);
   glPopMatrix();
#endif /* !MMDFILES_CONVERTCOORDINATESYSTEM */
}

/* PMDModel::renderEdge: render toon edge */
void PMDModel::renderEdge()
{
   unsigned long numSurface;
   unsigned short *surfaceList;
   float modelAlpha;

   if (!m_vertexList) return;

   if (m_forceEdge) {
      /* force edge drawing even if this model has no edge surface or no-toon mode */
      if (m_numSurfaceForEdge == 0) {
         numSurface = m_numSurface;
         surfaceList = m_surfaceList;
      } else {
         numSurface = m_numSurfaceForEdge;
         surfaceList = m_surfaceListForEdge;
      }
   } else {
      /* draw edge when toon mode, skip when this model has no edge surface */
      if (!m_toon) return;
      if (m_numSurfaceForEdge == 0) return;
      numSurface = m_numSurfaceForEdge;
      surfaceList = m_surfaceListForEdge;
   }

#ifndef MMDFILES_CONVERTCOORDINATESYSTEM
   glPushMatrix();
   glScalef(1.0f, 1.0f, -1.0f);
   glCullFace(GL_BACK);
#else
   /* draw back surface only */
   glCullFace(GL_FRONT);
#endif /* !MMDFILES_CONVERTCOORDINATESYSTEM */

   /* calculate alpha value */
   modelAlpha = m_globalAlpha;

   glDisable(GL_LIGHTING);
   glEnableClientState(GL_VERTEX_ARRAY);
   glVertexPointer(3, GL_FLOAT, sizeof(btVector3), m_edgeVertexList);
   glColor4f(m_edgeColor[0], m_edgeColor[1], m_edgeColor[2], m_edgeColor[3] * modelAlpha);
   glDrawElements(GL_TRIANGLES, numSurface, GL_UNSIGNED_SHORT, surfaceList);
   glDisableClientState(GL_VERTEX_ARRAY);
   glEnable(GL_LIGHTING);

   /* draw front again */
#ifndef MMDFILES_CONVERTCOORDINATESYSTEM
   glPopMatrix();
   glCullFace(GL_FRONT);
#else
   glCullFace(GL_BACK);
#endif /* !MMDFILES_CONVERTCOORDINATESYSTEM */
}

/* PMDModel::renderForShadow: render for shadow */
void PMDModel::renderForShadow()
{
   if (!m_vertexList) return;

   /* plain drawing of only edge surfaces */
   if (m_numSurfaceForEdge == 0) return;

   glDisable(GL_CULL_FACE);
   glEnableClientState(GL_VERTEX_ARRAY);
   glVertexPointer(3, GL_FLOAT, sizeof(btVector3), m_skinnedVertexList);
   glDrawElements(GL_TRIANGLES, m_numSurfaceForEdge, GL_UNSIGNED_SHORT, m_surfaceListForEdge);
   glDisableClientState(GL_VERTEX_ARRAY);
   glEnable(GL_CULL_FACE);
}

/* PMDModel::renderForPick: render for pick */
void PMDModel::renderForPick()
{
   if (!m_vertexList) return;

   /* plain drawing of all surfaces */
   glDisable(GL_CULL_FACE);
   glEnableClientState(GL_VERTEX_ARRAY);
   glVertexPointer(3, GL_FLOAT, sizeof(btVector3), m_skinnedVertexList);
   glDrawElements(GL_TRIANGLES, m_numSurface, GL_UNSIGNED_SHORT, m_surfaceList);
   glDisableClientState(GL_VERTEX_ARRAY);
   glEnable(GL_CULL_FACE);
}

/* PMDModel::renderDebug: render for debug view */
void PMDModel::renderDebug()
{
   unsigned short i;

   if (!m_vertexList) return;

   glDisable(GL_DEPTH_TEST);
   glDisable(GL_LIGHTING);
   glDisable(GL_TEXTURE_2D);

   /* draw bones */
   for (i = 0; i < m_numBone; i++)
      m_boneList[i].renderDebug();

   glEnable(GL_DEPTH_TEST);
   glEnable(GL_LIGHTING);
}


text:
For **help**, **support**, **questions** and **ideas** please use **[our forum](https://forum.ghost.org)**  🚑.

Please **_do not_** raise an issue on GitHub.

We have a **help** category in our **[forum](https://forum.ghost.org/)** where you can get quick answers,
help with debugging weird issues, and general help with any aspect of Ghost. There's also an **ideas** category for feature requests.

Our extensive **documentation** can be found at https://docs.ghost.org/.

Please go to https://forum.ghost.org and signup to join our community.
You can create a new account, or signup using Google, Twitter or Facebook.

Issues which are not bug reports will be closed.

## Using Ghost(Pro)?

**Ghost(Pro)** users have access to email support via the support at ghost dot org address.

## Why not GitHub?

GitHub is our office, it's the place where our development team does its work. We use the issue list
to keep track of bugs and the features that we are working on. We do this openly for transparency.

With the forum, you can leverage the knowledge of our wider community to get help with any problems you are
having with Ghost. Please keep in mind that Ghost is FLOSS, and free support is provided by the goodwill
of our wonderful community members.


text:
  $(function () {
                    $("#injectNavbarHere").load("navBar_BitManipulation.html", function () {
                        //<!--Menu Toggle Script -- >
                        $("#navbarToggleButton").click(function (e) {
                            e.preventDefault();
                            $("#wrapper").toggleClass("toggled");
                            $("#navbarToggleButton").toggleClass("closed");
                        });
                    });
                });


text:
- **scala-sbt.ftl**
- **sbt-autoplugin.ftl**
- **scala-native.ftl**

## Using the sandbox for evaluation
The sandbox project is included for convenience. It is a bare, minimal sbt project with the `sbt-fmpp-template` plugin installed. You can use it to evaluate the included example projects.

## Evaluating these templates from your local environment
Alternatively, you can evaluate these templates from your local environment. An installation of the `sbt-fmpp-template` plugin is required. It is recommended to install it globally, however, it will also work if installed on a given project. The project on which the plugin is installed must be used as the sbt session which will evaluate the templates.


text:
class PagesController < ApplicationController
  def index
    session[:error] = nil
  end
end


text:
 - Update a dependency to the latest release.

## 0.2.2+13

 - Update a dependency to the latest release.

## 0.2.2+12

 - Update a dependency to the latest release.

## 0.2.2+11

 - **REFACTOR**: add `verify` to `QueryPlatform` and change internal `verifyToken` API to `verify` ([#9711](https://github.com/firebase/flutterfire/issues/9711)). ([c99a842f](https://github.com/firebase/flutterfire/commit/c99a842f3e3f5f10246e73f51530cc58c42b49a3))

## 0.2.2+10

 - Update a dependency to the latest release.

## 0.2.2+9

 - Update a dependency to the latest release.

## 0.2.2+8

 - Update a dependency to the latest release.

## 0.2.2+7

 - **FIX**: Exceptions inside Query.snapshots() and more now have a stack trace that correctly points to the invocation of the throwing method ([#9639](https://github.com/firebase/flutterfire/issues/9639)). ([2f7adcb7](https://github.com/firebase/flutterfire/commit/2f7adcb777cd6bc4e3b5b3dd03c975c725bacef7))

## 0.2.2+6

 - Update a dependency to the latest release.

## 0.2.2+5

 - Update a dependency to the latest release.

## 0.2.2+4

 - Update a dependency to the latest release.

## 0.2.2+3

 - Update a dependency to the latest release.

## 0.2.2+2

 - Update a dependency to the latest release.

## 0.2.2+1

 - Update a dependency to the latest release.

## 0.2.2

 - **FEAT**: `ServerValue.increment()` now correctly accepts a `num`  to support both integers and doubles. ([#9101](https://github.com/firebase/flutterfire/issues/9101)). ([35cce5b0](https://github.com/firebase/flutterfire/commit/35cce5b03fae00b1753fc9b6ed688c7f020a5007))

## 0.2.1+12

 - Update a dependency to the latest release.

## 0.2.1+11

 - Update a dependency to the latest release.

## 0.2.1+10

 - **FIX**: bump `firebase_core_platform_interface` version to fix previous release. ([bea70ea5](https://github.com/firebase/flutterfire/commit/bea70ea5cbbb62cbfd2a7a74ae3a07cb12b3ee5a))

## 0.2.1+9

 - Update a dependency to the latest release.

## 0.2.1+8

 - **REFACTOR**: use "firebase" instead of "FirebaseExtended" as organisation in all links for this repository (#8791). ([d90b8357](https://github.com/firebase/flutterfire/commit/d90b8357db01d65e753021358668f0b129713e6b))

## 0.2.1+7

 - Update a dependency to the latest release.

## 0.2.1+6

 - **REFACTOR**: fix analyzer issue introduced in Flutter 3.0.0 ([#8652](https://github.com/firebase/flutterfire/issues/8652)). ([b781153a](https://github.com/firebase/flutterfire/commit/b781153ac65df629c0a181219bf0b01999a5fa59))

## 0.2.1+5

 - Update a dependency to the latest release.

## 0.2.1+4

 - Update a dependency to the latest release.

## 0.2.1+3

 - Update a dependency to the latest release.

## 0.2.1+2

 - Update a dependency to the latest release.

## 0.2.1+1

 - **FIX**: update all Dart SDK version constraints to Dart >= 2.16.0 (#8184). ([df4a5bab](https://github.com/firebase/flutterfire/commit/df4a5bab3c029399b4f257a5dd658d302efe3908))

## 0.2.1

 - **FEAT**: refactor error handling to preserve stack traces on platform exceptions (#8156). ([6ac77d99](https://github.com/firebase/flutterfire/commit/6ac77d99042de2a1950f89b35972e3ee1116dc9f))

## 0.2.0+5

 - **FIX**: Fixed transaction bug by removing duplicate arguments when they are already set as defaults. (#7839). ([df6568c2](https://github.com/firebase/flutterfire/commit/df6568c2f5f58f1c93abebca4df477114ed7a68e))

## 0.2.0+4

 - Update a dependency to the latest release.

## 0.2.0+3

 - Update a dependency to the latest release.

## 0.2.0+2

 - **FIX**: database path should default to `/` if no path specified rather than an empty string (fixes #7515). ([c33c3c93](https://github.com/firebase/flutterfire/commit/c33c3c931d7e4c654dd0b2cd23d800b43192d95d))

## 0.2.0+1

 - **FIX**: query modifier asserts not correctly triggering.

## 0.2.0

 - Graduate package to a stable release. See pre-releases prior to this version for changelog entries.

## 0.2.0-dev.1

 - Update a dependency to the latest release.

## 0.2.0-dev.0

> Note: This release has breaking changes.

 - **BREAKING** **REFACTOR**: rework as part of #6979 (#7202).

## 0.1.0+4

 - Update a dependency to the latest release.

## 0.1.0+3

 - Update a dependency to the latest release.

## 0.1.0+2

 - Update a dependency to the latest release.

## 0.1.0+1

 - Update a dependency to the latest release.

## 0.1.0

> Note: This release has breaking changes.

 - **FIX**: List of values erroring on transaction result (#7001).
 - **BREAKING** **FEAT**: add initial support for Web.

## 0.0.1+1

 - **REFACTOR**: firebase_database_platform_interface (#6668).
 - **CHORE**: release firebase_database_platform_interface.

## 0.0.1

 - Initial release of firebase_database_platform_interface.


text:
package com.worldline.engine.dependency.invoker;

import com.worldline.engine.dependency.command.BaseCommand;
import com.worldline.engine.dependency.listener.CommandFinishedListener;
import com.worldline.engine.dependency.listener.ProcessFinishedInterface;

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

/**
 * Class used for creating and executing an array of tasks with dependencies
 */
public abstract class Invoker <R> implements CommandFinishedListener {

    private String id;

    private List<BaseCommand> commandList;

    private List<String> currentStates;

    private List<String> requiredStates;

    private List<String> errorStates;

    private boolean processFinished;

    private ProcessFinishedInterface<R> listener;

    private R receiver;

    /**
     * Constructor for the Invoker class
     *
     * @param id             the id of the process which is used to identify the process when it's finished
     * @param receiver       the receiver object that will be passed to all the commands and where the results will be stored
     * @param listener       the callback which needs to be called when the process finishes
     * @param requiredStates an optional array of required states which are used to determine if the process finished successfully
     *                       or no
     */
    public Invoker(String id, R receiver, ProcessFinishedInterface<R> listener, String... requiredStates) {
        this.id = id;
        this.receiver = receiver;
        this.listener = listener;
        this.requiredStates = new ArrayList<String>();
        commandList = new ArrayList<BaseCommand>();
        currentStates = new ArrayList<String>();
        errorStates = new ArrayList<String>();
        processFinished = false;
        Collections.addAll(this.requiredStates, requiredStates);
    }

    /**
     * Constructor for the Invoker class
     *
     * @param id             the id of the process which is used to identify the process when it's finished
     * @param listener       the callback which needs to be called when the process finishes
     * @param requiredStates an optional array of required states which are used to determine if the process finished successfully
     *                       or no
     */
    public Invoker(String id, ProcessFinishedInterface<R> listener, String... requiredStates) {
        this(id, null, listener, requiredStates);
    }

    public void startProcess(String... initialStates) {
        log("Starting process " + id);
        currentStates.clear();
        errorStates.clear();
        Collections.addAll(currentStates, initialStates);
        process();
    }

    public abstract void log(String message);

    public String getId() {
        return id;
    }

    public R getReceiver() {
        return receiver;
    }

    public void setReceiver(R receiver) {
        this.receiver = receiver;
        for (int i = 0; i < commandList.size(); i++) {
            commandList.get(i).setReceiver(receiver);
        }
    }

    public List<String> getErrorStates() {
        return errorStates;
    }

    /**
     * This method gets the command from the command list;
     *
     * @param commandId the ID of the command to be returned;
     *
     * @return the command or null if no command was found
     */
    public BaseCommand getCommandById(String commandId) {
        BaseCommand result = null;
        for (int i = 0; i < commandList.size(); i++) {
            if (commandList.get(i).getId().equals(commandId)) {
                result = commandList.get(i);
                break;
            }
        }
        return result;
    }

    /**
     * This method is used to add a task (command) to the process.
     *
     * @param command the task (command) to be added
     */
    public void takeCommand(BaseCommand command) {
        command.setListener(this);
        command.setReceiver(receiver);
        commandList.add(command);
    }

    /**
     * This method is used to find and execute the first available task.
     * It also determines (based on the current states) if the process has already finished.
     */
    protected void process() {
        BaseCommand current;
        for (int i = 0; i < commandList.size(); i++) {
            current = commandList.get(i);
            if (currentStates.containsAll(current.getUpdatingStates())) {
                log("Command " + current.getId() + " has already been executed.");
                processFinished = true;
            } else {
                if (currentStates.containsAll(current.getRestrictingStates())) {
                    log("Execute command " + current.getId());
                    processFinished = false;
                    commandList.get(i).execute();
                    break;
                } else {
                    log("Command " + current.getId() + " can not be executed yet!");
                }
            }
        }
        if (processFinished) {
            if (currentStates.containsAll(requiredStates)) {
                finishWithSuccess();
            } else {
                finishWithError();
            }
            processFinished = false;
        }
    }

    @Override
    public void commandFinished(BaseCommand command) {
        if (command.getErrorStates().size() > 0) {
            log("Command " + command.getId() + " finished with Error " + command.getErrorStates());
            errorStates.addAll(command.getErrorStates());
            if (currentStates.containsAll(requiredStates)) {
                finishWithSuccess();
            } else {
                errorStates.add("");
                finishWithError();
            }
        } else {
            log("Command " + command.getId() + " finished with Success " + command.getUpdatedStates());
            currentStates.addAll(command.getUpdatedStates());
            process();
        }
    }

    protected void finishWithError() {
        listener.processFinished(ProcessFinishedInterface.ERROR, this);
    }

    protected void finishWithSuccess() {
        listener.processFinished(ProcessFinishedInterface.SUCCESS, this);
    }
}


text:
#pragma once

#if ENABLE(WEBGPU)

#include "WebGPUObject.h"

#include <wtf/Vector.h>

namespace WebCore {

class GPUComputePipelineState;
class WebGPUFunction;

class WebGPUComputePipelineState : public WebGPUObject {
public:
    virtual ~WebGPUComputePipelineState();
    static Ref<WebGPUComputePipelineState> create(WebGPURenderingContext*, WebGPUFunction*);
    GPUComputePipelineState* computePipelineState() { return m_computePipelineState.get(); }

private:
    WebGPUComputePipelineState(WebGPURenderingContext*, WebGPUFunction*);
    RefPtr<GPUComputePipelineState> m_computePipelineState;
};

} // namespace WebCore

#endif