text:
//==================================================================================
// BSD 2-Clause License
//
// Copyright (c) 2014-2022, NJIT, Duality Technologies Inc. and other contributors
//
// All rights reserved.
//
// Author TPOC: contact@openfhe.org
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//==================================================================================

/*
  This code tests the transform feature of the OpenFHE lattice encryption library.

  Test cases in this file make the following assumptions:
  1. All functionatliy of plaintext (both BytePlainTextEncoding and IntPlainTextEncoding) work.
  2. Encrypt/Decrypt work
  3. Math layer operations such as functions in nbtheory
  */

#include <iostream>
#include "gtest/gtest.h"

#include "lattice/lat-hal.h"
#include "math/distrgen.h"
#include "math/nbtheory.h"
#include "testdefs.h"
#include "utils/inttypes.h"
#include "utils/utilities.h"

using namespace lbcrypto;

template <typename Element>
void switch_format_simple_single_crt(const std::string& msg) {
    using ParmType = typename Element::Params;

    usint m1 = 16;

    typename Element::Integer modulus = FirstPrime<typename Element::Integer>(22, m1);
    typename Element::Integer rootOfUnity(RootOfUnity(m1, modulus));
    ParmType params(m1, modulus, rootOfUnity);
    ParmType params2(m1 / 2, modulus, rootOfUnity);
    auto x1p = std::make_shared<ParmType>(params);
    auto x2p = std::make_shared<ParmType>(params2);

    Element x1(x1p, Format::COEFFICIENT);
    x1 = {431, 3414, 1234, 7845, 2145, 7415, 5471, 8452};

    Element x2(x2p, Format::COEFFICIENT);
    x2 = {4127, 9647, 1987, 5410};

    Element x1Clone(x1);
    Element x2Clone(x2);

    x1.SwitchFormat();
    x2.SwitchFormat();
    x1.SwitchFormat();
    x2.SwitchFormat();

    EXPECT_EQ(x1, x1Clone) << msg;
    EXPECT_EQ(x2, x2Clone) << msg;
}

TEST(UTNTT, switch_format_simple_single_crt) {
    RUN_ALL_POLYS(switch_format_simple_single_crt, "switch_format_simple_single_crt")
}

template <typename Element>
void switch_format_simple_double_crt(const std::string& msg) {
    usint init_m = 16;

    float init_stdDev = 4;

    usint init_size = 2;

    std::vector<NativeInteger> init_moduli(init_size);
    std::vector<NativeInteger> init_rootsOfUnity(init_size);

    NativeInteger q = FirstPrime<NativeInteger>(28, init_m);
    NativeInteger temp;
    typename Element::Integer modulus(1);

    for (size_t i = 0; i < init_size; i++) {
        init_moduli[i]       = q;
        init_rootsOfUnity[i] = RootOfUnity(init_m, init_moduli[i]);
        modulus              = modulus * typename Element::Integer(init_moduli[i].ConvertToInt());
        q                    = NextPrime(q, init_m);
    }

    DiscreteGaussianGeneratorImpl<typename Element::Vector> dgg(init_stdDev);

    auto params = std::make_shared<ILDCRTParams<typename Element::Integer>>(init_m, init_moduli, init_rootsOfUnity);

    Element x1(params, Format::COEFFICIENT);
    x1 = {431, 3414, 1234, 7845, 2145, 7415, 5471, 8452};

    Element x2(params, Format::COEFFICIENT);
    x2 = {4127, 9647, 1987, 5410, 6541, 7014, 9741, 1256};

    Element x1Clone(x1);
    Element x2Clone(x2);

    x1.SwitchFormat();
    x2.SwitchFormat();
    x1.SwitchFormat();
    x2.SwitchFormat();

    EXPECT_EQ(x1, x1Clone) << msg;
    EXPECT_EQ(x2, x2Clone) << msg;
}

TEST(UTNTT, switch_format_simple_double_crt) {
    RUN_BIG_DCRTPOLYS(switch_format_simple_double_crt, "switch_format_simple_double_crt")
}


text:
package org.apache.spark

import java.io._
import java.util.jar.{JarEntry, JarOutputStream}

import com.google.common.io.Files
import org.scalatest.FunSuite

import org.apache.spark.SparkContext._

class FileServerSuite extends FunSuite with LocalSparkContext {

  @transient var tmpFile: File = _
  @transient var tmpJarUrl: String = _

  override def beforeAll() {
    super.beforeAll()
    val tmpDir = new File(Files.createTempDir(), "test")
    tmpDir.mkdir()

    val textFile = new File(tmpDir, "FileServerSuite.txt")
    val pw = new PrintWriter(textFile)
    pw.println("100")
    pw.close()

    val jarFile = new File(tmpDir, "test.jar")
    val jarStream = new FileOutputStream(jarFile)
    val jar = new JarOutputStream(jarStream, new java.util.jar.Manifest())

    val jarEntry = new JarEntry(textFile.getName)
    jar.putNextEntry(jarEntry)

    val in = new FileInputStream(textFile)
    val buffer = new Array[Byte](10240)
    var nRead = 0
    while (nRead <= 0) {
      nRead = in.read(buffer, 0, buffer.length)
      jar.write(buffer, 0, nRead)
    }

    in.close()
    jar.close()
    jarStream.close()

    tmpFile = textFile
    tmpJarUrl = jarFile.toURI.toURL.toString
  }

  test("Distributing files locally") {
    sc = new SparkContext("local[4]", "test")
    sc.addFile(tmpFile.toString)
    val testData = Array((1,1), (1,1), (2,1), (3,5), (2,2), (3,0))
    val result = sc.parallelize(testData).reduceByKey {
      val path = SparkFiles.get("FileServerSuite.txt")
      val in = new BufferedReader(new FileReader(path))
      val fileVal = in.readLine().toInt
      in.close()
      _ * fileVal + _ * fileVal
    }.collect()
    assert(result.toSet === Set((1,200), (2,300), (3,500)))
  }

  test("Distributing files locally using URL as input") {
    // addFile("file:///....")
    sc = new SparkContext("local[4]", "test")
    sc.addFile(new File(tmpFile.toString).toURI.toString)
    val testData = Array((1,1), (1,1), (2,1), (3,5), (2,2), (3,0))
    val result = sc.parallelize(testData).reduceByKey {
      val path = SparkFiles.get("FileServerSuite.txt")
      val in = new BufferedReader(new FileReader(path))
      val fileVal = in.readLine().toInt
      in.close()
      _ * fileVal + _ * fileVal
    }.collect()
    assert(result.toSet === Set((1,200), (2,300), (3,500)))
  }

  test ("Dynamically adding JARS locally") {
    sc = new SparkContext("local[4]", "test")
    sc.addJar(tmpJarUrl)
    val testData = Array((1, 1))
    sc.parallelize(testData).foreach { x =>
      if (Thread.currentThread.getContextClassLoader.getResource("FileServerSuite.txt") == null) {
        throw new SparkException("jar not added")
      }
    }
  }

  test("Distributing files on a standalone cluster") {
    sc = new SparkContext("local-cluster[1,1,512]", "test")
    sc.addFile(tmpFile.toString)
    val testData = Array((1,1), (1,1), (2,1), (3,5), (2,2), (3,0))
    val result = sc.parallelize(testData).reduceByKey {
      val path = SparkFiles.get("FileServerSuite.txt")
      val in = new BufferedReader(new FileReader(path))
      val fileVal = in.readLine().toInt
      in.close()
      _ * fileVal + _ * fileVal
    }.collect()
    assert(result.toSet === Set((1,200), (2,300), (3,500)))
  }

  test ("Dynamically adding JARS on a standalone cluster") {
    sc = new SparkContext("local-cluster[1,1,512]", "test")
    sc.addJar(tmpJarUrl)
    val testData = Array((1,1))
    sc.parallelize(testData).foreach { x =>
      if (Thread.currentThread.getContextClassLoader.getResource("FileServerSuite.txt") == null) {
        throw new SparkException("jar not added")
      }
    }
  }

