text:
function getJasmineRequireObj() {
  if (typeof module !== 'undefined' && module.exports) {
    return exports;
  } else {
    window.jasmineRequire = window.jasmineRequire || {};
    return window.jasmineRequire;
  }
}

getJasmineRequireObj().console = function(jRequire, j$) {
  j$.ConsoleReporter = jRequire.ConsoleReporter();
};

getJasmineRequireObj().ConsoleReporter = function() {

  var noopTimer = {
    start: function(){},
    elapsed: function(){ return 0; }
  };

  function ConsoleReporter(options) {
    var print = options.print,
      showColors = options.showColors || false,
      onComplete = options.onComplete || function() {},
      timer = options.timer || noopTimer,
      specCount,
      failureCount,
      failedSpecs = [],
      pendingCount,
      suiteIndentation = 0,
      ansi = {
        green: '\x1B[32m',
        red: '\x1B[31m',
        yellow: '\x1B[33m',
        none: '\x1B[0m'
      };

    this.jasmineStarted = function() {
      specCount = 0;
      failureCount = 0;
      pendingCount = 0;
      print('Started');
      printNewline();
      timer.start();
    };

    this.jasmineDone = function() {
      printNewline();
      for (var i = 0; i < failedSpecs.length; i++) {
        if(!i) {
          print('Failures:');
        }
        specFailureDetails(failedSpecs[i]);
      }

      printNewline();

      if(specCount > 0) {

        var successCount = specCount - failureCount,
            specCounts = specCount + ' ' + plural('spec', specCount);

        if(successCount) {
          specCounts += ', ' + colored('green',  successCount + ' ' + plural('success', successCount));
        }

        if(failureCount) {
          specCounts += ', ' + colored('red', failureCount + ' ' + plural('failure', failureCount));
        }

        if (pendingCount) {
          specCounts += ', ' + colored('yellow', pendingCount + ' pending ');
        }

        print(specCounts);
      } else {
        print('No specs found');
      }

      var seconds = timer.elapsed() / 1000;
      print('Finished in ' + seconds + ' ' + plural('second', seconds));

      onComplete(failureCount === 0);
    };

    this.suiteStarted = function(suite) {
      print(indent(suite.fullName, suiteIndentation));
      suiteIndentation += 2;
    };

    this.suiteDone = function(suite) {
      suiteIndentation -= 2;
    };

    this.specDone = function(result) {
      specCount++;

      if (result.status == 'pending') {
        pendingCount++;
        print(indent(colored('yellow', '* ' + result.fullName), suiteIndentation));
        return;
      }

      if (result.status == 'passed') {
        print(indent(colored('green', '\u2714 ' + result.fullName), suiteIndentation));
        return;
      }

      if (result.status == 'failed') {
        failureCount++;
        failedSpecs.push(result);
        print(indent(colored('red', '\u2716 ' + result.fullName), suiteIndentation));
      }
    };

    return this;

    function printNewline() {
      print('\n');
    }

    function colored(color, str) {
      return showColors ? (ansi[color] + str + ansi.none) : str;
    }

    function plural(str, count) {
      if(str[str.length-1] === 's') {
        return count == 1 ? str : str + 'es';
      }
      return count == 1 ? str : str + 's';
    }

    function repeat(thing, times) {
      var arr = [];
      for (var i = 0; i < times; i++) {
        arr.push(thing);
      }
      return arr;
    }

    function indent(str, spaces) {
      var lines = (str || '').split('\n');
      var newArr = [];
      for (var i = 0; i < lines.length; i++) {
        newArr.push(repeat(' ', spaces).join('') + lines[i]);
      }
      return newArr.join('\n');
    }

    function specFailureDetails(result) {
      print(indent(result.fullName, 2));

      for (var i = 0; i < result.failedExpectations.length; i++) {
        var failedExpectation = result.failedExpectations[i];
        print(indent(colored('red', failedExpectation.message), 4));
        //print(indent(failedExpectation.stack, 2));
      }

    }
  }

  return ConsoleReporter;
};


text:
<?php
namespace eMapper\ORM\Association;

use eMapper\Fluent\Query\AbstractQuery;
use eMapper\Reflection\Profiler;
use eMapper\ORM\AssociationManager;
use eMapper\Query\Schema;
use eMapper\Query\Column;
use eMapper\Mapper;
use Omocha\AnnotationBag;

/**
 * The ManyToMany class is an abstraction of many-to-many associations.
 * @author emaphp
 */
class ManyToMany extends Association {
	/**
	 * Join table
	 * @var string
	 */
	protected $joinTable;

	/**
	 * Parent class column
	 * @var string
	 */
	protected $parentColumn;

	/**
	 * Entity class column
	 * @var string
	 */
	protected $entityColumn;

	public function __construct($propertyName, $reflectionProperty, $propertyAnnotations) {
		parent::__construct('ManyToMany', $propertyName, $reflectionProperty, $propertyAnnotations);
	}

	protected function parseConfig(AnnotationBag $propertyAnnotations) {
		parent::parseConfig($propertyAnnotations);

		//get join table
		$this->joinTable = $this->join->getValue();
		if (empty($this->joinTable) || !is_string($this->joinTable))
			throw new \RuntimeException(sprintf("Many-to-many association '%s' in class '%s' must define a join table through a @Join annotation", $this->name, $this->parentClass));

		//get join columns
		$join = $this->join->getArgument();
		if (empty($join))
			throw new \RuntimeException(sprintf("Many-to-many association '%s' in class '%s' must define a join column list for table '%s'", $this->name, $this->parentClass, $this->joinTable));
		$columns = explode(',', $join);
		if (count($columns) < 2)
			throw new \RuntimeException(sprintf("Many-to-many association '%s' in class '%s' doesn't define enough columns for join table '%s'", $this->name, $this->parentClass, $this->joinTable));

		$this->parentColumn = trim($columns[0]);
		$this->entityColumn = trim($columns[1]);
	}

	public function getJoinPredicate($entity) {
		//get primary key value
		$parentProfile = Profiler::getClassProfile($this->parentClass);
		$parameter = $this->getPropertyValue($parentProfile, $entity, $parentProfile->getPrimaryKey());

		//set appropiate prefix
		$joinTableAlias = Schema::DEFAULT_ALIAS . Schema::CONTEXT_ALIAS;

		//build predicate
		return Column::__callstatic($joinTableAlias . '__' . $this->parentColumn)->eq($parameter);
	}

	public function appendJoin(AbstractQuery &$query, $sourceAlias, $targetAlias, $left_join = false) {
		$parentProfile = Profiler::getClassProfile($this->parentClass);
		$entityProfile = Profiler::getClassProfile($this->entityClass);

		//join table alias
		$joinTableAlias = $sourceAlias . $targetAlias;

		//first join -> join table
		$cond = sprintf(
			'%s.%s = %s.%s',
			$sourceAlias, $parentProfile->getPrimaryKey(true),
			$joinTableAlias, $this->parentColumn
		);

		$query->innerJoin($this->joinTable, $joinTableAlias, $cond);

		//second join -> context
		$cond = sprintf(
			'%s.%s = %s.%s',
			$targetAlias, $entityProfile->getPrimaryKey(true),
			$joinTableAlias, $this->entityColumn
		);

		$query->innerJoin($entityProfile->getEntityTable(), $targetAlias, $cond);
	}

	public function appendContextJoin(AbstractQuery &$query, $mainAlias, $contextAlias) {
		$parentProfile = Profiler::getClassProfile($this->parentClass);
		$entityProfile = Profiler::getClassProfile($this->entityClass);

		//join table alias
		$joinTableAlias = $mainAlias . $contextAlias;

		//first join -> join table
		$cond = sprintf(
			'%s.%s = %s.%s',
			$joinTableAlias, $this->entityColumn,
			$mainAlias, $entityProfile->getPrimaryKey(true)
		);

		$query->innerJoin($this->joinTable, $joinTableAlias, $cond);

		//second join -> context
		$cond = sprintf(
			'%s.%s = %s.%s',
			$joinTableAlias, $this->parentColumn,
			$contextAlias, $parentProfile->getPrimaryKey(true)
		);

		$query->innerJoin($parentProfile->getEntityTable(), $contextAlias, $cond);
	}

	public function fetchValue(AssociationManager $manager) {
		return $manager->find();
	}

	public function save(Mapper $mapper, $parent, $value, $depth) {
		//if no array then return
		if ($value instanceof AssociationManager || !is_array($value))
			return null;

		$entityProfile = Profiler::getClassProfile($this->entityClass);
		$parentProfile = Profiler::getClassProfile($this->parentClass);

		//get foreign key value
		$foreignKey = $this->getPropertyValue($parentProfile, $parent, $parentProfile->getPrimaryKey());
		$manager = $mapper->newManager($this->entityClass);
		$keys = [];

		//save related data, store ids
		foreach ($value as &$entity)
			$keys[] = $manager->save($entity, $depth);

		//get join table associations
		$current = $mapper->newQuery()
		->from($this->joinTable)
		->select($this->entityColumn)
		->where(Column::__callstatic($this->parentColumn)->eq($foreignKey))
		->fetch('int[]');

		//get new elements
		$diff = array_diff($keys, $current);

		//if new elements are available add rows in join table
		if (!empty($diff)) {
			$query = $mapper->newQuery()
			->insertInto($this->joinTable)
			->columns($this->entityColumn, $this->parentColumn);

			foreach ($diff as $id) {
				$query->values($id, $foreignKey);
				$query->exec();
			}
		}

		//delete old data
		$query = $mapper->newQuery()
		->deleteFrom($this->joinTable)
		->where(Column::__callstatic($this->parentColumn)->eq($foreignKey), Column::__callstatic($this->entityColumn)->in($keys, false));
		$query->exec();
	}

	public function delete(Mapper $mapper, $foreignKey) {
		$query = $mapper->newQuery()
		->deleteFrom($this->joinTable)
		->where(Column::__callstatic($this->parentColumn)->eq($foreignKey));
		$query->exec();
	}
}

redpajama_set_name: RedPajamaGithub


text:
enum class BlockType
{
	GRASS, LOG, LEAVES, DIRT, SAND, SNOW
};

struct Block
{
	Block(){}
	Block(glm::vec3 position, BlockType blockType)
		: m_position(position)
		, m_blockType(blockType)
	{}

	//Getters
	glm::vec3 getPosition() const { return m_position; }
	BlockType getBlockType() const { return m_blockType; }

private:
	//Local position of the block in its chunk
	glm::vec3 m_position;

	//Type of the block
	BlockType m_blockType;
};


text:
SYNONYM

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

#### Published in
Ber. dt. bot. Ges. 27: 217 (1947)

#### Original name
Cortinarius balteatoclaricolor Jul. Schäff., 1947

### Remarks
null


text:
<!DOCTYPE HTML>

<meta charset="utf-8">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
	content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,menu-scalable=no" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<link href="{$responseAdmin}/css/H-ui.min.css" rel="stylesheet"
	type="text/css" />
<link href="{$responseAdmin}/css/H-ui.admin.css" rel="stylesheet"
	type="text/css" />
<link href="{$responseAdmin}/lib/Hui-iconfont/1.0.1/iconfont.css"
	rel="stylesheet" type="text/css" />

<title>渠道列表</title>


		 404

不好意思,您访问的页面不存在~

您可以:
		< 返回上一页
		|
		去首页 >

<literal>

</literal>


text:
package com.appolica.flubber.animation.providers;

import android.animation.ObjectAnimator;
import android.view.View;

import androidx.annotation.NonNull;

import com.appolica.flubber.AnimationBody;
import com.appolica.flubber.utils.DimensionUtils;

public class FadeInRight extends BaseFadeIn {

