text:
<input type="text" ng-model="localValue.label" class="form-control">

<div class="oppia-form-error">
  <[getWarningText()]>
</div>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using ConsoleApplication8;

namespace Tasque
{
	public class TaskCompletionDateComparer : Comparer<Task>
	{
		public override int Compare (Task x, Task y)
		{
			if (x == null && y == null)
				return 0;
			else if (x == null)
				return -1;
			else if (y == null)
				return 1;

			bool isSameDate = true;
			if (x.CompletionDate.Year != y.CompletionDate.Year
			    || x.CompletionDate.DayOfYear != y.CompletionDate.DayOfYear)
				isSameDate = false;

			if (!isSameDate) {
				if (x.CompletionDate == DateTime.MinValue) {
					// No completion date set for some reason.  Since we already
					// tested to see if the dates were the same above, we know
					// that the passed-in task has a CompletionDate set, so the
					// passed-in task should be "higher" in the sort.
					return 1;
				} else if (y.CompletionDate == DateTime.MinValue) {
					// "this" task has a completion date and should evaluate
					// higher than the passed-in task which doesn't have a
					// completion date.
					return -1;
				}

				return x.CompletionDate.CompareTo (y.CompletionDate);
			}

			// The completion dates are the same, so no sort based on other things.
			return x.CompareToByPriorityAndName (y);
		}
	}
}


text:
<?php
/**
 * @author
 */

namespace oba\core\assets;

use yii\base\Exception;
use yii\web\AssetBundle;

class AdminLteAsset extends AssetBundle
{
    public $sourcePath = '@vendor/almasaeed2010/adminlte/dist';
    public $css = [
        'css/AdminLTE.min.css',
        'css/skins/_all-skins.min.css',
    ];
    public $js = [
        'js/app.min.js',
//        'js/demo.js',
    ];
    public $depends = [
        'rmrevin\yii\fontawesome\AssetBundle',
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
        'yii\bootstrap\BootstrapPluginAsset',
    ];

    /**
     * @var string|bool Choose skin color, eg. `'skin-blue'` or set `false` to disable skin loading
     * @see https://almsaeedstudio.com/themes/AdminLTE/documentation/index.html#layout
     */
//    public $skin = 'skin-blue';
    public $skin = 'skin-red';

    /**
     * @inheritdoc
     */
    public function init()
    {
        // Append skin color file if specified
        if ($this->skin) {
            if (('_all-skins' !== $this->skin) && (strpos($this->skin, 'skin-') !== 0)) {
                throw new Exception('Invalid skin specified');
            }

            $this->css[] = sprintf('css/skins/%s.min.css', $this->skin);
        }

        parent::init();
    }
}


text:
'use strict';

const logger = require('./logger/logger').logger;
const vehicleHistoryModel = require('vehicle-history-model');
const responseBuilder = vehicleHistoryModel.builder.responseBuilder;

const isExampleBusPlate = function isExampleBusPlate(plate, options) {
  return options.get('providers.bus-pl.example.plate') === plate;
};

const getBusExampleReportV1 = function getBusExampleReportV1(options, callback) {
  const map = {
    'name.manufacturer': 'SOLARIS',
    'name.name': null,
    'name.model': 'URBINO 12',
    'variant.type': 'BUS',
    'variant.kind': 'CITY',
    'engine.cc': 2396,
    'engine.fuel': 'DIESEL',
    'production.year': 2008,
    'policy.status': 'UPTODATE',
    'registration.status': 'REGISTERED',
    'registration.firstDate': '2008-11-21T00:00:00.000Z',
    'inspection.status': 'UPTODATE',
    'mileage.value': 779951,
    'mileage.type': 'KM',
    'status.stolen': null,
    'plate.value': 'SBE12345',
    'plate.country': 'PL',
    'vin.value': 'SUU2411618BPN1684',
    'events': [
      {
        type: 'REGISTRATION',
        ownerType: null,
        location: null,
        note: null,
        createdAt: '2008-01-16T22:00:00.000Z',
        expireAt: null,
        description: 'First registration',
        firstOwner: null,
        mileage: null,
        abroadRegistration: false
      },
      {
        type: 'INSPECTION',
        ownerType: null,
        location: null,
        note: null,
        createdAt: '2016-03-11T22:00:00.000Z',
        expireAt: '2021-09-11T22:00:00.000Z',
        description: 'Inspection (11.03.2016)',
        firstOwner: null,
        mileage: {
          value: 779951,
          type: 'KM'
        },
        abroadRegistration: null
      }
    ]
  };

  responseBuilder.build(map, options, (buildErr, report) => {
    if (buildErr) {
      logger.error('unable to generate example report by responseBuilder: %s', buildErr);
      return callback(buildErr);
    }

    return callback(buildErr, report);
  });
};

module.exports = {
  getBusExampleReportV1: getBusExampleReportV1,
  isExampleBusPlate: isExampleBusPlate
};


text:
"""
Driver classes for cisco devices.

  - IOS - driver for cisco IOS operating system
"""

import logging
from nocexec.drivers.base import NOCExecDriver
from nocexec.exception import SSHClientError, TelnetClientError, \
    NOCExecError, SSHClientExecuteCmdError, TelnetClientExecuteCmdError

LOG = logging.getLogger('nocexec.drivers.cisco')

__all__ = ['IOSError', 'IOSCommandError', 'IOS']

class IOSError(NOCExecError):
    """
    The base exception class for Cisco IOS driver
    """
    pass

class IOSCommandError(IOSError):
    """
    The exception class for command errors
    """
    pass

class IOS(NOCExecDriver):  # pylint: disable=too-many-instance-attributes
    """
    A driver class for connecting to Cisco IOS devices using the SSH or Telnet
    protocol and executing commands.

        :param device: domain or ip address of device (default: "")
        :param login: username for authorization on device (default: "")
        :param password: password for authorization on device (default: "")
        :param port: port number for connection (default: 22)
        :param timeout: timeout waiting for connection (default: 5)
        :param protocol: use protocol ('ssh' or 'telnet') for
                         connection (default: "ssh")
        :type device: string
        :type login: string
        :type password: string
        :type port: int
        :type timeout: int
        :type protocol: string

    :Example:

    >>> from nocexec.drivers.cisco import IOS
    >>> with IOS("192.168.0.1", "user", "password") as cli:
    ...     for l in cli.view("show system mtu"):
    ...         print(l)
    ['', 'System MTU size is 1500 bytes', 'System Jumbo MTU size is 1500
    bytes', 'System Alternate MTU size is 1500 bytes', 'Routing MTU size is
    1500 bytes']

    .. seealso:: :class:`nocexec.drivers.juniper.JunOS` and
                 :class:`nocexec.drivers.extreme.XOS`
    .. note::
        raises exceptions inherited from IOSError exception
    """

    def __init__(self, *args, **kwargs):
        super(IOS, self).__init__(*args, **kwargs)
        self._shell_prompt = "#"
        self._config_prompt = r"\(config.*?\)#"
        self._priv_mode = False
        self._config_mode = False

    def _prepare_shell(self):
        # disable clipaging, check permission level nad fill hostname
        shell_ends = ['>', '#']
        self.cli.connection.sendline("terminal length 0")
        answ = self.cli.connection.expect(shell_ends)
        self._hostname = self.cli.connection.before.splitlines()[-1]
        self._shell_prompt = self._hostname + "#"
        self._config_prompt = self._hostname + self._config_prompt
        self._priv_mode = bool(answ)

    def _enable_privileged(self):
        try:
            self.cli.execute("enable", wait=[self._hostname + "#"])
            self._shell_prompt = self._hostname + "#"
            self._priv_mode = True
            return True
        except (SSHClientExecuteCmdError, TelnetClientExecuteCmdError):
            return False

    def _disable_privileged(self):
        try:
            self.cli.execute("disable", wait=[self._hostname + ">"])
            self._shell_prompt = self._hostname + ">"
            self._priv_mode = False
            return True
        except (SSHClientExecuteCmdError, TelnetClientExecuteCmdError):
            return False

    def _enter_config(self):
        if not self._priv_mode and not self._enable_privileged():
            LOG.error("unregistered mode is used")
            return False
        if self._config_mode:
            return True
        try:
            self.cli.execute("configure terminal",
                             wait=[self._config_prompt])
            self._config_mode = True
            return True
        except (SSHClientExecuteCmdError, TelnetClientExecuteCmdError) as err:
            LOG.error("enter config mode error: %s", str(err))
            return False

    def _exit_config(self):
        if not self._config_mode:
            return True
        try:
            self.cli.execute("end", wait=[self._shell_prompt])
            self._config_mode = False
            return True
        except (SSHClientExecuteCmdError, TelnetClientExecuteCmdError) as err:
            LOG.error("enter config mode error: %s", str(err))
            return False

    def connect(self):
        """
        Connection to the device via the specified protocol.

        .. note::
            raises an exception IOSError if a connection error occurs.
        """
        super(IOS, self).init_client()
        try:
            self.cli.connect()
        except (SSHClientError, TelnetClientError) as err:
            raise IOSError(err)
        self._prepare_shell()

    def edit(self, command):
        """
        Running a command on the Cisco IOS device in configuration mode with
        the expected result and error handling. Before executing the command,
        the access level is checked and the configuration mode is enabled.

            :param command: sent command
            :type command: string
            :returns: list of lines with the result of the command execution
            :rtype: list of lines

        .. warning:: command is required argument
        .. note::
            raises an exception IOSError if connection not established.
            raises an exception IOSCommandError if an error occurs.
        """
        if self.cli is None:
            raise IOSError("no connection to the device")
        if not self._enter_config():
            raise IOSCommandError("can not enter configuration mode")
        try:
            result = self.cli.execute(
                command=command, wait=[self._config_prompt])
        except (SSHClientExecuteCmdError, TelnetClientExecuteCmdError) as err:
            raise IOSCommandError(err)
        return result

    def view(self, command):
        """
        Running a command on the Cisco IOS device in view mode with
        the expected result and error handling. Before executing the command,
        the configuration mode is disabled.

            :param command: sent command
            :type command: string
            :returns: list of lines with the result of the command execution
            :rtype: list of lines

        .. warning:: command is required argument
        .. note::
            raises an exception IOSError if connection not established.
            raises an exception IOSCommandError if an error occurs.
        """
        if self.cli is None:
            raise IOSError("no connection to the device")
        if not self._exit_config():
            raise IOSCommandError("can not exit the configuration mode")
        try:
            result = self.cli.execute(
                command=command, wait=[self._shell_prompt])
        except (SSHClientExecuteCmdError, TelnetClientExecuteCmdError) as err:
            raise IOSCommandError(err)
        return result

    def save(self):
        """
        Saving the configuration on the device

            :returns: True if configuration saved, False if not
            :rtype: bool

        .. note::
            not raises exceptions.
        """
        if self.cli is None:
            return False
        if not self._exit_config():
            return False
        try:
            self.cli.execute(command="write memory", wait=[r"\[OK\]"])
            return True
        except (SSHClientExecuteCmdError, TelnetClientExecuteCmdError) as err:
            LOG.error("CiscoIOS save configuration on device '%s' error: %s",
                      self._device, str(err))
            return False


text:
describe("System object", function() {
    var system = require('system');

    it("should exist", function() {
        expect(typeof system).toEqual('object');
        expect(system).toNotEqual(null);
    });

    it("should have platform as string", function() {
        expect(typeof system.platform).toEqual('string');
    });

    it("should have platform set to 'phantomjs'", function() {
        expect(system.platform).toEqual('phantomjs');
    });

    it("should have args as array", function() {
        expect(system.args instanceof Array).toBeTruthy();
    });

    it("should have args with at least one item", function() {
        expect(system.args.length >= 1).toBeTruthy();
    });

    it("should have args[0] as the this test runner", function() {
        expect(system.args[0]).toMatch(/run-tests.js$/);
    });

    it("should have env as object", function() {
        expect(typeof system.env).toEqual('object');
    });

});