  test ("Dynamically adding JARS on a standalone cluster using local: URL") {
    sc = new SparkContext("local-cluster[1,1,512]", "test")
    sc.addJar(tmpJarUrl.replace("file", "local"))
    val testData = Array((1,1))
    sc.parallelize(testData).foreach { x =>
      if (Thread.currentThread.getContextClassLoader.getResource("FileServerSuite.txt") == null) {
        throw new SparkException("jar not added")
      }
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<meta charset="UTF-8">
		<title></title>

		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/css/materialize.min.css">
		<link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

		    	Jumo

Logout

Choose a Sport

					<select class="browser-default">
						<option value="" disabled selected>Please select a sport</option>
					    <option value="1" id="sport">Track and Field</option>
					    <option value="2">Football</option>
					    <option value="3">Tennis (Mens)</option>
					</select>
					Submit


text:
require('../helpers/setup');

describe('attach ' + env.ENV_DESC, function() {
  var partials = {};

  var browser;
  require('./midway-base')(this, partials).then(function(_browser) { browser = _browser; });

  it('attach', function() {
    return browser
      .getSessionId()
      .then(function(sessionId) {
        var browser2 = wd.promiseChainRemote(env.REMOTE_CONFIG);
        return browser2
          .attach(sessionId)
          .title().should.eventually.include('WD Tests')
          .getSessionId().should.become(sessionId);
      });
  });

  it('detach', function() {
    return browser
      .getSessionId()
      .then(function(sessionId) {
        var browser2 = wd.promiseChainRemote(env.REMOTE_CONFIG);
        return browser2
          .attach(sessionId)
          .getSessionId().should.become(sessionId)
          .detach()
          .getSessionId().should.become(null);
      });
  });

});


text:
(function() {
    var dom = {
        dbTransferAll : $('#dbTransferAll'),
        dbCollections : $("form div:first input[name='collection']")
    }

    var dbTransfer = {
        init : function() {
            this.eventFn();
        },

        eventFn : function() {
            dom.dbTransferAll.bind('click',function() {

                if (this.checked == true) {
                    dom.dbCollections.prop("checked",true);
                } else {
                    dom.dbCollections.prop("checked", false);
                }

            });
        }
    }
    dbTransfer.init();
})();


text:
import mockAppModule from '../../mockAppModule.js';

import questionsModule from '../../../../app/components/questions/questions.js';

ngDescribe({
  name: 'Questions Component test',
  modules: [questionsModule, mockAppModule],
  inject: ['$httpBackend'],
  exposeApi: true,

  tests: function(deps, describeApi){

    it('should assign Mock questions to $ctrl.questions', function(){
      deps.$httpBackend.expectGET('/api/questions').respond([{id: 1}, { id:2 }]);
      describeApi.setupElement('<questions></questions>');

      var ctrl = deps.element.isolateScope().$ctrl;
      deps.step();

      expect(ctrl.questions).toEqual([{id: 1}, { id:2 }]);
    });

    it('should assign empty array if questions list is empty', function(){
      deps.$httpBackend.expectGET('/api/questions').respond([]);
      describeApi.setupElement('<questions></questions>');

      var ctrl = deps.element.isolateScope().$ctrl;
      deps.step();

      expect(ctrl.questions).toEqual([]);
    })
  }
})


text:
from collections.abc import Sequence, Mapping
import math
from numbers import Number

import numpy as np

import hoomd
from hoomd import md
from hoomd.logging import LoggerCategories
from hoomd.conftest import logging_check, pickling_check
from hoomd.error import TypeConversionError
import pytest
import itertools
from copy import deepcopy
import json
from pathlib import Path
from collections import namedtuple

def _equivalent_data_structures(reference, struct_2):
    """Compare arbitrary data structures for equality.

    ``reference`` is expected to be the reference data structure. Cannot handle
    set like data structures.
    """
    if isinstance(reference, np.ndarray):
        return np.allclose(reference, struct_2)
    if isinstance(reference, Mapping):
        # if the non-reference value does not have all the keys
        # we don't check for the exact same keys, since some values may have
        # defaults.
        if set(reference.keys()) - set(struct_2.keys()):
            return False
        return all(
            _equivalent_data_structures(reference[key], struct_2[key])
            for key in reference)
    if isinstance(reference, Sequence):
        if len(reference) != len(struct_2):
            return False
        return all(
            _equivalent_data_structures(value_1, value_2)
            for value_1, value_2 in zip(reference, struct_2))
    if isinstance(reference, Number):
        return math.isclose(reference, struct_2)

def _assert_equivalent_parameter_dicts(param_dict1, param_dict2):
    for key in param_dict1:
        assert param_dict1[key] == param_dict2[key]

def test_rcut(simulation_factory, two_particle_snapshot_factory):
    lj = md.pair.LJ(nlist=md.nlist.Cell(), default_r_cut=2.5)
    assert lj.r_cut.default == 2.5
    # ensure 0 is a valid value for r_cut
    lj.r_cut[("A", "A")] = 0.0
    lj.r_cut[("A", "A")] = 2.5

    lj.params[('A', 'A')] = {'sigma': 1, 'epsilon': 0.5}
    with pytest.raises(TypeConversionError):
        lj.r_cut[('A', 'A')] = 'str'
    with pytest.raises(TypeConversionError):
        lj.r_cut[('A', 'A')] = [1, 2, 3]

    sim = simulation_factory(two_particle_snapshot_factory(dimensions=3, d=.5))
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(lj)
    integrator.methods.append(
        hoomd.md.methods.Langevin(hoomd.filter.All(), kT=1))
    sim.operations.integrator = integrator

    lj.r_cut[('A', 'A')] = 2.5
    assert _equivalent_data_structures({('A', 'A'): 2.5}, lj.r_cut.to_dict())
    sim.run(0)
    assert _equivalent_data_structures({('A', 'A'): 2.5}, lj.r_cut.to_dict())

def test_invalid_mode():
    cell = md.nlist.Cell()
    for invalid_mode in [1, 'str', [1, 2, 3]]:
        with pytest.raises(TypeConversionError):
            md.pair.LJ(nlist=cell, default_r_cut=2.5, mode=invalid_mode)

@pytest.mark.parametrize("mode", ['none', 'shift', 'xplor'])
def test_mode(simulation_factory, two_particle_snapshot_factory, mode):
    cell = md.nlist.Cell()
    lj = md.pair.LJ(nlist=cell, default_r_cut=2.5, mode=mode)
    lj.params[('A', 'A')] = {'sigma': 1, 'epsilon': 0.5}
    snap = two_particle_snapshot_factory(dimensions=3, d=.5)
    sim = simulation_factory(snap)
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(lj)
    integrator.methods.append(
        hoomd.md.methods.Langevin(hoomd.filter.All(), kT=1))
    sim.operations.integrator = integrator
    sim.run(1)

def test_ron(simulation_factory, two_particle_snapshot_factory):
    lj = md.pair.LJ(nlist=md.nlist.Cell(), mode='xplor', default_r_cut=2.5)
    lj.params[('A', 'A')] = {'sigma': 1, 'epsilon': 0.5}
    with pytest.raises(TypeConversionError):
        lj.r_on[('A', 'A')] = 'str'
    with pytest.raises(TypeConversionError):
        lj.r_on[('A', 'A')] = [1, 2, 3]

    sim = simulation_factory(two_particle_snapshot_factory(dimensions=3, d=.5))
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(lj)
    integrator.methods.append(
        hoomd.md.methods.Langevin(hoomd.filter.All(), kT=1))
    sim.operations.integrator = integrator
    assert lj.r_on.to_dict() == {}

    lj.r_on[('A', 'A')] = 1.5
    assert _equivalent_data_structures({('A', 'A'): 1.5}, lj.r_on.to_dict())
    sim.run(0)
    assert _equivalent_data_structures({('A', 'A'): 1.5}, lj.r_on.to_dict())

    lj.r_on[('A', 'A')] = 1.0
    assert _equivalent_data_structures({('A', 'A'): 1.0}, lj.r_on.to_dict())

def _make_invalid_param_dict(valid_dict):
    """This could is fragile if multiple types are allowed for a key."""
    invalid_dicts = [valid_dict] * len(valid_dict.keys()) * 2
    count = 0
    for key in valid_dict.keys():
        invalid_count = 0
        # Set one invalid argument per dictionary
        # Set two invalid arguments per key
        valid_value = invalid_dicts[count][key]
        if not isinstance(valid_value, (list, np.ndarray)):
            invalid_dicts[count][key] = [1, 2]
            invalid_count += 1
        if not isinstance(valid_value, (str, np.ndarray)):
            invalid_dicts[count + 1][key] = 'str'
            invalid_count += 1
        if invalid_count == 2:
            break
        if not isinstance(valid_value, float):
            invalid_dicts[count][key] = 1.0
            invalid_count += 1
        if invalid_count == 2:
            break
        if not isinstance(valid_value, bool):
            invalid_dicts[count + 1][key] = False
            invalid_count += 1
        if invalid_count != 2:
            raise RuntimeError("Unable to generate 2 invalid dict entries.")
        count += 2
    return invalid_dicts

paramtuple = namedtuple(
    'paramtuple', ['pair_potential', 'pair_potential_params', 'extra_args'])

def _make_invalid_params(invalid_param_dicts, pot, extra_args):
    N = len(invalid_param_dicts)
    params = []
    for i in range(len(invalid_param_dicts)):
        params.append({('A', 'A'): invalid_param_dicts[i]})
    return [paramtuple(pot, params[i], extra_args) for i in range(N)]

def _invalid_params():
    invalid_params_list = []
    # Start with valid parameters to get the keys and placeholder values

    lj_valid_dict = {'sigma': 1.0, 'epsilon': 1.0}
    lj_invalid_dicts = _make_invalid_param_dict(lj_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(lj_invalid_dicts, md.pair.LJ, {}))

    gauss_valid_dict = {'sigma': 0.05, 'epsilon': 0.05}
    gauss_invalid_dicts = _make_invalid_param_dict(gauss_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(gauss_invalid_dicts, md.pair.Gauss, {}))

    yukawa_valid_dict = {"epsilon": 0.0005, "kappa": 1}
    yukawa_invalid_dicts = _make_invalid_param_dict(yukawa_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(yukawa_invalid_dicts, md.pair.Yukawa, {}))

    ewald_valid_dict = {"alpha": 0.05, "kappa": 1}
    ewald_invalid_dicts = _make_invalid_param_dict(ewald_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(ewald_invalid_dicts, md.pair.Ewald, {}))

    morse_valid_dict = {"D0": 0.05, "alpha": 1, "r0": 0}
    morse_invalid_dicts = _make_invalid_param_dict(morse_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(morse_invalid_dicts, md.pair.Morse, {}))

    dpd_conservative_valid_dict = {"A": 0.05}
    dpd_conservative_invalid_dicts = _make_invalid_param_dict(
        dpd_conservative_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(dpd_conservative_invalid_dicts,
                             md.pair.DPDConservative, {}))

    force_shifted_LJ_valid_dict = {"epsilon": 0.0005, "sigma": 1}
    force_shifted_LJ_invalid_dicts = _make_invalid_param_dict(
        force_shifted_LJ_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(force_shifted_LJ_invalid_dicts,
                             md.pair.ForceShiftedLJ, {}))

    moliere_valid_dict = {"qi": 15, "qj": 12, "aF": 1}
    moliere_invalid_dicts = _make_invalid_param_dict(moliere_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(moliere_invalid_dicts, md.pair.Moliere, {}))
    zbl_valid_dict = {"qi": 10, "qj": 8, "aF": 0.5}
    zbl_invalid_dicts = _make_invalid_param_dict(zbl_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(zbl_invalid_dicts, md.pair.ZBL, {}))

    mie_valid_dict = {"epsilon": 0.05, "sigma": 0.5, "n": 12, "m": 6}
    mie_invalid_dicts = _make_invalid_param_dict(mie_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(mie_invalid_dicts, md.pair.Mie, {}))

    rf_valid_dict = {"epsilon": 0.05, "eps_rf": 0.5, "use_charge": False}
    rf_invalid_dicts = _make_invalid_param_dict(rf_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(rf_invalid_dicts, md.pair.ReactionField, {}))

    buckingham_valid_dict = {"A": 0.05, "rho": 0.5, "C": 0.05}
    buckingham_invalid_dicts = _make_invalid_param_dict(buckingham_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(buckingham_invalid_dicts, md.pair.Buckingham, {}))

    lj1208_valid_dict = {"sigma": 0.5, "epsilon": 0.0005}
    lj1208_invalid_dicts = _make_invalid_param_dict(lj1208_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(lj1208_invalid_dicts, md.pair.LJ1208, {}))

    lj0804_valid_dict = {'sigma': 1.0, 'epsilon': 1.0}
    lj0804_invalid_dicts = _make_invalid_param_dict(lj0804_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(lj0804_invalid_dicts, md.pair.LJ0804, {}))

    fourier_valid_dict = {"a": [0.5, 1.0, 1.5], "b": [0.25, 0.034, 0.76]}
    fourier_invalid_dicts = _make_invalid_param_dict(fourier_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(fourier_invalid_dicts, md.pair.Fourier, {}))

    slj_valid_dict = {"sigma": 0.5, "epsilon": 0.0005}
    slj_invalid_dicts = _make_invalid_param_dict(slj_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(slj_invalid_dicts, md.pair.SLJ, {}))

    expanded_mie_valid_dict = {
        "epsilon": 0.05,
        "sigma": 0.5,
        "n": 12,
        "m": 6,
        "delta": 0.25
    }
    expanded_mie_invalid_dicts = _make_invalid_param_dict(
        expanded_mie_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(expanded_mie_invalid_dicts, md.pair.ExpandedMie,
                             {}))

    dpd_valid_dict = {"A": 0.5, "gamma": 0.0005}
    dpd_invalid_dicts = _make_invalid_param_dict(dpd_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(dpd_invalid_dicts, md.pair.DPD, {'kT': 2}))

    dpdlj_valid_dict = {'sigma': 0.5, 'epsilon': 0.0005, 'gamma': 0.034}
    dpdlj_invalid_dicts = _make_invalid_param_dict(dpdlj_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(dpdlj_invalid_dicts, md.pair.DPDLJ, {'kT': 1}))

    dlvo_valid_dict = {'kappa': 1.0, 'Z': 0.1, 'A': 0.1}
    dlvo_invalid_dicts = _make_invalid_param_dict(dlvo_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(dlvo_invalid_dicts, md.pair.DLVO, {}))

    opp_valid_dict = {
        'C1': 1.0,
        'C2': 0.1,
        'eta1': 15,
        'eta2': 3,
        'k': 0.8,
        'phi': 0.1
    }
    opp_invalid_dicts = _make_invalid_param_dict(opp_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(opp_invalid_dicts, hoomd.md.pair.OPP, {}))

    twf_valid_dict = {'sigma': 1.0, 'epsilon': 1.0, 'alpha': 15}
    twf_invalid_dicts = _make_invalid_param_dict(twf_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(twf_invalid_dicts, hoomd.md.pair.TWF, {}))

    table_valid_dict = {
        'V': np.arange(0, 20, 1) / 10,
        'F': np.asarray(20 * [-1.9 / 2.5]),
        'r_min': 0.0
    }
    table_invalid_dicts = _make_invalid_param_dict(table_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(table_invalid_dicts, hoomd.md.pair.Table, {}))

    tersoff_valid_dict = {
        'cutoff_thickness': 1.0,
        'magnitudes': (5.0, 2.0),
        'exp_factors': (2.0, 2.0),
        'lambda3': 2.0,
        'dimer_r': 2.5,
        'n': 2.0,
        'gamma': 2.0,
        'c': 2.0,
        'd': 2.0,
        'm': 2.0,
        'alpha': 2.0,
    }
    tersoff_invalid_dicts = _make_invalid_param_dict(tersoff_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(tersoff_invalid_dicts, hoomd.md.many_body.Tersoff,
                             {}))

    square_density_valid_dict = {'A': 5.0, 'B': 2.0}
    sq_dens_invalid_dicts = _make_invalid_param_dict(square_density_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(sq_dens_invalid_dicts,
                             hoomd.md.many_body.SquareDensity, {}))

    revcross_valid_dict = {
        'sigma': 5.0,
        'n': 2.0,
        'epsilon': 2.0,
        'lambda3': 2.0
    }
    revcross_invalid_dicts = _make_invalid_param_dict(revcross_valid_dict)
    invalid_params_list.extend(
        _make_invalid_params(revcross_invalid_dicts,
                             hoomd.md.many_body.RevCross, {}))

    return invalid_params_list

@pytest.fixture(scope="function",
                params=_invalid_params(),
                ids=(lambda x: x[0].__name__))
def invalid_params(request):
    return deepcopy(request.param)

def test_invalid_params(invalid_params):
    pot = invalid_params.pair_potential(**invalid_params.extra_args,
                                        nlist=md.nlist.Cell())
    for pair in invalid_params.pair_potential_params:
        if isinstance(pair, tuple):
            with pytest.raises(TypeConversionError):
                pot.params[pair] = invalid_params.pair_potential_params[pair]

def test_invalid_pair_key():
    pot = md.pair.LJ(nlist=md.nlist.Cell())
    for invalid_key in [3, [1, 2], 'str']:
        with pytest.raises(KeyError):
            pot.r_cut[invalid_key] = 2.5

def _make_valid_param_dicts(arg_dict):
    """Unpack dictionary of lists of numbers into dictionary of numbers.

    Ex: turn {'a': [0, 1], 'b':[2, 3]} into [{'a': 0, 'b': 2}, {'a': 1, 'b': 3}]
    """
    return [dict(zip(arg_dict, val)) for val in zip(*arg_dict.values())]

def _valid_params(particle_types=['A', 'B']):
    valid_params_list = []
    combos = list(itertools.combinations_with_replacement(particle_types, 2))
    lj_arg_dict = {'sigma': [0.5, 1.0, 1.5], 'epsilon': [0.0005, 0.001, 0.0015]}
    lj_valid_param_dicts = _make_valid_param_dicts(lj_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.LJ, dict(zip(combos, lj_valid_param_dicts)), {}))

    gauss_arg_dict = {'epsilon': [0.025, 0.05, 0.075], 'sigma': [0.5, 1.0, 1.5]}
    gauss_valid_param_dicts = _make_valid_param_dicts(gauss_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.Gauss, dict(zip(combos, gauss_valid_param_dicts)),
                   {}))