    @NonNull
    protected ObjectAnimator getTranslation(AnimationBody animationBody, View view) {
        final float startY = -DimensionUtils.dp2px(300) * animationBody.getForce();
        final float endY = 0;

        final ObjectAnimator translateAnimation =
                ObjectAnimator.ofFloat(view, View.TRANSLATION_X, startY, endY);

        return translateAnimation;
    }

}


text:
'use strict';

if (!waitlist) {
	var waitlist = {};
}

waitlist.reform = (function(){

	var getMetaData = waitlist.base.getMetaData;
	var displayMessage = waitlist.base.displayMessage;

	var data = {
			trigger_selector: "#btn-send-invites",
			trigger_action: "click",
			user_list_selector: "#char-list",
			// it gets a jquery object of the element gotten with the
			// user_list_selector
			user_list_extractor_func: function(el) {
				return el.val().split(/\n/);
			},
			progress_selector: "#progressbar"
	};

	function invite(playerName) {
		$.post({
			'url': data.api_invite_by_name.replace('-1', playerName),
			'data': {
				'_csrf_token': data.csrf
			},
			'error': function(data) {
				var message = data.statusText;

				if (typeof data.responseJSON !== 'undefined' && typeof data.responseJSON.message !== 'undefined') {
					message += ": " + data.responseJSON.message;
				}
				else if (typeof data.responseText !== 'undefined') {
						message += ": " + data.responseText;
				}
				displayMessage(message, "danger");
				increaseCounter(1);
			},
			'success': function(){
				increaseCounter(1);
			},
			'dataType': 'json'
		});
	}

	function increaseCounter(inc) {
		var bar = $(data.progress_selector);
		var old = Number(bar.attr('value'));
		bar.attr('value', old+inc);
	}

	function startInvites() {
		var character_names = data.user_list_extractor_func($(data.user_list_selector));
		var bar = $(data.progress_selector);
		bar.attr('max', character_names.length);
		bar.attr('value', 0);
		for (let name of character_names) {
			invite(name);
		}
	}

	function init() {
		data.api_invite_by_name = getMetaData('api-invite-by-name');
		data.csrf = getMetaData('csrf-token');
		var button = $(data.trigger_selector);
		button.on(data.trigger_action, startInvites);
	}

    $(document).ready(init);

	return {};
}());


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('tournament', '0103_playerbye_player_rating'),
    ]

    operations = [
        migrations.AddField(
            model_name='alternate',
            name='player_rating',
            field=models.PositiveIntegerField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='teammember',
            name='player_rating',
            field=models.PositiveIntegerField(blank=True, null=True),
        ),
    ]


text:
namespace creator {

CreatorApi::CreatorApi() = default;
CreatorApi::~CreatorApi() = default;

}  // namespace creator


text:
define([
	"src/oskari/oskari",
	"./sandbox",
	"./sandbox-key-listener-methods",
	"./sandbox-map-layer-methods",
	"./sandbox-map-methods",
	"./sandbox-abstraction-methods",
	"sources/framework/sandbox/sandbox-state-methods"
], function(Oskari) {
	Oskari.bundleCls('sandbox-base');
	Oskari.bundleCls('sandbox-map');
});


text:
package Applications.RefFeatures;

import java.util.*;
import HOSemiCRF.*;

/**
 * Edge features between two consecutive segments
 * @author Nguyen Viet Cuong
 */
public class Edge extends FeatureType {

    public ArrayList<String> generateObsAt(DataSequence seq, int segStart, int segEnd) {
        ArrayList<String> obs = new ArrayList<String>();
        if (segStart >= 1) {
            obs.add("E.");
        }
        return obs;
    }

    public int order() {
        return 1;
    }
}


text:
package com.github.fcannizzaro.autosize.annotations;

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

/**
 * @author Francesco Cannizzaro (fcannizzaro)
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AutoMargin {
    int l() default 0;
    int r() default 0;
    int t() default 0;
    int b() default 0;
    int value() default 0;
}


text:
<?php

// Hook into WP Login Form

// Get Client IP Address

// Check to See if a custom GeoIP Server is set

	// If no Custom Server use FreeGeoIP.net

		// http://freegeoip.net/json/$varIPAddress

	// if Custom is Set

		// Go them

// Phrase Return for Country

	// Get Country

	// Compare to Approved Countries

	// If Allowed , continued to Login Page

		// Else (If Allowed in Settings), log IP address and Send Annoymous Details back to developer

/* Settings

	List of Countries/Regions
		* North America
			* United States (Set a Default)
			* Canada
			* Mexico
		* Latin America
		* South America

		* Europe
		* Africa
		* Middle East
		* Russia (Note)
		* Asia
		* China (note)
		* Japan
		* Tw
		* Aus

		Note: It is unreliable to Limit to City/State/Province so request the feature

	White Listed IP (For Those Emergency Times)
		Only Network Blocks
			Based on ISP
				Comcast
				AT&T

	Custom Geo IP Server
		Default http://freegeoip.net
		Custom Server: URL

	Opt In to Send Annoymous Data to Developer: IP Address that Attempted to access the Login Page and were Deny

	Deny/Rejected Users Reaction?
		* Basic 403 Error Page: default
		* Redirect to Homepage
		* Redirect to trap (Logs/traps/ban IP)
		* Redirect to custom Page


text:
import React, { Component, PropTypes } from 'react';
import shouldPureComponentUpdate from 'react-pure-render/function';
import { collectionRenamePayloadShape } from 'client/store/shapes';

class CollectionRename extends Component {
  static propTypes = {
    payload: collectionRenamePayloadShape.isRequired,
    doDestroy: PropTypes.func.isRequired,
    actions: PropTypes.object.isRequired,
  };

  state = { collectionName: this.props.payload.collection };

  shouldComponentUpdate = shouldPureComponentUpdate;

  onChange = (e) => {
    this.setState({ collectionName: e.target.value });
  };

  onKeyDown = (e) => {
    if (e.keyCode == 13) {
      // on enter
      this.save(e);
    } else if (e.keyCode == 27) {
      // on esc
      this.props.doDestroy(e);
    }
  };

  save = (e) => {
    e.preventDefault();
    this.props.actions.renameCollection(this.props.payload, this.state.collectionName);
    this.props.doDestroy(e);
  };

  render() {
    return (

Rename collection

            New name:
            <input type="text" value={this.state.collectionName} onChange={this.onChange} onKeyDown={this.onKeyDown} autoFocus />

          Cancel
          <button onClick={this.save}>Save</button>

    );
  }
}

export default CollectionRename;


text:
/**
 * @file	src/core/TaskNotification.h
 * @date	June 2016
 * @author	Applied Informatics Software Engineering GmbH and contributors
 *
 * Original Poco::Task code checked out from https://github.com/pocoproject/poco
 * commit d6ebf591 (May 2016)
 */

//
// TaskNotification.h
//
// $Id: //poco/1.4/Foundation/include/Poco/TaskNotification.h#1 $
//
// Library: Foundation
// Package: Tasks
// Module:  Tasks
//
// Definition of the TaskNotification class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier:	BSL-1.0
//

#ifndef CUSTOM_Foundation_TaskNotification_INCLUDED
#define CUSTOM_Foundation_TaskNotification_INCLUDED

#include "Poco/Notification.h"
#include "Poco/Exception.h"

class MergeableTask;

class TaskNotification: public Poco::Notification
	/// Base class for TaskManager notifications.
{
public:
	TaskNotification(MergeableTask* pTask);
		/// Creates the TaskNotification.

	MergeableTask* task() const;
		/// Returns the subject of the notification.

protected:
	virtual ~TaskNotification();
		/// Destroys the TaskNotification.

private:
	MergeableTask* _pTask;
};

class TaskStartedNotification: public TaskNotification
	/// This notification is posted by the TaskManager for
	/// every task that has been started.
{
public:
	TaskStartedNotification(MergeableTask* pTask);

protected:
	~TaskStartedNotification();
};

class TaskCancelledNotification: public TaskNotification
	/// This notification is posted by the TaskManager for
	/// every task that has been cancelled.
{
public:
	TaskCancelledNotification(MergeableTask* pTask);

protected:
	~TaskCancelledNotification();
};

class TaskFinishedNotification: public TaskNotification
	/// This notification is posted by the TaskManager for
	/// every task that has finished.
{
public:
	TaskFinishedNotification(MergeableTask* pTask);

protected:
	~TaskFinishedNotification();
};

class TaskEnslavedNotification: public TaskNotification
	/// This notification is posted by the TaskManager for
	/// every task that has been enslaved.
{
public:
	TaskEnslavedNotification(MergeableTask* pTask, MergeableTask* enslaved);

	MergeableTask* slave() const;

protected:
	~TaskEnslavedNotification();

private:
	MergeableTask* mSlave;
};

class TaskFailedNotification: public TaskNotification
	/// This notification is posted by the TaskManager for
	/// every task that has failed with an exception.
{
public:
	TaskFailedNotification(MergeableTask* pTask, const Poco::Exception& exc);

	const Poco::Exception& reason() const;

protected:
	~TaskFailedNotification();

private:
	Poco::Exception* _pException;
};

class TaskFailedOnCancellationNotification: public TaskNotification
    /// This notification is posted by the TaskManager for
    /// every task that has failed after a cancellation.
{
public:
    TaskFailedOnCancellationNotification(MergeableTask* pTask, const Poco::Exception& exc);

    const Poco::Exception& reason() const;

protected:
    ~TaskFailedOnCancellationNotification();

private:
    Poco::Exception* _pException;
};

class TaskProgressNotification: public TaskNotification
	/// This notification is posted by the TaskManager for
	/// a task when its progress changes.
{
public:
	TaskProgressNotification(MergeableTask* pTask, float progress);

	float progress() const;

protected:
	~TaskProgressNotification();

private:
	float _progress;
};

//template <class C>
//class TaskCustomNotification: public TaskNotification
//	/// This is a template for "custom" notification.
//	/// Unlike other notifications, this notification
//	/// is instantiated and posted by the task itself.
//	/// The purpose is to provide generic notification
//	/// mechanism between the task and its observer(s).
//{
//public:
//	TaskCustomNotification(MergeableTask* pTask, const C& rCustom):
//		TaskNotification(pTask),
//		_custom(rCustom)
//	{
//	}
//
//	const C& custom() const
//	{
//		return _custom;
//	}
//
//protected:
//	~TaskCustomNotification(){};
//
//private:
//	C _custom;
//};

//
// inlines
//
inline MergeableTask* TaskNotification::task() const
{
	return _pTask;
}

inline const Poco::Exception& TaskFailedNotification::reason() const
{
	return *_pException;
}

inline const Poco::Exception& TaskFailedOnCancellationNotification::reason() const
{
    return *_pException;
}

inline MergeableTask* TaskEnslavedNotification::slave() const
{
	return mSlave;
}

inline float TaskProgressNotification::progress() const
{
	return _progress;
}

#endif // CUSTOM_Foundation_TaskNotification_INCLUDED


text:
<?php

namespace JsonRpcServer;

use JsonRpcServer\Request\Validator;

/**
 * Class Request
 * @package JsonRpcServer
 */
class Request
{
    /**
     * @var array
     */
    private $calls;

    /**
     * @var int
     */
    private $totalCalls;

    /**
     * @var Validator
     */
    private $validator;

    /**
     * Request constructor.
     * @param $data
     */
    public function __construct($data)
    {
        $this->validator = new Validator();

        $this->validator->validateInput($data);
        $this->process($data);
    }

    /**
     * @return Validator
     */
    public function getValidator()
    {
        return $this->validator;
    }

    /**
     * @return array
     */
    public function getCalls()
    {
        return $this->calls;
    }