text:
package com.amazonaws.services.ec2.model.transform;

import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map.Entry;

import javax.xml.stream.events.XMLEvent;

import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * BundleTaskError StAX Unmarshaller
 */
public class BundleTaskErrorStaxUnmarshaller implements
        Unmarshaller<BundleTaskError, StaxUnmarshallerContext> {

    public BundleTaskError unmarshall(StaxUnmarshallerContext context)
            throws Exception {
        BundleTaskError bundleTaskError = new BundleTaskError();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return bundleTaskError;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("code", targetDepth)) {
                    bundleTaskError.setCode(StringStaxUnmarshaller
                            .getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("message", targetDepth)) {
                    bundleTaskError.setMessage(StringStaxUnmarshaller
                            .getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return bundleTaskError;
                }
            }
        }
    }

    private static BundleTaskErrorStaxUnmarshaller instance;

    public static BundleTaskErrorStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new BundleTaskErrorStaxUnmarshaller();
        return instance;
    }
}


text:
var adminModel = require('../../models/context.js').admin();
var roleModel = require('../../models/context.js').role();
var adminRoleModel = require('../../models/context.js').adminRole();

var async = require('async');

var config = require("../../config/config.js");
var moment = require('moment');
var jwt = require('jwt-simple');

var _ = require("underscore");
/**
 * 访问控制
 * @type {Object}
 */
module.exports = {

    /**
     * 登陆
     * @param  {[type]}   req  [description]
     * @param  {[type]}   res  [description]
     * @param  {Function} done [description]
     * @return {[type]}        [description]
     */
    login: function(req, res, done) {

        var userName = req.params.userName;
        var password = req.params.password;

        adminModel.login(userName, password, function(result) {
            if (result.status) {
                var expires = moment().add(7, 'days').valueOf();
                var token = jwt.encode({
                    iss: userName,
                    exp: expires
                }, config.jwtTokenSecret);

                res.json({
                    status: true,
                    token: token,
                    expires: expires,
                    user: result.data
                });
                res.end()

            } else {
                res.json({
                    status: false,
                    errMsg: '用户名或密码不存在'
                });
                res.end();
            }
        })

    },
    /**
     * 获取白名单
     * @param  {[type]}   req  [description]
     * @param  {[type]}   res  [description]
     * @param  {Function} done [description]
     * @return {[type]}        [description]
     */
    getWhiteList: function(req, res, done) {

        var token = req.headers['x-access-token'];

        if (token) {
            try {
                var decoded = jwt.decode(token, config.jwtTokenSecret);

                if (decoded.exp <= Date.now()) {
                    console.log('401 登录已超时')
                    res.send(401, { message: '登录已超时' })
                    res.end()
                }

                var userName = decoded.iss;

                //用户及接口访问列表
                adminModel.getCompletelyInfos(userName, function(result) {

                    if (result.status) {

                        var roles = result.data.role;

                        var interfaces = [];

                        for (var i = 0; i < roles.length; i++) {
                            interfaces = _.union(interfaces, roles[i].interfaceList);
                        }
                        //管理员
                        req.admin = result.data;
                        done(interfaces);

                    } else {
                        res.send(401, { message: '找不到该用户' })
                        res.end()
                    }

                });

            } catch (err) {
                res.send(401, { message: 'catch err :' + err })
                res.end()
            }
        } else {

            res.send(401, { message: '请登录' })
            res.end()
        }

    },
    /**
     * 重置管理员权限
     * @param  {[type]}   req        [description]
     * @param  {[type]}   res        [description]
     * @param  {[type]}   interfaces [description]
     * @param  {Function} done       [description]
     * @return {[type]}              [description]
     */
    resetSystemAdmin: function(req, res, interfaces, done) {

        var userName = 'sysAdmin';
        var password = '123456';
        var roleName = '超级管理员';
        var interfaceList = [];
        _.each(interfaces, function(e, i, l) {
            interfaceList.push(e.route);
        })

        async.auto({
            resetAdmin: function(callback) {

                adminModel.upsert(userName, password, function(result) {
                    if (result.status) {
                        callback();
                    } else {
                        callback('resetAdmin');
                    }
                })
            },
            findAdmin: ['resetAdmin', function(callback, results) {

                adminModel.findOne({ userName: userName }, function(result) {
                    if (result.status) {
                        callback(null, result.data);
                    } else {
                        callback('findAdmin');
                    }

                })

            }],
            resetRole: function(callback) {

                var filter = {
                    name: roleName
                };
                var entity = {
                    name: roleName,
                    interfaceList: interfaceList,
                    menuList: []
                }

                roleModel.upsert(filter, entity, function(result) {
                    if (result.status) {
                        callback();
                    } else {
                        callback('resetRole');
                    }
                })

            },
            findRole: ['resetRole', function(callback, results) {

                roleModel.findOne({ name: roleName }, function(result) {
                    if (result.status) {
                        callback(null, result.data);
                    } else {
                        callback('findRole');
                    }
                })

            }],
            resetAdminRole: ['findAdmin', 'findRole', function(callback, results) {

                var admin = results.findAdmin;
                var role = results.findRole;
                console.log(admin, role);
                adminRoleModel.create(admin._id, role._id, function(result) {
                    if (result.status) {
                        callback(null, result.data);
                    } else {
                        callback('resetAdminRole');
                    }
                })
            }]

        }, function(err, results) {
            if (!err) {
                res.json({
                    status: true,
                    data: results.resetAdminRole
                });
                res.end();
            } else {

                res.json({
                    status: false,
                    errMsg: err
                })
                res.end();
            }

        })

    }

}


text:
package org.apache.accumulo.test.functional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.time.Duration;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import org.apache.accumulo.cluster.ClusterUser;
import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.security.SecurityErrorCode;
import org.apache.accumulo.core.client.security.tokens.AuthenticationToken;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.harness.AccumuloClusterHarness;
import org.apache.hadoop.security.UserGroupInformation;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class CredentialsIT extends AccumuloClusterHarness {

  private boolean saslEnabled;
  private String username;
  private String password;

  @Override
  protected Duration defaultTimeout() {
    return Duration.ofMinutes(2);
  }

  @BeforeEach
  public void createLocalUser() throws AccumuloException, AccumuloSecurityException {
    try (AccumuloClient client = Accumulo.newClient().from(getClientProps()).build()) {
      ClusterUser user = getUser(0);
      username = user.getPrincipal();
      saslEnabled = saslEnabled();
      // Create the user if it doesn't exist
      Set<String> users = client.securityOperations().listLocalUsers();
      if (!users.contains(username)) {
        PasswordToken passwdToken = null;
        if (!saslEnabled) {
          password = user.getPassword();
          passwdToken = new PasswordToken(password);
        }
        client.securityOperations().createLocalUser(username, passwdToken);
      }
    }
  }

  @AfterEach
  public void deleteLocalUser() throws Exception {
    if (saslEnabled) {
      ClusterUser root = getAdminUser();
      UserGroupInformation.loginUserFromKeytab(root.getPrincipal(),
          root.getKeytab().getAbsolutePath());
    }
    try (AccumuloClient client = Accumulo.newClient().from(getClientProps()).build()) {
      client.securityOperations().dropLocalUser(username);
    }
  }

  @Test
  public void testConnectorWithDestroyedToken() throws Exception {
    AuthenticationToken token = getUser(0).getToken();
    assertFalse(token.isDestroyed());
    token.destroy();
    assertTrue(token.isDestroyed());
    Properties props = getClientProps();
    var e = assertThrows(IllegalArgumentException.class,
        () -> Accumulo.newClient().from(props).as("non_existent_user", token).build().close());
    assertEquals(e.getMessage(), "AuthenticationToken has been destroyed");
  }

  @Test
  public void testDestroyTokenBeforeRPC() throws Exception {
    try (AccumuloClient client = Accumulo.newClient().from(getClientProps()).build()) {
      AuthenticationToken token = getUser(0).getToken();
      try (
          AccumuloClient userAccumuloClient =
              Accumulo.newClient().from(client.properties()).as(username, token).build();
          Scanner scanner =
              userAccumuloClient.createScanner(MetadataTable.NAME, Authorizations.EMPTY)) {
        assertFalse(token.isDestroyed());
        token.destroy();
        assertTrue(token.isDestroyed());

        Iterator<Entry<Key,Value>> iter = scanner.iterator();
        var e = assertThrows(RuntimeException.class, iter::hasNext);
        assertTrue(e.getCause() instanceof AccumuloSecurityException);
        assertEquals(((AccumuloSecurityException) e.getCause()).getSecurityErrorCode(),
            SecurityErrorCode.TOKEN_EXPIRED);
      }
    }
  }
}


text:
. "$TMUXER_ROOT/lib/command-helpers.sh"

shorthelp "Remove a registered session" "$@"

check_session "$@"

if [ -d "$location" ]; then
	echo "The directory '$location' will be deleted!"
fi

echo -n "Are you sure you want to remove '$name'? (y/N) "
rkey

if [ "$REPLY" = "y" ] || [ "$REPLY" = "Y" ]; then
	rm -rf "$location"
	echo
	echo "Session '$name' was deleted successfully"
	if [ "$repository" != "$location" ]; then
		if [ -d "$repository" ]; then
			echo "The repository location '$repository' will not be touched"
		else
			echo "The repository location '$repository' doesn't exist"
		fi
	fi
else
	echo
	echo "Session '$name' was not removed"
fi


text:
<!DOCTYPE html>

  <title>Page Number Two</title>

This is page number two!

< previous page


text:
package com.android.server.display;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.util.FloatProperty;
import android.util.IntProperty;
import android.util.Slog;
import android.view.Choreographer;
import android.view.Display;

import java.io.PrintWriter;

/**
 * Controls the display power state.
 *

 * This component is similar in nature to a {@link android.view.View} except that it
 * describes the properties of a display.  When properties are changed, the component
 * invalidates itself and posts a callback to apply the changes in a consistent order.
 * This mechanism enables multiple properties of the display power state to be animated
 * together smoothly by the animation framework.  Some of the work to blank or unblank
 * the display is done on a separate thread to avoid blocking the looper.
 *

 * This component must only be created or accessed by the {@link Looper} thread
 * that belongs to the {@link DisplayPowerController}.
 *

 * We don't need to worry about holding a suspend blocker here because the
 * power manager does that for us whenever there is a change in progress.
 *

 */
final class DisplayPowerState {
    private static final String TAG = "DisplayPowerState";

    private static boolean DEBUG = false;

    private final Handler mHandler;
    private final Choreographer mChoreographer;
    private final DisplayBlanker mBlanker;
    private final ColorFade mColorFade;
    private final PhotonicModulator mPhotonicModulator;

    private int mScreenState;
    private int mScreenBrightness;
    private boolean mScreenReady;
    private boolean mScreenUpdatePending;

    private boolean mColorFadePrepared;
    private float mColorFadeLevel;
    private boolean mColorFadeReady;
    private boolean mColorFadeDrawPending;

    private Runnable mCleanListener;

    public DisplayPowerState(DisplayBlanker blanker, ColorFade colorFade) {
        mHandler = new Handler(true /*async*/);
        mChoreographer = Choreographer.getInstance();
        mBlanker = blanker;
        mColorFade = colorFade;
        mPhotonicModulator = new PhotonicModulator();
        mPhotonicModulator.start();

        // At boot time, we know that the screen is on and the electron beam
        // animation is not playing.  We don't know the screen's brightness though,
        // so prepare to set it to a known state when the state is next applied.
        // Although we set the brightness to full on here, the display power controller
        // will reset the brightness to a new level immediately before the changes
        // actually have a chance to be applied.
        mScreenState = Display.STATE_ON;
        mScreenBrightness = PowerManager.BRIGHTNESS_ON;
        scheduleScreenUpdate();

        mColorFadePrepared = false;
        mColorFadeLevel = 1.0f;
        mColorFadeReady = true;
    }