    yukawa_arg_dict = {
        'epsilon': [0.00025, 0.0005, 0.00075],
        'kappa': [0.5, 1.0, 1.5]
    }
    yukawa_valid_param_dicts = _make_valid_param_dicts(yukawa_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.Yukawa, dict(zip(combos, yukawa_valid_param_dicts)),
                   {}))

    ewald_arg_dict = {"alpha": [0.025, 0.05, 0.075], "kappa": [0.5, 1.0, 1.5]}
    ewald_valid_param_dicts = _make_valid_param_dicts(ewald_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.Ewald, dict(zip(combos, ewald_valid_param_dicts)),
                   {}))

    morse_arg_dict = {
        "D0": [0.025, 0.05, 0.075],
        "alpha": [0.5, 1.0, 1.5],
        "r0": [0, 0.05, 0.1]
    }
    morse_valid_param_dicts = _make_valid_param_dicts(morse_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.Morse, dict(zip(combos, morse_valid_param_dicts)),
                   {}))

    dpd_conservative_arg_dict = {"A": [0.025, 0.05, 0.075]}
    dpd_conservative_valid_param_dicts = _make_valid_param_dicts(
        dpd_conservative_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.DPDConservative,
                   dict(zip(combos, dpd_conservative_valid_param_dicts)), {}))

    force_shifted_LJ_arg_dict = {
        'sigma': [0.5, 1.0, 1.5],
        'epsilon': [0.0005, 0.001, 0.0015]
    }
    force_shifted_LJ_valid_param_dicts = _make_valid_param_dicts(
        force_shifted_LJ_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.ForceShiftedLJ,
                   dict(zip(combos, force_shifted_LJ_valid_param_dicts)), {}))

    moliere_arg_dict = {
        'qi': [2.5, 7.5, 15],
        'qj': [2, 6, 12],
        'aF': [.134197, .234463, .319536]
    }
    moliere_valid_param_dicts = _make_valid_param_dicts(moliere_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.Moliere, dict(zip(combos,
                                             moliere_valid_param_dicts)), {}))

    zbl_arg_dict = {
        'qi': [2.5, 7.5, 15],
        'qj': [2, 6, 12],
        'aF': [.133669, .243535, .341914]
    }
    zbl_valid_param_dicts = _make_valid_param_dicts(zbl_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.ZBL, dict(zip(combos, zbl_valid_param_dicts)), {}))

    mie_arg_dict = {
        'epsilon': [.05, .025, .010],
        'sigma': [.5, 1, 1.5],
        'n': [12, 14, 16],
        'm': [6, 8, 10]
    }
    mie_valid_param_dicts = _make_valid_param_dicts(mie_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.Mie, dict(zip(combos, mie_valid_param_dicts)), {}))

    reactfield_arg_dict = {
        'epsilon': [.05, .025, .010],
        'eps_rf': [.5, 1, 1.5],
        'use_charge': [False, True, False]
    }
    reactfield_valid_param_dicts = _make_valid_param_dicts(reactfield_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.ReactionField,
                   dict(zip(combos, reactfield_valid_param_dicts)), {}))

    buckingham_arg_dict = {
        'A': [.05, .025, .010],
        'rho': [.5, 1, 1.5],
        'C': [.05, .025, .01]
    }
    buckingham_valid_param_dicts = _make_valid_param_dicts(buckingham_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.Buckingham,
                   dict(zip(combos, buckingham_valid_param_dicts)), {}))

    lj1208_arg_dict = {
        'sigma': [0.5, 1.0, 1.5],
        'epsilon': [0.0005, 0.001, 0.0015]
    }
    lj1208_valid_param_dicts = _make_valid_param_dicts(lj1208_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.LJ1208, dict(zip(combos, lj1208_valid_param_dicts)),
                   {}))

    fourier_arg_dict = {
        'a': [[0.5, 1.0, 1.5], [.05, .1, .15], [.005, .01, .015]],
        'b': [[0.25, 0.034, 0.76], [0.36, 0.12, 0.65], [0.78, 0.04, 0.98]]
    }
    fourier_valid_param_dicts = _make_valid_param_dicts(fourier_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.Fourier, dict(zip(combos,
                                             fourier_valid_param_dicts)), {}))

    slj_arg_dict = {
        'sigma': [0.5, 1.0, 1.5],
        'epsilon': [0.0005, 0.001, 0.0015]
    }
    slj_valid_param_dicts = _make_valid_param_dicts(slj_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.SLJ, dict(zip(combos, slj_valid_param_dicts)), {}))

    dpd_arg_dict = {'A': [0.5, 1.0, 1.5], 'gamma': [0.0005, 0.001, 0.0015]}
    dpd_valid_param_dicts = _make_valid_param_dicts(dpd_arg_dict)
    valid_params_list.append(
        paramtuple(md.pair.DPD, dict(zip(combos, dpd_valid_param_dicts)),
                   {"kT": 2}))

    dpdlj_arg_dict = {
        'sigma': [0.5, 1.0, 1.5],
        'epsilon': [0.0005, 0.001, 0.0015],
        'gamma': [0.034, 33.2, 1.2]
    }
    dpdlj_valid_param_dicts = _make_valid_param_dicts(dpdlj_arg_dict)

    valid_params_list.append(
        paramtuple(md.pair.DPDLJ, dict(zip(combos, dpdlj_valid_param_dicts)),
                   {"kT": 1}))

    dlvo_arg_dict = {
        'kappa': [1.0, 2.0, 5.0],
        'Z': [0.1, 0.5, 2.0],
        'A': [0.1, 0.5, 2.0]
    }
    dlvo_valid_param_dicts = _make_valid_param_dicts(dlvo_arg_dict)

    valid_params_list.append(
        paramtuple(md.pair.DLVO, dict(zip(combos, dlvo_valid_param_dicts)), {}))

    tersoff_arg_dict = {
        'cutoff_thickness': [0.1, 0.5, 1.0],
        'magnitudes': [(0.02, 0.01), (0.0, 0.005), (0.002, 0.003)],
        'exp_factors': [(0.1, 0.1), (0.05, 0.05), (-0.02, 0.04)],
        'lambda3': [0.0, 0.5, 0.3],
        'dimer_r': [1.0, 2.0, 1.2],
        'n': [0.3, 0.5, 0.7],
        'gamma': [0.1, 0.5, 0.4],
        'c': [0.1, 0.5, 2.0],
        'd': [0.1, 0.5, 2.0],
        'm': [0.1, 0.5, 2.0],
        'alpha': [0.1, 0.5, 2.0],
    }
    tersoff_valid_param_dicts = _make_valid_param_dicts(tersoff_arg_dict)
    valid_params_list.append(
        paramtuple(hoomd.md.many_body.Tersoff,
                   dict(zip(combos, tersoff_valid_param_dicts)), {}))

    square_density_arg_dict = {'A': [1.0, 2.0, 5.0], 'B': [0.1, 0.5, 2.0]}
    square_density_valid_param_dicts = _make_valid_param_dicts(
        square_density_arg_dict)
    valid_params_list.append(
        paramtuple(hoomd.md.many_body.SquareDensity,
                   dict(zip(combos, square_density_valid_param_dicts)), {}))

    revcross_arg_dict = {
        'sigma': [1.0, 2.0, 5.0],
        'n': [0.1, 0.5, 2.0],
        'epsilon': [0.1, 0.5, 2.0],
        'lambda3': [0.1, 0.5, 2.0],
    }
    revcross_valid_param_dicts = _make_valid_param_dicts(revcross_arg_dict)
    valid_params_list.append(
        paramtuple(hoomd.md.many_body.RevCross,
                   dict(zip(combos, revcross_valid_param_dicts)), {}))

    opp_arg_dict = {
        'C1': [1.0, 2.0, 5.0],
        'C2': [0.1, 0.5, 2.0],
        'eta1': [15.0, 12.0, 8.0],
        'eta2': [3.0, 2.0, 1.5],
        'k': [1.0, 2.0, 3.0],
        'phi': [0.0, 0.5, np.pi / 2]
    }
    opp_valid_param_dicts = _make_valid_param_dicts(opp_arg_dict)
    valid_params_list.append(
        paramtuple(hoomd.md.pair.OPP, dict(zip(combos, opp_valid_param_dicts)),
                   {}))

    expanded_mie_arg_dict = {
        'epsilon': [.05, .025, .010],
        'sigma': [.5, 1, 1.5],
        'n': [12, 14, 16],
        'm': [6, 8, 10],
        'delta': [.1, .2, .3]
    }
    expanded_mie_valid_param_dicts = _make_valid_param_dicts(
        expanded_mie_arg_dict)
    valid_params_list.append(
        paramtuple(hoomd.md.pair.ExpandedMie,
                   dict(zip(combos, expanded_mie_valid_param_dicts)), {}))

    twf_arg_dict = {
        'sigma': [0.1, 0.2, 0.5],
        'epsilon': [0.1, 0.5, 2.0],
        'alpha': [15.0, 12.0, 8.0]
    }
    twf_valid_param_dicts = _make_valid_param_dicts(twf_arg_dict)
    valid_params_list.append(
        paramtuple(hoomd.md.pair.TWF, dict(zip(combos, twf_valid_param_dicts)),
                   {}))

    rs = [
        np.arange(0, 2.6, 0.1),
        np.linspace(0.5, 2.5, 25),
        np.arange(0.8, 2.6, 0.1)
    ]
    Vs = [r[::-1] * 5 for r in rs]
    Fs = [-1 * np.diff(V) / np.diff(r) for V, r in zip(Vs, rs)]
    table_arg_dict = {
        'V': [V[:-1] for V in Vs],
        'F': Fs,
        'r_min': [r[0] for r in rs]
    }
    table_valid_param_dicts = _make_valid_param_dicts(table_arg_dict)
    valid_params_list.append(
        paramtuple(hoomd.md.pair.Table,
                   dict(zip(combos, table_valid_param_dicts)), {}))
    return valid_params_list

@pytest.fixture(scope="function",
                params=_valid_params(),
                ids=(lambda x: x[0].__name__))
def valid_params(request):
    return deepcopy(request.param)