    /**
     * @return int
     */
    public function getTotalCalls()
    {
        return $this->totalCalls;
    }

    /**
     * @param array $data
     */
    private function process(array $data)
    {
        if (array_key_exists(0, $data)) {
            $this->calls = $data;
            $this->totalCalls = count($this->calls);

            return;
        }

        $this->totalCalls = 1;
        $this->calls = [
            $data
        ];

    }
}


text:
<?php

namespace SF;

/*
 * This file is part of the SimpleFramework
 *
 * (c) Jules Boussekeyt <jules.boussekeyt@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

class Console
{
    private $kernel;
    private $commands;

    public function __construct(Kernel $kernel, $commands = array())
    {
        $this->kernel = $kernel;
        $this->commands = $commands;
    }

    public function register($name, $command)
    {
        $this->commands[$name] = $command;
    }

    public function run($argv)
    {
        if (!isset($argv[1])) {
            echo "please specify a command:\n";
            echo '- '.implode(PHP_EOL."- ", array_keys($this->commands)).PHP_EOL;
            exit;
        }

        $name = $argv[1];

        if (!isset($this->commands[$name])) {
            echo "invalid command '{$name}'\n";
            exit;
        }

        array_splice($argv, 0, 2);

        if (!method_exists($command = $this->commands[$name], 'run')) {
            echo "command '{$name}' should have a run() method\n";
            exit;
        }

        $command->run($this->kernel->getContainer(), $argv);
    }
}


text:
VarDict
=======

VarDict is an ultra sensitive variant caller for both single and paired sample variant calling from BAM files.
VarDict implements several novel features such as amplicon bias aware variant calling from targeted
sequencing experiments, rescue of long indels by realigning bwa soft clipped reads and better scalability
than many Java based variant callers.

Due to the philosophy of VarDict in calling "everything", several downstream strategies have been developed
to filter variants to for example the most likely cancer driving events. These strategies are based on evidence
in different databases and/or quality metrics. http://bcb.io/2016/04/04/vardict-filtering/ provides an overview of
how to develop further filters for VarDict. The script at https://github.com/AstraZeneca-NGS/VarDict/blob/master/vcf2txt.pl
can be used to put the variants into a context by including information from dbSNP, Cosmic and ClinVar. We are open to
suggestions from the community on how to best narrow down to the variants of most interest.

A Java based drop-in replacement for vardict.pl is being developed at https://github.com/AstraZeneca-NGS/VarDictJava.
The Java implementation is approximately 10 times faster than the original
Perl implementation and does not depend
on samtools

To enable amplicon aware variant calling (single sample mode only; not supported in paired variant calling),
please make sure the bed file has 8 columns with the 7th and 8th columns containing the insert interval
(therefore subset of the 2nd and 3rd column interval). The bed files typically look similar to the below two
overlapping intervals:

``chr1    115247094       115247253       NRAS    0       .       115247117       115247232``

``chr1    115247202       115247341       NRAS    0       .       115247224       115247323``

For more information on amplicon aware calling please see https://github.com/AstraZeneca-NGS/VarDict/wiki/Amplicon-Mode-in-VarDict

VarDict is fully integrated in e.g. bcbio-nextgen, see https://github.com/chapmanb/bcbio-nextgen

Please cite VarDict:

Lai Z, Markovets A, Ahdesmaki M, Chapman B, Hofmann O, McEwen R, Johnson J, Dougherty B, Barrett JC, and Dry JR.  VarDict: a novel and versatile variant caller for next-generation sequencing in cancer research. Nucleic Acids Res. 2016, pii: gkw227.

The link to is article can be accessed through: http://nar.oxfordjournals.org/cgi/content/full/gkw227?ijkey=Tk8eKQcYwNlQRNU&keytype=ref

Coded by Zhongwu Lai 2014.

Requirements
------------

- Perl (uses /usr/bin/env perl)
- R (uses /usr/bin/env R)
- samtools (must be in path, not required if using the Java implementation in place of vardict.pl)

Quick start
-----------

Make sure the VarDict folder (scripts ``vardict.pl``, ``vardict``, ``testsomatic.R``, ``teststrandbias.R``, ``var2vcf_valid.pl`` and ``var2vcf_paired.pl``) is in path before running the following commands.

- Running in single sample mode::

         AF_THR="0.01" # minimum allele frequency
         vardict -G /path/to/hg19.fa -f $AF_THR -N sample_name -b /path/to/my.bam -c 1 -S 2 -E 3 -g 4 /path/to/my.bed | teststrandbias.R | var2vcf_valid.pl -N sample_name -E -f $AF_THR

- Paired variant calling::

         AF_THR="0.01" # minimum allele frequency
         vardict -G /path/to/hg19.fa -f $AF_THR -N tumor_sample_name -b "/path/to/tumor.bam|/path/to/normal.bam" -c 1 -S 2 -E 3 -g 4 /path/to/my.bed | testsomatic.R | var2vcf_paired.pl -N "tumor_sample_name|normal_sample_name" -f $AF_THR

Contributors
------------

- `Zhongwu Lai`_, AstraZeneca
.. _Zhongwu Lai: https://github.com/zhongwulai
- `Miika Ahdesmaki`_, AstraZeneca
.. _Miika Ahdesmaki: https://github.com/mjafin
- `Brad Chapman`_, Harvard School of Public Health
.. _Brad Chapman: https://github.com/chapmanb

License
-------

The code is freely available under the `MIT license`_.

.. _MIT license: http://www.opensource.org/licenses/mit-license.html


text:
<?php

$db = new PDO('mysql:host=victorbarcelo.net;dbname=victorba_igni941', 'victorba_igni941', 'f(hP6(92S5');
$st = $db->prepare('INSERT INTO temperatures (temperature,time) VALUES (?,?)');
$rand_temp = rand(45, 80) + rand(1, 9) / 10;
$st->execute(array($rand_temp, time()));

if ($rand_temp > 70) {
    send_temperture_alert_notification($rand_temp);
}

function send_temperture_alert_notification($temp) {
    $url = 'http://pistats.victorbarcelo.net/users/notify_temperature_alert';
    $options = array(CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => 1, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => array('login' => 'vto', 'password' => '1234', 'temperature' => $temp));
    do_curl($options);
}

function do_curl($options) {
    $curl = curl_init();
    curl_setopt_array($curl, $options);
    $output = curl_exec($curl);
    curl_close($curl);
}


text:
<?php

namespace Magento\Framework\Url;

use Magento\TestFramework\Helper\ObjectManager;

class ValidatorTest extends \PHPUnit_Framework_TestCase
{
    /** @var \Magento\Framework\Url\Validator */
    protected $object;

    /** @var string[] */
    protected $expectedValidationMessages = ['invalidUrl' => "Invalid URL '%value%'."];

    protected function setUp()
    {
        $objectManager = new ObjectManager($this);
        $this->object = $objectManager->getObject('Magento\Framework\Url\Validator');
    }

    public function testConstruct()
    {
        $this->assertEquals($this->expectedValidationMessages, $this->object->getMessageTemplates());
    }

    public function testIsValidWhenValid()
    {
        $this->assertEquals(true, $this->object->isValid('http://example.com'));
        $this->assertEquals([], $this->object->getMessages());
    }

    public function testIsValidWhenInvalid()
    {
        $this->assertEquals(false, $this->object->isValid('%value%'));
        $this->assertEquals($this->expectedValidationMessages, $this->object->getMessages());
    }
}


text:
<!DOCTYPE html>

		<meta name="viewport" content="width=device-width, initial-scale=1">

		<meta charset="utf-8">
		<title>SSO sample</title>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

Sample code for SSO


text:
'use strict';function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
/**
 * @module
 * @description
 * Starting point to import all public core APIs.
 */
__export(require('./src/core/metadata'));
__export(require('./src/core/util'));
__export(require('./src/core/di'));
__export(require('./src/common/pipes'));
__export(require('./src/facade/facade'));
__export(require('./src/core/application'));
__export(require('./src/core/bootstrap'));
__export(require('./src/core/services'));
__export(require('./src/core/linker'));
var application_ref_1 = require('./src/core/application_ref');
exports.ApplicationRef = application_ref_1.ApplicationRef;
__export(require('./src/core/zone'));
__export(require('./src/core/render'));
__export(require('./src/common/directives'));
__export(require('./src/common/forms'));
__export(require('./src/core/debug'));
__export(require('./src/core/change_detection'));
__export(require('./src/core/platform_directives_and_pipes'));
__export(require('./src/core/dev_mode'));
//# sourceMappingURL=core.js.map


text:
const os = require('os');