    public static final FloatProperty<DisplayPowerState> COLOR_FADE_LEVEL =
            new FloatProperty<DisplayPowerState>("electronBeamLevel") {
        @Override
        public void setValue(DisplayPowerState object, float value) {
            object.setColorFadeLevel(value);
        }

        @Override
        public Float get(DisplayPowerState object) {
            return object.getColorFadeLevel();
        }
    };

    public static final IntProperty<DisplayPowerState> SCREEN_BRIGHTNESS =
            new IntProperty<DisplayPowerState>("screenBrightness") {
        @Override
        public void setValue(DisplayPowerState object, int value) {
            object.setScreenBrightness(value);
        }

        @Override
        public Integer get(DisplayPowerState object) {
            return object.getScreenBrightness();
        }
    };

    /**
     * Sets whether the screen is on, off, or dozing.
     */
    public void setScreenState(int state) {
        if (mScreenState != state) {
            if (DEBUG) {
                Slog.d(TAG, "setScreenState: state=" + state);
            }

            mScreenState = state;
            mScreenReady = false;
            scheduleScreenUpdate();
        }
    }

    /**
     * Gets the desired screen state.
     */
    public int getScreenState() {
        return mScreenState;
    }

    /**
     * Sets the display brightness.
     *
     * @param brightness The brightness, ranges from 0 (minimum / off) to 255 (brightest).
     */
    public void setScreenBrightness(int brightness) {
        if (mScreenBrightness != brightness) {
            if (DEBUG) {
                Slog.d(TAG, "setScreenBrightness: brightness=" + brightness);
            }

            mScreenBrightness = brightness;
            if (mScreenState != Display.STATE_OFF) {
                mScreenReady = false;
                scheduleScreenUpdate();
            }
        }
    }

    /**
     * Gets the screen brightness.
     */
    public int getScreenBrightness() {
        return mScreenBrightness;
    }

    /**
     * Prepares the electron beam to turn on or off.
     * This method should be called before starting an animation because it
     * can take a fair amount of time to prepare the electron beam surface.
     *
     * @param mode The electron beam animation mode to prepare.
     * @return True if the electron beam was prepared.
     */
    public boolean prepareColorFade(Context context, int mode) {
        if (!mColorFade.prepare(context, mode)) {
            mColorFadePrepared = false;
            mColorFadeReady = true;
            return false;
        }

        mColorFadePrepared = true;
        mColorFadeReady = false;
        scheduleColorFadeDraw();
        return true;
    }

    /**
     * Dismisses the color fade surface.
     */
    public void dismissColorFade() {
        mColorFade.dismiss();
        mColorFadePrepared = false;
        mColorFadeReady = true;
    }

   /**
     * Dismisses the color fade resources.
     */
    public void dismissColorFadeResources() {
        mColorFade.dismissResources();
    }

    /**
     * Sets the level of the electron beam steering current.
     *
     * The display is blanked when the level is 0.0.  In normal use, the electron
     * beam should have a value of 1.0.  The electron beam is unstable in between
     * these states and the picture quality may be compromised.  For best effect,
     * the electron beam should be warmed up or cooled off slowly.
     *
     * Warning: Electron beam emits harmful radiation.  Avoid direct exposure to
     * skin or eyes.
     *
     * @param level The level, ranges from 0.0 (full off) to 1.0 (full on).
     */
    public void setColorFadeLevel(float level) {
        if (mColorFadeLevel != level) {
            if (DEBUG) {
                Slog.d(TAG, "setColorFadeLevel: level=" + level);
            }

            mColorFadeLevel = level;
            if (mScreenState != Display.STATE_OFF) {
                mScreenReady = false;
                scheduleScreenUpdate(); // update backlight brightness
            }
            if (mColorFadePrepared) {
                mColorFadeReady = false;
                scheduleColorFadeDraw();
            }
        }
    }

    /**
     * Gets the level of the electron beam steering current.
     */
    public float getColorFadeLevel() {
        return mColorFadeLevel;
    }

    /**
     * Returns true if no properties have been invalidated.
     * Otherwise, returns false and promises to invoke the specified listener
     * when the properties have all been applied.
     * The listener always overrides any previously set listener.
     */
    public boolean waitUntilClean(Runnable listener) {
        if (!mScreenReady || !mColorFadeReady) {
            mCleanListener = listener;
            return false;
        } else {
            mCleanListener = null;
            return true;
        }
    }

    public void dump(PrintWriter pw) {
        pw.println();
        pw.println("Display Power State:");
        pw.println("  mScreenState=" + Display.stateToString(mScreenState));
        pw.println("  mScreenBrightness=" + mScreenBrightness);
        pw.println("  mScreenReady=" + mScreenReady);
        pw.println("  mScreenUpdatePending=" + mScreenUpdatePending);
        pw.println("  mColorFadePrepared=" + mColorFadePrepared);
        pw.println("  mColorFadeLevel=" + mColorFadeLevel);
        pw.println("  mColorFadeReady=" + mColorFadeReady);
        pw.println("  mColorFadeDrawPending=" + mColorFadeDrawPending);

        mPhotonicModulator.dump(pw);
        mColorFade.dump(pw);
    }

    private void scheduleScreenUpdate() {
        if (!mScreenUpdatePending) {
            mScreenUpdatePending = true;
            postScreenUpdateThreadSafe();
        }
    }

    private void postScreenUpdateThreadSafe() {
        mHandler.removeCallbacks(mScreenUpdateRunnable);
        mHandler.post(mScreenUpdateRunnable);
    }

    private void scheduleColorFadeDraw() {
        if (!mColorFadeDrawPending) {
            mColorFadeDrawPending = true;
            mChoreographer.postCallback(Choreographer.CALLBACK_TRAVERSAL,
                    mColorFadeDrawRunnable, null);
        }
    }

    private void invokeCleanListenerIfNeeded() {
        final Runnable listener = mCleanListener;
        if (listener != null && mScreenReady && mColorFadeReady) {
            mCleanListener = null;
            listener.run();
        }
    }

    private final Runnable mScreenUpdateRunnable = new Runnable() {
        @Override
        public void run() {
            mScreenUpdatePending = false;

            int brightness = mScreenState != Display.STATE_OFF
                    && mColorFadeLevel > 0f ? mScreenBrightness : 0;
            if (mPhotonicModulator.setState(mScreenState, brightness)) {
                if (DEBUG) {
                    Slog.d(TAG, "Screen ready");
                }
                mScreenReady = true;
                invokeCleanListenerIfNeeded();
            } else {
                if (DEBUG) {
                    Slog.d(TAG, "Screen not ready");
                }
            }
        }
    };

    private final Runnable mColorFadeDrawRunnable = new Runnable() {
        @Override
        public void run() {
            mColorFadeDrawPending = false;

            if (mColorFadePrepared) {
                mColorFade.draw(mColorFadeLevel);
            }

            mColorFadeReady = true;
            invokeCleanListenerIfNeeded();
        }
    };

    /**
     * Updates the state of the screen and backlight asynchronously on a separate thread.
     */
    private final class PhotonicModulator extends Thread {
        private static final int INITIAL_SCREEN_STATE = Display.STATE_OFF; // unknown, assume off
        private static final int INITIAL_BACKLIGHT = -1; // unknown

        private final Object mLock = new Object();

        private int mPendingState = INITIAL_SCREEN_STATE;
        private int mPendingBacklight = INITIAL_BACKLIGHT;
        private int mActualState = INITIAL_SCREEN_STATE;
        private int mActualBacklight = INITIAL_BACKLIGHT;
        private boolean mStateChangeInProgress;
        private boolean mBacklightChangeInProgress;

        public PhotonicModulator() {
            super("PhotonicModulator");
        }

        public boolean setState(int state, int backlight) {
            synchronized (mLock) {
                boolean stateChanged = state != mPendingState;
                boolean backlightChanged = backlight != mPendingBacklight;
                if (stateChanged || backlightChanged) {
                    if (DEBUG) {
                        Slog.d(TAG, "Requesting new screen state: state="
                                + Display.stateToString(state) + ", backlight=" + backlight);
                    }

                    mPendingState = state;
                    mPendingBacklight = backlight;

                    boolean changeInProgress = mStateChangeInProgress || mBacklightChangeInProgress;
                    mStateChangeInProgress = stateChanged;
                    mBacklightChangeInProgress = backlightChanged;

                    if (!changeInProgress) {
                        mLock.notifyAll();
                    }
                }
                return !mStateChangeInProgress;
            }
        }

        public void dump(PrintWriter pw) {
            synchronized (mLock) {
                pw.println();
                pw.println("Photonic Modulator State:");
                pw.println("  mPendingState=" + Display.stateToString(mPendingState));
                pw.println("  mPendingBacklight=" + mPendingBacklight);
                pw.println("  mActualState=" + Display.stateToString(mActualState));
                pw.println("  mActualBacklight=" + mActualBacklight);
                pw.println("  mStateChangeInProgress=" + mStateChangeInProgress);
                pw.println("  mBacklightChangeInProgress=" + mBacklightChangeInProgress);
            }
        }

        @Override
        public void run() {
            for (;;) {
                // Get pending change.
                final int state;
                final boolean stateChanged;
                final int backlight;
                final boolean backlightChanged;
                synchronized (mLock) {
                    state = mPendingState;
                    stateChanged = (state != mActualState);
                    backlight = mPendingBacklight;
                    backlightChanged = (backlight != mActualBacklight);
                    if (!stateChanged) {
                        // State changed applied, notify outer class.
                        postScreenUpdateThreadSafe();
                        mStateChangeInProgress = false;
                    }
                    if (!backlightChanged) {
                        mBacklightChangeInProgress = false;
                    }
                    if (!stateChanged && !backlightChanged) {
                        try {
                            mLock.wait();
                        } catch (InterruptedException ex) { }
                        continue;
                    }
                    mActualState = state;
                    mActualBacklight = backlight;
                }

                // Apply pending change.
                if (DEBUG) {
                    Slog.d(TAG, "Updating screen state: state="
                            + Display.stateToString(state) + ", backlight=" + backlight);
                }
                mBlanker.requestDisplayState(state, backlight);
            }
        }
    }
}


text:
@interface LogASentenceCommand : GCGISequenceCommand
@end


text:
package hex;

import water.Job;
import water.Key;
import water.util.Log;

abstract public class ClusteringModelBuilder<M extends ClusteringModel<M,P,O>, P extends ClusteringModel.ClusteringParameters, O extends ClusteringModel.ClusteringOutput> extends ModelBuilder<M,P,O> {
  public boolean isSupervised() { return false; }

  /** Constructor called from an http request; MUST override in subclasses. */
  public ClusteringModelBuilder(P parms         ) { super(parms    );  /*only call init in leaf classes*/ }
  public ClusteringModelBuilder(P parms, Job job) { super(parms,job);  /*only call init in leaf classes*/ }
  public ClusteringModelBuilder(P parms, boolean startup_once) { super(parms,startup_once);  /*only call init in leaf classes*/ }

  /** Initialize the ModelBuilder, validating all arguments and preparing the
   *  training frame.  This call is expected to be overridden in the subclasses
   *  and each subclass will start with "super.init();".  This call is made
   *  by the front-end whenever the GUI is clicked, and needs to be fast;
   *  heavy-weight prep needs to wait for the trainModel() call. */
  @Override public void init(boolean expensive) {
    super.init(expensive);
    if( _parms._k < 1 || _parms._k > 1e7 ) error("_k", "k must be between 1 and 1e7");
    if( _train != null && _train.numRows() < _parms._k ) error("_k","Cannot make " + _parms._k + " clusters out of " + _train.numRows() + " rows");
  }
}