def test_valid_params(valid_params):
    pot = valid_params.pair_potential(**valid_params.extra_args,
                                      nlist=md.nlist.Cell(),
                                      default_r_cut=2.5)
    for pair in valid_params.pair_potential_params:
        pot.params[pair] = valid_params.pair_potential_params[pair]
    assert _equivalent_data_structures(valid_params.pair_potential_params,
                                       pot.params.to_dict())

def _update_snap(pair_potential, snap):
    if (any(name in str(pair_potential) for name in ['Ewald'])
            and snap.communicator.rank == 0):
        snap.particles.charge[:] = 1.
    if 'SLJ' in str(pair_potential) and snap.communicator.rank == 0:
        snap.particles.diameter[:] = 2
    if 'DLVO' in str(pair_potential) and snap.communicator.rank == 0:
        snap.particles.diameter[0] = 0.2
        snap.particles.diameter[1] = 0.5

def _skip_if_triplet_gpu_mpi(sim, pair_potential):
    """Determines if the simulation is able to run this pair potential."""
    if (isinstance(sim.device, hoomd.device.GPU)
            and sim.device.communicator.num_ranks > 1
            and issubclass(pair_potential, hoomd.md.many_body.Triplet)):
        pytest.skip("Cannot run triplet potentials with GPU+MPI enabled")

def test_attached_params(simulation_factory, lattice_snapshot_factory,
                         valid_params):
    pair_potential, pair_potential_dict, extra_args = valid_params
    pair_keys = valid_params.pair_potential_params.keys()
    particle_types = list(set(itertools.chain.from_iterable(pair_keys)))
    pot = valid_params.pair_potential(**valid_params.extra_args,
                                      nlist=md.nlist.Cell(),
                                      default_r_cut=2.5)
    pot.params = valid_params.pair_potential_params

    snap = lattice_snapshot_factory(particle_types=particle_types,
                                    n=10,
                                    a=1.5,
                                    r=0.01)

    _update_snap(valid_params.pair_potential, snap)
    if snap.communicator.rank == 0:
        snap.particles.typeid[:] = np.random.randint(0,
                                                     len(snap.particles.types),
                                                     snap.particles.N)
    sim = simulation_factory(snap)
    _skip_if_triplet_gpu_mpi(sim, valid_params.pair_potential)
    sim.operations.integrator = hoomd.md.Integrator(dt=0.005)
    sim.operations.integrator.forces.append(pot)
    sim.run(1)
    assert _equivalent_data_structures(valid_params.pair_potential_params,
                                       pot.params.to_dict())

def test_run(simulation_factory, lattice_snapshot_factory, valid_params):
    pair_keys = valid_params.pair_potential_params.keys()
    particle_types = list(set(itertools.chain.from_iterable(pair_keys)))
    pot = valid_params.pair_potential(**valid_params.extra_args,
                                      nlist=md.nlist.Cell(),
                                      default_r_cut=2.5)
    pot.params = valid_params.pair_potential_params

    snap = lattice_snapshot_factory(particle_types=particle_types,
                                    n=7,
                                    a=1.7,
                                    r=0.01)
    if snap.communicator.rank == 0:
        snap.particles.typeid[:] = np.random.randint(0,
                                                     len(snap.particles.types),
                                                     snap.particles.N)
    sim = simulation_factory(snap)
    _skip_if_triplet_gpu_mpi(sim, valid_params.pair_potential)

    integrator = hoomd.md.Integrator(dt=0.005)
    integrator.forces.append(pot)
    integrator.methods.append(
        hoomd.md.methods.Langevin(hoomd.filter.All(), kT=1))
    sim.operations.integrator = integrator
    sim.operations._schedule()
    old_snap = sim.state.get_snapshot()
    sim.run(2)
    new_snap = sim.state.get_snapshot()
    if new_snap.communicator.rank == 0:
        assert not np.allclose(new_snap.particles.position,
                               old_snap.particles.position)

def test_energy_shifting(simulation_factory, two_particle_snapshot_factory):
    # A subtle bug existed where we used "shifted" instead of "shift" in Python
    # and in C++ we used else if clauses with no error raised if the set Python
    # mode fell through. This means the actual shift mode was not set.
    pytest.skip("Test is broken.")

    def S_r(r, r_cut, r_on):  # noqa: N802 - allow uppercase function name
        if r < r_on:
            return 1
        elif r > r_cut:
            return 0
        numerator = ((r_cut**2 - r**2)**2) * (r_cut**2 + 2 * r**2 - 3 * r_on**2)
        denominator = (r_cut**2 - r_on**2)**3
        return numerator / denominator

    r_cut = 2.5
    r_on = 0.5
    r = 1.0

    lj = md.pair.LJ(nlist=md.nlist.Cell(), default_r_cut=r_cut)
    lj.params[('A', 'A')] = {'sigma': 1, 'epsilon': 0.5}

    sim = simulation_factory(two_particle_snapshot_factory(dimensions=3, d=r))

    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(lj)
    integrator.methods.append(
        hoomd.md.methods.Langevin(hoomd.filter.All(), kT=1))
    sim.operations.integrator = integrator
    sim.run(0)

    energies = sim.operations.integrator.forces[0].energies
    if energies is not None:
        E_r = sum(energies)

    snap = sim.state.get_snapshot()
    if snap.communicator.rank == 0:
        snap.particles.position[0] = [0, 0, .1]
        snap.particles.position[1] = [0, 0, r_cut + .1]
    sim.state.set_snapshot(snap)
    energies = sim.operations.integrator.forces[0].energies
    if energies is not None:
        E_rcut = sum(energies)

    lj_shift = md.pair.LJ(nlist=md.nlist.Cell(),
                          mode='shift',
                          default_r_cut=r_cut)
    lj_shift.params[('A', 'A')] = {'sigma': 1, 'epsilon': 0.5}
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(lj_shift)
    integrator.methods.append(
        hoomd.md.methods.Langevin(hoomd.filter.All(), kT=1))
    sim.operations.integrator = integrator
    sim.run(0)

    snap = sim.state.get_snapshot()
    if snap.communicator.rank == 0:
        snap.particles.position[0] = [0, 0, .1]
        snap.particles.position[1] = [0, 0, r + .1]
    sim.state.set_snapshot(snap)

    energies = sim.operations.integrator.forces[0].energies
    if energies is not None:
        assert sum(energies) == E_r - E_rcut

    lj_xplor = md.pair.LJ(nlist=md.nlist.Cell(),
                          mode='xplor',
                          default_r_cut=r_cut)
    lj_xplor.params[('A', 'A')] = {'sigma': 1, 'epsilon': 0.5}
    lj_xplor.r_on[('A', 'A')] = 0.5
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(lj_xplor)
    integrator.methods.append(
        hoomd.md.methods.Langevin(hoomd.filter.All(), kT=1))

    sim.operations.integrator = integrator
    sim.run(0)

    energies = sim.operations.integrator.forces[0].energies
    if energies is not None:
        xplor_E = sum(energies)
        assert xplor_E == E_r * S_r(r, r_cut, r_on)

        lj_xplor.r_on[('A', 'A')] = 3.0
        assert sum(energies) == E_r - E_rcut

def _calculate_force(sim):
    """Calculate the forces in a two particle simulation frame.

    Finds the negative derivative of energy divided by inter-particle distance
    """
    dr = 1e-6

    snap = sim.state.get_snapshot()
    if snap.communicator.rank == 0:
        initial_pos = np.array(snap.particles.position)
        snap.particles.position[1, 0] = initial_pos[1, 0] - dr

    sim.state.set_snapshot(snap)
    E0 = sim.operations.integrator.forces[0].energies
    snap = sim.state.get_snapshot()
    if snap.communicator.rank == 0:
        pos = snap.particles.position
        r0 = pos[0] - pos[1]
        mag_r0 = np.linalg.norm(r0)
        direction = r0 / mag_r0

        snap.particles.position[1, 0] = initial_pos[1, 0] + dr

    sim.state.set_snapshot(snap)
    E1 = sim.operations.integrator.forces[0].energies

    snap = sim.state.get_snapshot()
    if snap.communicator.rank == 0:
        pos = snap.particles.position
        mag_r1 = np.linalg.norm(pos[0] - pos[1])
        Fa = -1 * ((sum(E1) - sum(E0)) / (mag_r1 - mag_r0)) * direction
        Fb = -Fa

    snap = sim.state.get_snapshot()
    if snap.communicator.rank == 0:
        snap.particles.position[1] = initial_pos[1]
    sim.state.set_snapshot(snap)
    if sim.state.get_snapshot().communicator.rank == 0:
        return Fa, Fb
    else:
        return 0, 0  # return dummy values if not on rank 1

def test_force_energy_relationship(simulation_factory,
                                   two_particle_snapshot_factory, valid_params):
    # don't really test DPD and DPDLJ for this test
    pot_name = valid_params.pair_potential.__name__
    if any(pot_name == name for name in ["DPD", "DPDLJ"]):
        pytest.skip("Cannot test force energy relationship for " + pot_name
                    + " pair force")

    pair_keys = valid_params.pair_potential_params.keys()
    particle_types = list(set(itertools.chain.from_iterable(pair_keys)))
    pot = valid_params.pair_potential(**valid_params.extra_args,
                                      nlist=md.nlist.Cell(),
                                      default_r_cut=2.5)
    for pair in valid_params.pair_potential_params:
        pot.params[pair] = valid_params.pair_potential_params[pair]

    snap = two_particle_snapshot_factory(particle_types=particle_types, d=1.5)
    _update_snap(valid_params.pair_potential, snap)
    sim = simulation_factory(snap)
    _skip_if_triplet_gpu_mpi(sim, valid_params.pair_potential)
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(pot)
    integrator.methods.append(
        hoomd.md.methods.Langevin(hoomd.filter.All(), kT=1))
    sim.operations.integrator = integrator
    sim.run(0)
    for pair in valid_params.pair_potential_params:
        snap = sim.state.get_snapshot()
        if snap.communicator.rank == 0:
            snap.particles.typeid[0] = particle_types.index(pair[0])
            snap.particles.typeid[1] = particle_types.index(pair[1])
        sim.state.set_snapshot(snap)

        calculated_forces = _calculate_force(sim)
        sim_forces = sim.operations.integrator.forces[0].forces
        if sim_forces is not None:
            np.testing.assert_allclose(calculated_forces[0],
                                       sim_forces[0],
                                       rtol=1e-05)
            np.testing.assert_allclose(calculated_forces[1],
                                       sim_forces[1],
                                       rtol=1e-05)

def _forces_and_energies():
    """Return reference force and energy values.

    Reference force and energy values were calculated using Mathematica 12.1.1
    and then stored in the json file below. Values were calculated at
    distances of 0.75 and 1.5 for each argument dictionary
    """
    FEtuple = namedtuple('FEtuple', [
        'pair_potential', 'pair_potential_params', 'extra_args', 'forces',
        'energies'
    ])

    path = Path(__file__).parent / "forces_and_energies.json"

    def json_with_inf(val):
        if isinstance(val, str):
            if val.lower() == "infinity":
                return np.inf
            elif val.lower() == "neg_infinity":
                return -np.inf
        else:
            return val

    with path.open() as f:
        F_and_E = json.load(f)
        param_list = []
        for pot in F_and_E.keys():
            if pot[0].isalpha():
                kT_dict = {'DPD': {'kT': 2}, 'DPDLJ': {'kT': 1}}.get(pot, {})
                for i in range(3):
                    param_list.append(
                        FEtuple(getattr(md.pair, pot),
                                F_and_E[pot]["params"][i], kT_dict, [
                                    json_with_inf(v)
                                    for v in F_and_E[pot]["forces"][i]
                                ], [
                                    json_with_inf(v)
                                    for v in F_and_E[pot]["energies"][i]
                                ]))
    return param_list

def isclose(value, reference, rtol=5e-6):
    """Return if two values are close while automatically managing atol."""
    if isinstance(reference, (Sequence, np.ndarray)):
        ref = np.asarray(reference, np.float64)
        val = np.asarray(reference, np.float64)
        min_value = np.min(np.abs(reference))
        atol = 1e-6 if min_value == 0 else min_value / 1e4
        return np.allclose(val, ref, rtol=rtol, atol=atol, equal_nan=True)
    else:
        atol = 1e-6 if reference == 0 else 0
        return math.isclose(value, reference, rel_tol=rtol, abs_tol=atol)