describe('Ravel', () => {
  let app, conf;
  beforeEach(async () => {
    jest.resetModules();
    jest.restoreAllMocks();
    jest.clearAllMocks();
    const Ravel = require('../../lib/ravel');
    app = new Ravel();
    app.set('keygrip keys', ['abc']);
    app.set('log level', app.$log.NONE);
  });

  describe('#registerParamter()', () => {
    it('should throw if a client attempts to register a parameter with a deliberately undefined default value', () => {
      expect(() => {
        const undefinedEnvironmentVariable = undefined;
        app.registerParameter('my param', true, undefinedEnvironmentVariable);
      }).toThrow(app.$err.IllegalValue);
    });
  });

  describe('#set()', () => {
    it('should allow clients to set the value of a parameter', async () => {
      app.registerParameter('test param', false);
      app.set('test param', 'test value');
      await app.init();
      expect(app.get('test param')).toBe('test value');
    });

    it('should throw a Ravel.$err.IllegalValue error when a client attempts to set an unknown parameter', async () => {
      expect(() => app.set('unknown param', 'test value')).toThrow(app.$err.IllegalValue);
    });
  });

  describe('#get()', () => {
    it('should allow clients to retrieve the value of a set optional parameter', async () => {
      app.registerParameter('test param', false);
      app.set('test param', 'test value');
      await app.init();
      expect(app.get('test param')).toEqual('test value');
    });

    it('should return undefined when clients attempt to retrieve the value of an unset optional parameter', async () => {
      app.registerParameter('test param', false);
      await app.init();
      expect(app.get('test param')).toEqual(undefined);
    });

    it('should allow clients to retrieve the value of a set required parameter', async () => {
      app.registerParameter('test param', true);
      app.set('test param', 'test value');
      await app.init();
      expect(app.get('test param')).toEqual('test value');
    });

    it('should throw a Ravel.$err.General error when clients attempt to retrieve a parameter before loading', async () => {
      expect(() => {
        app.registerParameter('test param', true);
        app.get('test param');
      }).toThrow(app.$err.General);
    });

    it('should throw a Ravel.$err.NotFound error when clients attempt to retrieve an unregistered parameter', async () => {
      await app.init();
      expect(() => app.get('test param')).toThrow(app.$err.NotFound);
    });

    it('should throw a Ravel.$err.NotFound error when clients attempt to retrieve the value of an unset required parameter', async () => {
      app.registerParameter('test param', true);
      await app.init();
      expect(() => app.get('test param')).toThrow(app.$err.NotFound);
    });
  });

  describe('.config', () => {
    it('should return the full configuration of the given `ravel instance`', async () => {
      const defaultConfig = app.config;
      app.registerParameter('test param', true);
      app.registerParameter('test param 2', true);
      app.set('test param', false);
      app.set('test param 2', 10);

      const expected = {
        'test param': false,
        'test param 2': 10
      };
      Object.assign(expected, defaultConfig);

      expect(app.config).toEqual(expected);
    });
  });

  describe('validateParameters', () => {
    it('should throw app.$err.NotFound when a required parameter is not present', async () => {
      app.registerParameter('test param', true);
      await app.init();
      await expect(app.listen()).rejects.toThrow(app.$err.NotFound);
      await app.close();
    });

    it('should rethrow errors when app.get throws a non-NotFound Error', async () => {
      app.registerParameter('test param', true);
      await app.init();
      app.get = jest.fn(() => { throw new Error(); });
      await expect(app.listen()).rejects.toThrow(Error);
      await app.close();
    });
  });

  describe('#_loadParameters()', () => {
    it('should load defaults if no configuration files are present', async () => {
      const oldParams = {
        'enable websockets': true,
        'max websocket payload bytes': 104857600,
        'redis port': 6379,
        'redis max retries': 10,
        'redis keepalive interval': 1000,
        'redis websocket channel prefix': 'ravel.ws',
        port: 8080,
        https: false,
        'https options': {},
        'app route': '/',
        'login route': '/login',
        'keygrip keys': ['123abc'],
        'session key': 'ravel.sid',
        'session max age': null,
        'session samesite': null,
        'session secure': true,
        'session rolling': false,
        'log level': 'NONE', // not a default, but we've set this in beforeEach
        'log colors': true,
        'log format': '[%(date)s] %(name)s.%(levelname)s: %(message)s'
      };
      app.set('keygrip keys', ['123abc']);
      await app.init();
      // now load params from non-existent ravelrc file
      expect(app.config).toEqual(oldParams);
    });

    it('should allow users to specify Ravel config parameters via a .ravelrc.json config file', async () => {
      conf = {
        'redis port': 1234
      };
      jest.doMock(upath.toUnix(upath.posix.join(app.cwd, '.ravelrc')), () => conf, { virtual: true });
      await app.init();
      expect(app.get('redis port')).toEqual(conf['redis port']);
    });

    it('should should support searching for .ravelrc.json files in any parent directory of app.cwd', async () => {
      conf = {
        'redis port': 1234
      };
      let parent = app.cwd.split(upath.sep).slice(0, -1).join(upath.sep);
      const root = (os.platform() === 'win32') ? process.cwd().split(upath.sep)[0] : upath.sep;
      parent = parent.length > 0 ? parent : root;
      const joined = upath.toUnix(upath.posix.join(parent, '.ravelrc'));
      jest.doMock(joined, () => conf, { virtual: true });
      await app.init();
      expect(app.get('redis port')).toEqual(conf['redis port']);
    });

    it('should should support searching for .ravelrc.json files in any parent directory of app.cwd, including root', async () => {
      conf = {
        'redis port': 1234
      };
      const root = (os.platform() === 'win32') ? process.cwd().split(upath.sep)[0] : upath.sep;
      // can't use extension on mock because mockery only works with exact matches
      const joined = upath.toUnix(upath.posix.join(root, '.ravelrc'));
      jest.doMock(joined, () => conf, { virtual: true });
      await app.init();
      expect(app.get('redis port')).toEqual(conf['redis port']);
    });

    it('should allow users to specify Ravel config parameters via a .ravelrc config file and parse it to JSON', async () => {
      conf = {
        'redis port': 1234
      };
      jest.doMock(upath.toUnix(upath.posix.join(app.cwd, '.ravelrc')), () => JSON.stringify(conf), { virtual: true });
      await app.init();
      expect(app.get('redis port')).toEqual(conf['redis port']);
    });

    it('should not override parameters set programmatically via app.set', async () => {
      conf = {
        'redis port': 1234
      };
      jest.doMock(upath.toUnix(upath.posix.join(app.cwd, '.ravelrc')), () => conf, { virtual: true });

      app.set('redis port', 6380);
      await app.init();
      expect(app.get('redis port')).toEqual(6380);
    });

    it('should throw a Ravel.$err.IllegalValue if an unregistered paramter is specified in the config file', async () => {
      conf = {
        'redis port': 1234
      };
      conf[Math.random().toString()] = false;
      jest.doMock(upath.toUnix(upath.posix.join(app.cwd, '.ravelrc')), () => conf, { virtual: true });

      app.set('redis port', 6380);
      await expect(app.init()).rejects.toThrow(app.$err.IllegalValue);
    });

    it('should throw a SyntaxError if a .ravelrc file is found but is malformed', async () => {
      jest.doMock(upath.toUnix(upath.posix.join(app.cwd, '.ravelrc')), () => { throw new SyntaxError(); }, { virtual: true });
      await expect(app.init()).rejects.toThrow(SyntaxError);
    });

    describe('environment variable interpolation', () => {
      beforeEach(() => {
        process.env.REDIS_HOST = 'localhost';
        process.env.REDIS_PORT = '9999';
      });

      afterEach(() => {
        delete process.env.REDIS_HOST;
        delete process.env.REDIS_PORT;
      });

      it('should interpolate variables in the config value with the value from environment variables', async () => {
        conf = {
          'redis host': '$REDIS_HOST',
          'redis port': '$REDIS_PORT'
        };
        jest.doMock(upath.toUnix(upath.posix.join(app.cwd, '.ravelrc')), () => JSON.stringify(conf), { virtual: true });
        await app.init();
        expect(app.get('redis port')).toEqual('9999');
        expect(app.get('redis host')).toEqual('localhost');
      });

      it('should interpolate variables in the config when there are multiple variables', async () => {
        app.registerParameter('redis url', false);
        conf = {
          'redis url': 'redis://$REDIS_HOST:$REDIS_PORT'
        };
        jest.doMock(upath.toUnix(upath.posix.join(app.cwd, '.ravelrc')), () => JSON.stringify(conf), { virtual: true });
        await app.init();
        expect(app.get('redis url')).toEqual('redis://localhost:9999');
      });

      it('should throw IllegalValueError when the environment variable referenced in the config value does not exist', async () => {
        app.registerParameter('redis url', false);
        conf = {
          'redis url': 'redis://$REDIS_USER:$REDIS_PASSWORD@$REDIS_HOST:$REDIS_PORT'
        };
        jest.doMock(upath.toUnix(upath.posix.join(app.cwd, '.ravelrc')), () => JSON.stringify(conf), { virtual: true });
        await expect(app.init()).rejects.toThrow(app.$err.IllegalValue);
      });
    });
  });
});


text:
module Config where

import Protolude hiding (option)

import Options.Applicative

import qualified Data.Configurator as C
import qualified Data.Configurator.Types as C

import Network.Socket (HostName, PortNumber)

import Nanocoin.Network.Utils (RPCPort, P2PPort)

data Config = Config
  { hostname     :: HostName        -- ^ Hostname of node
  , rpcPort      :: RPCPort         -- ^ Port to run RPC server on
  , p2pPort      :: P2PPort         -- ^ Port to run p2p process on
  , bootnodes    :: [Text]          -- ^ List of bootnode hostnames and ports
  , keysFilePath :: Maybe FilePath  -- ^ Filepath to read node keys from
  , logFilePath  :: Maybe FilePath  -- ^ Filepath to log to
  }

-- Read config from config file
readConfig :: FilePath -> IO Config
readConfig cfgFile = do
  cfg <- C.load [C.Required cfgFile]
  Config <$> C.require cfg "nanocoin.hostname"
         <*> C.require cfg "nanocoin.rpcPort"
         <*> readP2PPort cfg
         <*> C.require cfg "nanocoin.bootnodes"
         <*> C.lookup  cfg "nanocoin.keysPath"
         <*> C.lookup  cfg "nanocoin.logFilePath"
  where
    readP2PPort :: C.Config -> IO P2PPort
    readP2PPort cfg = do
      portNum <- C.require cfg "nanocoin.p2pPort"
      return $ intToP2PPort portNum

    intToP2PPort :: Int -> P2PPort
    intToP2PPort = fromIntegral

-- Parse Config options via command line
parseConfig config = Config
    <$> hostnameParser `fallback` (hostname config)
    <*> rpcPortParser  `fallback` (rpcPort config)
    <*> p2pPortParser  `fallback` (p2pPort config)
    <*> pure (bootnodes config) -- XXX add cmd line option for adding bootnodes
    <*> keysParser
    <*> logFileParser
  where
    hostnameParser :: Parser (Maybe HostName)
    hostnameParser = optional $
      option auto $ long "hostname"
                 <> metavar "HOSTNAME"

    rpcPortParser :: Parser (Maybe RPCPort)
    rpcPortParser = optional $
      option auto $ long "rpc-port"
                 <> short 'p'
                 <> metavar "RPC_PORT"

    p2pPortParser :: Parser (Maybe P2PPort)
    p2pPortParser =
      fmap (fmap fromIntegral) $
        optional $ option auto $
             long "p2p-port"
          <> short 'n'
          <> metavar "P2P_PORT"

    keysParser :: Parser (Maybe FilePath)
    keysParser = optional $
      strOption $ long "keys"
               <> short 'k'
               <> metavar "KEYS_DIR"

    logFileParser :: Parser (Maybe FilePath)
    logFileParser = optional $
      strOption $ long "logfile"
              <> short 'f'
              <> metavar "LOG_FILE"

fallback :: Parser (Maybe a) -> a -> Parser a
fallback parser x = flip fallback' x <$> parser
  where
    fallback' (Just x) _ = x
    fallback' Nothing x  = x


text:
/*
 * Version 0.1
 * Made By Patrick Kolenic
 * Roll20: https://app.roll20.net/users/5259711/articblast
 * Patreon: https://www.patreon.com/ratworkshop
 * Github: https://github.com/pkolenic/roll20-api-scripts
 */
/**
 * Utility Functions
 */
class RatWorkshop_Library {
  constructor() {
  }

  /**
   * Converts String to Snake Case, underscore instead of - or space
   * @param string
   * @return {void | string}
   */
  static snakeCase(string) {
    let converted = string.replace(/-/g, '_');
    converted = converted.replace(/ /g, '_');
    return converted
  }

  /**
   *Covererts String to Camel Case; underscore, dash, and space removed and first letter capitalized
   * @param string
   * @return {*}
   */
  static camelCase(string) {
    return string.replace(/[-_ ]+(.)?/g, (m, c) => c.toUpperCase());
  }

  /**
   * Generates a Universally Unique ID
   * @return {string}
   */
  static generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }
}

/**
 * Contains Core Methods for sending messages to chat, as well as fetching data from a character sheet
 */
class RatWorkshop_Module {
  static VERSION = 0.2;
  static MODULE_NAME = 'Base Module';
  static DEFAULT_STATE = {
    version: RatWorkshop_Module.VERSION,
    gcUpdated: 0,
  };

  MSG_CONTENT = '###CONTENT###';
  MSG_SOURCE = 'RatWorkshop';
  MSG_OPTIONS = {
    NO_ARCHIVE: { noarchive: true },
  };
  MSG_TYPE = {
    STATUS: '/w gm ',
  };
  MSG_TEMPLATES = {
    DESC: `

${this.MSG_CONTENT}

`,
    ERROR: `<div style="background: #FFD2AD; border-radius: 3px; border: 1px solid #D1D1D1; margin: 0 -5px 0 -45px;"><div style="margin: 5px 5px 5px 45px;">${this.MSG_CONTENT}</div></div>`
  };

  /**
   * Renders the Template, replacing the CONTENT Placeholder with the message and attaching the prefix
   * @param template
   * @param message
   * @param prefix
   * @return {string}
   */
  render_template(template, message, prefix = '') {
    const body = template.replace(this.MSG_CONTENT, message);
    return `${prefix}${body}`;
  }

  /**
   * Dispatches a Message to a player's chat window
   * @param who
   * @param message
   * @param template
   * @param prefix
   * @param options
   * @param callback
   */
  sendMessage(who, message, template, prefix = '', options = {}, callback = null) {
    sendChat(who, this.render_template(template, message, prefix), callback, options);
  }