text:
static std::map<wchar_t,int> s_unrecognizedChars;

FontRenderer::FontRenderer(const char* pFontName, int windowHeight)
: m_texDimension(0)
, m_charTable()
, m_kernTable()
, m_pageFilenames()
, m_pageTextures()
, m_windowHeight(windowHeight)
, m_lineHeight(0)
, m_basePx(0)
, m_shader()
{
    const std::string fontName = pFontName;
    const std::string dataHome = APP_DATA_DIRECTORY;
    std::string homedir = dataHome;

    homedir.append("fonts/");
    const std::string fntFilename = homedir + fontName + ".fnt";
    _LoadFntFile(fntFilename.c_str());

    _AddCustomKerningEntries(fntFilename.c_str());
    //PrintKerningPairs(0,0);
    //PrintKerningPairs((int)'t',0);
    //PrintKerningPairs(0,(int)'t');

    /// Load all pages of font
    for (std::vector<std::string>::iterator it=m_pageFilenames.begin();
         it != m_pageFilenames.end();
         ++it)
    {
        const std::string pageName = *it;
        const std::string suffixless = pageName.substr(0, pageName.length()-4);
        ///@todo png support
        const std::string texFilename = homedir + suffixless + ".raw";
        const GLuint tex = CreateTextureFromRawFile(texFilename.c_str(), m_texDimension);
        m_pageTextures.push_back(tex);
    }

    m_shader.initProgram("fontrenderer");
    m_shader.bindVAO();
    {
        GLuint vertVbo = 0;
        glGenBuffers(1, &vertVbo);
        m_shader.AddVbo("a_position", vertVbo);
        glBindBuffer(GL_ARRAY_BUFFER, vertVbo);
        glBufferData(GL_ARRAY_BUFFER, 4*3*sizeof(GLfloat), NULL, GL_STATIC_DRAW);
        glVertexAttribPointer(m_shader.GetAttrLoc("a_position"), 3, GL_FLOAT, GL_FALSE, 0, NULL);

        GLuint colVbo = 0;
        glGenBuffers(1, &colVbo);
        m_shader.AddVbo("a_texCoord", colVbo);
        glBindBuffer(GL_ARRAY_BUFFER, colVbo);
        glBufferData(GL_ARRAY_BUFFER, 4*2*sizeof(GLfloat), NULL, GL_STATIC_DRAW);
        glVertexAttribPointer(m_shader.GetAttrLoc("a_texCoord"), 2, GL_FLOAT, GL_FALSE, 0, NULL);

        glEnableVertexAttribArray(m_shader.GetAttrLoc("a_position"));
        glEnableVertexAttribArray(m_shader.GetAttrLoc("a_texCoord"));
    }
    glBindVertexArray(0);
}

FontRenderer::~FontRenderer()
{
    if (!m_pageTextures.empty())
        glDeleteTextures(m_pageTextures.size(), &m_pageTextures[0]);
}

/// Utility function for BMF binary font reading
/// Blocks are preceded by 1 byte identifier and 4 byte size.
/// Allocates and returns a block of memory to be frreed by the caller.
unsigned char* GetBlock(std::ifstream& fin, unsigned char& id, unsigned int& sz)
{
    fin.read(reinterpret_cast<char*>(&id), 1);
    fin.read(reinterpret_cast<char*>(&sz), sizeof(unsigned int));

    unsigned char* pBlock = new unsigned char[sz];
    fin.read(reinterpret_cast<char*>(pBlock), sz);

    return pBlock;
}

/// See BMF docs
/// http://www.angelcode.com/products/bmfont/doc/file_format.html
void FontRenderer::_ProcessBlock(unsigned char id, unsigned int sz, unsigned char* pBlock)
{
    switch(id)
    {
    default: break;

    case 1: // info
        BMF_blockInfo bi;
        memcpy(&bi, pBlock, sizeof(BMF_blockInfo));
        {
            //unsigned int namelen = sz - sizeof(BMF_blockInfo);
            //const unsigned char* pName = pBlock + sizeof(BMF_blockInfo);
        }
        break;

    case 2: // common
        BMF_blockCommon b;
        memcpy(&b, pBlock, sizeof(BMF_blockCommon));
        {
            m_texDimension = b.scaleW;
            if (b.scaleW != b.scaleH)
            {
                LOG_INFO("WARNING: Non-square font scale dimensions\n");
                ///@todo NPOT warning? Padding?
            }
            m_lineHeight = b.lineHeight;
            m_basePx = b.base;
        }
        break;

    case 3: // pages
        {
            const char* pName = reinterpret_cast<const char*>(pBlock);
            if (pName != NULL)
            {
                std::string name(reinterpret_cast<const char*>(pName));
                const unsigned int len = name.length()+1; // include terminator
                const unsigned int num = sz / len;
                for (unsigned int i=0; i<num; ++i)
                {
                    m_pageFilenames.push_back(name);
                    pName += len;
                    name.assign(pName);
                }
            }
        }
        break;

    case 4: // chars
        {
            const size_t charCount = sz / sizeof(BMF_char);
            //m_charTable.resize(charCount);
            //memcpy(&m_charTable[0], pBlock, charCount * sizeof(BMF_char));
            const BMF_char* pCharBlock = reinterpret_cast<const BMF_char*>(pBlock);
            for(int i=0; i<static_cast<int>(charCount); ++i)
            {
                const BMF_char& pC = pCharBlock[i];
                m_charTable[pC.id] = pC;
            }
        }
        break;

    case 5: /// kerning pairs
        {
            const size_t kernCount = sz / sizeof(BMF_kern);
            //m_kernTable.resize(kernCount);
            //memcpy(&m_kernTable[0], pBlock, kernCount * sizeof(BMF_kern));
            const BMF_kern* pKernBlock = reinterpret_cast<const BMF_kern*>(pBlock);
            for(int i=0; i<static_cast<int>(kernCount); ++i)
            {
                const BMF_kern& bk = pKernBlock[i];
                _AddKerningEntry(bk.first, bk.second, bk.amount);
            }
        }
        break;
    }
}

/// Load a bitmap font file created by:
/// http://www.angelcode.com/products/bmfont/
///@param pFilename Filename of .fnt binary file exported by BMFont
void FontRenderer::_LoadFntFile(const char* pFilename)
{
    if (pFilename == NULL)
        return;

    LOG_INFO_NONEWLINE("Opening font file %s ...", pFilename);
    std::ifstream fin(pFilename, std::ios::binary);

    if (fin)
    {
        // Header is 4 bytes, BMF followed by 3.
        unsigned char header[4];
        fin.read(reinterpret_cast<char*>(header), 4);
        if ((header[0] == 'B') &&
            (header[1] == 'M') &&
            (header[2] == 'F') &&
            (header[3] == 3))
        {
            for (unsigned int i=0; i<5; ++i)
            {
                unsigned char id;
                unsigned int sz;
                unsigned char* pBlock = GetBlock(fin, id, sz);

                _ProcessBlock(id, sz, pBlock);

                delete [] pBlock;
            }
        }

        fin.close();
        LOG_INFO("success.");
    }
    else
    {
        LOG_ERROR("Font file %s not found.\n", pFilename);
    }
}

/// Just for curiosity, print a list of the font's kerning pairs to stdout.
void FontRenderer::PrintKerningPairs(int firstChar, int secondChar) const
{
    LOG_INFO("___Kerning pairs(%d):___", m_kernTable.size());
    for (std::map< std::pair<int,int>,short >::const_iterator it = m_kernTable.begin();
        it != m_kernTable.end();
        ++it)
    {
        const std::pair<int,int>& key = it->first;
        const short& val = it->second;

        if ((firstChar != 0) && (key.first != firstChar))
            continue;
        if ((secondChar != 0) && (key.second != secondChar))
            continue;

        LOG_INFO("  %c %c  %dpx", key.first, key.second, val);
    }
}

void FontRenderer::_AddKerningEntry(int chprev, int ch, short amount)
{
    const std::pair<int,int> kp(chprev, ch);
    m_kernTable[kp] = amount;
}

///@brief Load custom kerning entries from .kern file.
/// One entry per line, first 2 wide chars are the pair, then a space, then the pixel displacement.
/// e.g.: "it -2"
int FontRenderer::_AddCustomKerningEntries(const char* pFilename)
{
#if 0
    std::string narrowFilename(pFilename);
    const std::string fntSuffix = ".fnt";
    size_t suffixFound = narrowFilename.rfind(fntSuffix);
    if (suffixFound != narrowFilename.length() - fntSuffix.length())
        return -1;
    const std::string suffixless = narrowFilename.substr(0, narrowFilename.length() - fntSuffix.length());
    const std::string kernFilename = suffixless + ".kern";

    // http://www.cplusplus.com/forum/beginner/75503/
    std::wstring wFilename(kernFilename.begin(), kernFilename.end());

    FILE *file;
    _wfopen_s(&file,
        wFilename.c_str(),
        L"rb,ccs=UTF-16LE" /// Be sure to open the UTF-16 file in binary mode
        );

    if (file == NULL)
        return 2;

    while(!feof(file) && !ferror(file))
    {
        const size_t bufSz = 512;
        wchar_t LineOfChars[bufSz];
        fgetws(LineOfChars, bufSz, file);
        std::wstring line(LineOfChars);

        if (line.empty()) // Blank lines ignored
            continue;
        if (line.at(0) == L'#') // comment lines ignored
            continue;
        if (line.length() < 4)
            continue;

        ///@note First line of file should be blank or we get a bad entry here.
        const int c1 = line[0];
        const int c2 = line[1];
        const std::string numstr(line.begin()+3, line.end());
        const int amt = atoi(numstr.c_str());
        _AddKerningEntry(c1, c2, static_cast<short>(amt));
    }

    fclose(file);
#endif

    return 0;
}

///@param pWStr [in] Wide-character string to determine the length of
///@return The length of the string as rendered on screen, in pixels
int FontRenderer::StringLengthPixels(const wchar_t* pWStr) const
{
    int totalPx = 0;
    // Let's hope that the string is properly NULL terminated here.
    const unsigned int len = wcslen(pWStr);
    for (unsigned int i=0; i<len; ++i)
    {
        const wchar_t ch = pWStr[i];
        const std::map<wchar_t, BMF_char>::const_iterator it = m_charTable.find(ch);
        if (it != m_charTable.end())
        {
            const BMF_char& charInfo = it->second;
            totalPx += charInfo.xadv;
        }
    }
    return totalPx;
}

///@brief Convert narrow string to wide and call into that function for compatibility.
int FontRenderer::StringLengthPixels(const char* pStr) const
{
    const std::string s(pStr);
    const std::wstring ws(s.begin(), s.end());

    return StringLengthPixels(ws.c_str());
}

///@brief Convert narrow string to wide and call into that function for compatibility.
void FontRenderer::DrawString(
    const char* pStr,
    int x,
    int y,
    float3 color,
    const float* pProjMtx,
    bool doKerning,
    const float* pMvMtx) const
{
    const std::string s(pStr);
    const std::wstring ws(s.begin(), s.end());

    DrawWString(ws.c_str(),
        x,
        y,
        color,
        pProjMtx,
        doKerning,
        pMvMtx);
}