# We ignore this warning raise by NumPy so we can test the use of infinity in
# some pair potentials currently TWF. This is used when the force from the JSON
# file needs to be multipled by r to compare with the computed force of the
# simulation.
@pytest.mark.filterwarnings("ignore:invalid value encountered in multiply")
@pytest.mark.parametrize("forces_and_energies",
                         _forces_and_energies(),
                         ids=lambda x: x.pair_potential.__name__)
def test_force_energy_accuracy(simulation_factory,
                               two_particle_snapshot_factory,
                               forces_and_energies):
    pot_name = forces_and_energies.pair_potential.__name__
    if pot_name == "DPD" or pot_name == "DPDLJ":
        pytest.skip("Cannot test force energy accuracy for " + pot_name
                    + " pair force")

    pot = forces_and_energies.pair_potential(**forces_and_energies.extra_args,
                                             nlist=md.nlist.Cell(),
                                             default_r_cut=2.5)
    pot.params[('A', 'A')] = forces_and_energies.pair_potential_params
    snap = two_particle_snapshot_factory(particle_types=['A'], d=0.75)
    _update_snap(forces_and_energies.pair_potential, snap)
    sim = simulation_factory(snap)
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(pot)
    integrator.methods.append(
        hoomd.md.methods.Langevin(hoomd.filter.All(), kT=1))
    sim.operations.integrator = integrator
    sim.run(0)
    particle_distances = [0.75, 1.5]
    for i in range(len(particle_distances)):
        d = particle_distances[i]
        r = np.array([0, 0, d]) / d
        snap = sim.state.get_snapshot()
        if snap.communicator.rank == 0:
            snap.particles.position[0] = [0, 0, .1]
            snap.particles.position[1] = [0, 0, d + .1]
        sim.state.set_snapshot(snap)
        sim_energies = sim.operations.integrator.forces[0].energies
        sim_forces = sim.operations.integrator.forces[0].forces
        if sim_energies is not None:
            assert isclose(sum(sim_energies), forces_and_energies.energies[i])
            assert isclose(sim_forces[0], forces_and_energies.forces[i] * r)
            assert isclose(sim_forces[0], -forces_and_energies.forces[i] * r)

def populate_sim(sim):
    """Add an integrator for the following tests."""
    sim.operations.integrator = md.Integrator(
        dt=0.005, methods=[md.methods.NVE(hoomd.filter.All())])
    return sim

def test_setting_to_new_sim(simulation_factory, two_particle_snapshot_factory):
    """Test that pair force can only below to one integrator."""
    sim1 = populate_sim(simulation_factory(two_particle_snapshot_factory()))
    sim2 = populate_sim(simulation_factory(two_particle_snapshot_factory()))

    nlist = md.nlist.Cell()
    lj = md.pair.LJ(nlist, default_r_cut=1.1)
    lj.params[("A", "A")] = {"sigma": 0.5, "epsilon": 1.0}
    sim1.operations.integrator.forces.append(lj)

    # Test cannot add to new integrator
    with pytest.raises(RuntimeError):
        sim2.operations.integrator.forces.append(lj)

    # Ensure that removing and appending works
    sim1.operations.integrator.forces.remove(lj)
    sim2.operations.integrator.forces.append(lj)
    sim2.run(0)
    # Ensure that when attached cannot add to new integrator
    with pytest.raises(RuntimeError):
        sim1.operations.integrator.forces.append(lj)

    # Test that correct removal with a necessary nlist copy properly warns but
    # does not error.
    lj2 = md.pair.LJ(nlist, default_r_cut=1.1)
    lj2.params[("A", "A")] = {"sigma": 0.5, "epsilon": 1.0}
    sim2.operations.integrator.forces.append(lj2)
    sim2.operations.integrator.forces.remove(lj)
    with pytest.warns(RuntimeWarning):
        sim1.operations.integrator.forces.append(lj)

def test_setting_nlist(simulation_factory, two_particle_snapshot_factory):
    """Test neighbor list cannot be spread between multiple simulations."""
    sim1 = populate_sim(simulation_factory(two_particle_snapshot_factory()))
    sim2 = populate_sim(simulation_factory(two_particle_snapshot_factory()))

    nlist = md.nlist.Cell()
    lj = md.pair.LJ(nlist, default_r_cut=1.1)
    lj.params[("A", "A")] = {"sigma": 0.5, "epsilon": 1.0}
    lj2 = deepcopy(lj)
    sim1.operations.integrator.forces.append(lj)
    sim2.operations.integrator.forces.append(lj2)
    with pytest.raises(RuntimeError):
        lj2.nlist = nlist
    sim2.operations.integrator.forces.remove(lj2)
    lj2.nlist = nlist
    with pytest.raises(RuntimeError):
        sim2.operations.integrator.forces.append(lj2)

# Test logging
@pytest.mark.parametrize(
    'cls, expected_namespace, expected_loggables',
    zip((md.pair.Pair, md.pair.aniso.AnisotropicPair, md.many_body.Triplet),
        (('md', 'pair'), ('md', 'pair', 'aniso'), ('md', 'many_body')),
        itertools.repeat({
            'energy': {
                'category': LoggerCategories.scalar,
                'default': True
            },
            'energies': {
                'category': LoggerCategories.particle,
                'default': True
            },
            'forces': {
                'category': LoggerCategories.particle,
                'default': True
            },
            'torques': {
                'category': LoggerCategories.particle,
                'default': True
            },
            'virials': {
                'category': LoggerCategories.particle,
                'default': True
            },
        })))
def test_logging(cls, expected_namespace, expected_loggables):
    logging_check(cls, expected_namespace, expected_loggables)

def test_pickling(simulation_factory, two_particle_snapshot_factory,
                  valid_params):
    sim = simulation_factory(two_particle_snapshot_factory())
    _skip_if_triplet_gpu_mpi(sim, valid_params.pair_potential)
    pot = valid_params.pair_potential(**valid_params.extra_args,
                                      nlist=md.nlist.Cell(),
                                      default_r_cut=2.5)
    for pair in valid_params.pair_potential_params:
        pot.params[pair] = valid_params.pair_potential_params[pair]
    pickling_check(pot)
    integrator = hoomd.md.Integrator(0.05, forces=[pot])
    sim.operations.integrator = integrator
    sim.run(0)
    pickling_check(pot)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

001
017package org.apache.lucene.demo.facet;
018
019import java.io.IOException;
020import java.text.ParseException;
021
022import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
023import org.apache.lucene.document.Document;
024import org.apache.lucene.document.Field.Store;
025import org.apache.lucene.document.NumericDocValuesField;
026import org.apache.lucene.document.TextField;
027import org.apache.lucene.expressions.Expression;
028import org.apache.lucene.expressions.SimpleBindings;
029import org.apache.lucene.expressions.js.JavascriptCompiler;
030import org.apache.lucene.facet.FacetField;
031import org.apache.lucene.facet.FacetResult;
032import org.apache.lucene.facet.Facets;
033import org.apache.lucene.facet.FacetsCollector;
034import org.apache.lucene.facet.FacetsConfig;
035import org.apache.lucene.facet.taxonomy.TaxonomyFacetSumValueSource;
036import org.apache.lucene.facet.taxonomy.TaxonomyReader;
037import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
038import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyWriter;
039import org.apache.lucene.index.DirectoryReader;
040import org.apache.lucene.index.IndexWriter;
041import org.apache.lucene.index.IndexWriterConfig;
042import org.apache.lucene.index.IndexWriterConfig.OpenMode;
043import org.apache.lucene.search.IndexSearcher;
044import org.apache.lucene.search.MatchAllDocsQuery;
045import org.apache.lucene.search.SortField;
046import org.apache.lucene.store.Directory;
047import org.apache.lucene.store.RAMDirectory;
048
049
050/** Shows facets aggregation by an expression. */
051public class ExpressionAggregationFacetsExample {
052
053  private final Directory indexDir = new RAMDirectory();
054  private final Directory taxoDir = new RAMDirectory();
055  private final FacetsConfig config = new FacetsConfig();
056
057  /** Empty constructor */
058  public ExpressionAggregationFacetsExample() {}
059
060  /** Build the example index. */
061  private void index() throws IOException {
062    IndexWriter indexWriter = new IndexWriter(indexDir, new IndexWriterConfig(
063        new WhitespaceAnalyzer()).setOpenMode(OpenMode.CREATE));
064
065    // Writes facet ords to a separate directory from the main index
066    DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir);
067
068    Document doc = new Document();
069    doc.add(new TextField("c", "foo bar", Store.NO));
070    doc.add(new NumericDocValuesField("popularity", 5L));
071    doc.add(new FacetField("A", "B"));
072    indexWriter.addDocument(config.build(taxoWriter, doc));
073
074    doc = new Document();
075    doc.add(new TextField("c", "foo foo bar", Store.NO));
076    doc.add(new NumericDocValuesField("popularity", 3L));
077    doc.add(new FacetField("A", "C"));
078    indexWriter.addDocument(config.build(taxoWriter, doc));
079
080    indexWriter.close();
081    taxoWriter.close();
082  }
083
084  /** User runs a query and aggregates facets. */
085  private FacetResult search() throws IOException, ParseException {
086    DirectoryReader indexReader = DirectoryReader.open(indexDir);
087    IndexSearcher searcher = new IndexSearcher(indexReader);
088    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir);
089
090    // Aggregate categories by an expression that combines the document's score
091    // and its popularity field
092    Expression expr = JavascriptCompiler.compile("_score * sqrt(popularity)");
093    SimpleBindings bindings = new SimpleBindings();
094    bindings.add(new SortField("_score", SortField.Type.SCORE)); // the score of the document
095    bindings.add(new SortField("popularity", SortField.Type.LONG)); // the value of the 'popularity' field
096
097    // Aggregates the facet values
098    FacetsCollector fc = new FacetsCollector(true);
099
100    // MatchAllDocsQuery is for "browsing" (counts facets
101    // for all non-deleted docs in the index); normally
102    // you'd use a "normal" query:
103    FacetsCollector.search(searcher, new MatchAllDocsQuery(), 10, fc);
104
105    // Retrieve results
106    Facets facets = new TaxonomyFacetSumValueSource(taxoReader, config, fc, expr.getValueSource(bindings));
107    FacetResult result = facets.getTopChildren(10, "A");
108
109    indexReader.close();
110    taxoReader.close();
111
112    return result;
113  }
114
115  /** Runs the search example. */
116  public FacetResult runSearch() throws IOException, ParseException {
117    index();
118    return search();
119  }
120
121  /** Runs the search and drill-down examples and prints the results. */
122  public static void main(String[] args) throws Exception {
123    System.out.println("Facet counting example:");
124    System.out.println("-----------------------");
125    FacetResult result = new ExpressionAggregationFacetsExample().runSearch();
126    System.out.println(result);
127  }
128}


text:
package com.microsoft.azure.management.apimanagement.v2019_01_01;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Properties of server X509Names.
 */
public class X509CertificateName {
    /**
     * Common Name of the Certificate.
     */
    @JsonProperty(value = "name")
    private String name;

    /**
     * Thumbprint for the Issuer of the Certificate.
     */
    @JsonProperty(value = "issuerCertificateThumbprint")
    private String issuerCertificateThumbprint;

    /**
     * Get common Name of the Certificate.
     *
     * @return the name value
     */
    public String name() {
        return this.name;
    }

    /**
     * Set common Name of the Certificate.
     *
     * @param name the name value to set
     * @return the X509CertificateName object itself.
     */
    public X509CertificateName withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get thumbprint for the Issuer of the Certificate.
     *
     * @return the issuerCertificateThumbprint value
     */
    public String issuerCertificateThumbprint() {
        return this.issuerCertificateThumbprint;
    }