  /**
   * Outputs an Error Message to the player
   * @param playerId
   * @param message
   */
  sendErrorMessage(playerId, message) {
    const player = getObj("player", playerId);
    if (player) {
      this.sendMessage(
        this.MSG_SOURCE,
        message,
        this.MSG_TEMPLATES.ERROR,
        `/w ${player.get('displayname')} `,
        this.MSG_OPTIONS.NO_ARCHIVE,
      )
    }
  }

  /**
   * Outputs an Action message to all players
   * @param character
   * @param message
   */
  sendActionMessage(character, message) {
    this.sendMessage(character, message, this.MSG_TEMPLATES.DESC);
  }

  /**
   * Adds an Event to the turn order after the current Turn
   * @param event
   */
  addTurnOrder(event) {
    event.eventId = RatWorkshop_Library.generateUUID();
    const turnOrder = JSON.parse(Campaign().get('turnorder') || '[]');
    // Either put the event after the current Turn or push it onto the empty array
    if (turnOrder.length) {
      turnOrder.splice(1, 0, event);
    } else {
      turnOrder.push(event);
    }
    Campaign().set('turnorder', JSON.stringify(turnOrder));
    return event.eventId;
  }

  /**
   * Adds an event for tracking
   * @param eventId
   * @param characterId
   * @param tokenId
   * @param action
   * @param callbackModule
   * @param callbackAction
   */
  addEvent(eventId, characterId, tokenId, action, callbackModule, callbackAction) {
    this.events.push({
      eventId,
      characterId,
      tokenId,
      action,
      callbackModule,
      callbackAction,
    });
  }

  /**
   * Attempts to return the first matching trait
   * @param characterId
   * @param trait
   * @return {null|{name: *, options_flag: *, description: *, display_flag: *, source_type: *, source: *}}
   */
  getTrait(characterId, trait) {
    const traits = filterObjs((obj) => {
      if (obj.get('type') !== 'attribute') return false;
      if (obj.get('characterid') !== characterId) return false;
      if (!obj.get('name').startsWith('repeating_traits') || !obj.get('name').endsWith('name')) return false;
      return obj.get('current').toLowerCase() === trait.toLowerCase();
    });
    // Trait not Found
    if (!traits.length) {
      return null;
    }
    // Get the Base name for the first found trait and return object with all trait attributes
    const traitName = traits[0].get('name').replace('_name', '');
    return {
      name: traits[0].get('current'),
      description: getAttrByName(characterId, `${traitName}_description`),
      source: getAttrByName(characterId, `${traitName}_source`),
      source_type: getAttrByName(characterId, `${traitName}_source_type`),
      options_flag: getAttrByName(characterId, `${traitName}_options-flag`),
      display_flag: getAttrByName(characterId, `${traitName}_display_flag`),
    };
  }

  /**
   * Attempts to return the first matching resource
   * @param characterId
   * @param resource
   * @return {null|{current: *, max: *}}
   */
  getResource(characterId, resource) {
    const resourceNames = filterObjs((obj) => {
      if (obj.get('type') !== 'attribute') return false;
      if (obj.get('characterid') !== characterId) return false;
      if (!obj.get('name').endsWith('_name')) return false;
      return /.*_resource_.*/.test(obj.get('name')) && obj.get('current').toLowerCase() === resource.toLowerCase();
    });
    // Resource not Found
    if (!resourceNames.length) {
      return null;
    }
    // Return the first resource
    const resourceName = resourceNames[0].get('name').replace('_name', '');
    return findObjs({ type: 'attribute', characterid: characterId, name: resourceName }, { caseInsensitive: true })[0];
  }

  /**
   * Attempts to return the first matching Global Modifier
   * @param characterId
   * @param modifier
   * @return {null}
   */
  getGlobalModifier(characterId, modifier) {
    const modifierNames = filterObjs((obj) => {
      if (obj.get('type') !== 'attribute') return false;
      if (obj.get('characterid') !== characterId) return false;
      if (!obj.get('name').startsWith('repeating_damagemod') || !obj.get('name').endsWith('name')) return false;
      return obj.get('current').toLowerCase() === modifier.toLowerCase();
    });
    // Modifier not Found
    if (!modifierNames.length) {
      return null;
    }
    // Get the Base name for the first found modifier and then fetch all attributes with that name
    const modifierName = modifierNames[0].get('name').replace('global_damage_name', '');
    const modifiers = filterObjs((obj) => {
      if (obj.get('type') !== 'attribute') return false;
      if (obj.get('characterid') !== characterId) return false;
      return obj.get('name').startsWith(modifierName);
    });
    //  Return object with all the related attributes
    const response = {};
    _.each(modifiers, (attribute) => {
      const key = attribute.get('name').replace(modifierName, '').replace('global_damage_', '');
      response[key] = attribute;
    });
    return response;
  }

  /**
   * Attempts to return the first matching Global Damage with the given damage type
   * @param characterId
   * @param damageType
   * @return {null}
   */
  getGlobalDamage(characterId, damageType) {
    try {
      const damageTypeAttribute = filterObjs((obj) => {
        if (obj.get('type') !== 'attribute') return false;
        if (obj.get('characterid') !== characterId) return false;
        if (!obj.get('name').endsWith('global_damage_type')) return false;
        return obj.get('current').toLowerCase() === damageType.toLowerCase();
      })[0];

      // Get the Base name for the first found attribute and then fetch all attributes with that name
      const baseName = damageTypeAttribute.get('name').replace('global_damage_type', '');
      const attributes = filterObjs((obj) => {
        if (obj.get('type') !== 'attribute') return false;
        if (obj.get('characterid') !== characterId) return false;
        return obj.get('name').startsWith(baseName);
      });

      // Return object with all the related attributes
      const response = {};
      _.each(attributes, (attribute) => {
        const key = attribute.get('name').replace(baseName, '').replace('global_damage_', '');
        response[key] = attribute;
      });
      return response;
    } catch (error) {
      log(`Unable to find Global Damage for => ${damageType}`);
      return null;
    }
  }

  getAttackRolls(characterId) {
    return filterObjs((obj) => {
      if (obj.get('type') !== 'attribute') return false;
      if (obj.get('characterid') !== characterId) return false;
      return (obj.get('name').endsWith('_rollbase_dmg') || obj.get('name').endsWith('_rollbase_crit'))
    });
  }

  /** Attempt to return Global Damage Attributes*
   * @param characterId
   * @return {null}
   */
  getGlobalDamageModifier(characterId) {
    const globalDmgObjs = filterObjs((obj) => {
      if (obj.get('type') !== 'attribute') return false;
      if (obj.get('characterid') !== characterId) return false;
      return obj.get('name').startsWith('global_damage');
    });
    // Global Damage Not Found
    if (!globalDmgObjs.length) {
      return null;
    }
    const response = {};
    _.each(globalDmgObjs, (attribute) => {
      const key = attribute.get('name').replace('global_damage_mod_', '');
      response[key] = attribute;
    });
    return response;
  }

  /**
   * Attempts to return the Character's token on the active page
   * @param characterId
   * @return {*}
   */
  getToken(characterId) {
    const pageId = Campaign().get('playerpageid');
    const tokens = findObjs({ type: 'graphic', represents: characterId, _pageid: pageId });
    return tokens[0] || null;
  }

  /**
   * Attempts to return all Tokens representing a character, npc, or monster on the active page
   * @param characterId
   * @return {Array}
   */
  getTokens(characterId) {
    const pageId = Campaign().get('playerpageid');
    const tokens = findObjs({ type: 'graphic', represents: characterId, _pageid: pageId });
    return tokens || [];
  }

  /** INITIALIZATION METHODS **/
  /**
   * Registers the Module with the Dungeon Master Tools
   */
  static register() {
    if (this.MODULE_NAME === RatWorkshop_Module.MODULE_NAME) {
      log('Base RatWorkshop Module can not be registers, extend it first');
      return;
    }

    if (typeof dungeonMasterTools === 'object') {
      log(`Registering ${this.MODULE_NAME} Module`);
      dungeonMasterTools.registerModule(this);
    }
  }

  /**
   * Used to update State based on One-Click useroptions
   */
  initialConfigurations() {
    // Override in SubClasses
  }

  /**
   * Populates the state references from the global state
   */
  setStateReferences() {
    // Quick Reference to the Stored States
    this.settings = state.RatWorkShop_DungeonMasterTools_Roll20_5E || {};
    this.configState = state.RatWorkShop_DungeonMasterTools_Roll20_5E.config || {};
    this.tokenTrack = state.RatWorkShop_DungeonMasterTools_Roll20_5E.tokenTrack || {};
    this.tokenIcons = state.RatWorkShop_DungeonMasterTools_Roll20_5E.tokenIcons || {};
    this.events = state.RatWorkShop_DungeonMasterTools_Roll20_5E.events || [];
  }

  constructor() {
    this.initialConfigurations();
    this.setStateReferences();
  }
}

/**
 * Handles Loading Configurations, Setting up Listeners, Registering Class Modules, Dispatching Actions, and Awarding XP
 */
class DungeonMasterTools extends RatWorkshop_Module {
  static MODULE_NAME = 'DungeonMasterTools';
  static VERSION = 0.2;
  static DEFAULT_STATE = {
    config: {
      'purge-turn-order': 'on',
      'track-active-tokens': 'on',
    },
    tokenTrack: {
      dead: 'on',
    },
    tokenIcons: {
      dead: 'dead',
    },
    tokenBars: {
      hp: 'bar1',
      ac: 'bar2',
    },
    activeToken: {
      'aura-color': '#ffff00',
      'aura-index': 2,
    },
    modules: {},
    events: [],
    version: DungeonMasterTools.VERSION,
    gcUpdated: 0,
  };

  COMMANDS = {
    // SET STATE COMMANDS
    'dm-award-xp': (options, msg) => this.awardXp(options, msg),
    'dm-award-selected-xp': (options, msg) => this.awardSelectedXp(options, msg),
    'dm-action': (options, msg) => this.handleAction(options, msg),
    'dm-config': (options, msg) => this.setConfigOption(options, msg),
    'dm-token-tracking': (options, msg) => this.setTokenTracking(options, msg),
    // UTILITY COMMANDS
    'dm-help': (options, msg) => log('help called'),
    'dm-status': (options, msg) => this.outputStatus(msg),
    'dm-reset': (options, msg) => this.resetState(msg),
  };

  /**
   * Dungeon Master Tools shouldn't register itself
   */
  static register() {
  }

  /**
   * Update Config with Values from globalConfig
   * @param config
   * @param globalConfig
   * @param prefix
   */
  updateConfiguration(config, globalConfig, prefix = '') {
    Object.keys(config || {}).forEach((key) => {
      if (`${prefix}${key}` in globalConfig) {
        config[key] = globalConfig[`${prefix}${key}`];
      }
    });
  }