/// Draw an ASCII string of text using font texture and data.
///@param pStr [in] The ASCII string to display
///@param x The x location on screen
///@param y The y location on screen
///@param pProjMtx [in] The projection matrix (typically to indicate pixel coordinates on screen)
///@param doKerning If true, adjust letter positions based on kerning pairs list
///@param pMvMtx [in] An optional pointer to modelview matrix(default NULL)
///@todo Reorder DrawString parameters to put 2 matrices together.
///@note When pMvMtx != NULL, projection matrix will not be ortho pixel coordinates.
void FontRenderer::DrawWString(const wchar_t* pStr,
                              int x,
                              int y,
                              float3 color,
                              const float* pProjMtx,
                              bool doKerning,
                              const float* pMvMtx) const
{
    const float tracking = 1.0f;

    if (m_charTable.empty())
        return;

    const GLuint prog = m_shader.prog();
    glUseProgram(prog);

    if (pMvMtx == NULL)
    {
        // The old 2D path - assume an identity mv matrix
        float mvmtx[16];
        MakeIdentityMatrix(mvmtx);
        glUniformMatrix4fv(m_shader.GetUniLoc("mvmtx"), 1, false, mvmtx);
        glUniformMatrix4fv(m_shader.GetUniLoc("prmtx"), 1, false, pProjMtx);
    }
    else
    {
        glUniformMatrix4fv(m_shader.GetUniLoc("mvmtx"), 1, false, pMvMtx);
        glUniformMatrix4fv(m_shader.GetUniLoc("prmtx"), 1, false, pProjMtx);
    }

    const int texDim = m_texDimension;
    const float fTexDim = static_cast<float>(texDim);

    float currx = static_cast<float>(x); // incremented with each character drawn

    // Let's hope that the string is properly NULL terminated here.
    const unsigned int len = wcslen(pStr);
    for (unsigned int i=0; i<len; ++i)
    {
        const wchar_t ch = pStr[i];
        if (ch == 0xfeff) // Skip byte order mark
            continue;
        if (ch == 0x0d) // Skip carriage returns
            continue;
        if (ch == 0x0a) // Skip line feeds
            continue;
        //if (ch == 0x09) ///<@todo Handle tab characters?
        //    continue;

        if (m_charTable.find(ch) == m_charTable.end())
        {
            // Since the draw function is const, we use a static table to hold
            // unrecognized chars for just one print each.
            if (s_unrecognizedChars.find(ch) == s_unrecognizedChars.end())
            {
                s_unrecognizedChars[ch] = 1;
                LOG_ERROR("Unrecognized Char: %d  %x", ch, ch);
            }
            continue;
        }

        const std::map<wchar_t, BMF_char>::const_iterator it = m_charTable.find(ch);
        if (it == m_charTable.end())
            continue;
        const BMF_char& charInfo = it->second;

        ///@todo Cache the value so we don't have to rebind it if it doesn't change.
        /// This is probably exactly what the driver does...
        const unsigned int tIdx = charInfo.page;
        if (tIdx >= m_pageTextures.size())
            continue;
        const GLuint texID = m_pageTextures[tIdx];
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texID);
        glUniform1i(m_shader.GetUniLoc("s_texture"), 0);

        glUniform3f(m_shader.GetUniLoc("u_fontColor"), color.x, color.y, color.z);

        int kernamt = 0;
        if (doKerning)
        {
            //if (i < (len-1))
            if (i > 0)
            {
                const wchar_t chprev = pStr[i-1];
                //const wchar_t chnext = pStr[i+1];

                // Find kern delta value for this specific character pair.
                std::pair<int,int> kpair(chprev, ch);
                const std::map<std::pair<int,int>,short>::const_iterator kit = m_kernTable.find(kpair);
                if (kit != m_kernTable.end())
                {
                    const short& val = kit->second;
                    kernamt = val;
                }
            }
        }

        // Shrink down some characters to 2/3 width
        const bool isKatakana = (ch >= 0x30a0) && (ch <= 0x30ff);
        const bool isCJK = (ch >= 0x4e00) && (ch <= 0x9fff);
        const bool shrink = isCJK | isKatakana;
        const float widthScale = shrink ? 2.f/3.f : 1.f;

        const float xoff = currx + static_cast<float>(kernamt);
        const float yoff = static_cast<float>(y + charInfo.yoff); ///@note Characters are top-aligned
        const float xf = static_cast<float>(charInfo.x);
        const float yf = static_cast<float>(charInfo.y);
        const float wf = static_cast<float>(charInfo.w);
        const float hf = static_cast<float>(charInfo.h);
        const GLfloat vVertices[] = {
            xoff                , yoff + hf, 0.0f,
            xoff                , yoff     , 0.0f,
            xoff + wf*widthScale, yoff     , 0.0f,
            xoff + wf*widthScale, yoff + hf, 0.0f,
        };

        const GLfloat vTexCoords[] = {
            (xf     )/fTexDim,  (yf + hf)/fTexDim,
            (xf     )/fTexDim,  (yf     )/fTexDim,
            (xf + wf)/fTexDim,  (yf     )/fTexDim,
            (xf + wf)/fTexDim,  (yf + hf)/fTexDim
        };

        const GLushort indices[] = { 0,1,2, 3,0,2 }; // CCW triangles by default

        m_shader.bindVAO();
        {
            glBindBuffer(GL_ARRAY_BUFFER, m_shader.GetVboLoc("a_position"));
            glBufferData(GL_ARRAY_BUFFER, 4*3*sizeof(GLfloat), vVertices, GL_STATIC_DRAW);
            glBindBuffer(GL_ARRAY_BUFFER, m_shader.GetVboLoc("a_texCoord"));
            glBufferData(GL_ARRAY_BUFFER, 4*2*sizeof(GLfloat), vTexCoords, GL_STATIC_DRAW);
            glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices);
        }
        glBindVertexArray(0);

        currx += tracking * static_cast<float>(charInfo.xadv) * widthScale;
    }
}


text:
These settings apply only when `--ruby` is specified on the command line.

``` yaml
package-name: azure_mgmt_appplatform
package-version: "0.17.0"
azure-arm: true
```

### Ruby multi-api

``` yaml $(ruby) && $(multiapi)
batch:
  - tag: package-preview-2020-11
  - tag: package-2020-07
  - tag: package-2019-05-01-preview
```

### Tag: package-preview-2020-11 and ruby

These settings apply only when `--tag=package-preview-2020-11 --ruby` is specified on the command line.
Please also specify `--ruby-sdks-folder=<path to the root directory of your azure-sdk-for-ruby clone>`.

``` yaml $(tag) == 'package-preview-2020-11' && $(ruby)
namespace: "Azure::AppPlatform::Mgmt::V2020_11_01_preview"
output-folder: $(ruby-sdks-folder)/management/azure_mgmt_appplatform/lib
```

### Tag: package-2020-07 and ruby

These settings apply only when `--tag=package-2020-07 --ruby` is specified on the command line.
Please also specify `--ruby-sdks-folder=<path to the root directory of your azure-sdk-for-ruby clone>`.

``` yaml $(tag) == 'package-2020-07' && $(ruby)
namespace: "Azure::AppPlatform::Mgmt::V2020_07_01"
output-folder: $(ruby-sdks-folder)/management/azure_mgmt_appplatform/lib
```

### Tag: package-2019-05-01-preview and ruby

These settings apply only when `--tag=package-2019-05-01-preview --ruby` is specified on the command line.
Please also specify `--ruby-sdks-folder=<path to the root directory of your azure-sdk-for-ruby clone>`.

``` yaml $(tag) == 'package-2019-05-01-preview' && $(ruby)
namespace: "Azure::AppPlatform::Mgmt::V2019_05_01_preview"
output-folder: $(ruby-sdks-folder)/management/azure_mgmt_appplatform/lib
```


text:
{{ partial "event_header.html" . }}

{{ $path := split $.Source.File.Path "/" }}
{{ $event_slug := index $path 1 }}
{{ $e :=  (index $.Site.Data.events $event_slug) }}

  {{ .Content }}

 {{/*
   For future reference, this range listed below is going to be a key element for when we refactor the data directory
   Notice how you pass the variables, etc. So the new code would probably be something like this:
   .Site.Data.events $e.year "speakers" (printf "%s" (lower $e.city))
   and to get at the meta.yml for the city it will be
   .Site.Data.events $e.year (printf "%s" (lower $e.city))
   - mattstratton
 */}}
 {{ range $fname, $s := index .Site.Data.speakers (print (chomp $e.year)) (lower $e.city) }}
   {{ if eq $fname ($.LinkTitle | urlize) }}

{{ $s.name }}

       {{ if $s.twitter }} @{{ $s.twitter }}
{{ end }}

     {{ $s.bio | markdownify }}

   {{ end }}
 {{ end }}

{{ partial "sponsors.html" . }}

{{ partial "footer.html" . }}


text:
import unittest

from unittest.mock import patch, PropertyMock

from airflow.operators.hive_to_mysql import HiveToMySqlTransfer
from airflow.utils.operator_helpers import context_to_airflow_vars

class TestHiveToMySqlTransfer(unittest.TestCase):

    def setUp(self):
        self.kwargs = dict(
            sql='sql',
            mysql_table='table',
            hiveserver2_conn_id='hiveserver2_default',
            mysql_conn_id='mysql_default',
            task_id='test_hive_to_mysql',
            dag=None
        )

    @patch('airflow.operators.hive_to_mysql.MySqlHook')
    @patch('airflow.operators.hive_to_mysql.HiveServer2Hook')
    def test_execute(self, mock_hive_hook, mock_mysql_hook):
        HiveToMySqlTransfer(**self.kwargs).execute(context={})

        mock_hive_hook.assert_called_once_with(hiveserver2_conn_id=self.kwargs['hiveserver2_conn_id'])
        mock_hive_hook.return_value.get_records.assert_called_once_with('sql', hive_conf={})
        mock_mysql_hook.assert_called_once_with(mysql_conn_id=self.kwargs['mysql_conn_id'])
        mock_mysql_hook.return_value.insert_rows.assert_called_once_with(
            table=self.kwargs['mysql_table'],
            rows=mock_hive_hook.return_value.get_records.return_value
        )

    @patch('airflow.operators.hive_to_mysql.MySqlHook')
    @patch('airflow.operators.hive_to_mysql.HiveServer2Hook')
    def test_execute_mysql_preoperator(self, mock_hive_hook, mock_mysql_hook):
        self.kwargs.update(dict(mysql_preoperator='preoperator'))

        HiveToMySqlTransfer(**self.kwargs).execute(context={})

        mock_mysql_hook.return_value.run.assert_called_once_with(self.kwargs['mysql_preoperator'])

    @patch('airflow.operators.hive_to_mysql.MySqlHook')
    @patch('airflow.operators.hive_to_mysql.HiveServer2Hook')
    def test_execute_with_mysql_postoperator(self, mock_hive_hook, mock_mysql_hook):
        self.kwargs.update(dict(mysql_postoperator='postoperator'))

        HiveToMySqlTransfer(**self.kwargs).execute(context={})

        mock_mysql_hook.return_value.run.assert_called_once_with(self.kwargs['mysql_postoperator'])

    @patch('airflow.operators.hive_to_mysql.MySqlHook')
    @patch('airflow.operators.hive_to_mysql.NamedTemporaryFile')
    @patch('airflow.operators.hive_to_mysql.HiveServer2Hook')
    def test_execute_bulk_load(self, mock_hive_hook, mock_tmp_file, mock_mysql_hook):
        type(mock_tmp_file).name = PropertyMock(return_value='tmp_file')
        context = {}
        self.kwargs.update(dict(bulk_load=True))

        HiveToMySqlTransfer(**self.kwargs).execute(context=context)

        mock_tmp_file.assert_called_once_with()
        mock_hive_hook.return_value.to_csv.assert_called_once_with(
            self.kwargs['sql'],
            mock_tmp_file.return_value.name,
            delimiter='\t',
            lineterminator='\n',
            output_header=False,
            hive_conf=context_to_airflow_vars(context)
        )
        mock_mysql_hook.return_value.bulk_load.assert_called_once_with(
            table=self.kwargs['mysql_table'],
            tmp_file=mock_tmp_file.return_value.name
        )
        mock_tmp_file.return_value.close.assert_called_once_with()

    @patch('airflow.operators.hive_to_mysql.MySqlHook')
    @patch('airflow.operators.hive_to_mysql.HiveServer2Hook')
    def test_execute_with_hive_conf(self, mock_hive_hook, mock_mysql_hook):
        context = {}
        self.kwargs.update(dict(hive_conf={'mapreduce.job.queuename': 'fake_queue'}))

        HiveToMySqlTransfer(**self.kwargs).execute(context=context)

        hive_conf = context_to_airflow_vars(context)
        hive_conf.update(self.kwargs['hive_conf'])
        mock_hive_hook.return_value.get_records.assert_called_once_with(
            self.kwargs['sql'],
            hive_conf=hive_conf
        )