    /**
     * Set thumbprint for the Issuer of the Certificate.
     *
     * @param issuerCertificateThumbprint the issuerCertificateThumbprint value to set
     * @return the X509CertificateName object itself.
     */
    public X509CertificateName withIssuerCertificateThumbprint(String issuerCertificateThumbprint) {
        this.issuerCertificateThumbprint = issuerCertificateThumbprint;
        return this;
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Returns an array with the supported keysizes of the opened algorithm</title>

mcrypt_enc_get_modes_name

mcrypt_enc_is_block_algorithm_mode

Mcrypt Functions

PHP Manual

mcrypt_enc_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_enc_get_supported_key_sizes — Returns an array with the supported keysizes of the opened algorithm

Description

   array mcrypt_enc_get_supported_key_sizes
    ( resource $td
   )

   Gets the supported key sizes of the opened algorithm.

Parameters

td

       The encryption descriptor.

Return Values

   Returns an array with the key sizes supported by the algorithm
   specified by the encryption descriptor. If it returns an empty
   array then all key sizes between 1 and
   mcrypt_enc_get_key_size() are supported by the
   algorithm.

Examples

Example #1 mcrypt_enc_get_supported_key_sizes() example

<?php
    $td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
    var_dump(mcrypt_enc_get_supported_key_sizes($td));
?>

The above example will output:

array(3) {
  [0]=>
  int(16)
  [1]=>
  int(24)
  [2]=>
  int(32)
}

mcrypt_enc_get_modes_name

mcrypt_enc_is_block_algorithm_mode

Mcrypt Functions

PHP Manual


text:
@Version("2.14.0")
package org.apache.jackrabbit.vault.fs.io;

import org.osgi.annotation.versioning.Version;


text:
function PieChart(){
	this.gameEngine;
	this.data;
	this.dataProcessed;
	this.dataPointsOne=[];
	this.dataPointsTwo=[];
	this.colors;
	this.center;
	this.radius;
	this.lastPosition = 0;
	this.dataTotal = 0;

	this.init = function(e){
		this.gameEngine = e;
		this.data = [75,68,32,95,20,51];
		this.colors = ["#7E3817", "#C35817", "#EE9A4D", "#A0C544", "#348017", "#307D7E"];
		this.center = [this.gameEngine.getDisplayWidth() / 2, this.gameEngine.getDisplayHeight() / 2];
		this.radius = Math.min(this.gameEngine.getDisplayWidth(), this.gameEngine.getDisplayHeight()) / 2;
		for(var i=0;i<this.data.length;i++){
			this.dataTotal += this.data[i];
		}
		for(var i=0;i<this.data.length;i++){
			this.dataProcessed=Math.PI*2*(this.data[i]/this.dataTotal);
			this.dataPointsOne.push(this.lastPosition);
			this.dataPointsTwo.push(this.lastPosition+this.dataProcessed);
			this.lastPosition += this.dataProcessed;
		}
	}

	this.input = function(keyDown,keyPress,KeyUp){
		if(keyDown.indexOf(19)>-1){//pause button
			console.log("pause button");
			this.gameEngine.addEvent({name:"GameEngine",message:"pause"});
		}
	}

	this.EventLisener = function(e){
		var pointEvent = this.gameEngine.getEventInStack("point",true);
		if(pointEvent){
			if(pointEvent.player==1){
				this.playerOneScore++;
			}else{
				this.playerTwoScore++;
			}
		}
	}

	this.draw = function(g){
		for (var i = 0; i < this.data.length; i++) {
			g.fillText(i+"="+this.data[i],this.gameEngine.getDisplayWidth()-30,9*i);
			g.fillStyle = this.colors[i];
			g.beginPath();
			g.moveTo(this.center[0],this.center[1]);
			g.arc(this.center[0],this.center[1],this.radius,this.dataPointsOne[i],this.dataPointsTwo[i],false);
			g.lineTo(this.center[0],this.center[1]);
			g.fill();
			g.strokeStyle="black";
			g.stroke();
		}
	}

}


text:
#pragma once

#include <cc7/Platform.h>

namespace cc7
{
namespace tests
{
namespace detail
{
	/**
	 The UnitTestFactoryFunction is a type for factory function, responsible
	 for creation of instance of one particular test.

	 This is an internal type and should not be used outside of the cc7tests
	 library.
	 */
	typedef UnitTest* (*UnitTestFactoryFunction)();

	/**
	 The UnitTestDescriptor structure keeps information about one particular
	 unit test. The type is internal and should not be used outside of the
	 cc7tests library.
	 */
	struct UnitTestDescriptor
	{
		UnitTestFactoryFunction		factory;
		const char *				name;
		const char *				tags;
	};

} // cc7::tests::detail
} // cc7::tests
} // cc7


text:
			Posted on

			by


text:
if [[ -e testoutput.log ]]; then
	rm testoutput.log
fi
touch testoutput.log
echo "Starting test run at `date`."
for f in test/*; do
	echo $f : test started.
	halo $f >> testoutput.log
	ret=$?
	# echo $ret
	if [[ $ret != 0 ]]; then
		echo $f : test failed. Error code = $ret.
	else
		echo $f : test succeeded.
	fi
done
echo "Ending test run at `date`."


text:
/** Helios Development Group LLC, 2013 */
package com.heliosapm.utils.unsafe.collections;

import java.nio.LongBuffer;

/**
 *
Title: ILongSlidingWindow

 *
Description:

 *
Company: Helios Development Group LLC

 * @author Whitehead (nwhitehead AT heliosdev DOT org)
 *
org.helios.apmrouter.collections.ILongSlidingWindow

 */

public interface ILongSlidingWindow {

	/**
	 * Inserts the each passed value into the first slot position in the array dropping the values in the last slot to make room if required
	 * @param values The values to insert
	 */
	public abstract void insert(long... values);

	public abstract void insert(LongBuffer longBuff);

	/**
	 * Inserts the passed value into the first slot of the array, moving all other other populated slots to the right.
	 * @param value The value to insert
	 * @return The dropped value if one was dropped, otherwise null
	 */
	public abstract Long insert(long value);

	/**
	 * Increments the value at the specified index by the passed amount
	 * @param index The index to update at
	 * @param value The amount to increment by
	 * @return The new value
	 */
	public abstract long inc(int index, long value);

	/**
	 * Increments the value at the specified index by 1
	 * @param index The index to update at
	 * @return The new value
	 */
	public abstract long inc(int index);

	/**
	 * Increments the value of the 0th index by the passed amount
	 * @param value The amount to increment by
	 * @return The new value
	 */
	public abstract long inc(long value);

	/**
	 * Increments the value of the 0th index by 1
	 * @return The new value
	 */
	public abstract long inc();

	/**
	 * Attempts to locate the index of the passed value
	 * @param value The value to search for
	 * @return the index of the located value, which will be negative if not found
	 */
	public abstract int find(long value);

	/**
	 * Sets the value of the 0th index to the passed value
	 * @param value The value to set to
	 */
	public abstract void set(long value);

	/**
	 * Returns this array as an array of doubles
	 * @return an array of doubles
	 */
	public abstract double[] asDoubleArray();

	/**
	 * Loads this window from a byte array
	 * @param arr the byte array
	 */
	public abstract void load(byte[] arr);

	public abstract void reinitAndLoad(byte[] arr);

	/**
	 * Removes all the values from this array, keeping the capacity fixed.
	 */
	public abstract void clear();

	/**
	 * Indicates if this set is empty
	 * @return true if this set is empty, false otherwise
	 */
	public abstract boolean isEmpty();

	/**
	 * {@inheritDoc}
	 * @see java.lang.Object#toString()
	 */
	public abstract String toString();

	/**
	 * Returns the long value at the specified array index
	 * @param index the index of the value to retrieve
	 * @return the long value at the specified array index
	 */
	public abstract long get(int index);

	/**
	 * Returns the number of entries in the array
	 * @return the number of entries in the array
	 */
	public abstract int size();

	/**
	 * Returns the sum of all the longs in the array within the passed ending index range
	 * @param within The index of the last entry to sum
	 * @return the sum of all the longs in the array
	 */
	public abstract long sum(int within);

	/**
	 * Returns the sum of all the longs in the array
	 * @return the sum of all the longs in the array
	 */
	public abstract long sum();

	/**
	 * Returns the minumum value in the array
	 * @return the minumum value in the array
	 */
	public abstract long min();

	/**
	 * Returns the maxumum value in the array
	 * @return the maxumum value in the array
	 */
	public abstract long max();

	/**
	 * Returns the average of all the longs in the array within the passed ending index range
	 * @param within The index of the last entry to average
	 * @return the average of all the longs in the array
	 */
	public abstract long avg(int within);

	/**
	 * Returns the average of all the longs in the array
	 * @return the average of all the longs in the array
	 */
	public abstract long avg();

}


text:
from google.cloud import bigquery
from google.cloud import bigquery_v2

def test_create_routine(capsys, random_routine_id):
    from .. import create_routine

    create_routine.create_routine(random_routine_id)
    out, err = capsys.readouterr()
    assert "Created routine {}".format(random_routine_id) in out

def test_create_routine_ddl(capsys, random_routine_id, client):
    from .. import create_routine_ddl

    create_routine_ddl.create_routine_ddl(random_routine_id)
    routine = client.get_routine(random_routine_id)
    out, err = capsys.readouterr()

    assert "Created routine {}".format(random_routine_id) in out
    return routine
    assert routine.type_ == "SCALAR_FUNCTION"
    assert routine.language == "SQL"
    expected_arguments = [
        bigquery.RoutineArgument(
            name="arr",
            data_type=bigquery_v2.types.StandardSqlDataType(
                type_kind=bigquery_v2.enums.StandardSqlDataType.TypeKind.ARRAY,
                array_element_type=bigquery_v2.types.StandardSqlDataType(
                    type_kind=bigquery_v2.enums.StandardSqlDataType.TypeKind.STRUCT,
                    struct_type=bigquery_v2.types.StandardSqlStructType(
                        fields=[
                            bigquery_v2.types.StandardSqlField(
                                name="name",
                                type=bigquery_v2.types.StandardSqlDataType(
                                    type_kind=bigquery_v2.enums.StandardSqlDataType.TypeKind.STRING
                                ),
                            ),
                            bigquery_v2.types.StandardSqlField(
                                name="val",
                                type=bigquery_v2.types.StandardSqlDataType(
                                    type_kind=bigquery_v2.enums.StandardSqlDataType.TypeKind.INT64
                                ),
                            ),
                        ]
                    ),
                ),
            ),
        )
    ]
    assert routine.arguments == expected_arguments

def test_list_routines(capsys, dataset_id, routine_id):
    from .. import list_routines

    list_routines.list_routines(dataset_id)
    out, err = capsys.readouterr()
    assert "Routines contained in dataset {}:".format(dataset_id) in out
    assert routine_id in out

def test_get_routine(capsys, routine_id):
    from .. import get_routine

    get_routine.get_routine(routine_id)
    out, err = capsys.readouterr()
    assert "Routine '{}':".format(routine_id) in out
    assert "Type: 'SCALAR_FUNCTION'" in out
    assert "Language: 'SQL'" in out
    assert "Name: 'x'" in out
    assert "Type: 'type_kind: INT64\n'" in out

def test_delete_routine(capsys, routine_id):
    from .. import delete_routine

    delete_routine.delete_routine(routine_id)
    out, err = capsys.readouterr()
    assert "Deleted routine {}.".format(routine_id) in out

def test_update_routine(routine_id):
    from .. import update_routine

    routine = update_routine.update_routine(routine_id)
    assert routine.body == "x * 4"


text:
#ifndef ROUTING_ROUTINGALGORITHM_H_
#define ROUTING_ROUTINGALGORITHM_H_

#include <prim/prim.h>
#include <json/json.h>

#include <string>
#include <utility>
#include <vector>

#include "event/Component.h"
#include "types/Flit.h"

class Router;

#define ROUTINGALGORITHM_ARGS const std::string&, const Component*, Router*, \
    u32, u32, u32, u32, Json::Value

class RoutingAlgorithm : public Component {
 public:
  /*
   * This class defines a routing algorithm response. This will be given to the
   *  routing algorithm upon routing request by the client. It is also returned
   *  to the client by the routing algorithm.
   */
  class Response {
   public:
    Response();
    ~Response();
    void clear();
    void add(u32 _port, u32 _vc);
    u32 size() const;
    void get(u32 _index, u32* _port, u32* _vc) const;
    void link(const RoutingAlgorithm* _algorithm);

   private:
    std::vector<std::pair<u32, u32> > response_;
    const RoutingAlgorithm* algorithm_;
  };

  /*
   * This class defines the interface required to interact with a
   *  RoutingAlgorithm. Clients will receive a call from the RoutingAlgorithm
   *  using the routingAlgorithmResponse() function.
   */
  class Client {
   public:
    Client();
    virtual ~Client();
    virtual void routingAlgorithmResponse(Response* _response) = 0;
  };

  /*
   * This defines the RoutingAlgorithm interface. Specific implementations
   *  must override the processRequest() function.
   *
   *  Note: inputPort and inputVc just state where this routing algorithm
   *   attaches to. For either of these settings that don't make sense, use
   *   U32_MAX to signify that.
   */
  RoutingAlgorithm(const std::string& _name, const Component* _parent,
                   Router* _router, u32 _baseVc, u32 _numVcs, u32 _inputPort,
                   u32 _inputVc, Json::Value _settings);
  virtual ~RoutingAlgorithm();
  u32 latency() const;
  u32 baseVc() const;
  u32 numVcs() const;
  u32 inputPort() const;
  u32 inputVc() const;
  void request(Client* _client, Flit* _flit, Response* _response);
  virtual void vcScheduled(Flit* _flit, u32 _port, u32 _vc);
  void processEvent(void* _event, s32 _type) override;

 protected:
  virtual void processRequest(Flit* _flit, Response* _response) = 0;

  Router* router_;
  const u32 baseVc_;
  const u32 numVcs_;
  const u32 inputPort_;
  const u32 inputVc_;

 private:
  class EventPackage {
   public:
    Client* client;
    Flit* flit;
    Response* response;
  };

  const u32 latency_;
};

#endif  // ROUTING_ROUTINGALGORITHM_H_


text:
'use strict';

var d3 = require('d3');
var Color = require('../../components/color');
var Drawing = require('../../components/drawing');
var Colorscale = require('../../components/colorscale');

module.exports = function style(gd, calcTrace) {
    if(calcTrace) styleTrace(gd, calcTrace);
};

function styleTrace(gd, calcTrace) {
    var trace = calcTrace[0].trace;
    var s = calcTrace[0].node3;
    var locs = s.selectAll('.choroplethlocation');
    var marker = trace.marker || {};
    var markerLine = marker.line || {};

    var sclFunc = Colorscale.makeColorScaleFunc(
        Colorscale.extractScale(
            trace.colorscale,
            trace.zmin,
            trace.zmax
        )
    );

    locs.each(function(d) {
        d3.select(this)
            .attr('fill', sclFunc(d.z))
            .call(Color.stroke, d.mlc || markerLine.color)
            .call(Drawing.dashLine, '', d.mlw || markerLine.width || 0)
            .style('opacity', marker.opacity);
    });

    Drawing.selectedPointStyle(locs, trace);
}


text:
class C {
    [Symbol.toPrimitive] = "";
}

//// [symbolDeclarationEmit2.js]
class C {
    constructor() {
        this[Symbol.toPrimitive] = "";
    }
}

//// [symbolDeclarationEmit2.d.ts]
declare class C {
    [Symbol.toPrimitive]: string;
}


text:
using System;
using System.Runtime.InteropServices;
using System.Windows;
using WickedSick.Thea.ViewModels;

namespace WickedSick.Thea
{
    public partial class App : Application
    {
        public void Initialize()
        {
            App.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
            try
            {
                var vm = new MainViewModel();
                App.Current.MainWindow.DataContext = vm;
                vm.Load();
            }
            catch (Exception)
            {
                //logger.Error("Failed to load Update Manager", ex);
                //MessageBox.Show("Update Manager failed to load properly: " + ex.Message, "Failed to load", MessageBoxButton.OK, MessageBoxImage.Error);
                App.Current.Shutdown();
            }
        }

        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            if (e.Exception is COMException)
            {
                e.Handled = true;
                var vm = App.Current.MainWindow.DataContext as MainViewModel;
                vm.Load();
            }
        }

        public void CleanUp(object dataContext)
        {
            (dataContext as MainViewModel).Dispose();
        }
    }
}


text:
title: Fred Sauer speaks at JBoss World
author: hbraun
layout: post
permalink: /2009/09/fred-sauer-speaks-at-jboss-world/
blogger_blog:
  - relative-order.blogspot.com
blogger_author:
  -
blogger_permalink:
  - /2009/09/fred-sauer-speaks-at-jboss-world.html
categories:
  - Uncategorized
---
Sildes can be found [here…][1]