  /**
   * Initialize Configurations and update from userOptions
   */
  initialConfigurations() {
    // For Storing State information
    if (!state.RatWorkShop_DungeonMasterTools_Roll20_5E ||
      !state.RatWorkShop_DungeonMasterTools_Roll20_5E.version ||
      state.RatWorkShop_DungeonMasterTools_Roll20_5E.version !== DungeonMasterTools.VERSION) {
      // Sync Settings to Latest Settings
      Object.entries(DungeonMasterTools.DEFAULT_STATE).forEach(([key, options]) => {
        if(!['version', 'gcUpdated', 'events', 'modules'].includes(key)) {
          const settings = Object.assign(state.RatWorkShop_DungeonMasterTools_Roll20_5E[key]);

          // Merge New Default Settings over old settings
          state.RatWorkShop_DungeonMasterTools_Roll20_5E[key] = { ...state.RatWorkShop_DungeonMasterTools_Roll20_5E[key], ...options };

          // Now Merge back any custom changes
          state.RatWorkShop_DungeonMasterTools_Roll20_5E[key] = { ...state.RatWorkShop_DungeonMasterTools_Roll20_5E[key], ...settings };
        }
      });
      // Set State Version to current Version
      state.RatWorkShop_DungeonMasterTools_Roll20_5E.version = DungeonMasterTools.VERSION;
    }

    const gc = globalconfig && globalconfig.RatWorkShop_DungeonMasterTools_Roll20_5E;
    if (gc && gc.lastsaved && gc.lastsaved > state.RatWorkShop_DungeonMasterTools_Roll20_5E.gcUpdated) {
      log('  > Updating from Global Config <  ['+(new Date(g.lastsaved*1000))+']');

      state.RatWorkShop_DungeonMasterTools_Roll20_5E.gcUpdated = gc.lastsaved;
      this.updateConfiguration(state.RatWorkShop_DungeonMasterTools_Roll20_5E.config, gc);
      this.updateConfiguration(state.RatWorkShop_DungeonMasterTools_Roll20_5E.tokenTrack, gc, 'tokenTrack-');
      this.updateConfiguration(state.RatWorkShop_DungeonMasterTools_Roll20_5E.tokenIcons, gc, 'tokenIcon-');
      this.updateConfiguration(state.RatWorkShop_DungeonMasterTools_Roll20_5E.tokenBars, gc, 'tokenBar-');
      this.updateConfiguration(state.RatWorkShop_DungeonMasterTools_Roll20_5E.activeToken, gc, 'activeToken-');
    }
  }

  setStateReferences() {
    super.setStateReferences();
    this.activeTokens = state.RatWorkShop_DungeonMasterTools_Roll20_5E.activeTurnTokens || [];
    this.tokenBars = state.RatWorkShop_DungeonMasterTools_Roll20_5E.tokenBars || {};
  }

  constructor() {
    super();
    // Object to store registered modules
    this.modules = {
      'DungeonMasterTools': this,
    };

    // Setup Listener for API messages
    on("chat:message", (msg) => {
      // HANDLE API Commands
      if (msg.type === 'api' && !msg.rolltemplate) {
        const params = msg.content.substring(1).split(" ");
        const command = params[0].toLowerCase() || '';
        const options = params.slice(1);

        // Only handle valid commands
        if (Object.keys(this.COMMANDS).includes(command)) {
          this.COMMANDS[command](options, msg);
        }
      }
    });

    // Register Listener for Changes to the Campaign
    on("change:campaign", campaign => {
      Object.values(this.modules).forEach((module) => {
        Object.entries(this.configState).forEach(([key, value]) => {
          const func = RatWorkshop_Library.camelCase(key);
          if (value === 'on' && typeof module[func] === 'function') {
            module[func]();
          }
        });
      });
    });

    // Register Listener for Token Changes
    on("change:graphic", token => {
      const pageId = Campaign().get('playerpageid');
      // Only listen for changes on the current page
      // - @TODO might change in case players are on multiple pages
      if (token.get('_pageid') === pageId) {
        Object.values(this.modules).forEach((module) => {
          Object.entries(this.tokenTrack).forEach(([key, value]) => {
            const func = RatWorkshop_Library.camelCase(`tokenTrack-${key}`);
            if (value === 'on' && typeof module[func] === 'function') {
              module[func](token);
            }
          });
        });
        this.handleTokenChange(token);
      }
    });

    log('Dungeon Master Tools Initialized!');
  }

  /**
   * Logic applied when a token has changed
   * @param token
   */
  handleTokenChange(token) {
    // @TODO move the token tracking into a tokenTrack method for the icon, such as tokenTrackRage(token) for the barbarian
    // Check if Token no longer has a tracked status
    const events = this.events.filter(x => x.tokenId === token.id);
    const currentState = token.get('statusmarkers').split(',');
    _.each(events, event => {
      if (!currentState.includes(this.tokenIcons[event.action])) {
        this.dispatchAction(event.callbackModule.toLowerCase(), event.callbackAction, event);
        // Remove the Event
        const index = this.events.findIndex((element) => {
          return element.tokenId === event.tokenId && element.action === event.action
        });
        this.events.splice(index, 1);
        // Remove the Turn Order
        const turnOrder = JSON.parse(Campaign().get('turnorder') || '[]');
        const turnOrderIndex = turnOrder.findIndex(element => element.eventId === event.eventId);
        turnOrder.splice(turnOrderIndex, 1);
        Campaign().set('turnorder', JSON.stringify(turnOrder));
      }
    });
  }

  /**
   * Triggers the action to fire
   * @param moduleName
   * @param action
   * @param options
   * @param msg
   */
  dispatchAction(moduleName, action, options, msg = null) {
    const moduleNames = Object.keys(this.modules);
    if (moduleNames.includes(moduleName)) {
      const module = this.modules[moduleName];
      if (typeof module[action] === 'function') {
        module[action](options, msg);
      }
    }
  }

  /**
   * Dispatches action to module to handle
   * @param options
   * @param msg
   */
  handleAction(options, msg) {
    const moduleName = options[0].toLowerCase() || '';
    const action = `action_${RatWorkshop_Library.snakeCase(options[1])}` || '';
    const actionOptions = options.slice(2);
    this.dispatchAction(moduleName, action, actionOptions, msg);
  }

  /**
   * Sets Configuration options
   * @param options
   * @param playerId
   */
  setConfigOption(options, { playerid: playerId }) {
    // Bail if no config specified or player is not GM
    if (!options.length || !playerIsGM(playerId)) {
      return;
    }

    const configOption = options[0].toLowerCase();
    const status = options[1] || 'off';
    // Only deal with valid Configuration Options
    if (Object.keys(this.configState).includes(configOption)) {
      // Only valid states are 'on' and 'off'
      this.configState[configOption] = status === 'off' ? 'off' : 'on';
      this.sendStateStatus(configOption, this.configState[configOption]);
    }
  }

  /**
   * Sets whether to track token status
   * @param options
   * @param playerId
   */
  setTokenTracking(options, { playerid: playerId }) {
    // Bail if no token tracking specified or player is not GM
    if (!options.length || !playerIsGM(playerId)) {
      return;
    }

    const token = options[0].toLowerCase();
    const status = options[1] ? options[1].toLowerCase() : false;

    // Only deal with valid Token Tracked Statues
    if (Object.keys(this.tokenTrack).includes(token)) {
      // Only valid states are 'on' and 'off'
      if (status && (status === "on" || status === "off")) {
        this.tokenTrack[token] = status;
      }
      this.sendStateStatus(`token tracking => ${token}`, this.tokenTrack[token]);
    }
  }

  /**
   * Resets the Settings back to their default values
   * @param playerId
   */
  resetState({ playerid: playerId }) {
    // Bail if player is not GM
    if (!playerIsGM(playerId)) {
      return;
    }
    // Reset State to default
    Object.values(this.modules).forEach((module) => {
      Object.entries(module.constructor.DEFAULT_STATE).forEach(([key, options]) => {
        if (!['version', 'gcUpdated', 'events'].includes(key)) {
          this.settings[key] = { ...this.settings[key], ...options };
        }
      });
    });
    this.settings.version = DungeonMasterTools.VERSION;
    this.setStateReferences();
    _.each(this.modules, module => {
      module.setStateReferences();
    });
    this.outputStatus({ playerid: playerId });
  }

  /**
   * Outputs a State Change status to player
   * @param command
   * @param state
   */
  sendStateStatus(command, state) {
    this.sendMessage(
      this.MSG_SOURCE,
      `<span style='display:block;'>${command}: ${state}</span>`,
      this.MSG_TEMPLATES.DESC,
      this.MSG_TYPE.STATUS,
      this.MSG_OPTIONS.NO_ARCHIVE,
    );
  }

  /**
   * Builds out the status array for the given state list
   * @param list
   * @param title
   * @return {[string]}
   */
  buildStatusOutput(list, title) {
    const status = [
      `<span style="display: block; margin: 2px 10px; text-align: left;">${title}</span>`,
    ];
    _.each(list, (value, key) => {
      status.push(`<span style='display: block; margin: 2px 0 2px 20px; text-align: left'>${key}: ${value}</span>`);
    });
    status.push('
');
    return status;
  }

  /**
   * Outputs the current status of the tracker
   * @param playerId
   */
  outputStatus({ playerid: playerId }) {
    // Bail if player is not GM
    if (!playerIsGM(playerId)) {
      return;
    }

    const status = [
      "STATUS",
    ];
    // Configuration
    const config = this.buildStatusOutput(this.configState, 'CONFIGURATIONS');
    status.push(...config);
    // Token Tracking
    const token = this.buildStatusOutput(this.tokenTrack, 'TOKEN TRACKING');
    status.push(...token);
    // Token Icon
    const icons = this.buildStatusOutput(this.tokenIcons, 'TOKEN ICONS');
    status.push(...icons);
    // Token Bar
    const bars = this.buildStatusOutput(this.tokenBars, 'TOKEN BARS');
    status.push(...bars);
    // Active Token
    if (this.configState['track-active-tokens'] === 'on') {
      const activeToken = this.buildStatusOutput(this.settings.activeToken, 'ACTIVE TOKEN TRACKING');
      status.push(...activeToken);
    }
    // Dispatch Message
    this.sendMessage(
      this.MSG_SOURCE,
      status.join(''),
      this.MSG_TEMPLATES.DESC,
      this.MSG_TYPE.STATUS,
      this.MSG_OPTIONS.NO_ARCHIVE,
    );
  }

  /**
   * Register a new Module with the Dungeon Master Tools
   * @param module - the new module to register
   * @param force - to force a new module even if the module would override existing actions
   */
  registerModule(module, force = false) {
    // Only register if it is not already registered
    if (!this.modules[module.MODULE_NAME.toLowerCase()] || force) {
      this.modules[module.MODULE_NAME.toLowerCase()] = new module();
      log(`${module.MODULE_NAME} has been registered`);
    }
  }

  /**
   * Looks up the Character for the Token and awards it XP
   * @param token
   * @param amount
   * @return {boolean} - whether the xp was awarded or not
   */
  awardCharacterXP(token, amount) {
    if (token) {
      const characterId = token.get('represents');
      const character = getObj("character", characterId);
      // Only attempt to assign xp to a Character
      if (character) {
        const traits = filterObjs((obj) => {
          if (obj.get('type') !== 'attribute') return false;
          if (obj.get('characterid') !== characterId) return false;
          if (obj.get('name') === 'experience') return true;
        });
        if (traits.length) {
          const xp = traits[0];
          const currentXp = parseInt(xp.get('current'), 10);
          xp.set({ current: `${currentXp + amount}` });
        }
        return true;
      }
    }
    return false;
  }

  /**
   * Awards XP To players' characters that are currently in the turn order
   * @param options
   * @param msg
   */
  awardXp(options, msg) {
    // Get Each Player
    const turnOrder = JSON.parse(Campaign().get('turnorder') || '[]');
    const amount = parseInt(options[0], 10);
    const message = options.slice(1).join(' ').replace('###XP###', amount);
    let awarded = false;
    _.each(turnOrder, turn => {
      awarded |= this.awardCharacterXP(getObj('graphic', turn.id), amount)
    });
    if (awarded) {
      this.sendActionMessage('Dungeon Master', message);
    }
  }

  /**
   * Awards XP To the selected players
   * @param options
   * @param msg
   */
  awardSelectedXp(options, msg) {
    const amount = parseInt(options[0], 10);
    const message = options.slice(1).join(' ').replace('###XP###', amount);
    let awarded = false;
    _.each(msg.selected, sel => {
      awarded |= this.awardCharacterXP(getObj('graphic', sel._id), amount)
    });
    if (awarded) {
      this.sendActionMessage('Dungeon Master', message);
    }
  }

  /** TOKEN CHANGE FUNCTIONS **/
  tokenTrackDead(token) {
    const token_bar = this.tokenBars.hp;
    if (!token_bar || token.get(`${token_bar}_max`) === "") {
      return;
    }
    const token_status = {};
    token_status[`status_${this.tokenIcons.dead}`] = token.get(`${token_bar}_value`) <= 0;
    token.set(token_status);
  }

  /** CAMPAIGN CHANGE FUNCTIONS **/
  /**
   * Purge actions from the Turn Order that have an initative value less than zero
   */
  purgeTurnOrder() {
    const turnOrder = JSON.parse(Campaign().get('turnorder') || '[]');

    const updatedTurnOrder = turnOrder.filter(event => parseInt(event.pr, 10) >= 0);
    Campaign().set('turnorder', JSON.stringify(updatedTurnOrder));

    // Check if removed turn orders have callback functions
    const expiredEvents = turnOrder.filter(x => !updatedTurnOrder.includes(x));
    _.each(expiredEvents, turnEvent => {
      const event = this.events.filter(x => x.eventId === turnEvent.eventId)[0] || null;
      if (event) {
        this.dispatchAction(event.callbackModule.toLowerCase(), event.callbackAction, event);
        // Remove the Event
        const index = this.events.findIndex((element) => element.eventId === event.eventId);
        this.events.splice(index, 1);
      }
    });
  }

  /**
   * Applies a visible Aura to all tokens representing the current Character in the Turn Tracker
   */
  trackActiveTokens() {
    const aura_index = this.settings.activeToken['aura-index'] || 2;
    const turnOrder = JSON.parse(Campaign().get('turnorder') || '[]');
    const options = {};
    // Remove turn aura from previously active tokens
    options[`showplayers_aura${aura_index}`] = false;
    options[`playersedit_aura${aura_index}`] = true;
    options[`aura${aura_index}_radius`] = '';
    options[`aura${aura_index}_color`] = 'transparent';
    options[`aura${aura_index}_square`] = false;
    // clear aura on tokens
    _.each(this.activeTokens, obj => {
      const tokenId = obj._id || obj.get('id');
      const token = getObj('graphic', tokenId);
      if (token) {
        token.set(options);
      }
    });
    this.activeTokens.length = 0;

    // Find all tokens for the current turn and set turn aura on them
    options[`showplayers_aura${aura_index}`] = true;
    options[`playersedit_aura${aura_index}`] = false;
    options[`aura${aura_index}_radius`] = '0.5';
    options[`aura${aura_index}_color`] = this.settings.activeToken['aura-color'] || '#ffff00';
    options[`aura${aura_index}_square`] = false;
    if (turnOrder.length) {
      const token = getObj('graphic', turnOrder[0].id);
      if (token) {
        const tokens = this.getTokens(token.get('represents'));
        // set aura on tokens
        _.each(tokens, token => {
          token.set(options);
          this.activeTokens.push(token);
        });
      }
    }

    // Persist activeTokens to state
    state.RatWorkShop_DungeonMasterTools_Roll20_5E.activeTurnTokens = this.activeTokens;
  }
}

// Initialize
dungeonMasterTools = new DungeonMasterTools();


text:
package com.android.base.app.dagger;

import android.arch.lifecycle.ViewModel;

import dagger.MapKey;
import kotlin.annotation.AnnotationTarget;
import kotlin.annotation.MustBeDocumented;
import kotlin.annotation.Retention;
import kotlin.annotation.Target;

@MustBeDocumented
@Target(allowedTargets = AnnotationTarget.FUNCTION)
@Retention()
@MapKey
public @interface ViewModelKey {