text:
package uk.ac.ebi.embl.api.validation.check.entry;

import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.sql.Connection;
import java.sql.SQLException;

import org.junit.Before;
import org.junit.Test;

import uk.ac.ebi.embl.api.entry.Entry;
import uk.ac.ebi.embl.api.entry.EntryFactory;
import uk.ac.ebi.embl.api.entry.feature.Feature;
import uk.ac.ebi.embl.api.entry.feature.FeatureFactory;
import uk.ac.ebi.embl.api.entry.location.Join;
import uk.ac.ebi.embl.api.entry.location.LocalRange;
import uk.ac.ebi.embl.api.entry.location.Location;
import uk.ac.ebi.embl.api.entry.location.LocationFactory;
import uk.ac.ebi.embl.api.entry.location.RemoteRange;
import uk.ac.ebi.embl.api.validation.*;
import uk.ac.ebi.embl.api.validation.dao.EntryDAOUtils;
import uk.ac.ebi.embl.api.validation.plan.EmblEntryValidationPlanProperty;

public class FeaturewithRemoteLocationCheckTest {

	private Entry entry;
	private FeatureFactory featureFactory;
	private FeaturewithRemoteLocationCheck check;
	private EmblEntryValidationPlanProperty property;
	private LocationFactory locationFactory;

	@Before
	public void setUp() throws SQLException {
        ValidationMessageManager.addBundle(ValidationMessageManager.STANDARD_VALIDATION_BUNDLE);
		EntryFactory entryFactory = new EntryFactory();
		featureFactory = new FeatureFactory();
		locationFactory=new LocationFactory();
		entry = entryFactory.createEntry();
		property=new EmblEntryValidationPlanProperty();
		check = new FeaturewithRemoteLocationCheck();
		check.setEmblEntryValidationPlanProperty(property);
	}

	@Test
	public void testCheck_NoEntry() throws ValidationEngineException {
		assertTrue(check.check(null).isValid());
	}

	@Test
	public void testCheck_NoFeatures() throws ValidationEngineException {
		assertTrue(check.check(entry).isValid());
	}

	@Test
	public void testCheck_featurewithRemoteLocationandNodbConnection() throws ValidationEngineException {

		RemoteRange remoteRange1 = locationFactory.createRemoteRange("A00001", 1,10L,20L);
		RemoteRange remoteRange2 = locationFactory.createRemoteRange("A00001", 1,10L,20L);
		Join<Location> join = new Join<Location>();
		join.addLocation(remoteRange1);
		join.addLocation(remoteRange2);
		Feature feature=featureFactory.createFeature("STS");
		feature.setLocations(join);
		entry.addFeature(feature);
		ValidationResult result = check.check(entry);
		assertEquals(1, result.count("FeaturewithRemoteLocationCheck-1", Severity.WARNING));
	}

	@Test
	public void testCheck_featurewithLocalLocationandNodbConnection() throws ValidationEngineException {

		LocalRange localRange1 = locationFactory.createLocalRange(10L, 20L);
		LocalRange localRange2 = locationFactory.createLocalRange(10L,20L);
		Join<Location> join = new Join<Location>();
		join.addLocation(localRange1);
		join.addLocation(localRange2);
		Feature feature=featureFactory.createFeature("STS");
		feature.setLocations(join);
		entry.addFeature(feature);
		ValidationResult result = check.check(entry);
		assertEquals(0, result.count("FeaturewithRemoteLocationCheck-1", Severity.WARNING));
	}

	@Test
	public void testCheck_featurewithvalidRemoteLocationwithdbConnection() throws SQLException, ValidationEngineException {

		property.enproConnection.set(createMock(Connection.class));
		RemoteRange remoteRange1 = locationFactory.createRemoteRange("A00001", 1,10L,20L);
		Join<Location> join = new Join<Location>();
		join.addLocation(remoteRange1);
		Feature feature=featureFactory.createFeature("STS");
		feature.setLocations(join);
		entry.addFeature(feature);
		check.setEmblEntryValidationPlanProperty(property);
		EntryDAOUtils entryDAOUtils=createMock(EntryDAOUtils.class);
		expect(entryDAOUtils.getSequenceLength("A00001.1")).andReturn(30L);
		replay(entryDAOUtils);
		check.setEntryDAOUtils(entryDAOUtils);
		ValidationResult result = check.check(entry);
		assertEquals(0, result.count("FeaturewithRemoteLocationCheck-2", Severity.ERROR));
	}
	@Test
	public void testCheck_featurewithInvalidRemoteLocationwithdbConnection() throws SQLException, ValidationEngineException {

		property.enproConnection.set(createMock(Connection.class));
		RemoteRange remoteRange1 = locationFactory.createRemoteRange("A00001", 1,10L,20L);
		Join<Location> join = new Join<Location>();
		join.addLocation(remoteRange1);
		Feature feature=featureFactory.createFeature("STS");
		feature.setLocations(join);
		entry.addFeature(feature);
		check.setEmblEntryValidationPlanProperty(property);
		EntryDAOUtils entryDAOUtils=createMock(EntryDAOUtils.class);
		expect(entryDAOUtils.getSequenceLength("A00001.1")).andReturn(10L);
		replay(entryDAOUtils);
		check.setEntryDAOUtils(entryDAOUtils);
		ValidationResult result = check.check(entry);
		assertEquals(1, result.count("FeaturewithRemoteLocationCheck-2", Severity.ERROR));
	}

	@Test
	public void testCheck_featurewithLocalLocationwithdbConnection() throws SQLException, ValidationEngineException {
		property.enproConnection.set(createMock(Connection.class));
		LocalRange localRange1 = locationFactory.createLocalRange(10L, 20L);
		LocalRange localRange2 = locationFactory.createLocalRange(10L,20L);
		Join<Location> join = new Join<Location>();
		join.addLocation(localRange1);
		join.addLocation(localRange2);
		Feature feature=featureFactory.createFeature("STS");
		feature.setLocations(join);
		entry.addFeature(feature);
		check.setEmblEntryValidationPlanProperty(property);
		ValidationResult result = check.check(entry);
		assertEquals(0, result.count("FeaturewithRemoteLocationCheck-1", Severity.WARNING));
	}
}


text:
var expect = require('chai').expect
var p2ptrade = require('../lib')
var ccCore = require('cc-wallet-core');
var BIP39 = require('bip39')
var EAgent = p2ptrade.Agent.EAgent
var MyEProposal = p2ptrade.ProtocolObjects.MyEProposal
var EOffer = p2ptrade.ProtocolObjects.EOffer
var dictLength = p2ptrade.Utils.dictLength
var OperationalETxSpec = p2ptrade.EWCtrl.OperationalETxSpec
var EWalletController = p2ptrade.EWCtrl.EWalletController
var ColorDefinition = ccCore.cclib.ColorDefinition
var ccWallet = ccCore.Wallet

// fixtures
var fixtures = require('./fixtures/protocol.json')
var alice = fixtures.wallet.alice // 123000 gold
var bob = fixtures.wallet.bob // 3300000 btc
var assetdefs = fixtures.assetDefinitions
var color_spec = assetdefs[0]["colorDescs"][0] // gold

function myEOffer(){
  return EOffer.fromData({
    "oid": "test_my_offer",
    "A": { "color_spec": "", "value": 200000 },
    "B": { "color_spec": color_spec, "value": 100000 }
  })
}

function theirEOffer(){
  return EOffer.fromData({
    "oid": "test_their_offer",
    "A": { "color_spec": color_spec, "value": 100000 },
    "B": { "color_spec": "", "value": 200000 }
  })
}

/**
 * Mock Ewctrl
 */
function MockEWCtrl(){
  //
}

MockEWCtrl.prototype.makeEtxSpec = function(a,b, cb){
  cb(null, { getData: function() { return mock_etx_spec } })
}
MockEWCtrl.prototype.makeReplyTx = function(etx_spec, a, b, cb){
  cb(null, { toHex: function(){ return "mock_reply_tx_hex";} })
}

MockEWCtrl.prototype.resolveColorDesc = function(color_desc){
  return new ColorDefinition(0)
}

var mock_etx_spec = {
  inputs: [],
  targets: []
}

/**
 * Mock Comm
 */
function MockComm(){
  this.agents = []
  this.messages = []
}

MockComm.prototype.addAgent = function(agent){
  this.agents.push(agent)
}

MockComm.prototype.postMessage = function(message){
  this.messages.push(message)
}

/**
 * Mock ExchangeProposal
 */
function MockExchangeProposal(){
  this.offer = myEOffer()
  this.etx_spec = mock_etx_spec
  this.reply_ep = {
    validate: function(cb){ cb(null)},
    getData: function(){
      return "mock_ep_data"
    }
  }
}

MockExchangeProposal.prototype.accept = function(my_offer, cb){
  cb(null, this.reply_ep)
}

/**
 * Test P2PTrade Agent
 */