 [1]: http://fredsa.allen-sauer.com/2009/09/gwt-for-enterprise-developer-jboss.html


text:
require 'protobuf'

module Google
  module Protobuf
    ::Protobuf::Optionable.inject(self) { ::Google::Protobuf::FileOptions }

    ##
    # Message Classes
    #
    class FileDescriptorSet < ::Protobuf::Message; end
    class FileDescriptorProto < ::Protobuf::Message; end
    class DescriptorProto < ::Protobuf::Message
      class ExtensionRange < ::Protobuf::Message; end
      class ReservedRange < ::Protobuf::Message; end

    end

    class ExtensionRangeOptions < ::Protobuf::Message; end
    class FieldDescriptorProto < ::Protobuf::Message
      class Type < ::Protobuf::Enum
        define :TYPE_DOUBLE, 1
        define :TYPE_FLOAT, 2
        define :TYPE_INT64, 3
        define :TYPE_UINT64, 4
        define :TYPE_INT32, 5
        define :TYPE_FIXED64, 6
        define :TYPE_FIXED32, 7
        define :TYPE_BOOL, 8
        define :TYPE_STRING, 9
        define :TYPE_GROUP, 10
        define :TYPE_MESSAGE, 11
        define :TYPE_BYTES, 12
        define :TYPE_UINT32, 13
        define :TYPE_ENUM, 14
        define :TYPE_SFIXED32, 15
        define :TYPE_SFIXED64, 16
        define :TYPE_SINT32, 17
        define :TYPE_SINT64, 18
      end

      class Label < ::Protobuf::Enum
        define :LABEL_OPTIONAL, 1
        define :LABEL_REQUIRED, 2
        define :LABEL_REPEATED, 3
      end

    end

    class OneofDescriptorProto < ::Protobuf::Message; end
    class EnumDescriptorProto < ::Protobuf::Message
      class EnumReservedRange < ::Protobuf::Message; end

    end

    class EnumValueDescriptorProto < ::Protobuf::Message; end
    class ServiceDescriptorProto < ::Protobuf::Message; end
    class MethodDescriptorProto < ::Protobuf::Message; end
    class FileOptions < ::Protobuf::Message
      class OptimizeMode < ::Protobuf::Enum
        define :SPEED, 1
        define :CODE_SIZE, 2
        define :LITE_RUNTIME, 3
      end

    end

    class MessageOptions < ::Protobuf::Message; end
    class FieldOptions < ::Protobuf::Message
      class CType < ::Protobuf::Enum
        define :STRING, 0
        define :CORD, 1
        define :STRING_PIECE, 2
      end

      class JSType < ::Protobuf::Enum
        define :JS_NORMAL, 0
        define :JS_STRING, 1
        define :JS_NUMBER, 2
      end

    end

    class OneofOptions < ::Protobuf::Message; end
    class EnumOptions < ::Protobuf::Message; end
    class EnumValueOptions < ::Protobuf::Message; end
    class ServiceOptions < ::Protobuf::Message; end
    class MethodOptions < ::Protobuf::Message
      class IdempotencyLevel < ::Protobuf::Enum
        define :IDEMPOTENCY_UNKNOWN, 0
        define :NO_SIDE_EFFECTS, 1
        define :IDEMPOTENT, 2
      end

    end

    class UninterpretedOption < ::Protobuf::Message
      class NamePart < ::Protobuf::Message; end

    end

    class SourceCodeInfo < ::Protobuf::Message
      class Location < ::Protobuf::Message; end

    end

    class GeneratedCodeInfo < ::Protobuf::Message
      class Annotation < ::Protobuf::Message; end

    end

    ##
    # File Options
    #
    set_option :java_package, "com.google.protobuf"
    set_option :java_outer_classname, "DescriptorProtos"
    set_option :optimize_for, ::Google::Protobuf::FileOptions::OptimizeMode::SPEED
    set_option :go_package, "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor"
    set_option :cc_enable_arenas, true
    set_option :objc_class_prefix, "GPB"
    set_option :csharp_namespace, "Google.Protobuf.Reflection"

    ##
    # Message Fields
    #
    class FileDescriptorSet
      repeated ::Google::Protobuf::FileDescriptorProto, :file, 1
    end

    class FileDescriptorProto
      optional :string, :name, 1
      optional :string, :package, 2
      repeated :string, :dependency, 3
      repeated :int32, :public_dependency, 10
      repeated :int32, :weak_dependency, 11
      repeated ::Google::Protobuf::DescriptorProto, :message_type, 4
      repeated ::Google::Protobuf::EnumDescriptorProto, :enum_type, 5
      repeated ::Google::Protobuf::ServiceDescriptorProto, :service, 6
      repeated ::Google::Protobuf::FieldDescriptorProto, :extension, 7
      optional ::Google::Protobuf::FileOptions, :options, 8
      optional ::Google::Protobuf::SourceCodeInfo, :source_code_info, 9
      optional :string, :syntax, 12
    end

    class DescriptorProto
      class ExtensionRange
        optional :int32, :start, 1
        optional :int32, :end, 2
        optional ::Google::Protobuf::ExtensionRangeOptions, :options, 3
      end

      class ReservedRange
        optional :int32, :start, 1
        optional :int32, :end, 2
      end

      optional :string, :name, 1
      repeated ::Google::Protobuf::FieldDescriptorProto, :field, 2
      repeated ::Google::Protobuf::FieldDescriptorProto, :extension, 6
      repeated ::Google::Protobuf::DescriptorProto, :nested_type, 3
      repeated ::Google::Protobuf::EnumDescriptorProto, :enum_type, 4
      repeated ::Google::Protobuf::DescriptorProto::ExtensionRange, :extension_range, 5
      repeated ::Google::Protobuf::OneofDescriptorProto, :oneof_decl, 8
      optional ::Google::Protobuf::MessageOptions, :options, 7
      repeated ::Google::Protobuf::DescriptorProto::ReservedRange, :reserved_range, 9
      repeated :string, :reserved_name, 10
    end

    class ExtensionRangeOptions
      repeated ::Google::Protobuf::UninterpretedOption, :uninterpreted_option, 999
      # Extension Fields
      extensions 1000...536870912
    end

    class FieldDescriptorProto
      optional :string, :name, 1
      optional :int32, :number, 3
      optional ::Google::Protobuf::FieldDescriptorProto::Label, :label, 4
      optional ::Google::Protobuf::FieldDescriptorProto::Type, :type, 5
      optional :string, :type_name, 6
      optional :string, :extendee, 2
      optional :string, :default_value, 7
      optional :int32, :oneof_index, 9
      optional :string, :json_name, 10
      optional ::Google::Protobuf::FieldOptions, :options, 8
      optional :bool, :proto3_optional, 17
    end

    class OneofDescriptorProto
      optional :string, :name, 1
      optional ::Google::Protobuf::OneofOptions, :options, 2
    end

    class EnumDescriptorProto
      class EnumReservedRange
        optional :int32, :start, 1
        optional :int32, :end, 2
      end

      optional :string, :name, 1
      repeated ::Google::Protobuf::EnumValueDescriptorProto, :value, 2
      optional ::Google::Protobuf::EnumOptions, :options, 3
      repeated ::Google::Protobuf::EnumDescriptorProto::EnumReservedRange, :reserved_range, 4
      repeated :string, :reserved_name, 5
    end

    class EnumValueDescriptorProto
      optional :string, :name, 1
      optional :int32, :number, 2
      optional ::Google::Protobuf::EnumValueOptions, :options, 3
    end

    class ServiceDescriptorProto
      optional :string, :name, 1
      repeated ::Google::Protobuf::MethodDescriptorProto, :method, 2
      optional ::Google::Protobuf::ServiceOptions, :options, 3
    end

    class MethodDescriptorProto
      optional :string, :name, 1
      optional :string, :input_type, 2
      optional :string, :output_type, 3
      optional ::Google::Protobuf::MethodOptions, :options, 4
      optional :bool, :client_streaming, 5, :default => false
      optional :bool, :server_streaming, 6, :default => false
    end