    Class<? extends ViewModel> value();
}


text:
#pragma once

#include "hazelcast/util/export.h"
#include "hazelcast/client/sql/sql_result.h"
#include "hazelcast/client/sql/sql_statement.h"

#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
#pragma warning(push)
#pragma warning(disable : 4251) // for dll export
#endif

namespace hazelcast {
namespace client {
namespace impl {
class hazelcast_client_instance_impl;
}
class hazelcast_client;
namespace sql {

/**
 * A service to execute SQL statements.
 *

 * In order to use the service, Jet engine must be enabled on the server side -
 * SQL statements are executed as Jet jobs. On members, the {@code
 * hazelcast-sql.jar} must be on the classpath, otherwise an exception will be
 * thrown; on client, it is not necessary.
 *
 *

 *
Overview

 * Hazelcast is currently able to execute distributed SQL queries using the
 * following connectors:
 *

 *
IMap
 *
Kafka
 *
Files
 *

 *
 * When an SQL statement is submitted to a member, it is parsed and optimized
 * hazelcast-sql module, that is based on Apache Calcite. During optimization a
 * statement is converted into a directed acyclic graph (DAG) that is sent to
 * cluster members for execution. Results are sent back to the originating
 * member asynchronously and returned to the user via {@link sql_result}.

 * SQL statements are not atomic. INSERT/SINK can fail and
 * commit part of the data.

Usage
 Before you can access any object
 * using SQL, a mapping has to be created. See the reference manual for
 * the CREATE MAPPING command.
 When a query is executed, an
 * sql_result is returned. You may get row iterator from the result. The result
 * must be closed at the end. The code snippet below demonstrates a typical
 * usage pattern:

 *     auto hz = hazelcast::new_client().get();
 *
 *     try {
 *         // Get the SQL service from the client and execute a query
 *         auto result = hz.get_sql().execute("SELECT * FROM person").get();
 *         for (auto it = result.page_iterator(); it; (++it).get()) {
 *              // iterate over the rows in the page
 *              for (auto const &row : (*it).rows()) {
 *                  auto person_id = row.get<int64_t>("personId");
 *                  auto name = row.get<std::string>("name");
 *                  ...
 *              }
 *         }
 *
 *         // Close the result when done.
 *         result.close().get();
 *     } catch (hazelcast::client::exception &e) {
 *          std::cerr << "Query failed: " << e.what() << std::endl;
 *     }
 *

 */
class HAZELCAST_API sql_service
{
public:
    /**
     * Convenient method to execute a distributed query with the given
     * parameter values.
     *

     * Converts passed SQL string and parameter values into an sql_statement
     * object and invokes execute(const sql_statement& statement).
     *
     * @param sql       SQL string
     * @param arguments query parameter values that will be passed to
     * sql_statement::add_parameter(const Param& param)
     * @return result of the execution
     *
     * @throws illegal_argument if the SQL string is empty
     * @throws hazelcast_sql_exception in case of execution error
     * @see sql_service
     * @see sql_statement
     * @see execute(const sql_statement& statement)
     */
    template<typename... Params>
    boost::future<std::shared_ptr<sql_result>> execute(const std::string& query,
                                      const Params&... params)
    {
        sql_statement s{ client_context_, query };
        int _[] = { 0, (s.add_parameter(params), 0)... };
        (void)_;
        return execute(s);
    }

    /**
     * Executes an SQL statement.
     *
     * @param statement statement to be executed
     * @return result of the execution
     * @throws hazelcast_sql_exception in case of execution error
     * @see sql_service
     */
    boost::future<std::shared_ptr<sql_result>> execute(
      const sql_statement& statement);

private:
    friend client::impl::hazelcast_client_instance_impl;
    friend sql_result;

    client::spi::ClientContext& client_context_;

    struct sql_execute_response_parameters
    {
        int64_t update_count;
        std::shared_ptr<sql_row_metadata> row_metadata;
        std::shared_ptr<sql_page> first_page;
        boost::optional<impl::sql_error> error;
        bool is_infinite_rows = false;
        bool is_infinite_rows_exist = false;
    };

    struct sql_fetch_response_parameters
    {
        std::shared_ptr<sql_page> page;
        boost::optional<impl::sql_error> error;
    };

    explicit sql_service(client::spi::ClientContext& context);

    std::shared_ptr<connection::Connection> query_connection();

    void rethrow(const std::exception_ptr& exc_ptr);
    void rethrow(std::exception_ptr cause_ptr,
                 const std::shared_ptr<connection::Connection>& connection);

    boost::uuids::uuid client_id();

    std::shared_ptr<sql_result> handle_execute_response(
      protocol::ClientMessage& msg,
      std::shared_ptr<connection::Connection> connection,
      impl::query_id id,
      int32_t cursor_buffer_size);

    static sql_execute_response_parameters decode_execute_response(
      protocol::ClientMessage& msg);

    impl::query_id create_query_id(
      const std::shared_ptr<connection::Connection>& query_conn);

    boost::future<std::shared_ptr<sql_page>> fetch_page(
      const impl::query_id& q_id,
      int32_t cursor_buffer_size,
      const std::shared_ptr<connection::Connection>& connection);

    static sql_fetch_response_parameters decode_fetch_response(
      protocol::ClientMessage message);

    static void handle_fetch_response_error(
      boost::optional<impl::sql_error> error);

    /**
     * Close remote query cursor.
     *
     * @param connection Connection.
     * @param id    Query ID.
     */
    boost::future<void> close(
      const std::shared_ptr<connection::Connection>& connection,
      impl::query_id id);
};
} // namespace sql
} // namespace client
} // namespace hazelcast
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
#pragma warning(pop)
#endif


text:
package com.intellij.lexer;

import com.intellij.psi.tree.IElementType;
import com.intellij.util.text.CharArrayUtil;

import java.io.IOException;

/** @deprecated use com.intellij.lang.java.JavaDocLexer (to remove in IDEA 14) */
public class DocCommentLexer extends MergingLexerAdapter {
  public DocCommentLexer(final DocCommentTokenTypes tokenTypes, final boolean isJdk15Enabled) {
    super(new AsteriskStripperLexer(new _JavaDocLexer(isJdk15Enabled, tokenTypes), tokenTypes),
          tokenTypes.spaceCommentsTokenSet());
  }

  private static class AsteriskStripperLexer extends LexerBase {
    private final _JavaDocLexer myFlex;
    private final DocCommentTokenTypes myTokenTypes;
    private CharSequence myBuffer;
    private int myBufferIndex;
    private int myBufferEndOffset;
    private int myTokenEndOffset;
    private int myState;
    private IElementType myTokenType;
    private boolean myAfterLineBreak;
    private boolean myInLeadingSpace;

    public AsteriskStripperLexer(final _JavaDocLexer flex, final DocCommentTokenTypes tokenTypes) {
      myFlex = flex;
      myTokenTypes = tokenTypes;
    }

    @Override
    public final void start(CharSequence buffer, int startOffset, int endOffset, int initialState) {
      myBuffer = buffer;
      myBufferIndex =  startOffset;
      myBufferEndOffset = endOffset;
      myTokenType = null;
      myTokenEndOffset = startOffset;
      myFlex.reset(myBuffer, startOffset, endOffset, initialState);
    }

    @Override
    public int getState() {
      return myState;
    }

    @Override
    public CharSequence getBufferSequence() {
      return myBuffer;
    }

    @Override
    public int getBufferEnd() {
      return myBufferEndOffset;
    }

    @Override
    public final IElementType getTokenType() {
      locateToken();
      return myTokenType;
    }

    @Override
    public final int getTokenStart() {
      locateToken();
      return myBufferIndex;
    }

    @Override
    public final int getTokenEnd() {
      locateToken();
      return myTokenEndOffset;
    }

    @Override
    public final void advance() {
      locateToken();
      myTokenType = null;
    }