describe('P2PTrade Agent', function(){

  var seed
  var wallet
  var ewctrl
  var config
  var agent
  var comm

  beforeEach(function(done) {

    // testnet wallet/ewctrl
    localStorage.clear()
    seed = BIP39.mnemonicToSeedHex(bob.mnemonic, bob.password)
    wallet = new ccWallet({
      testnet: true,
      systemAssetDefinitions: assetdefs
    })
    wallet.initialize(seed)
    ewctrl = new EWalletController(wallet, seed)
    ewctrl.neverSendOnPublishTx = true

    // test agent
    config = {
      ep_expiry_interval: 42,
      offer_expiry_interval: 42,
      offer_grace_interval: 0
    }
    comm = new MockComm()
    agent = new EAgent(ewctrl, config, comm)

    wallet.once('syncStop', done)
  })

  afterEach(function () {
    wallet.removeListeners()
    wallet.clearStorage()
    wallet = undefined
  })

  it('fire_event handles correct type', function(){
    var handled = false
    var received = null
    agent.setEventHandler('b', function(data){
      received = data
      handled = true
    })
    agent.fireEvent('b', "test")
    expect(handled).to.deep.equal(true)
    expect(received).to.deep.equal("test")
  })

  it('fire_event ignores incorrect type', function(){
    var handled = false
    agent.setEventHandler('a', function(data){
      handled = true
    })
    agent.fireEvent('b', "test")
    expect(handled).to.deep.equal(false)
  })

  it('setActiveEP clears', function(){
    agent.epTimeout = "test"
    agent.activeEP = "test"
    agent.setActiveEP(null)
    expect(agent.epTimeout).to.be.null
    expect(agent.activeEP).to.be.null
  })

  it('setActiveEP updates', function(){
    var config = { ep_expiry_interval: 0 }
    var agent = new EAgent(null, config, new MockComm())

    agent.setActiveEP("test")
    expect(agent.activeEP).to.deep.equal("test")
    expect(agent.epTimeout > 1400000000).to.be.true
  })

  it('hasActiveEP', function(){
    expect(agent.hasActiveEP()).to.be.false
    agent.setActiveEP("test")
    expect(agent.hasActiveEP()).to.be.true
  })

  it('hasActiveEP checks timeout', function(){
    var config = { ep_expiry_interval: -42 }
    var agent = new EAgent(null, config, new MockComm())

    expect(agent.hasActiveEP()).to.be.false
    agent.setActiveEP("test")
    expect(agent.hasActiveEP()).to.be.false
  })

  it('serviceMyOffers ignores activeEP.my_offer', function(){
    var my_offer = EOffer.fromData({
      "oid": "test_my_offer",
      "A": { "color_spec": "", "value": 100000 },
      "B": { "color_spec": color_spec, "value": 100000 }
    })
    agent.registerMyOffer(my_offer)
    agent.setActiveEP({my_offer: my_offer})
    agent.serviceMyOffers()
    expect(comm.messages.length == 0).to.be.true
  })

  it('serviceMyOffers', function(){
    var my_offer = EOffer.fromData({
      "oid": "test_my_offer",
      "A": { "color_spec": "", "value": 100000 },
      "B": { "color_spec": color_spec, "value": 100000 }
    })
    agent.registerMyOffer(my_offer)
    agent.serviceMyOffers()
    expect(comm.messages.length == 1).to.be.true // expired by default
    agent.serviceMyOffers()
    expect(comm.messages.length == 1).to.be.true // ignores unexpired
  })

  it('serviceTheirOffers removes expired', function(){
    config = {
      ep_expiry_interval: 42,
      offer_expiry_interval: -42,
      offer_grace_interval: 0
    }
    ewctrl = new MockEWCtrl()
    comm = new MockComm()
    agent = new EAgent(ewctrl, config, comm)
    agent.registerTheirOffer(theirEOffer())
    agent.serviceTheirOffers()
    expect(dictLength(agent.theirOffers) == 0).to.be.true
  })

  it('serviceTheirOffers ignores unexpired', function(){
    agent.registerTheirOffer(theirEOffer())
    agent.serviceTheirOffers()
    expect(dictLength(agent.theirOffers) == 1).to.be.true
  })

  it('registerMyOffer', function(){
    expect(agent.myOffers).to.deep.equal({}) // previously empty
    expect(agent.offersUpdated).to.be.false // previously unset
    var offer = myEOffer()
    agent.registerMyOffer(offer)
    expect(agent.offersUpdated).to.be.true // sets flag
    expect(agent.myOffers).to.deep.equal({test_my_offer:offer}) // offer saved
  })

  it('cancel_my_offer clears activeEP', function(){
    var offer = myEOffer()
    var ep = { offer: offer, my_offer: offer }
    agent.setActiveEP(ep)
    agent.cancelMyOffer(offer)
    expect(agent.hasActiveEP()).to.be.false
  })

  it('cancel_my_offer clears myOffers', function(){
    var offer = myEOffer()
    agent.registerMyOffer(offer)
    agent.cancelMyOffer(offer)
    expect(agent.myOffers).to.deep.equal({})
  })

  it('registerTheirOffer', function(){
    expect(agent.myOffers).to.deep.equal({}) // previously empty
    expect(agent.offersUpdated).to.be.false // previously unset
    var offer = { oid:"test" }

    // monkeypatch refresh
    var refresh_interval = 0
    offer.refresh = function(interval){ refresh_interval = interval }

    agent.registerTheirOffer(offer)
    expect(refresh_interval).to.deep.equal(42) // called refresh
    expect(agent.offersUpdated).to.be.true // sets flag
    expect(agent.theirOffers).to.deep.equal({test:offer}) // offer saved
  })

  it('matchOffers does nothing if has active ep ', function(done){
    agent.setActiveEP("test")
    agent.matchOffers(function(error, ep){
      expect(error).to.be.null
      expect(ep).to.be.null
      done()
    })
  })

  it('matchOffers ignores unmatching', function(done){
    var my_offer = EOffer.fromData({
      "oid": "my_oid",
      "A": { "color_spec": "mock_my_color_spec", "value": 100000 },
      "B": { "color_spec": "", "value": 100000 }
    })
    var their_offer = EOffer.fromData({
      "oid": "their_oid",
      "A": { "color_spec": "", "value": 100000 },
      "B": { "color_spec": "mock_their_color_spec", "value": 100000 }
    })
    agent.registerMyOffer(my_offer)
    agent.registerTheirOffer(their_offer)
    agent.matchOffers(function(error, ep){
      expect(error).to.be.null
      expect(ep).to.be.null
      done()
    })
  })

  it('matchOffers finds matching', function(done){
    var my_offer = EOffer.fromData({
      "oid": "my_oid",
      "A": { "color_spec": "", "value": 100000 },
      "B": { "color_spec": color_spec, "value": 100000 }
    })
    var their_offer = EOffer.fromData({
      "oid": "their_oid",
      "A": { "color_spec": color_spec, "value": 100000 },
      "B": { "color_spec": "", "value": 100000 }
    })
    agent.registerMyOffer(my_offer)
    agent.registerTheirOffer(their_offer)
    agent.matchOffers(function(error, ep){
      expect(error).to.be.null
      expect(ep).to.not.be.null

      // check if makeExchangeProposal called
      expect(agent.hasActiveEP()).to.be.true
      expect(comm.messages.length > 0).to.be.true
      done()
    })

  })

  it('makeExchangeProposal', function(done){
    var my_offer = myEOffer()
    var their_offer = theirEOffer()
    agent.makeExchangeProposal(their_offer, my_offer, function(error, ep){
      if(error) { throw error }
      expect(agent.hasActiveEP()).to.be.true
      expect(comm.messages.length > 0).to.be.true
      done()
    })
  })

  it('makeExchangeProposal fails if active ep', function(done){
    agent.setActiveEP("test")
    agent.makeExchangeProposal('o', 'm', function(error, ep){
      expect(!error).to.be.false
      done()
    })
  })

  it.skip('dispatchExchangeProposal updates activeEP if matches', function(done){
    // update_exchange_proposal if activeEP and matching pid

    // FIXME how does this test anything?
    var my_offer = myEOffer()
    var their_offer = theirEOffer()
    agent.makeExchangeProposal(their_offer, my_offer, function(error, ep){
      agent.activeEP.processReply = function (ep) {
        // monkeypatch to not process reply
      }
      expect(error).to.be.null
      var data = {
        'pid' : ep.pid, 'offer' : myEOffer(),
        'etx_spec' : mock_etx_spec
      }
      agent.dispatchExchangeProposal(data, function(error){
        expect(error).to.be.null
        // FIXME shouldn't i be testing something here
        done()
      })
    })
  })

  it.skip('dispatchExchangeProposal accepts offer if matches', function(done){
    // acceptExchangeProposal if no activeEP and matching oid
    // FIXME can't use mock_etx_spec

    var data = {
      'pid' : 'mock_pid', 'offer' : myEOffer(),
      'etx_spec' : mock_etx_spec
    }
    agent.registerMyOffer(myEOffer())
    agent.dispatchExchangeProposal(data, function(error){
      if(error){ throw error }
      expect(agent.hasActiveEP()).to.be.true
      expect(comm.messages.length > 0).to.be.true
      done()
    })
  })

  it('dispatchExchangeProposal removes their_offer if no matches', function(done){
    var data = { 'pid' : 'mock_pid', 'offer' : theirEOffer() }
    agent.registerTheirOffer(theirEOffer())
    expect(dictLength(agent.theirOffers) == 1).to.be.true
    agent.dispatchExchangeProposal(data, function(error){
      expect(error).to.be.null
      expect(dictLength(agent.theirOffers) == 0).to.be.true
      done()
    })
  })

  it('acceptExchangeProposal', function(done){
    var ep = new MockExchangeProposal()
    agent.registerMyOffer(myEOffer())
    agent.acceptExchangeProposal(ep, function(error){
      expect(error).to.be.null
      expect(agent.activeEP).to.deep.equal(ep.reply_ep)
      expect(comm.messages).to.deep.equal([ep.reply_ep.getData()])
      done()
    })
  })

  it('clearOrders', function(){
    var my_offer = myEOffer()
    agent.myOffers = { "test_my_offer": my_offer }
    var their_offer = theirEOffer()
    agent.theirOffers = { "test_their_offer": their_offer }

    // test clear MyEProposal
    agent.clearOrders(new MyEProposal(ewctrl, their_offer, my_offer))
    expect(agent.myOffers).to.deep.equal({})
    expect(agent.theirOffers).to.deep.equal({})

    // test clear other
    agent.myOffers = { "test_my_offer": my_offer}
    agent.clearOrders({ offer: my_offer })
    expect(agent.myOffers).to.deep.equal({})
  })

  it('finishExchangeProposal', function(done){

    // setup my_ep
    var my_offer = myEOffer()
    var their_offer = theirEOffer()
    var etxSpec = { getData: function() { return mock_etx_spec } }
    var my_ep = new MyEProposal(ewctrl, their_offer, my_offer, etxSpec)

    // monkeypatch processReply
    var process_reply_called = false
    my_ep.processReply = function(ep){ process_reply_called = true }

    var reply_ep = {
      pid: "reply_pid",
      processReply: function(ep){},
      offer: myEOffer()
    }

    agent.setActiveEP(my_ep)
    agent.finishExchangeProposal(reply_ep, function(error){
      expect(process_reply_called).to.be.true
      expect(agent.hasActiveEP()).to.be.false
      expect(comm.messages.length > 0).to.be.true
      done()
    })
  })

  it('postMessage', function(){
    var obj = { getData: function(){ return "test"} }
    agent.postMessage(obj)
    expect(comm.messages).to.deep.equal(["test"])
  })

  it.skip('dispatchMessage', function(){
    // TODO how to test it?
    expect(false).to.be.true
  })

  it.skip('update', function(){
    // TODO how to test it?
    expect(false).to.be.true
  })

})


text:
#ifndef MOZILLA_GFX_BASERECT_H_
#define MOZILLA_GFX_BASERECT_H_

#include <cmath>

namespace mozilla {
namespace gfx {

// XXX - <algorithm> conflicts with exceptions on 10.6. Define our own gfx_min/gfx_max
// functions here. Avoid min/max to avoid conflicts with existing #defines on windows.
template<typename T>
T gfx_min(T aVal1, T aVal2)
{
  return (aVal1 < aVal2) ? aVal1 : aVal2;
}

template<typename T>
T gfx_max(T aVal1, T aVal2)
{
  return (aVal1 > aVal2) ? aVal1 : aVal2;
}

/**
 * Rectangles have two interpretations: a set of (zero-size) points,
 * and a rectangular area of the plane. Most rectangle operations behave
 * the same no matter what interpretation is being used, but some operations
 * differ:
 * -- Equality tests behave differently. When a rectangle represents an area,
 * all zero-width and zero-height rectangles are equal to each other since they
 * represent the empty area. But when a rectangle represents a set of
 * mathematical points, zero-width and zero-height rectangles can be unequal.
 * -- The union operation can behave differently. When rectangles represent
 * areas, taking the union of a zero-width or zero-height rectangle with
 * another rectangle can just ignore the empty rectangle. But when rectangles
 * represent sets of mathematical points, we may need to extend the latter
 * rectangle to include the points of a zero-width or zero-height rectangle.
 *
 * To ensure that these interpretations are explicitly disambiguated, we
 * deny access to the == and != operators and require use of IsEqualEdges and
 * IsEqualInterior instead. Similarly we provide separate Union and UnionEdges
 * methods.
 *
 * Do not use this class directly. Subclass it, pass that subclass as the
 * Sub parameter, and only use that subclass.
 */
template <class T, class Sub, class Point, class SizeT, class Margin>
struct BaseRect {
  T x, y, width, height;

  // Constructors
  BaseRect() : x(0), y(0), width(0), height(0) {}
  BaseRect(const Point& aOrigin, const SizeT &aSize) :
      x(aOrigin.x), y(aOrigin.y), width(aSize.width), height(aSize.height)
  {
  }
  BaseRect(T aX, T aY, T aWidth, T aHeight) :
      x(aX), y(aY), width(aWidth), height(aHeight)
  {
  }