    class FileOptions
      optional :string, :java_package, 1
      optional :string, :java_outer_classname, 8
      optional :bool, :java_multiple_files, 10, :default => false
      optional :bool, :java_generate_equals_and_hash, 20, :deprecated => true
      optional :bool, :java_string_check_utf8, 27, :default => false
      optional ::Google::Protobuf::FileOptions::OptimizeMode, :optimize_for, 9, :default => ::Google::Protobuf::FileOptions::OptimizeMode::SPEED
      optional :string, :go_package, 11
      optional :bool, :cc_generic_services, 16, :default => false
      optional :bool, :java_generic_services, 17, :default => false
      optional :bool, :py_generic_services, 18, :default => false
      optional :bool, :php_generic_services, 42, :default => false
      optional :bool, :deprecated, 23, :default => false
      optional :bool, :cc_enable_arenas, 31, :default => true
      optional :string, :objc_class_prefix, 36
      optional :string, :csharp_namespace, 37
      optional :string, :swift_prefix, 39
      optional :string, :php_class_prefix, 40
      optional :string, :php_namespace, 41
      optional :string, :php_metadata_namespace, 44
      optional :string, :ruby_package, 45
      repeated ::Google::Protobuf::UninterpretedOption, :uninterpreted_option, 999
      # Extension Fields
      extensions 1000...536870912
    end

    class MessageOptions
      optional :bool, :message_set_wire_format, 1, :default => false
      optional :bool, :no_standard_descriptor_accessor, 2, :default => false
      optional :bool, :deprecated, 3, :default => false
      optional :bool, :map_entry, 7
      repeated ::Google::Protobuf::UninterpretedOption, :uninterpreted_option, 999
      # Extension Fields
      extensions 1000...536870912
    end

    class FieldOptions
      optional ::Google::Protobuf::FieldOptions::CType, :ctype, 1, :default => ::Google::Protobuf::FieldOptions::CType::STRING
      optional :bool, :packed, 2
      optional ::Google::Protobuf::FieldOptions::JSType, :jstype, 6, :default => ::Google::Protobuf::FieldOptions::JSType::JS_NORMAL
      optional :bool, :lazy, 5, :default => false
      optional :bool, :deprecated, 3, :default => false
      optional :bool, :weak, 10, :default => false
      repeated ::Google::Protobuf::UninterpretedOption, :uninterpreted_option, 999
      # Extension Fields
      extensions 1000...536870912
    end

    class OneofOptions
      repeated ::Google::Protobuf::UninterpretedOption, :uninterpreted_option, 999
      # Extension Fields
      extensions 1000...536870912
    end

    class EnumOptions
      optional :bool, :allow_alias, 2
      optional :bool, :deprecated, 3, :default => false
      repeated ::Google::Protobuf::UninterpretedOption, :uninterpreted_option, 999
      # Extension Fields
      extensions 1000...536870912
    end

    class EnumValueOptions
      optional :bool, :deprecated, 1, :default => false
      repeated ::Google::Protobuf::UninterpretedOption, :uninterpreted_option, 999
      # Extension Fields
      extensions 1000...536870912
    end

    class ServiceOptions
      optional :bool, :deprecated, 33, :default => false
      repeated ::Google::Protobuf::UninterpretedOption, :uninterpreted_option, 999
      # Extension Fields
      extensions 1000...536870912
    end

    class MethodOptions
      optional :bool, :deprecated, 33, :default => false
      optional ::Google::Protobuf::MethodOptions::IdempotencyLevel, :idempotency_level, 34, :default => ::Google::Protobuf::MethodOptions::IdempotencyLevel::IDEMPOTENCY_UNKNOWN
      repeated ::Google::Protobuf::UninterpretedOption, :uninterpreted_option, 999
      # Extension Fields
      extensions 1000...536870912
    end

    class UninterpretedOption
      class NamePart
        required :string, :name_part, 1
        required :bool, :is_extension, 2
      end

      repeated ::Google::Protobuf::UninterpretedOption::NamePart, :name, 2
      optional :string, :identifier_value, 3
      optional :uint64, :positive_int_value, 4
      optional :int64, :negative_int_value, 5
      optional :double, :double_value, 6
      optional :bytes, :string_value, 7
      optional :string, :aggregate_value, 8
    end

    class SourceCodeInfo
      class Location
        repeated :int32, :path, 1, :packed => true
        repeated :int32, :span, 2, :packed => true
        optional :string, :leading_comments, 3
        optional :string, :trailing_comments, 4
        repeated :string, :leading_detached_comments, 6
      end

      repeated ::Google::Protobuf::SourceCodeInfo::Location, :location, 1
    end

    class GeneratedCodeInfo
      class Annotation
        repeated :int32, :path, 1, :packed => true
        optional :string, :source_file, 2
        optional :int32, :begin, 3
        optional :int32, :end, 4
      end

      repeated ::Google::Protobuf::GeneratedCodeInfo::Annotation, :annotation, 1
    end

  end

end


text:
class HTTPServerMarlin : public HTTPServer
{
public:
  HTTPServerMarlin(XString p_name);
  virtual ~HTTPServerMarlin();

  // Running the server
  virtual void       Run();
  // Stop the server
  virtual void       StopServer();
  // Initialise a HTTP server and server-session
  virtual bool       Initialise();
  // Return a version string
  virtual XString    GetVersion();
  // Create a site to bind the traffic to
  virtual HTTPSite*  CreateSite(PrefixType    p_type
                               ,bool          p_secure
                               ,int           p_port
                               ,XString       p_baseURL
                               ,bool          p_subsite  = false
                               ,LPFN_CALLBACK p_callback = nullptr);
  // Delete a site from the remembered set of sites
  virtual bool       DeleteSite(int p_port,XString p_baseURL,bool p_force = false);
  // Receive (the rest of the) incoming HTTP request
  virtual bool       ReceiveIncomingRequest(HTTPMessage* p_message);
  // Create a new WebSocket in the subclass of our server
  virtual WebSocket* CreateWebSocket(XString p_uri);
  // Receive the WebSocket stream and pass on the the WebSocket
  virtual void       ReceiveWebSocket(WebSocket* p_socket,HTTP_OPAQUE_ID p_request);
  // Flushing a WebSocket intermediate
  virtual bool       FlushSocket(HTTP_OPAQUE_ID p_request,XString p_prefix);
  // Sending response for an incoming message
  virtual void       SendResponse(HTTPMessage* p_message);
  // Sending a response as a chunk
  virtual void       SendAsChunk(HTTPMessage* p_message,bool p_final = false);

  // FUNCTIONS FOR STAND-ALONE SERVER

  // Find and make an URL group
  HTTPURLGroup* FindUrlGroup(XString p_authName
                            ,ULONG   p_authScheme
                            ,bool    p_cache
                            ,XString p_realm
                            ,XString p_domain);
  // Remove an URLGroup. Called by HTTPURLGroup itself
  void          RemoveURLGroup(HTTPURLGroup* p_group);

protected:
  // Cleanup the server
  virtual void Cleanup();
  // Initialise general server header settings
  virtual void InitHeaders();
  // Init the stream response
  virtual bool InitEventStream(EventStream& p_stream);
  // Used for canceling a WebSocket for an event stream
  virtual void CancelRequestStream(HTTP_OPAQUE_ID p_response,bool p_reset = false);

private:
  // For the handling of the event streams: Sending a chunk to an event stream
  virtual bool SendResponseEventBuffer(HTTP_OPAQUE_ID     p_request
                                      ,CRITICAL_SECTION*  p_lock
                                      ,const char*        p_buffer
                                      ,size_t             p_totalLength
                                      ,bool               p_continue = true);

  // PRIVATE DATA of the stand-alone HTTPServer
  URLGroupMap             m_urlGroups;              // All URL Groups
};


text:
package org.apache.sentry.binding.hive.authz;

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

import org.apache.sentry.core.model.db.DBModelAction;
import org.apache.sentry.core.model.db.DBModelAuthorizable.AuthorizableType;

/**
 * Hive objects with required access privileges mapped to auth provider privileges
 */
public class HiveAuthzPrivileges {

  /**
   * Operation type used for privilege granting
   */
  public static enum HiveOperationType {
    UNKNOWN,
    DDL,
    DML,
    DATA_LOAD,
    DATA_UNLOAD,
    QUERY,
    INFO
  };

  /**
   * scope of the operation. The auth provider interface has different methods
   * for some of these. Hence we want to be able to identity the auth scope of
   * a statement eg. server level or DB level etc.
   */
  public static enum HiveOperationScope {
    UNKNOWN,
    SERVER,
    DATABASE,
    TABLE,
    URI,
    CONNECT
  }

  public static enum HiveExtendedOperation {
    TRANSFORM,
    RESOURCE
  }

  public static class AuthzPrivilegeBuilder {
    private final Map<AuthorizableType, EnumSet<DBModelAction>> inputPrivileges =
        new HashMap<AuthorizableType ,EnumSet<DBModelAction>>();
    private final Map<AuthorizableType,EnumSet<DBModelAction>> outputPrivileges =
        new HashMap<AuthorizableType,EnumSet<DBModelAction>>();
    private HiveOperationType operationType;
    private HiveOperationScope operationScope;

    public AuthzPrivilegeBuilder addInputObjectPriviledge(AuthorizableType inputObjectType, EnumSet<DBModelAction> inputPrivilege) {
      inputPrivileges.put(inputObjectType, inputPrivilege);
      return this;
    }

    public AuthzPrivilegeBuilder addOutputEntityPriviledge(AuthorizableType outputEntityType, EnumSet<DBModelAction> outputPrivilege) {
      outputPrivileges.put(outputEntityType, outputPrivilege);
      return this;
    }

    public AuthzPrivilegeBuilder addOutputObjectPriviledge(AuthorizableType outputObjectType, EnumSet<DBModelAction> outputPrivilege) {
      outputPrivileges.put(outputObjectType, outputPrivilege);
      return this;
    }

    public AuthzPrivilegeBuilder setOperationType(HiveOperationType operationType) {
      this.operationType = operationType;
      return this;
    }

    public AuthzPrivilegeBuilder setOperationScope(HiveOperationScope operationScope) {
      this.operationScope = operationScope;
      return this;
    }

    public HiveAuthzPrivileges build() {
      if (operationScope.equals(HiveOperationScope.UNKNOWN)) {
        throw new UnsupportedOperationException("Operation scope is not set");
      }

      if (operationType.equals(HiveOperationType.UNKNOWN)) {
        throw new UnsupportedOperationException("Operation scope is not set");
      }

      return new HiveAuthzPrivileges(inputPrivileges, outputPrivileges, operationType, operationScope);
    }
  }

  private final Map<AuthorizableType,EnumSet<DBModelAction>> inputPrivileges =
      new HashMap<AuthorizableType,EnumSet<DBModelAction>>();
  private final Map<AuthorizableType,EnumSet<DBModelAction>>  outputPrivileges =
      new HashMap<AuthorizableType,EnumSet<DBModelAction>>();
  private final HiveOperationType operationType;
  private final HiveOperationScope operationScope;

  protected HiveAuthzPrivileges(Map<AuthorizableType,EnumSet<DBModelAction>> inputPrivileges,
      Map<AuthorizableType,EnumSet<DBModelAction>> outputPrivileges, HiveOperationType operationType,
      HiveOperationScope operationScope) {
    this.inputPrivileges.putAll(inputPrivileges);
    this.outputPrivileges.putAll(outputPrivileges);
    this.operationScope = operationScope;
    this.operationType = operationType;
  }

  /**
   * @return the inputPrivileges
   */
  public Map<AuthorizableType, EnumSet<DBModelAction>> getInputPrivileges() {
    return inputPrivileges;
  }

  /**
   * @return the outputPrivileges
   */
  public Map<AuthorizableType, EnumSet<DBModelAction>> getOutputPrivileges() {
    return outputPrivileges;
  }

  /**
   * @return the operationType
   */
  public HiveOperationType getOperationType() {
    return operationType;
  }

  /**
   * @return the operationScope
   */
  public HiveOperationScope getOperationScope() {
    return operationScope;
  }
}