    protected final void locateToken() {
      if (myTokenType != null) return;
      _locateToken();

      if (myTokenType == myTokenTypes.space()) {
        myAfterLineBreak = CharArrayUtil.containLineBreaks(myBuffer, getTokenStart(), getTokenEnd());
      }
    }

    private void _locateToken() {
      if (myTokenEndOffset == myBufferEndOffset) {
        myTokenType = null;
        myBufferIndex = myBufferEndOffset;
        return;
      }

      myBufferIndex = myTokenEndOffset;

      if (myAfterLineBreak) {
        myAfterLineBreak = false;
        while (myTokenEndOffset < myBufferEndOffset && myBuffer.charAt(myTokenEndOffset) == '*' &&
               (myTokenEndOffset + 1 >= myBufferEndOffset || myBuffer.charAt(myTokenEndOffset + 1) != '/')) {
          myTokenEndOffset++;
        }

        myInLeadingSpace = true;
        if (myBufferIndex < myTokenEndOffset) {
          myTokenType = myTokenTypes.commentLeadingAsterisks();
          return;
        }
      }

      if (myInLeadingSpace) {
        myInLeadingSpace = false;
        boolean lf = false;
        while (myTokenEndOffset < myBufferEndOffset && Character.isWhitespace(myBuffer.charAt(myTokenEndOffset))) {
          if (myBuffer.charAt(myTokenEndOffset) == '\n') lf = true;
          myTokenEndOffset++;
        }

        final int state = myFlex.yystate();
        if (state == _JavaDocLexer.COMMENT_DATA ||
            myTokenEndOffset < myBufferEndOffset && (myBuffer.charAt(myTokenEndOffset) == '@' ||
                                                     myBuffer.charAt(myTokenEndOffset) == '{' ||
                                                     myBuffer.charAt(myTokenEndOffset) == '\"' ||
                                                     myBuffer.charAt(myTokenEndOffset) == '<')) {
          myFlex.yybegin(_JavaDocLexer.COMMENT_DATA_START);
        }

        if (myBufferIndex < myTokenEndOffset) {
          myTokenType = lf || state == _JavaDocLexer.PARAM_TAG_SPACE || state == _JavaDocLexer.TAG_DOC_SPACE || state == _JavaDocLexer.INLINE_TAG_NAME || state == _JavaDocLexer.DOC_TAG_VALUE_IN_PAREN
                        ? myTokenTypes.space()
                        : myTokenTypes.commentData();

          return;
        }
      }

      flexLocateToken();
    }

    private void flexLocateToken() {
      try {
        myState = myFlex.yystate();
        myFlex.goTo(myBufferIndex);
        myTokenType = myFlex.advance();
        myTokenEndOffset = myFlex.getTokenEnd();
      }
      catch (IOException e) {
        // Can't be
      }
    }
  }
}


text:
package org.apache.jackrabbit.oak.security.authorization.permission;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

import javax.annotation.Nonnull;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;

import junit.framework.Assert;

import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import org.junit.Test;

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

public class PermissionEntryProviderImplTest {

    private final String GROUP_LONG_MAX = "groupLongMax";
    private final String GROUP_LONG_MAX_MINUS_10 = "groupLongMaxMinus10";
    private final String GROUP_50 = "group50";

    /**
     * @see OAK-2465
     */
    @Test
    public void testInitLongOverflow() throws Exception {
        MockPermissionStore store = new MockPermissionStore();
        PermissionEntryCache cache = new MockPermissionEntryCache();
        Set<String> principalNames = ImmutableSet.of(GROUP_LONG_MAX);

        /*
        create a new PermissionEntryProviderImpl to have it's #init() method
        called, which may trigger the cache to be pre-filled if the max number
        if entries is not exceeded -> in case of PermissionStore#getNumEntries
        return Long.MAX_VALUE the cache should not be filled (-> the mock-cache
        implementation will fail.
        */
        PermissionEntryProviderImpl provider = new PermissionEntryProviderImpl(store, cache, principalNames, ConfigurationParameters.EMPTY);
        Field existingNamesField = provider.getClass().getDeclaredField("existingNames");
        existingNamesField.setAccessible(true);

        // test that PermissionEntryProviderImpl.existingNames nevertheless is
        // properly filled with all principal names for which permission entries exist
        assertEquals(principalNames, existingNamesField.get(provider));
        assertNotSame(Iterators.emptyIterator(), provider.getEntryIterator(new EntryPredicate()));
    }

    /**
     * @see OAK-2465
     */
    @Test
    public void testInitLongOverflow2() throws Exception {
        MockPermissionStore store = new MockPermissionStore();
        PermissionEntryCache cache = new MockPermissionEntryCache();
        Set<String> principalNames = ImmutableSet.of(GROUP_LONG_MAX_MINUS_10, GROUP_50);

        /*
        create a new PermissionEntryProviderImpl to have it's #init() method
        called, which may trigger the cache to be pre-filled if the max number
        if entries is not exceeded -> still counting up the number of permission
        entries must deal with the fact that the counter may become bigger that
        Long.MAX_VALUE
        */
        PermissionEntryProviderImpl provider = new PermissionEntryProviderImpl(store, cache, principalNames, ConfigurationParameters.EMPTY);
        Set<String> existingNames = getExistingNames(provider);

        assertEquals(principalNames, existingNames);
        assertNotSame(Iterators.emptyIterator(), provider.getEntryIterator(new EntryPredicate()));
    }

    /**
     * @see OAK-2465
     */
    @Test
    public void testExistingNamesAndLongOverFlow() throws Exception {
        MockPermissionStore store = new MockPermissionStore();
        PermissionEntryCache cache = new MockPermissionEntryCache();
        Set<String> principalNames = Sets.newHashSet(GROUP_LONG_MAX_MINUS_10, GROUP_50, "noEntries");

        /*
        same as before but principal-set contains a name for which not entries
        exist -> the 'existingNames' set must properly reflect that
        */
        PermissionEntryProviderImpl provider = new PermissionEntryProviderImpl(store, cache, principalNames, ConfigurationParameters.EMPTY);
        Set<String> existingNames = getExistingNames(provider);

        assertFalse(principalNames.equals(existingNames));
        assertEquals(2, existingNames.size());

        principalNames.remove("noEntries");
        assertEquals(principalNames, existingNames);
    }

    @Test
    public void testNoExistingName() throws Exception {
        MockPermissionStore store = new MockPermissionStore();
        PermissionEntryCache cache = new MockPermissionEntryCache();
        Set<String> principalNames = Sets.newHashSet("noEntries", "noEntries2", "noEntries3");

        PermissionEntryProviderImpl provider = new PermissionEntryProviderImpl(store, cache, principalNames, ConfigurationParameters.EMPTY);
        Set<String> existingNames = getExistingNames(provider);

        assertTrue(existingNames.isEmpty());

        Field pathMapField = provider.getClass().getDeclaredField("pathEntryMap");
        pathMapField.setAccessible(true);
        assertNull(pathMapField.get(provider));
    }

    /**
     * Use reflection to access the private "existingNames" field storing the
     * names of those principals associated with the entry provider for which
     * any permission entries exist.
     *
     * @param provider The permission entry provider
     * @return the existingNames set.
     * @throws Exception
     */
    private static Set<String> getExistingNames(@Nonnull PermissionEntryProviderImpl provider) throws Exception {
        Field existingNamesField = provider.getClass().getDeclaredField("existingNames");
        existingNamesField.setAccessible(true);
        return (Set<String>) existingNamesField.get(provider);
    }

    // Inner Classes
    private class MockPermissionStore implements PermissionStore {

        @Override
        public Collection<PermissionEntry> load(
                Collection<PermissionEntry> entries, @Nonnull String principalName,
                @Nonnull String path) {
            return null;
        }

        @Nonnull
        @Override
        public PrincipalPermissionEntries load(@Nonnull String principalName) {
            return new PrincipalPermissionEntries();
        }

        @Override
        public long getNumEntries(@Nonnull String principalName, long max) {
            long cnt = 0;
            if (GROUP_LONG_MAX_MINUS_10.equals(principalName)) {
                cnt = Long.MAX_VALUE - 10;
            } else if (GROUP_50.equals(principalName)) {
                cnt = 50;
            } else if (GROUP_LONG_MAX.equals(principalName)) {
                cnt = Long.MAX_VALUE;
            }
            return cnt;
        }

    }

    private class MockPermissionEntryCache extends PermissionEntryCache {
        @Override
        public void load(@Nonnull PermissionStore store,
                @Nonnull Map<String, Collection<PermissionEntry>> pathEntryMap,
                @Nonnull String principalName) {
            Assert.fail("The number of  entries exceeds the max cache size");
        }
    }
}


text:
package name.kropp.intellij.makefile.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface MakefileInclude extends PsiElement {

  @NotNull
  List<MakefileFilename> getFilenameList();

}


text:
import Ember from 'ember';

export default Ember.Route.extend({
    actions: {
        saveSubcategoryField: function(field) {
            field.save();
        },

        revertSubcategoryField: function(field) {
            field.rollbackAttributes();
        }
    },

    model: function() {
        var self = this;
        var subcategory = this.modelFor('categories/category/subcategory');

        /*var store = this.store;
        var cfs = store.peekAll('categoryField');
        var toManys = cfs.filter(function(cf) { if (cf.get('type') === 'toMany') { return true; } });

        var subcategoryType = subcategory.get('id').split("_");
        if (subcategoryType.length > 0) {
            subcategoryType = subcategoryType[0];
        }

        var relations = [];

        toManys.forEach(function(cf) {
            if (cf.get('relation') === subcategoryType) {
                var catId = null;
                var catField = null;

                var idParts = cf.get('id').split("_");
                if (idParts.length >= 2) {
                    catId = idParts[0];
                    catField = idParts[1];
                }

                if (catId && catField) {
                    console.log('Related to category: ' + catId + " through field: " + catField);

                    var relatedCategory = self.store.peekRecord("category", catId);

                    console.log("category: " + relatedCategory.get('id'));
                    console.log(relatedCategory);

                    var relatedSubcategories = relatedCategory.get('subcategories');

                    console.log("subcategories: " + relatedSubcategories);

                    relations.pushObject(Ember.Object.create({
                        relatedToCategory: catId,
                        throughField: catField,
                        relatedSubcategories: relatedSubcategories
                    }));
                }
            }
        });

        subcategory.set('relatedCategoryFields', relations);*/

        return subcategory;
    }
});


text:
package org.specs.specification
import org.specs._

/**
 * This trait adds the possibility to declare an included specification as "linked" in order to
 * control its reporting in a separate file for example.
 */
trait LinkedSpecification { this: BaseSpecification =>
  /** storing the parent links for this specification */
  private var parentLinks = List[LinkedSpecification]()
  /** add a new parent link to this specification */
  private[specs] def addParent(s: LinkedSpecification): this.type = { parentLinks = s :: parentLinks; this }
  /** @return true if this specification has s as one of its parents */
  private[specs] def hasParent(s: LinkedSpecification): Boolean = parentLinks.contains(s)
  /** link this specification to a subordinate one */
  def linkTo(subSpec: Specification): this.type = {
    if (!contains(subSpec)) include(subSpec)
    subSpec.addParent(this)
    this
  }
  /**
   * partitions the subspecifications in a pair where the first member is the list of linked specifications,
   * and the second member is the unlinked ones
   */
  def partitionLinkedSpecifications: (List[Specification], List[Specification]) = {
    this.subSpecifications.partition(_.hasParent(this))
  }
  /** @return the linked specifications */
  def linkedSpecifications = this.partitionLinkedSpecifications._1
  /** @return the unlinked specifications */
  def unlinkedSpecifications = this.partitionLinkedSpecifications._2
}


text: curl -k -X GET https://example.com