  // Emptiness. An empty rect is one that has no area, i.e. its height or width
  // is <= 0
  bool IsEmpty() const { return height <= 0 || width <= 0; }
  void SetEmpty() { width = height = 0; }

  // Returns true if this rectangle contains the interior of aRect. Always
  // returns true if aRect is empty, and always returns false is aRect is
  // nonempty but this rect is empty.
  bool Contains(const Sub& aRect) const
  {
    return aRect.IsEmpty() ||
           (x <= aRect.x && aRect.XMost() <= XMost() &&
            y <= aRect.y && aRect.YMost() <= YMost());
  }
  // Returns true if this rectangle contains the rectangle (aX,aY,1,1).
  bool Contains(T aX, T aY) const
  {
    return x <= aX && aX + 1 <= XMost() &&
           y <= aY && aY + 1 <= YMost();
  }
  // Returns true if this rectangle contains the rectangle (aPoint.x,aPoint.y,1,1).
  bool Contains(const Point& aPoint) const { return Contains(aPoint.x, aPoint.y); }

  // Intersection. Returns TRUE if the receiver's area has non-empty
  // intersection with aRect's area, and FALSE otherwise.
  // Always returns false if aRect is empty or 'this' is empty.
  bool Intersects(const Sub& aRect) const
  {
    return x < aRect.XMost() && aRect.x < XMost() &&
           y < aRect.YMost() && aRect.y < YMost();
  }
  // Returns the rectangle containing the intersection of the points
  // (including edges) of *this and aRect. If there are no points in that
  // intersection, returns an empty rectangle with x/y set to the gfx_max of the x/y
  // of *this and aRect.
  Sub Intersect(const Sub& aRect) const
  {
    Sub result;
    result.x = gfx_max(x, aRect.x);
    result.y = gfx_max(y, aRect.y);
    result.width = gfx_min(XMost(), aRect.XMost()) - result.x;
    result.height = gfx_min(YMost(), aRect.YMost()) - result.y;
    if (result.width < 0 || result.height < 0) {
      result.SizeTo(0, 0);
    }
    return result;
  }
  // Sets *this to be the rectangle containing the intersection of the points
  // (including edges) of *this and aRect. If there are no points in that
  // intersection, sets *this to be an empty rectangle with x/y set to the gfx_max
  // of the x/y of *this and aRect.
  //
  // 'this' can be the same object as either aRect1 or aRect2
  bool IntersectRect(const Sub& aRect1, const Sub& aRect2)
  {
    *static_cast<Sub*>(this) = aRect1.Intersect(aRect2);
    return !IsEmpty();
  }

  // Returns the smallest rectangle that contains both the area of both
  // this and aRect2.
  // Thus, empty input rectangles are ignored.
  // If both rectangles are empty, returns this.
  Sub Union(const Sub& aRect) const
  {
    if (IsEmpty()) {
      return aRect;
    } else if (aRect.IsEmpty()) {
      return *static_cast<const Sub*>(this);
    } else {
      return UnionEdges(aRect);
    }
  }
  // Returns the smallest rectangle that contains both the points (including
  // edges) of both aRect1 and aRect2.
  // Thus, empty input rectangles are allowed to affect the result.
  Sub UnionEdges(const Sub& aRect) const
  {
    Sub result;
    result.x = gfx_min(x, aRect.x);
    result.y = gfx_min(y, aRect.y);
    result.width = gfx_max(XMost(), aRect.XMost()) - result.x;
    result.height = gfx_max(YMost(), aRect.YMost()) - result.y;
    return result;
  }
  // Computes the smallest rectangle that contains both the area of both
  // aRect1 and aRect2, and fills 'this' with the result.
  // Thus, empty input rectangles are ignored.
  // If both rectangles are empty, sets 'this' to aRect2.
  //
  // 'this' can be the same object as either aRect1 or aRect2
  void UnionRect(const Sub& aRect1, const Sub& aRect2)
  {
    *static_cast<Sub*>(this) = aRect1.Union(aRect2);
  }

  // Computes the smallest rectangle that contains both the points (including
  // edges) of both aRect1 and aRect2.
  // Thus, empty input rectangles are allowed to affect the result.
  //
  // 'this' can be the same object as either aRect1 or aRect2
  void UnionRectEdges(const Sub& aRect1, const Sub& aRect2)
  {
    *static_cast<Sub*>(this) = aRect1.UnionEdges(aRect2);
  }

  void SetRect(T aX, T aY, T aWidth, T aHeight)
  {
    x = aX; y = aY; width = aWidth; height = aHeight;
  }
  void SetRect(const Point& aPt, const SizeT& aSize)
  {
    SetRect(aPt.x, aPt.y, aSize.width, aSize.height);
  }
  void MoveTo(T aX, T aY) { x = aX; y = aY; }
  void MoveTo(const Point& aPoint) { x = aPoint.x; y = aPoint.y; }
  void MoveBy(T aDx, T aDy) { x += aDx; y += aDy; }
  void MoveBy(const Point& aPoint) { x += aPoint.x; y += aPoint.y; }
  void SizeTo(T aWidth, T aHeight) { width = aWidth; height = aHeight; }
  void SizeTo(const SizeT& aSize) { width = aSize.width; height = aSize.height; }

  void Inflate(T aD) { Inflate(aD, aD); }
  void Inflate(T aDx, T aDy)
  {
    x -= aDx;
    y -= aDy;
    width += 2 * aDx;
    height += 2 * aDy;
  }
  void Inflate(const Margin& aMargin)
  {
    x -= aMargin.left;
    y -= aMargin.top;
    width += aMargin.LeftRight();
    height += aMargin.TopBottom();
  }
  void Inflate(const SizeT& aSize) { Inflate(aSize.width, aSize.height); }

  void Deflate(T aD) { Deflate(aD, aD); }
  void Deflate(T aDx, T aDy)
  {
    x += aDx;
    y += aDy;
    width = gfx_max(T(0), width - 2 * aDx);
    height = gfx_max(T(0), height - 2 * aDy);
  }
  void Deflate(const Margin& aMargin)
  {
    x += aMargin.left;
    y += aMargin.top;
    width = gfx_max(T(0), width - aMargin.LeftRight());
    height = gfx_max(T(0), height - aMargin.TopBottom());
  }
  void Deflate(const SizeT& aSize) { Deflate(aSize.width, aSize.height); }

  // Return true if the rectangles contain the same set of points, including
  // points on the edges.
  // Use when we care about the exact x/y/width/height values being
  // equal (i.e. we care about differences in empty rectangles).
  bool IsEqualEdges(const Sub& aRect) const
  {
    return x == aRect.x && y == aRect.y &&
           width == aRect.width && height == aRect.height;
  }
  // Return true if the rectangles contain the same area of the plane.
  // Use when we do not care about differences in empty rectangles.
  bool IsEqualInterior(const Sub& aRect) const
  {
    return IsEqualEdges(aRect) || (IsEmpty() && aRect.IsEmpty());
  }

  Sub operator+(const Point& aPoint) const
  {
    return Sub(x + aPoint.x, y + aPoint.y, width, height);
  }
  Sub operator-(const Point& aPoint) const
  {
    return Sub(x - aPoint.x, y - aPoint.y, width, height);
  }
  Sub& operator+=(const Point& aPoint)
  {
    MoveBy(aPoint);
    return *static_cast<Sub*>(this);
  }
  Sub& operator-=(const Point& aPoint)
  {
    MoveBy(-aPoint);
    return *static_cast<Sub*>(this);
  }

  // Find difference as a Margin
  Margin operator-(const Sub& aRect) const
  {
    return Margin(aRect.x - x, aRect.y - y,
                  XMost() - aRect.XMost(), YMost() - aRect.YMost());
  }

  // Helpers for accessing the vertices
  Point TopLeft() const { return Point(x, y); }
  Point TopRight() const { return Point(XMost(), y); }
  Point BottomLeft() const { return Point(x, YMost()); }
  Point BottomRight() const { return Point(XMost(), YMost()); }
  Point Center() const { return Point(x, y) + Point(width, height)/2; }
  SizeT Size() const { return SizeT(width, height); }

  // Helper methods for computing the extents
  T X() const { return x; }
  T Y() const { return y; }
  T Width() const { return width; }
  T Height() const { return height; }
  T XMost() const { return x + width; }
  T YMost() const { return y + height; }

  // Scale 'this' by aScale, converting coordinates to integers so that the result is
  // the smallest integer-coordinate rectangle containing the unrounded result.
  // Note: this can turn an empty rectangle into a non-empty rectangle
  void ScaleRoundOut(double aScale) { ScaleRoundOut(aScale, aScale); }
  // Scale 'this' by aXScale and aYScale, converting coordinates to integers so
  // that the result is the smallest integer-coordinate rectangle containing the
  // unrounded result.
  // Note: this can turn an empty rectangle into a non-empty rectangle
  void ScaleRoundOut(double aXScale, double aYScale)
  {
    T right = static_cast<T>(ceil(double(XMost()) * aXScale));
    T bottom = static_cast<T>(ceil(double(YMost()) * aYScale));
    x = static_cast<T>(floor(double(x) * aXScale));
    y = static_cast<T>(floor(double(y) * aYScale));
    width = right - x;
    height = bottom - y;
  }
  // Scale 'this' by aScale, converting coordinates to integers so that the result is
  // the largest integer-coordinate rectangle contained by the unrounded result.
  void ScaleRoundIn(double aScale) { ScaleRoundIn(aScale, aScale); }
  // Scale 'this' by aXScale and aYScale, converting coordinates to integers so
  // that the result is the largest integer-coordinate rectangle contained by the
  // unrounded result.
  void ScaleRoundIn(double aXScale, double aYScale)
  {
    T right = static_cast<T>(floor(double(XMost()) * aXScale));
    T bottom = static_cast<T>(floor(double(YMost()) * aYScale));
    x = static_cast<T>(ceil(double(x) * aXScale));
    y = static_cast<T>(ceil(double(y) * aYScale));
    width = gfx_max<T>(0, right - x);
    height = gfx_max<T>(0, bottom - y);
  }
  // Scale 'this' by 1/aScale, converting coordinates to integers so that the result is
  // the smallest integer-coordinate rectangle containing the unrounded result.
  // Note: this can turn an empty rectangle into a non-empty rectangle
  void ScaleInverseRoundOut(double aScale) { ScaleInverseRoundOut(aScale, aScale); }
  // Scale 'this' by 1/aXScale and 1/aYScale, converting coordinates to integers so
  // that the result is the smallest integer-coordinate rectangle containing the
  // unrounded result.
  // Note: this can turn an empty rectangle into a non-empty rectangle
  void ScaleInverseRoundOut(double aXScale, double aYScale)
  {
    T right = static_cast<T>(ceil(double(XMost()) / aXScale));
    T bottom = static_cast<T>(ceil(double(YMost()) / aYScale));
    x = static_cast<T>(floor(double(x) / aXScale));
    y = static_cast<T>(floor(double(y) / aYScale));
    width = right - x;
    height = bottom - y;
  }

private:
  // Do not use the default operator== or operator!= !
  // Use IsEqualEdges or IsEqualInterior explicitly.
  bool operator==(const Sub& aRect) const { return false; }
  bool operator!=(const Sub& aRect) const { return false; }
};

}
}

#endif /* MOZILLA_GFX_BASERECT_H_ */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Assets.BeMoBI.Scripts.Controls
{
    public interface IHeadMovementController : IInputController
    {
        Transform Head { get; set; }
    }
}


text:
/*
 * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package javax.lang.model.type;

/**
 * Represents the null type.
 * This is the type of the expression {@code null},
 *
 * @author Joseph D. Darcy
 * @author Scott Seligman
 * @author Peter von der Ahé
 * @since 1.6
 */

public interface NullType extends ReferenceType {
}