text:
function [type] = ft_senstype(input, desired)

% FT_SENSTYPE determines the type of acquisition device by looking at the
% channel names and comparing them with predefined lists.
%
% Use as
%   [type] = ft_senstype(sens)
%   [flag] = ft_senstype(sens, desired)
%
% The output type can be any of the following
%   'ctf64'
%   'ctf151'
%   'ctf151_planar'
%   'ctf275'
%   'ctf275_planar'
%   'bti148'
%   'bti148_planar'
%   'bti248'
%   'bti248_planar'
%   'bti248grad'
%   'bti248grad_planar'
%   'itab28'
%   'itab153'
%   'itab153_planar'
%   'yokogawa9'
%   'yokogawa64'
%   'yokogawa64_planar'
%   'yokogawa160'
%   'yokogawa160_planar'
%   'yokogawa440'
%   'ext1020'       this includes eeg1020, eeg1010 and eeg1005)
%   'neuromag122'
%   'neuromag306'
%   'babysquid74'   this is a BabySQUID system from Tristan Technologies
%   'artemis123'    this is a BabySQUID system from Tristan Technologies
%   'magview'       this is a BabySQUID system from Tristan Technologies
%   'egi32'
%   'egi64'
%   'egi128'
%   'egi256'
%   'biosemi64'
%   'biosemi128'
%   'biosemi256'
%   'neuralynx'
%   'plexon'
%   'artinis'
%   'eeg' (this was called 'electrode' in older versions)
%   'meg' (this was called 'magnetometer' in older versions)
%   'nirs'
%
% The optional input argument for the desired type can be any of the above,
% or any of the following generic classes of acquisition systems
%   'eeg'
%   'meg'
%   'meg_planar'
%   'meg_axial'
%   'ctf'
%   'bti'
%   'neuromag'
%   'yokogawa'
%   'babysquid'
% If you specify the desired type, this function will return a boolean
% true/false depending on the input data.
%
% Besides specifiying a sensor definition (i.e. a grad or elec structure,
% see FT_DATATYPE_SENS), it is also possible to give a data structure
% containing a grad or elec field, or giving a list of channel names (as
% cell-arrray). So assuming that you have a FieldTrip data structure, any
% of the following calls would also be fine.
%   ft_senstype(hdr)
%   ft_senstype(data)
%   ft_senstype(data.label)
%   ft_senstype(data.grad)
%   ft_senstype(data.grad.label)
%
% See also FT_SENSLABEL, FT_CHANTYPE, FT_READ_SENS, FT_COMPUTE_LEADFIELD, FT_DATATYPE_SENS

% Copyright (C) 2007-2015, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_senstype.m 10789 2015-10-19 08:43:13Z roboos $

% these are for remembering the type on subsequent calls with the same input arguments
persistent previous_argin previous_argout

% this is to avoid a recursion loop
persistent recursion
if isempty(recursion)
  recursion = false;
end

if iscell(input) && numel(input)<4 && ~all(cellfun(@ischar, input))
  % this might represent combined EEG, ECoG and/or MEG
  type = cell(size(input));
  if nargin<2
    desired = cell(size(input)); % empty elements
  end
  for i=1:numel(input)
    type{i} = ft_senstype(input{i}, desired{i});
  end
  return
end

if nargin<2
  % ensure that all input arguments are defined
  desired = [];
end

current_argin = {input, desired};
if isequal(current_argin, previous_argin)
  % don't do the type detection again, but return the previous output from cache
  type = previous_argout{1};
  return
end

isdata   = isa(input, 'struct')  && (isfield(input, 'hdr') || isfield(input, 'time') || isfield(input, 'freq') || isfield(input, 'grad') || isfield(input, 'elec') || isfield(input, 'opto'));
isheader = isa(input, 'struct')  && isfield(input, 'label') && isfield(input, 'Fs');
isgrad   = isa(input, 'struct')  && isfield(input, 'label') && isfield(input, 'pnt')  &&  isfield(input, 'ori'); % old style
iselec   = isa(input, 'struct')  && isfield(input, 'label') && isfield(input, 'pnt')  && ~isfield(input, 'ori'); % old style
isgrad   = (isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'coilpos')) || isgrad;             % new style
iselec   = (isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'elecpos')) || iselec;             % new style
isnirs   = isa(input, 'struct')  && isfield(input, 'label') && isfield(input, 'transceiver');
islabel  = isa(input, 'cell')    && ~isempty(input) && isa(input{1}, 'char');
haslabel = isa(input, 'struct')  && isfield(input, 'label');

if ~(isdata || isheader || isgrad || iselec || isnirs || islabel || haslabel) && isfield(input, 'hdr')
  input    = input.hdr;
  isheader = true;
end

if isdata
  % the input may be a data structure which then contains a grad/elec structure, a header or only the labels
  % preferably look at the data and not the header for the grad, because it might be re-balanced and/or planar
  if isfield(input, 'grad')
    sens   = input.grad;
    isgrad = true;
  elseif isfield(input, 'elec')
    sens   = input.elec;
    iselec = true;
  elseif issubfield(input, 'hdr.grad')
    sens   = input.hdr.grad;
    isgrad = true;
  elseif issubfield(input, 'hdr.elec')
    sens   = input.hdr.elec;
    iselec = true;
  elseif issubfield(input, 'hdr.opto')
    sens   = input.hdr.opto;
    isnirs = true;
  elseif issubfield(input, 'hdr.label')
    sens.label = input.hdr.label;
    islabel    = true;
  elseif isfield(input, 'label')
    sens.label = input.label;
    islabel    = true;
  else
    sens = [];
  end

elseif isheader
  if isfield(input, 'grad')
    sens   = input.grad;
    isgrad = true;
  elseif isfield(input, 'elec')
    sens   = input.elec;
    iselec = true;
  elseif isfield(input, 'opto')
    sens   = input.opto;
    isnirs = true;
  elseif isfield(input, 'label')
    sens.label = input.label;
    islabel    = true;
  end

elseif isgrad
  sens = input;

elseif iselec
  sens = input;

elseif isnirs
  sens = input;

elseif islabel
  sens.label = input;

elseif haslabel
  % it does not resemble anything that we had expected at this location, but it does have channel labels
  % the channel labels can be used to determine the type of sensor array
  sens.label = input.label;
  islabel    = true;

else
  sens = [];
end

if isfield(sens, 'type')
  % preferably the structure specifies its own type
  type = sens.type;

  % do not make a distinction between the neuromag data with or without space in the channel names
  if strcmp(type, 'neuromag306alt')
    type = 'neuromag306';
  elseif strcmp(type, 'neuromag122alt')
    type = 'neuromag122';
  end

elseif isfield(input, 'nChans') && input.nChans==1 && isfield(input, 'label') && ~isempty(regexp(input.label{1}, '^csc', 'once'))
  % this is a single channel header that was read from a Neuralynx file, might be fcdc_matbin or neuralynx_nsc
  type = 'neuralynx';

elseif issubfield(input, 'orig.FileHeader') &&  issubfield(input, 'orig.VarHeader')
  % this is a complete header that was read from a Plexon *.nex file using read_plexon_nex
  type = 'plexon';

elseif issubfield(input, 'orig.stname')
  % this is a complete header that was read from an ITAB dataset
  type = 'itab';

elseif issubfield(input, 'orig.sys_name')
  % this is a complete header that was read from a Yokogawa dataset
  if strcmp(input.orig.sys_name, '9ch Biomagnetometer System') || input.orig.channel_count<20
    % this is the small animal system that is installed at the UCL Ear Institute
    % see http://www.ucl.ac.uk/news/news-articles/0907/09070101
    type = 'yokogawa9';
  elseif input.orig.channel_count<160
    type = 'yokogawa64';
  elseif input.orig.channel_count<300
    type = 'yokogawa160';
  else
    % FIXME this might fail if there are many bad channels
    type = 'yokogawa440';
  end

elseif issubfield(input, 'orig.FILE.Ext') && strcmp(input.orig.FILE.Ext, 'edf')
  % this is a complete header that was read from an EDF or EDF+ dataset
  type = 'eeg';

else
  % start with unknown, then try to determine the proper type by looking at the labels
  type = 'unknown';

  if isgrad && isfield(sens, 'type')
    type = sens.type;

  elseif isgrad
    % this looks like MEG
    % revert the component balancing that was previously applied
    if isfield(sens, 'balance') && strcmp(sens.balance.current, 'comp')
      sens = undobalancing(sens);
    end

    % determine the type of magnetometer/gradiometer system based on the channel names alone
    % this uses a recursive call to the "islabel" section further down
    type = ft_senstype(sens.label);
    %sens_temp.type = type;
    if strcmp(type, 'unknown') %|| ~ft_senstype(sens_temp,'meg')
      % although we don't know the type, we do know that it is MEG
      type = 'meg';
    end

  elseif iselec
    % this looks like EEG

    % determine the type of eeg/acquisition system based on the channel names alone
    % this uses a recursive call to the "islabel" section further down
    type = ft_senstype(sens.label);
    %sens_temp.type = type;
    if strcmp(type, 'unknown') %|| ~ft_senstype(sens_temp,'eeg')
      % although we don't know the type, we do know that it is EEG
      type = 'eeg';
    end

  elseif isnirs
    % this looks like NIRS

    % determine the type of eeg/acquisition system based on the channel names alone
    % this uses a recursive call to the "islabel" section further down
    type = ft_senstype(sens.label);
    %sens_temp.type = type;
    if strcmp(type, 'unknown') %|| ~ft_senstype(sens_temp,'eeg')
      % although we don't know the type, we do know that it is EEG
      type = 'nirs';
    end

  elseif islabel
    % look only at the channel labels
    if     (mean(ismember(ft_senslabel('ant128'),         sens.label)) > 0.8)
      type = 'ant128';
    elseif (mean(ismember(ft_senslabel('ctf275'),         sens.label)) > 0.8)
      type = 'ctf275';
    elseif (mean(ismember(ft_senslabel('ctfheadloc'),     sens.label)) > 0.8)  % look at the head localization channels
      type = 'ctf275';
    elseif (mean(ismember(ft_senslabel('ctf151'),         sens.label)) > 0.8)
      type = 'ctf151';
    elseif (mean(ismember(ft_senslabel('ctf64'),          sens.label)) > 0.8)
      type = 'ctf64';
    elseif (mean(ismember(ft_senslabel('ctf275_planar'),  sens.label)) > 0.8)
      type = 'ctf275_planar';
    elseif (mean(ismember(ft_senslabel('ctf151_planar'),  sens.label)) > 0.8)
      type = 'ctf151_planar';
    elseif (mean(ismember(ft_senslabel('bti248'),         sens.label)) > 0.8) % note that it might also be a bti248grad system
      type = 'bti248';
    elseif (mean(ismember(ft_senslabel('bti148'),         sens.label)) > 0.8)
      type = 'bti148';
    elseif (mean(ismember(ft_senslabel('bti248_planar'),  sens.label)) > 0.8) % note that it might also be a bti248grad_planar system
      type = 'bti248_planar';
    elseif (mean(ismember(ft_senslabel('bti148_planar'),  sens.label)) > 0.8)
      type = 'bti148_planar';
    elseif (mean(ismember(ft_senslabel('itab28'),         sens.label)) > 0.8)
      type = 'itab28';
    elseif (mean(ismember(ft_senslabel('itab153'),        sens.label)) > 0.8)
      type = 'itab153';
    elseif (mean(ismember(ft_senslabel('itab153_planar'), sens.label)) > 0.8)
      type = 'itab153_planar';

      % the order is important for the different yokogawa systems, because they all share the same channel names
    elseif (mean(ismember(ft_senslabel('yokogawa440'),        sens.label)) > 0.7)
      type = 'yokogawa440';
    elseif (mean(ismember(ft_senslabel('yokogawa160'),        sens.label)) > 0.4)
      type = 'yokogawa160';
    elseif (mean(ismember(ft_senslabel('yokogawa160_planar'), sens.label)) > 0.4)
      type = 'yokogawa160_planar';
    elseif (mean(ismember(ft_senslabel('yokogawa64'),         sens.label)) > 0.4)
      type = 'yokogawa64';
    elseif (mean(ismember(ft_senslabel('yokogawa64_planar'),  sens.label)) > 0.4)
      type = 'yokogawa64_planar';
    elseif all(ismember(ft_senslabel('yokogawa9'),            sens.label))
      type = 'yokogawa9';

    elseif any(mean(ismember(ft_senslabel('neuromag306'),     sens.label)) > 0.4) % there are two possibilities for the channel labels: with and without a space
      type = 'neuromag306';
    elseif any(mean(ismember(ft_senslabel('neuromag122'),     sens.label)) > 0.4) % there are two possibilities for the channel labels: with and without a space
      type = 'neuromag122';

    elseif (mean(ismember(ft_senslabel('biosemi256'),         sens.label)) > 0.8)
      type = 'biosemi256';
    elseif (mean(ismember(ft_senslabel('biosemi128'),         sens.label)) > 0.8)
      type = 'biosemi128';
    elseif (mean(ismember(ft_senslabel('biosemi64'),          sens.label)) > 0.8)
      type = 'biosemi64';
    elseif (mean(ismember(ft_senslabel('egi256'),             sens.label)) > 0.8)
      type = 'egi256';
    elseif (mean(ismember(ft_senslabel('egi128'),             sens.label)) > 0.8)
      type = 'egi128';
    elseif (mean(ismember(ft_senslabel('egi64'),              sens.label)) > 0.8)
      type = 'egi64';
    elseif (mean(ismember(ft_senslabel('egi32'),              sens.label)) > 0.8)
      type = 'egi32';

      % the following check on the fraction of channels in the user's data rather than on the fraction of channels in the predefined set
    elseif (mean(ismember(sens.label, ft_senslabel('eeg1020'))) > 0.8)
      type = 'eeg1020';
    elseif (mean(ismember(sens.label, ft_senslabel('eeg1010'))) > 0.8)
      type = 'eeg1010';
    elseif (mean(ismember(sens.label, ft_senslabel('eeg1005'))) > 0.8)
      type = 'eeg1005';

    elseif (sum(ismember(sens.label, ft_senslabel('eeg1005'))) > 10) % Otherwise it's not even worth recognizing
      type = 'ext1020'; % this will also cover small subsets of eeg1020, eeg1010 and eeg1005
    elseif any(ismember(ft_senslabel('btiref'), sens.label))
      type = 'bti'; % it might be 148 or 248 channels
    elseif any(ismember(ft_senslabel('ctfref'), sens.label))
      type = 'ctf'; % it might be 151 or 275 channels

%     elseif (mean(ismember(sens.label,    ft_senslabel('nirs'))) > 0.8)
%       type = 'nirs';
    end
  end % look at label, ori and/or pos
end % if isfield(sens, 'type')

if strcmp(type, 'unknown') && ~recursion
  % try whether only lowercase channel labels makes a difference
  if islabel
    recursion = true;
    type = ft_senstype(lower(input));
    recursion = false;
  elseif isfield(input, 'label')
    input.label = lower(input.label);
    recursion = true;
    type = ft_senstype(input);
    recursion = false;
  end
end

if strcmp(type, 'unknown') && ~recursion
  % try whether only uppercase channel labels makes a difference
  if islabel
    recursion = true;
    type = ft_senstype(upper(input));
    recursion = false;
  elseif isfield(input, 'label')
    input.label = upper(input.label);
    recursion = true;
    type = ft_senstype(input);
    recursion = false;
  end
end

if ~isempty(desired)
  % return a boolean flag
  switch desired
    case 'ext1020'
      type = any(strcmp(type, {'eeg1005' 'eeg1010' 'eeg1020' 'ext1020'}));
    case {'eeg' 'electrode'}
      type = any(strcmp(type, {'eeg' 'electrode' 'ant128' 'biosemi64' 'biosemi128' 'biosemi256' 'egi32' 'egi64' 'egi128' 'egi256' 'eeg1005' 'eeg1010' 'eeg1020' 'ext1020'}));
    case 'biosemi'
      type = any(strcmp(type, {'biosemi64' 'biosemi128' 'biosemi256'}));
    case 'egi'
      type = any(strcmp(type, {'egi32' 'egi64' 'egi128' 'egi256'}));
    case 'meg'
      type = any(strcmp(type, {'meg' 'magnetometer' 'ctf' 'bti' 'ctf64' 'ctf151' 'ctf275' 'ctf151_planar' 'ctf275_planar' 'neuromag122' 'neuromag306' 'bti148' 'bti148_planar' 'bti248' 'bti248_planar' 'bti248grad' 'bti248grad_planar' 'yokogawa9' 'yokogawa160' 'yokogawa160_planar' 'yokogawa64' 'yokogawa64_planar' 'yokogawa440' 'itab' 'itab28' 'itab153' 'itab153_planar'}));
    case 'ctf'
      type = any(strcmp(type, {'ctf' 'ctf64' 'ctf151' 'ctf275' 'ctf151_planar' 'ctf275_planar'}));
    case 'bti'
      type = any(strcmp(type, {'bti' 'bti148' 'bti148_planar' 'bti248' 'bti248_planar' 'bti248grad' 'bti248grad_planar'}));
    case 'neuromag'
      type = any(strcmp(type, {'neuromag122' 'neuromag306'}));
    case 'babysquid'
      type = any(strcmp(type, {'babysquid74' 'artenis123' 'magview'}));
    case 'yokogawa'
      type = any(strcmp(type, {'yokogawa160' 'yokogawa160_planar' 'yokogawa64' 'yokogawa64_planar' 'yokogawa440'}));
    case 'itab'
      type = any(strcmp(type, {'itab' 'itab28' 'itab153' 'itab153_planar'}));
    case 'meg_axial'
      % note that neuromag306 is mixed planar and axial
      type = any(strcmp(type, {'neuromag306' 'ctf64' 'ctf151' 'ctf275' 'bti148' 'bti248' 'bti248grad' 'yokogawa9' 'yokogawa64' 'yokogawa160' 'yokogawa440'}));
    case 'meg_planar'
      % note that neuromag306 is mixed planar and axial
      type = any(strcmp(type, {'neuromag122' 'neuromag306' 'ctf151_planar' 'ctf275_planar' 'bti148_planar' 'bti248_planar' 'bti248grad_planar' 'yokogawa160_planar' 'yokogawa64_planar'}));
    otherwise
      type = any(strcmp(type, desired));
  end % switch desired
end % detemine the correspondence to the desired type

% remember the current input and output arguments, so that they can be
% reused on a subsequent call in case the same input argument is given
current_argout = {type};
previous_argin  = current_argin;
previous_argout = current_argout;

return % ft_senstype main()


text:
#if !defined(BOOST_PHOENIX_DONT_USE_PREPROCESSED_FILES)

#ifndef BOOST_PHOENIX_CORE_DETAIL_FUNCTION_EVAL_HPP
#define BOOST_PHOENIX_CORE_DETAIL_FUNCTION_EVAL_HPP

#include <boost/phoenix/core/limits.hpp>
#include <boost/phoenix/support/iterate.hpp>
#include <boost/phoenix/core/call.hpp>
#include <boost/phoenix/core/expression.hpp>
#include <boost/phoenix/core/meta_grammar.hpp>
#include <boost/phoenix/core/detail/phx2_result.hpp>
#include <boost/utility/result_of.hpp>

#include <boost/phoenix/core/detail/preprocessed/function_eval.hpp>

#endif
#else

#if !BOOST_PHOENIX_IS_ITERATING

#ifndef BOOST_PHOENIX_CORE_DETAIL_FUNCTION_EVAL_HPP
#define BOOST_PHOENIX_CORE_DETAIL_FUNCTION_EVAL_HPP

#include <boost/phoenix/core/limits.hpp>
#include <boost/phoenix/support/iterate.hpp>
#include <boost/phoenix/core/call.hpp>
#include <boost/phoenix/core/expression.hpp>
#include <boost/phoenix/core/meta_grammar.hpp>
#include <boost/phoenix/core/detail/phx2_result.hpp>
#include <boost/utility/result_of.hpp>

#if defined(__WAVE__) && defined(BOOST_PHOENIX_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 0, output: "preprocessed/function_eval_" BOOST_PHOENIX_LIMIT_STR ".hpp")
#endif

#if defined(__WAVE__) && defined(BOOST_PHOENIX_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 1)
#endif

BOOST_PHOENIX_DEFINE_EXPRESSION_VARARG(
    (boost)(phoenix)(detail)(function_eval)
  , (meta_grammar)
    (meta_grammar)
  , BOOST_PP_DEC(BOOST_PHOENIX_COMPOSITE_LIMIT)
)

namespace boost { namespace phoenix {
    namespace detail
    {
        template <typename T>
        T& help_rvalue_deduction(T& x)
        {
            return x;
        }

        template <typename T>
        T const& help_rvalue_deduction(T const& x)
        {
            return x;
        }

        struct function_eval
        {
            template <typename Sig>
            struct result;

            template <typename This, typename F, typename Context>
            struct result<This(F, Context)>
            {
                typedef typename
                    remove_reference<
                        typename boost::result_of<evaluator(F, Context)>::type
                    >::type
                    fn;

                typedef typename boost::result_of<fn()>::type type;
            };

            template <typename F, typename Context>
            typename result<function_eval(F const&, Context const&)>::type
            operator()(F const & f, Context const & ctx) const
            {
                return boost::phoenix::eval(f, ctx)();
            }

            template <typename F, typename Context>
            typename result<function_eval(F &, Context const&)>::type
            operator()(F & f, Context const & ctx) const
            {
                return boost::phoenix::eval(f, ctx)();
            }

        #define PHOENIX_GET_ARG(z, n, data)                                     \
            typedef                                                             \
                typename boost::result_of<                                      \
                    boost::phoenix::evaluator(                                                  \
                        BOOST_PP_CAT(A, n)                                      \
                      , Context                                                 \
                    )                                                           \
                >::type                                                         \
                BOOST_PP_CAT(a, n);

        #define PHOENIX_EVAL_ARG(z, n, data)                                    \
            help_rvalue_deduction(boost::phoenix::eval(BOOST_PP_CAT(a, n), ctx))

        #define M0(z, n, data)                                     \
            typename proto::detail::uncvref<BOOST_PP_CAT(a, n)>::type

        #define BOOST_PHOENIX_ITERATION_PARAMS                                  \
            (3, (1, BOOST_PP_DEC(BOOST_PHOENIX_ACTOR_LIMIT),                    \
            <boost/phoenix/core/detail/function_eval.hpp>))
#include BOOST_PHOENIX_ITERATE()

        #undef PHOENIX_GET_ARG
        #undef PHOENIX_EVAL_ARG
        #undef M0

        };

    }

    template <typename Dummy>
    struct default_actions::when<detail::rule::function_eval, Dummy>
        : phoenix::call<detail::function_eval>
    {};
}}

#if defined(__WAVE__) && defined(BOOST_PHOENIX_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif

#endif

#else
            template <
                typename This
              , typename F
              , BOOST_PHOENIX_typename_A
              , typename Context
            >
            struct result<This(F, BOOST_PHOENIX_A, Context)>
            {
                typedef typename
                    remove_reference<
                        typename boost::result_of<evaluator(F, Context)>::type
                    >::type
                    fn;

                BOOST_PP_REPEAT(BOOST_PHOENIX_ITERATION, PHOENIX_GET_ARG, _)

                typedef typename
                    boost::result_of<fn(BOOST_PHOENIX_a)>::type
                    type;
                /*
                typedef typename
                    mpl::eval_if_c<
                        has_phx2_result<
                            fn
                          , BOOST_PP_ENUM(BOOST_PHOENIX_ITERATION, M0, _)
                        >::value
                      , boost::result_of<
                            fn(
                                BOOST_PHOENIX_a
                            )
                        >
                      , phx2_result<
                            fn
                          , BOOST_PHOENIX_a
                        >
                    >::type
                    type;
                */
            };

            template <typename F, BOOST_PHOENIX_typename_A, typename Context>
            typename result<
                function_eval(
                    F const &
                  , BOOST_PHOENIX_A_ref
                  , Context const &
                )
            >::type
            operator()(F const & f, BOOST_PHOENIX_A_ref_a, Context const & ctx) const
            {
                return boost::phoenix::eval(f, ctx)(BOOST_PP_ENUM(BOOST_PHOENIX_ITERATION, PHOENIX_EVAL_ARG, _));
            }

            template <typename F, BOOST_PHOENIX_typename_A, typename Context>
            typename result<
                function_eval(
                    F &
                  , BOOST_PHOENIX_A_ref
                  , Context const &
                )
            >::type
            operator()(F & f, BOOST_PHOENIX_A_ref_a, Context const & ctx) const
            {
                return boost::phoenix::eval(f, ctx)(BOOST_PP_ENUM(BOOST_PHOENIX_ITERATION, PHOENIX_EVAL_ARG, _));
            }
#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
import unittest
from programy.processors.post.formatpunctuation import FormatPunctuationProcessor
from programy.bot import Bot
from programy.brain import Brain
from programy.config.brain import BrainConfiguration
from programy.config.bot import BotConfiguration

class FormatNmbersTests(unittest.TestCase):

    def setUp(self):
        self.bot = Bot(Brain(BrainConfiguration()), config=BotConfiguration())

    def test_format_punctuation(self):
        processor = FormatPunctuationProcessor()

        result = processor.process(self.bot, "testid", 'Hello " World "')
        self.assertIsNotNone(result)
        self.assertEqual('Hello "World"', result)

        result = processor.process(self.bot, "testid", '"Hello World"')
        self.assertIsNotNone(result)
        self.assertEqual('"Hello World"', result)

        result = processor.process(self.bot, "testid", "' Hello World '")
        self.assertIsNotNone(result)
        self.assertEqual("'Hello World'", result)

        result = processor.process(self.bot, "testid", '" Hello World "')
        self.assertIsNotNone(result)
        self.assertEqual('"Hello World"', result)

        result = processor.process(self.bot, "testid", '"This" and "That"')
        self.assertIsNotNone(result)
        self.assertEqual('"This" and "That"', result)

        result = processor.process(self.bot, "testid", "Hello World .")
        self.assertIsNotNone(result)
        self.assertEqual("Hello World.", result)

        result = processor.process(self.bot, "testid", "Hello World ,")
        self.assertIsNotNone(result)
        self.assertEqual("Hello World,", result)

        result = processor.process(self.bot, "testid", "Hello World :")
        self.assertIsNotNone(result)
        self.assertEqual("Hello World:", result)

        result = processor.process(self.bot, "testid", "Hello World ;")
        self.assertIsNotNone(result)
        self.assertEqual("Hello World;", result)

        result = processor.process(self.bot, "testid", "Hello World ?")
        self.assertIsNotNone(result)
        self.assertEqual("Hello World?", result)

        result = processor.process(self.bot, "testid", "Hello World !")
        self.assertIsNotNone(result)
        self.assertEqual("Hello World!", result)

        result = processor.process(self.bot, "testid", "Hello World . This is it.")
        self.assertIsNotNone(result)
        self.assertEqual("Hello World. This is it.", result)

        result = processor.process(self.bot, "testid", "Hello World . 23.45.")
        self.assertIsNotNone(result)
        self.assertEqual("Hello World. 23.45.", result)


text:
BASE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
cd $BASE_DIR

export JVM_OPTS="-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:ReservedCodeCacheSize=96m -XX:+TieredCompilation -XX:MaxPermSize=256m -Xms256m -Xmx512m -Xss2m"
$BASE_DIR/scripts/unpackDeps.sh

INNER_JAVA_OPTS="set javaOptions += \"-Dlog4j.configuration=file://$TRAVIS_BUILD_DIR/project/travis-log4j.properties\""

withCmd() {
  CMD=$1
  for t in $TEST_TARGET; do echo -n "; $t/$CMD "; done
}

bash -c "while true; do echo -n .; sleep 5; done" &

PROGRESS_REPORTER_PID=$!

echo "running..."

echo time ./sbt -Dhttp.keepAlive=false -Dsbt.repository.secure=false ++$TRAVIS_SCALA_VERSION "$(withCmd "test:compile")"
export JVM_OPTS="-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:ReservedCodeCacheSize=168m -XX:+TieredCompilation -XX:MaxPermSize=256m -Xms512m -Xmx1500m -Xss8m"

time ./sbt -Dhttp.keepAlive=false -Dsbt.repository.secure=false ++$TRAVIS_SCALA_VERSION "$(withCmd "test:compile")" # &> /dev/null

kill -9 $PROGRESS_REPORTER_PID

export JVM_OPTS="-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:ReservedCodeCacheSize=128m -XX:+TieredCompilation -XX:MaxPermSize=256m -Xms256m -Xmx768m -Xss2m"
echo "calling ... "
echo "time ./sbt ++$TRAVIS_SCALA_VERSION $(withCmd test)"
time ./sbt -Dhttp.keepAlive=false -Dsbt.repository.secure=false  ++$TRAVIS_SCALA_VERSION "$(withCmd test)"
TST_EXIT_CODE=$?
echo "all done"

$BASE_DIR/scripts/packDeps.sh
exit $TST_EXIT_CODE


text:
#ifndef QMITK_QmitkAdaptiveRegionGrowingToolGUI_H
#define QMITK_QmitkAdaptiveRegionGrowingToolGUI_H

#include "mitkDataStorage.h"
#include "itkImage.h"
#include "mitkGeometry3D.h"
#include "mitkPointSet.h"

#include "qwidget.h"
#include "ui_QmitkAdaptiveRegionGrowingToolGUIControls.h"

#include "SegmentationUIExports.h"

#include "QmitkToolGUI.h"

#include "mitkAdaptiveRegionGrowingTool.h"

class QmitkStdMultiWidget;
class DataNode;
class QmitkAdaptiveRegionGrowingToolGUIControls;

/*!
*
* \brief QmitkAdaptiveRegionGrowingToolGUI
*
* Adaptive Region Growing View class of the segmentation.
*
*/

class SegmentationUI_EXPORT QmitkAdaptiveRegionGrowingToolGUI : public QmitkToolGUI
{

  Q_OBJECT

public:
  mitkClassMacro(QmitkAdaptiveRegionGrowingToolGUI, QmitkToolGUI);

  itkNewMacro(QmitkAdaptiveRegionGrowingToolGUI);

  QmitkAdaptiveRegionGrowingToolGUI(QWidget* parent=0);

  /** \brief Method to create the connections for the component. This Method is obligatory even if no connections is needed*/
  virtual void CreateConnections();

  ///** \brief Method to set the default data storage.*/
  virtual void SetDataStorage(mitk::DataStorage* dataStorage);

  void SetMultiWidget(QmitkStdMultiWidget* multiWidget);

  void SetDataNodeNames(std::string labledSegmentation, std::string binaryImage, /*std::string vesselTree,*/ std::string surface);

  void EnableControls(bool enable);

  void SetInputImageNode(mitk::DataNode* node);

  void Deactivated();
  void Activated();

  /**
  * @brief The created GUI from the .ui-File. This Attribute is obligatory
  */
  Ui::QmitkAdaptiveRegionGrowingToolGUIControls m_Controls;

protected slots:

    void RunSegmentation();

    void ChangeLevelWindow(double newValue);//called, when the Level Window is changed via the slider in the ControlWidget

    //****called, when the slider-position is modified via the +/- buttons
    void IncreaseSlider();

    void DecreaseSlider();
    //***

    void ConfirmSegmentation();

    void UseVolumeRendering(bool on);

    void SetLowerThresholdValue(double lowerThreshold);

    void SetUpperThresholdValue(double upperThreshold);

    void OnNewToolAssociated(mitk::Tool*);

protected:

  mitk::AdaptiveRegionGrowingTool::Pointer m_RegionGrow3DTool;

  /** \brief Destructor. */
  virtual ~QmitkAdaptiveRegionGrowingToolGUI();

  //Pointer to the main widget to be able to reach the renderer
  QmitkStdMultiWidget* m_MultiWidget;

  mitk::DataStorage* m_DataStorage;

  mitk::DataNode::Pointer m_InputImageNode;

  void OnPointAdded();

private:

  std::string m_NAMEFORORGIMAGE;
  std::string m_NAMEFORLABLEDSEGMENTATIONIMAGE;
  std::string m_NAMEFORBINARYIMAGE;
  std::string m_NAMEFORSURFACE;

  mitk::ScalarType m_LOWERTHRESHOLD; //Hounsfield value
  mitk::ScalarType m_UPPERTHRESHOLD; //Hounsfield value
  mitk::ScalarType m_SeedPointValueMean;

  void RemoveHelperNodes();

  int m_DetectedLeakagePoint;

  bool m_CurrentRGDirectionIsUpwards; // defines fixed threshold (true = LOWERTHRESHOLD fixed, false = UPPERTHRESHOLD fixed)

  int m_SeedpointValue;
  bool m_SliderInitialized;
  bool m_UseVolumeRendering;
  bool m_UpdateSuggestedThreshold;
  float m_SuggestedThValue;

  long m_PointSetAddObserverTag;

  template < typename TPixel, unsigned int VImageDimension >
  void StartRegionGrowing( itk::Image< TPixel, VImageDimension >* itkImage, mitk::Geometry3D* imageGeometry, mitk::PointSet::PointType seedPoint );

  template < typename TPixel, unsigned int VImageDimension >
  void ITKThresholding( itk::Image< TPixel, VImageDimension >* inputImage );

  void InitializeLevelWindow();

  void EnableVolumeRendering(bool enable);

  void UpdateVolumeRenderingThreshold(int thValue);

};

#endif


text:
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.forms import modelformset_factory
from django.db.models import Count, Q
from dojo.forms import Benchmark_Product_SummaryForm, DeleteBenchmarkForm
from dojo.models import Benchmark_Type, Benchmark_Category, Benchmark_Requirement, Benchmark_Product, Product, Benchmark_Product_Summary
from dojo.utils import add_breadcrumb, Product_Tab

logger = logging.getLogger(__name__)

def add_benchmark(queryset, product):
    requirements = []
    for requirement in queryset:
        benchmark_product = Benchmark_Product()
        benchmark_product.product = product
        benchmark_product.control = requirement
        requirements.append(benchmark_product)

    try:
        Benchmark_Product.objects.bulk_create(requirements)
    except:
        pass

def return_score(queryset):
    asvs_level_1_benchmark = 0
    asvs_level_1_score = 0
    for item in queryset:
        if item["pass_fail"]:
            asvs_level_1_score = item["pass_fail__count"]
        asvs_level_1_benchmark = asvs_level_1_benchmark + item["pass_fail__count"]

    return asvs_level_1_benchmark, asvs_level_1_score

def score_asvs(product, benchmark_type):
    # Compliant to ASVS level 1 benchmarks
    asvs_level_1 = Benchmark_Product.objects.filter(enabled=True, control__enabled=True, product=product, control__category__type=benchmark_type, control__category__enabled=True, control__level_1=True).values('pass_fail').annotate(Count('pass_fail')).order_by()
    asvs_level_1_benchmark, asvs_level_1_score = return_score(asvs_level_1)

    # Compliant to ASVS level 2 benchmarks
    asvs_level_2 = Benchmark_Product.objects.filter(~Q(control__level_1=True), enabled=True, control__enabled=True, product=product, control__category__type=benchmark_type, control__category__enabled=True, control__level_2=True).values('pass_fail').annotate(Count('pass_fail')).order_by()
    asvs_level_2_benchmark, asvs_level_2_score = return_score(asvs_level_2)

    # Compliant to ASVS level 3 benchmarks
    asvs_level_3 = Benchmark_Product.objects.filter(~Q(control__level_1=True), ~Q(control__level_2=True), enabled=True, control__enabled=True, control__category__enabled=True, product=product, control__category__type=benchmark_type, control__level_3=True).values('pass_fail').annotate(Count('pass_fail')).order_by()
    asvs_level_3_benchmark, asvs_level_3_score = return_score(asvs_level_3)
    benchmark_product_summary = Benchmark_Product_Summary.objects.get(product=product, benchmark_type=benchmark_type)

    benchmark_product_summary.asvs_level_1_benchmark = asvs_level_1_benchmark
    benchmark_product_summary.asvs_level_1_score = asvs_level_1_score
    benchmark_product_summary.asvs_level_2_benchmark = asvs_level_2_benchmark
    benchmark_product_summary.asvs_level_2_score = asvs_level_2_score
    benchmark_product_summary.asvs_level_3_benchmark = asvs_level_3_benchmark
    benchmark_product_summary.asvs_level_3_score = asvs_level_3_score

    benchmark_product_summary.save()

@user_passes_test(lambda u: u.is_staff)
def benchmark_view(request, pid, type, cat=None):
    product = get_object_or_404(Product, id=pid)
    benchmark_type = get_object_or_404(Benchmark_Type, id=type)
    benchmark_category = Benchmark_Category.objects.filter(type=type, enabled=True).order_by('name')
    category_name = ""

    # Add requirements to the product
    add_benchmark(Benchmark_Requirement.objects.filter(category__type=type, category__type__enabled=True, enabled=True).all(), product)

    if cat:
        category_name = Benchmark_Category.objects.get(id=cat, enabled=True).name

    # Create the benchmark summary category
    try:
        benchmark_product_summary = Benchmark_Product_Summary.objects.get(product=product, benchmark_type=benchmark_type)
    except:
        pass
        benchmark_product_summary = Benchmark_Product_Summary(product=product, benchmark_type=benchmark_type)
        benchmark_product_summary.save()

    # Insert any new benchmarks since last created
    new_benchmarks = Benchmark_Requirement.objects.filter(category__type=type, category__type__enabled=True, enabled=True).exclude(id__in=Benchmark_Product.objects.filter(product=product).values_list('control_id', flat=True))
    add_benchmark(new_benchmarks, product)

    Benchmark_ProductFormSet = modelformset_factory(Benchmark_Product, exclude=['product, control'], extra=0)

    if request.method == 'POST':
        form = Benchmark_ProductFormSet(request.POST)
        summary_form = Benchmark_Product_SummaryForm(request.POST, instance=benchmark_product_summary)

        if form.is_valid():
            # print summary_form.errors
            summary_form_save = summary_form.save()
            form_save = form.save()
            score_asvs(product, benchmark_type)
            benchmark_product_summary = Benchmark_Product_Summary.objects.get(product=product, benchmark_type=benchmark_type)

            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Benchmarks saved.',
                                 extra_tags='alert-success')

    add_breadcrumb(title="Benchmarks", top_level=False, request=request)

    if cat:
        benchmarks = Benchmark_Product.objects.filter(product=product.id, control__category=cat, control__category__enabled=True, control__category__type=type, control__enabled=True).all().order_by('control__objective_number')

        benchmark_formset = Benchmark_ProductFormSet(queryset=Benchmark_Product.objects.filter(product=product.id, control__category=cat, control__category__enabled=True, control__category__type=type, control__enabled=True).all().order_by('control__objective_number'))
    else:
        benchmarks = Benchmark_Product.objects.filter(product=product.id, control__category__enabled=True, control__category__type=type, control__enabled=True).all().order_by('control__category__name', 'control__objective_number')

        benchmark_formset = Benchmark_ProductFormSet(queryset=Benchmark_Product.objects.filter(product=product.id, control__category__enabled=True, control__category__type=type, control__enabled=True).all().order_by('control__category__name', 'control__objective_number'))

    benchmark_summary_form = Benchmark_Product_SummaryForm(instance=benchmark_product_summary)

    product_tab = Product_Tab(pid, title="Benchmarks", tab="benchmarks")

    return render(request, 'dojo/benchmark.html',
                  {'benchmarks': benchmarks,
                   'active_tab': 'benchmarks',
                   'product_tab': product_tab,
                   'benchmark_product_summary': benchmark_product_summary,
                   'benchmark_summary_form': benchmark_summary_form,
                   'benchmark_formset': benchmark_formset,
                   'benchmark_type': benchmark_type,
                   'product': product,
                   'category_name': category_name,
                   'benchmark_category': benchmark_category})

@user_passes_test(lambda u: u.is_staff)
def delete(request, pid, type):
    product = get_object_or_404(Product, id=pid)
    benchmark_type = get_object_or_404(Benchmark_Type, id=type)
    benchmark_product_summary = Benchmark_Product_Summary.objects.filter(product=product, benchmark_type=type).first()
    form = DeleteBenchmarkForm(instance=benchmark_product_summary)

    if request.method == 'POST':
        if 'id' in request.POST and str(benchmark_product_summary.id) == request.POST['id']:
            form = DeleteBenchmarkForm(request.POST, instance=benchmark_product_summary)
            if form.is_valid():
                benchmark_product = Benchmark_Product.objects.filter(product=product, control__category__type=type)
                benchmark_product.delete()
                benchmark_product_summary.delete()
                messages.add_message(request,
                                     messages.SUCCESS,
                                     'Benchmarks removed.',
                                     extra_tags='alert-success')
                return HttpResponseRedirect(reverse('product'))

    product_tab = Product_Tab(pid, title="Delete Benchmarks", tab="benchmarks")
    return render(request, 'dojo/delete_benchmark.html',
                  {'product': product,
                   'form': form,
                   'product_tab': product_tab
                   })


text:
<?php

namespace UghAuthentication\Authentication;

use UghAuthentication\Authentication\Event\AuthenticationEvent;
use Zend\Authentication\Adapter\ValidatableAdapterInterface;
use Zend\Authentication\Result;
use Zend\Authentication\Storage\StorageInterface;
use Zend\EventManager\EventInterface;
use Zend\EventManager\EventManagerAwareInterface;

class AuthenticationService implements AuthenticationServiceInterface, EventManagerAwareInterface
{

    use \Zend\EventManager\EventManagerAwareTrait;

    /** @var ValidatableAdapterInterface */
    private $adapter;

    /** @var StorageInterface */
    private $storage;

    /** @var string */
    private $identity;

    /** @var string */
    private $credential;

    /**
     *
     * @param StorageInterface $storage
     * @param ValidatableAdapterInterface $adapter
     */
    public function __construct(StorageInterface $storage, ValidatableAdapterInterface $adapter)
    {
        $this->adapter = $adapter;
        $this->storage = $storage;
    }

    /**
     *
     * @return Result
     */
    public function authenticate()
    {
        $this->adapter->setIdentity($this->identity);
        $this->adapter->setCredential($this->credential);

        $result = $this->adapter->authenticate();

        if ($this->hasIdentity()) {
            $this->clearIdentity();
        }

        if ($result->isValid()) {
            $this->storage->write($result->getIdentity());
            $this->triggerAuthenticationSuccessEvent($result);
        } else {
            $this->triggerAuthenticationFailureEvent($result);
        }

        return $result;
    }

    public function clearIdentity()
    {
        $this->storage->clear();
    }

    public function setIdentity($identity)
    {
        $this->identity = $identity;
    }

    public function getIdentity()
    {
        return $this->storage->read();
    }

    /**
     *
     * @return boolean
     */
    public function hasIdentity()
    {
        return !$this->storage->isEmpty();
    }

    public function setCredential($credential)
    {
        $this->credential = $credential;
    }

    private function triggerAuthenticationSuccessEvent(Result $result)
    {
        $event = new AuthenticationEvent(AuthenticationEvent::AUTHENTICATION_SUCCESS_EVENT, $result);
        $this->triggerAuthenticationEvent($event);
    }

    private function triggerAuthenticationFailureEvent(Result $result)
    {
        $event = new AuthenticationEvent(AuthenticationEvent::AUTHENTICATION_FAILURE_EVENT, $result);
        $this->triggerAuthenticationEvent($event);
    }

    private function triggerAuthenticationEvent(EventInterface $event)
    {
        $this->getEventManager()->trigger($event);
    }
}


text:
const sass = require('sass');
const fs = require('fs');
const sass_options = require('./esbuild/sass_options');
let output_path = process.argv[2];
let scss_content = process.argv[3];
scss_content = scss_content.replace(/\\n/g, '\n');

sass.render({
	data: scss_content,
	outputStyle: 'compressed',
	...sass_options
}, function(err, result) {
	if (err) {
		console.error(err.formatted); // eslint-disable-line
		return;
	}

	fs.writeFile(output_path, result.css, function(err) {
		if (!err) {
			console.log(output_path); // eslint-disable-line
		} else {
			console.error(err); // eslint-disable-line
		}
	});
});


text:
__author__ = 'Zachary'
from negotiator_base import BaseNegotiator
from itertools import permutations
from random import sample
from functools import reduce

class zws3mb_Negotiator(BaseNegotiator):
    # initialize(self : BaseNegotiator, preferences : list(String), iter_limit : Int)
        # Performs per-round initialization - takes in a list of items, ordered by the item's
        # preferability for this negotiator
        # You can do other work here, but still need to store the preferences
    def __init__(self):
        BaseNegotiator.__init__(self)
        self.round_count=0
        self.first=False
        self.their_offers=[]
        self.their_utilities=[]
        self.our_score=0
        self.their_score=0
        self.last_offer=None
        self.encounter=0
        self.agreed=False
    def initialize(self, preferences, iter_limit):
        BaseNegotiator.initialize(self,preferences,iter_limit)
        self.offer_space()

    # make_offer(self : BaseNegotiator, offer : list(String)) --> list(String)
        # Given the opposing negotiator's last offer (represented as an ordered list),
        # return a new offer. If you wish to accept an offer & end negotiations, return the same offer
        # Note: Store a copy of whatever offer you make in self.offer at the end of this method.
    def offer_space(self):
        offerspace=[]
        if len(self.preferences)<7:     #Enumerate the whole space
            for subset in permutations(self.preferences,len(self.preferences)):
                self.offer=subset
                temp=self.utility()
                offerspace.append((subset,temp))

        else:
            for i in range(0,5000):
                self.offer=sample(self.preferences,len(self.preferences))
                temp=self.utility()
                offerspace.append((self.offer,temp))
        offerspace.sort(key=lambda tup:tup[1],reverse=True)
        #print offerspace
        self.my_offerspace=offerspace

    def ith_in_our_space(self,their_offer):
        temp=self.offer
        self.offer=their_offer
        this_util=self.utility()
        self.offer=temp
        for i in range(0,len(self.my_offerspace)):
            off,util=self.my_offerspace[i]
            if off==their_offer:
                return i
            if util<=this_util:
                return i
        return -1;
    def tic_tac_check(self,offer):
        if self.round_count+1==self.iter_limit: #last round
            print('Last round behavior'+str(self.__class__), end=' ')
            if self.first:      #We accept/receive this final offer
                if self.their_score>self.our_score:
                    if self.encounter>=0:   #potentially last time we see this opponenet
                        print(' Try to accept ', end=' ')
                        temp=self.offer
                        self.offer=self.their_offers[len(self.their_offers)-1]
                        val=self.utility()
                        self.offer=temp
                        if val>-len(self.preferences):

                                return self.their_offers[len(self.their_offers)-1] #if we aren't hurt by accepting,
                        else:
                            print("Deny, hurts more to accept than deny")
                            return self.preferences[:]                          # or screw both of us!
                    else:                   #can we manipulate them into being softer?
                        print('not the last encounter, deny for the first time')
                        return self.preferences[:]
                else:
                    print(("Going last, even if we are ahead, only accept if smart"), end=' ')
                    print('Try to accept,')
                    temp=self.offer
                    self.offer=self.their_offers[len(self.their_offers)-1]
                    val=self.utility()
                    self.offer=temp
                    if val>-len(self.preferences):

                        return self.their_offers[len(self.their_offers)-1] #if we aren't hurt by accepting,
                    else:
                        print("Deny, hurts more to accept than deny")
                        return self.preferences[:]                          # or screw both of us!
            else:               # We make final offer
                if self.their_score >self.our_score:    #been beating us
                    if not self.agreed:     #If it's in them to cut us, offer them something "fair"
                        return offer
                    else:
                        print('Come down some', end=' ')
                        our_i=self.ith_in_our_space(self.last_offer)
                        return self.my_offerspace[our_i][0]  #
                else:                                   #continue aggressive policy
                    if self.encounter>0 and not self.agreed:
                        our_i=self.ith_in_our_space(self.last_offer)
                        return self.my_offerspace[our_i+1][0]  #come down some
                        #return self.preferences[:]
                    else:
                        return self.preferences[:] #be greedy
        return offer
    def make_offer(self, offer):
        dec_off=None
        if offer==None and self.round_count==0:
            print("I am Negotiator A!")
            self.first=True
            self.offer=self.preferences[:]
            return self.offer
        else:
            self.their_offers.append(offer)
            if len(self.their_offers)>1: #not their first offer
                if self.their_utilities[len(self.their_utilities)-1]<self.their_utilities[len(self.their_utilities)-2]: #coming down
                    their_i=self.ith_in_our_space(offer)
                    last_i=self.ith_in_our_space(self.last_offer)
                    print('Haggling:'+str(last_i)+' '+str(their_i))
                    if their_i-last_i>0:        #is there room to come down
                        dec_off= self.my_offerspace[int(last_i+(their_i-last_i)/2)][0]
                    else:
                        dec_off=self.my_offerspace[last_i][0]
                else:                   #holding out or wrong direction
                    print('Being stubborn')
                    dec_off=self.last_offer
            else:   #their first offer
                print('refuse to budge')
                dec_off=self.preferences[:]
        self.offer=self.tic_tac_check(dec_off)
        self.last_offer=self.offer
        self.round_count+=1
        return self.offer

    # utility(self : BaseNegotiator) --> Float
        # Return the utility given by the last offer - Do not modify this method.
    def utility(self):
        total = len(self.preferences)
        return reduce(lambda points, item: points + ((total / (self.offer.index(item) + 1)) - abs(self.offer.index(item) - self.preferences.index(item))), self.offer, 0)

    # receive_utility(self : BaseNegotiator, utility : Float)
        # Store the utility the other negotiator received from their last offer
    def receive_utility(self, utility):
        self.their_utilities.append(utility)

    # receive_results(self : BaseNegotiator, results : (Boolean, Float, Float, Int))
        # Store the results of the last series of negotiation (points won, success, etc.)
    def receive_results(self, results):
        agreed,neg_a,neg_b,rounds=results
        self.agreed=agreed
        if self.first:
            self.our_score+=neg_a
            self.their_score+=neg_b
        else:
            self.our_score+=neg_b
            self.their_score+=neg_a
        self.first=False
        self.encounter+=1
        self.their_offers=[]
        self.round_count=0


text:
package local

import (
	"context"
	"fmt"
	"os"
	"sync"
	"testing"

	"github.com/hashicorp/terraform/backend"
	"github.com/hashicorp/terraform/config/module"
	"github.com/hashicorp/terraform/terraform"
)

func TestLocal_applyBasic(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")

	p.ApplyReturn = &terraform.InstanceState{ID: "yes"}

	mod, modCleanup := module.TestTree(t, "./test-fixtures/apply")
	defer modCleanup()

	op := testOperationApply()
	op.Module = mod

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()
	if run.Err != nil {
		t.Fatalf("err: %s", err)
	}

	if p.RefreshCalled {
		t.Fatal("refresh should not be called")
	}

	if !p.DiffCalled {
		t.Fatal("diff should be called")
	}

	if !p.ApplyCalled {
		t.Fatal("apply should be called")
	}

	checkState(t, b.StateOutPath, `
test_instance.foo:
  ID = yes
	`)
}

func TestLocal_applyEmptyDir(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")

	p.ApplyReturn = &terraform.InstanceState{ID: "yes"}

	op := testOperationApply()
	op.Module = nil

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()
	if run.Err == nil {
		t.Fatal("should error")
	}

	if p.ApplyCalled {
		t.Fatal("apply should not be called")
	}

	if _, err := os.Stat(b.StateOutPath); err == nil {
		t.Fatal("should not exist")
	}
}

func TestLocal_applyEmptyDirDestroy(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")

	p.ApplyReturn = nil

	op := testOperationApply()
	op.Module = nil
	op.Destroy = true

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()
	if run.Err != nil {
		t.Fatalf("err: %s", err)
	}

	if p.ApplyCalled {
		t.Fatal("apply should not be called")
	}

	checkState(t, b.StateOutPath, `<no state>`)
}

func TestLocal_applyError(t *testing.T) {
	b := TestLocal(t)
	p := TestLocalProvider(t, b, "test")

	var lock sync.Mutex
	errored := false
	p.ApplyFn = func(
		info *terraform.InstanceInfo,
		s *terraform.InstanceState,
		d *terraform.InstanceDiff) (*terraform.InstanceState, error) {
		lock.Lock()
		defer lock.Unlock()

		if !errored && info.Id == "test_instance.bar" {
			errored = true
			return nil, fmt.Errorf("error")
		}

		return &terraform.InstanceState{ID: "foo"}, nil
	}
	p.DiffFn = func(
		*terraform.InstanceInfo,
		*terraform.InstanceState,
		*terraform.ResourceConfig) (*terraform.InstanceDiff, error) {
		return &terraform.InstanceDiff{
			Attributes: map[string]*terraform.ResourceAttrDiff{
				"ami": &terraform.ResourceAttrDiff{
					New: "bar",
				},
			},
		}, nil
	}

	mod, modCleanup := module.TestTree(t, "./test-fixtures/apply-error")
	defer modCleanup()

	op := testOperationApply()
	op.Module = mod

	run, err := b.Operation(context.Background(), op)
	if err != nil {
		t.Fatalf("bad: %s", err)
	}
	<-run.Done()
	if run.Err == nil {
		t.Fatal("should error")
	}

	checkState(t, b.StateOutPath, `
test_instance.foo:
  ID = foo
	`)
}

func testOperationApply() *backend.Operation {
	return &backend.Operation{
		Type: backend.OperationTypeApply,
	}
}

// testApplyState is just a common state that we use for testing refresh.
func testApplyState() *terraform.State {
	return &terraform.State{
		Version: 2,
		Modules: []*terraform.ModuleState{
			&terraform.ModuleState{
				Path: []string{"root"},
				Resources: map[string]*terraform.ResourceState{
					"test_instance.foo": &terraform.ResourceState{
						Type: "test_instance",
						Primary: &terraform.InstanceState{
							ID: "bar",
						},
					},
				},
			},
		},
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2011 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<resources>
    <!-- These are the attributes that we want to retrieve for
         app/FragmentArguments.java -->
<!-- BEGIN_INCLUDE(fragment_arguments) -->
    <declare-styleable name="FragmentArguments">
        <attr name="android:label" />
    </declare-styleable>
<!-- END_INCLUDE(fragment_arguments) -->
</resources>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Dermatocarpon anzianum f. basaltica Servít

### Remarks
null


text:
package com.nike.cerberus.auth.connector.okta.statehandlers;

import com.nike.cerberus.auth.connector.AuthData;
import com.nike.cerberus.auth.connector.AuthResponse;
import com.nike.cerberus.auth.connector.AuthStatus;
import com.okta.authn.sdk.client.AuthenticationClient;
import com.okta.authn.sdk.resource.AuthenticationResponse;
import java.util.concurrent.CompletableFuture;

public class PushStateHandler extends AbstractOktaStateHandler {
  public PushStateHandler(
      AuthenticationClient client, CompletableFuture<AuthResponse> authenticationResponseFuture) {
    super(client, authenticationResponseFuture);
  }

  /**
   * Handles MFA Challenge, when a MFA challenge has been initiated for call or sms.
   *
   * @param mfaChallengeResponse - Authentication response from the Completable Future
   */
  @Override
  public void handleMfaChallenge(AuthenticationResponse mfaChallengeResponse) {

    final String userId = mfaChallengeResponse.getUser().getId();
    final String userLogin = mfaChallengeResponse.getUser().getLogin();
    final String factorResult = mfaChallengeResponse.getFactorResult();

    final AuthData authData =
        AuthData.builder().userId(userId).username(userLogin).factorResult(factorResult).build();
    AuthResponse authResponse =
        AuthResponse.builder().data(authData).status(AuthStatus.MFA_CHALLENGE).build();

    authenticationResponseFuture.complete(authResponse);
  }

  /**
   * Handles MFA Challenge, when a MFA challenge has been initiated for call or sms.
   *
   * @param mfaChallengeResponse - Authentication response from the Completable Future
   */
  @Override
  public void handleSuccess(AuthenticationResponse mfaChallengeResponse) {

    final String userId = mfaChallengeResponse.getUser().getId();
    final String userLogin = mfaChallengeResponse.getUser().getLogin();
    final String factorResult = mfaChallengeResponse.getStatus().toString();

    final AuthData authData =
        AuthData.builder().userId(userId).username(userLogin).factorResult(factorResult).build();
    AuthResponse authResponse =
        AuthResponse.builder().data(authData).status(AuthStatus.SUCCESS).build();

    authenticationResponseFuture.complete(authResponse);
  }
}


text:
package com.boozallen.cognition.endpoint.health;

import com.yammer.metrics.core.HealthCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Check the health of your application, server, services, etc.
 * Enter specific tests here.
 */
public class ServiceHealthCheck extends HealthCheck {

  final static Logger LOGGER = LoggerFactory.getLogger(ServiceHealthCheck.class);

  public ServiceHealthCheck() {
    super("service");
  }

  @Override
  protected Result check() throws Exception {
    return Result.healthy();
  }
}


text:
<?php

/**
 * HTML anchor element block
 *
 * @category   Mage
 * @package    Mage_Core
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Core_Block_Html_Link extends Mage_Core_Block_Template
{

    /**
     * Internal constructor
     *
     */
    protected function _construct()
    {
        $this->setTemplate('core/link.phtml');
        parent::_construct();
    }
    /**
     * Prepare link attributes as serialized and formated string
     *
     * @return string
     */
    public function getLinkAttributes()
    {
        $allow = array(
            'href', 'title', 'charset', 'name', 'hreflang', 'rel', 'rev', 'accesskey', 'shape',
            'coords', 'tabindex', 'onfocus', 'onblur', // %attrs
            'id', 'class', 'style', // %coreattrs
            'lang', 'dir', // %i18n
            'onclick', 'ondblclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmousemove',
            'onmouseout', 'onkeypress', 'onkeydown', 'onkeyup' // %events
        );

        $attributes = array();
        foreach ($allow as $attribute) {
            $value = $this->getDataUsingMethod($attribute);
            if (!is_null($value)) {
                $attributes[$attribute] = $this->escapeHtml($value);
            }
        }

        if (!empty($attributes)) {
            return $this->serialize($attributes);
        }
        return '';
    }

    /**
     * serialize attributes
     *
     * @param   array $attributes
     * @param   string $valueSeparator
     * @param   string $fieldSeparator
     * @param   string $quote
     * @return  string
     */
    public function serialize($attributes = array(), $valueSeparator='=', $fieldSeparator=' ', $quote='"')
    {
        $res  = '';
        $data = array();

        foreach ($attributes as $key => $value) {
            $data[] = $key . $valueSeparator . $quote . $value . $quote;
        }
        $res = implode($fieldSeparator, $data);
        return $res;
    }
}


text:
package com.twosigma.beaker.clojure.handlers;

import com.twosigma.jupyter.KernelFunctionality;
import com.twosigma.jupyter.handler.KernelHandler;
import com.twosigma.jupyter.message.Header;
import com.twosigma.jupyter.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;

import static com.twosigma.beaker.jupyter.msg.JupyterMessages.KERNEL_INFO_REPLY;

public class ClojureKernelInfoHandler extends KernelHandler<Message> {

  private final static Logger logger = LoggerFactory.getLogger(ClojureKernelInfoHandler.class);

  public ClojureKernelInfoHandler(KernelFunctionality kernel) {
    super(kernel);
  }

  @Override
  public void handle(Message message) {
    logger.debug("Processing kernel info request");
    Message reply = new Message();
    HashMap<String, Serializable> map = new HashMap<>(6);
    map.put("protocol_version", "5.0");
    map.put("implementation", "clojure");
    map.put("implementation_version", "1.0.0");
    HashMap<String, Serializable> map1 = new HashMap<String, Serializable>(7);
    map1.put("name", "Clojure");
    map1.put("version", "1.7");
    map1.put("mimetype", "text/x-clojure");
    map1.put("file_extension", ".clj");
    map1.put("codemirror_mode", "Clojure");
    map1.put("nbconverter_exporter", "");
    map.put("language_info", map1);
    map.put("banner", "BeakerX kernel for Clojure");
    map.put("help_links", new ArrayList<String>());
    reply.setContent(map);
    reply.setHeader(new Header(KERNEL_INFO_REPLY, message.getHeader().getSession()));
    reply.setParentHeader(message.getHeader());
    reply.setIdentities(message.getIdentities());
    send(reply);
  }

}


text:
package org.apache.ignite.internal.processors.platform;

import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteAtomicSequence;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.NearCacheConfiguration;
import org.apache.ignite.configuration.PlatformConfiguration;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.binary.BinaryRawReaderEx;
import org.apache.ignite.internal.binary.BinaryRawWriterEx;
import org.apache.ignite.internal.logger.platform.PlatformLogger;
import org.apache.ignite.internal.processors.GridProcessorAdapter;
import org.apache.ignite.internal.processors.cache.IgniteCacheProxy;
import org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl;
import org.apache.ignite.internal.processors.datastructures.GridCacheAtomicLongImpl;
import org.apache.ignite.internal.processors.platform.binary.PlatformBinaryProcessor;
import org.apache.ignite.internal.processors.platform.cache.PlatformCache;
import org.apache.ignite.internal.processors.platform.cache.PlatformCacheExtension;
import org.apache.ignite.internal.processors.platform.cache.affinity.PlatformAffinity;
import org.apache.ignite.internal.processors.platform.cache.store.PlatformCacheStore;
import org.apache.ignite.internal.processors.platform.cluster.PlatformClusterGroup;
import org.apache.ignite.internal.processors.platform.compute.PlatformCompute;
import org.apache.ignite.internal.processors.platform.datastreamer.PlatformDataStreamer;
import org.apache.ignite.internal.processors.platform.datastructures.PlatformAtomicLong;
import org.apache.ignite.internal.processors.platform.datastructures.PlatformAtomicReference;
import org.apache.ignite.internal.processors.platform.datastructures.PlatformAtomicSequence;
import org.apache.ignite.internal.processors.platform.dotnet.PlatformDotNetCacheStore;
import org.apache.ignite.internal.processors.platform.events.PlatformEvents;
import org.apache.ignite.internal.processors.platform.memory.PlatformMemory;
import org.apache.ignite.internal.processors.platform.memory.PlatformOutputStream;
import org.apache.ignite.internal.processors.platform.messaging.PlatformMessaging;
import org.apache.ignite.internal.processors.platform.services.PlatformServices;
import org.apache.ignite.internal.processors.platform.transactions.PlatformTransactions;
import org.apache.ignite.internal.processors.platform.utils.PlatformConfigurationUtils;
import org.apache.ignite.internal.processors.platform.utils.PlatformUtils;
import org.apache.ignite.internal.util.typedef.CI1;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteFuture;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * GridGain platform processor.
 */
public class PlatformProcessorImpl extends GridProcessorAdapter implements PlatformProcessor {
    /** Start latch. */
    private final CountDownLatch startLatch = new CountDownLatch(1);

    /** Stores pending initialization. */
    private final Collection<StoreInfo> pendingStores =
        Collections.newSetFromMap(new ConcurrentHashMap<StoreInfo, Boolean>());

    /** Lock for store lifecycle operations. */
    private final ReadWriteLock storeLock = new ReentrantReadWriteLock();

    /** Logger. */
    @SuppressWarnings("FieldCanBeLocal")
    private final IgniteLogger log;

    /** Context. */
    private final PlatformContext platformCtx;

    /** Interop configuration. */
    private final PlatformConfigurationEx interopCfg;

    /** Whether processor is started. */
    private boolean started;

    /** Whether processor if stopped (or stopping). */
    private volatile boolean stopped;

    /** Cache extensions. */
    private final PlatformCacheExtension[] cacheExts;

    /** Cluster restart flag for the reconnect callback. */
    private volatile boolean clusterRestarted;

    /**
     * Constructor.
     *
     * @param ctx Kernal context.
     */
    public PlatformProcessorImpl(GridKernalContext ctx) {
        super(ctx);

        log = ctx.log(PlatformProcessorImpl.class);

        PlatformConfiguration interopCfg0 = ctx.config().getPlatformConfiguration();

        assert interopCfg0 != null : "Must be checked earlier during component creation.";

        if (!(interopCfg0 instanceof PlatformConfigurationEx))
            throw new IgniteException("Unsupported platform configuration: " + interopCfg0.getClass().getName());

        interopCfg = (PlatformConfigurationEx)interopCfg0;

        if (!F.isEmpty(interopCfg.warnings())) {
            for (String w : interopCfg.warnings())
                U.warn(log, w);
        }

        platformCtx = new PlatformContextImpl(ctx, interopCfg.gate(), interopCfg.memory(), interopCfg.platform());

        // Initialize cache extensions (if any).
        cacheExts = prepareCacheExtensions(interopCfg.cacheExtensions());

        if (interopCfg.logger() != null)
            interopCfg.logger().setContext(platformCtx);
    }

    /** {@inheritDoc} */
    @Override public void start() throws IgniteCheckedException {
        try (PlatformMemory mem = platformCtx.memory().allocate()) {
            PlatformOutputStream out = mem.output();

            BinaryRawWriterEx writer = platformCtx.writer(out);

            writer.writeString(ctx.gridName());

            out.synchronize();

            platformCtx.gateway().onStart(this, mem.pointer());
        }

        // At this moment all necessary native libraries must be loaded, so we can process with store creation.
        storeLock.writeLock().lock();

        try {
            for (StoreInfo store : pendingStores)
                registerStore0(store.store, store.convertBinary);

            pendingStores.clear();

            started = true;
        }
        finally {
            storeLock.writeLock().unlock();
        }

        // Add Interop node attributes.
        ctx.addNodeAttribute(PlatformUtils.ATTR_PLATFORM, interopCfg.platform());
    }

    /** {@inheritDoc} */
    @Override public void onKernalStop(boolean cancel) {
        startLatch.countDown();
    }

    /** {@inheritDoc} */
    @Override public void stop(boolean cancel) throws IgniteCheckedException {
        if (platformCtx != null) {
            stopped = true;
            platformCtx.gateway().onStop();
        }
    }

    /** {@inheritDoc} */
    @Override public Ignite ignite() {
        return ctx.grid();
    }

    /** {@inheritDoc} */
    @Override public long environmentPointer() {
        return platformCtx.gateway().environmentPointer();
    }

    /** {@inheritDoc} */
    @Override public void releaseStart() {
        startLatch.countDown();
    }

    /** {@inheritDoc} */
    @Override public void awaitStart() throws IgniteCheckedException {
        U.await(startLatch);
    }

    /** {@inheritDoc} */
    @Override public PlatformContext context() {
        // This method is a single point of entry for all remote closures
        // CPP platform does not currently support remote code execution
        // Therefore, all remote execution attempts come from .NET
        // Throw an error if current platform is not .NET
        if (!PlatformUtils.PLATFORM_DOTNET.equals(interopCfg.platform())) {
            throw new IgniteException(".NET platform is not available [nodeId=" + ctx.grid().localNode().id() + "] " +
                "(Use Apache.Ignite.Core.Ignition.Start() or Apache.Ignite.exe to start Ignite.NET nodes).");
        }

        return platformCtx;
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget cache(@Nullable String name) throws IgniteCheckedException {
        IgniteCacheProxy cache = (IgniteCacheProxy)ctx.grid().cache(name);

        if (cache == null)
            throw new IllegalArgumentException("Cache doesn't exist: " + name);

        return createPlatformCache(cache);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget createCache(@Nullable String name) throws IgniteCheckedException {
        IgniteCacheProxy cache = (IgniteCacheProxy)ctx.grid().createCache(name);

        assert cache != null;

        return createPlatformCache(cache);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget getOrCreateCache(@Nullable String name) throws IgniteCheckedException {
        IgniteCacheProxy cache = (IgniteCacheProxy)ctx.grid().getOrCreateCache(name);

        assert cache != null;

        return createPlatformCache(cache);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget createCacheFromConfig(long memPtr) throws IgniteCheckedException {
        BinaryRawReaderEx reader = platformCtx.reader(platformCtx.memory().get(memPtr));
        CacheConfiguration cfg = PlatformConfigurationUtils.readCacheConfiguration(reader);

        IgniteCacheProxy cache = reader.readBoolean()
            ? (IgniteCacheProxy)ctx.grid().createCache(cfg, PlatformConfigurationUtils.readNearConfiguration(reader))
            : (IgniteCacheProxy)ctx.grid().createCache(cfg);

        return createPlatformCache(cache);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget getOrCreateCacheFromConfig(long memPtr) throws IgniteCheckedException {
        BinaryRawReaderEx reader = platformCtx.reader(platformCtx.memory().get(memPtr));
        CacheConfiguration cfg = PlatformConfigurationUtils.readCacheConfiguration(reader);

        IgniteCacheProxy cache = reader.readBoolean()
            ? (IgniteCacheProxy)ctx.grid().getOrCreateCache(cfg,
                    PlatformConfigurationUtils.readNearConfiguration(reader))
            : (IgniteCacheProxy)ctx.grid().getOrCreateCache(cfg);

        return createPlatformCache(cache);
    }

    /** {@inheritDoc} */
    @Override public void destroyCache(@Nullable String name) throws IgniteCheckedException {
        ctx.grid().destroyCache(name);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget affinity(@Nullable String name) throws IgniteCheckedException {
        return new PlatformAffinity(platformCtx, ctx, name);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget dataStreamer(@Nullable String cacheName, boolean keepBinary)
        throws IgniteCheckedException {
        IgniteDataStreamer ldr = ctx.dataStream().dataStreamer(cacheName);

        ldr.keepBinary(true);

        return new PlatformDataStreamer(platformCtx, cacheName, (DataStreamerImpl)ldr, keepBinary);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget transactions() {
        return new PlatformTransactions(platformCtx);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget projection() throws IgniteCheckedException {
        return new PlatformClusterGroup(platformCtx, ctx.grid().cluster());
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget compute(PlatformTarget grp) {
        PlatformClusterGroup grp0 = (PlatformClusterGroup)grp;

        return new PlatformCompute(platformCtx, grp0.projection(), PlatformUtils.ATTR_PLATFORM);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget message(PlatformTarget grp) {
        PlatformClusterGroup grp0 = (PlatformClusterGroup)grp;

        return new PlatformMessaging(platformCtx, grp0.projection().ignite().message(grp0.projection()));
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget events(PlatformTarget grp) {
        PlatformClusterGroup grp0 = (PlatformClusterGroup)grp;

        return new PlatformEvents(platformCtx, grp0.projection().ignite().events(grp0.projection()));
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget services(PlatformTarget grp) {
        PlatformClusterGroup grp0 = (PlatformClusterGroup)grp;

        return new PlatformServices(platformCtx, grp0.projection().ignite().services(grp0.projection()), false);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget extensions() {
        return null;
    }

    /** {@inheritDoc} */
    @Override public void registerStore(PlatformCacheStore store, boolean convertBinary)
        throws IgniteCheckedException {
        storeLock.readLock().lock();

        try {
            if (stopped)
                throw new IgniteCheckedException("Failed to initialize interop store because node is stopping: " +
                    store);

            if (started)
                registerStore0(store, convertBinary);
            else
                pendingStores.add(new StoreInfo(store, convertBinary));
        }
        finally {
            storeLock.readLock().unlock();
        }
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget atomicLong(String name, long initVal, boolean create) throws IgniteException {
        GridCacheAtomicLongImpl atomicLong = (GridCacheAtomicLongImpl)ignite().atomicLong(name, initVal, create);

        if (atomicLong == null)
            return null;

        return new PlatformAtomicLong(platformCtx, atomicLong);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget atomicSequence(String name, long initVal, boolean create) throws IgniteException {
        IgniteAtomicSequence atomicSeq = ignite().atomicSequence(name, initVal, create);

        if (atomicSeq == null)
            return null;

        return new PlatformAtomicSequence(platformCtx, atomicSeq);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget atomicReference(String name, long memPtr, boolean create) throws IgniteException {
        return PlatformAtomicReference.createInstance(platformCtx, name, memPtr, create);
    }

    /** {@inheritDoc} */
    @Override public void onDisconnected(IgniteFuture<?> reconnectFut) throws IgniteCheckedException {
        platformCtx.gateway().onClientDisconnected();

        // 1) onReconnected is called on all grid components.
        // 2) After all of grid components have completed their reconnection, reconnectFut is completed.
        reconnectFut.listen(new CI1<IgniteFuture<?>>() {
            @Override public void apply(IgniteFuture<?> future) {
                platformCtx.gateway().onClientReconnected(clusterRestarted);
            }
        });
    }

    /** {@inheritDoc} */
    @Override public IgniteInternalFuture<?> onReconnected(boolean clusterRestarted) throws IgniteCheckedException {
        // Save the flag value for callback of reconnectFut.
        this.clusterRestarted = clusterRestarted;

        return null;
    }

    /** {@inheritDoc} */
    @Override public void getIgniteConfiguration(long memPtr) {
        PlatformOutputStream stream = platformCtx.memory().get(memPtr).output();
        BinaryRawWriterEx writer = platformCtx.writer(stream);

        PlatformConfigurationUtils.writeIgniteConfiguration(writer, ignite().configuration());

        stream.synchronize();
    }

    /** {@inheritDoc} */
    @Override public void getCacheNames(long memPtr) {
        PlatformOutputStream stream = platformCtx.memory().get(memPtr).output();
        BinaryRawWriterEx writer = platformCtx.writer(stream);

        Collection<String> names = ignite().cacheNames();

        writer.writeInt(names.size());

        for (String name : names)
            writer.writeString(name);

        stream.synchronize();
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget createNearCache(@Nullable String cacheName, long memPtr) {
        NearCacheConfiguration cfg = getNearCacheConfiguration(memPtr);

        IgniteCacheProxy cache = (IgniteCacheProxy)ctx.grid().createNearCache(cacheName, cfg);

        return createPlatformCache(cache);
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget getOrCreateNearCache(@Nullable String cacheName, long memPtr) {
        NearCacheConfiguration cfg = getNearCacheConfiguration(memPtr);

        IgniteCacheProxy cache = (IgniteCacheProxy)ctx.grid().getOrCreateNearCache(cacheName, cfg);

        return createPlatformCache(cache);
    }

    /**
     * Creates new platform cache.
     */
    private PlatformTarget createPlatformCache(IgniteCacheProxy cache) {
        return new PlatformCache(platformCtx, cache, false, cacheExts);
    }

    /** {@inheritDoc} */
    @Override public boolean loggerIsLevelEnabled(int level) {
        IgniteLogger log = ctx.grid().log();

        switch (level) {
            case PlatformLogger.LVL_TRACE:
                return log.isTraceEnabled();
            case PlatformLogger.LVL_DEBUG:
                return log.isDebugEnabled();
            case PlatformLogger.LVL_INFO:
                return log.isInfoEnabled();
            case PlatformLogger.LVL_WARN:
                return true;
            case PlatformLogger.LVL_ERROR:
                return true;
            default:
                assert false;
        }

        return false;
    }

    /** {@inheritDoc} */
    @Override public void loggerLog(int level, String message, String category, String errorInfo) {
        IgniteLogger log = ctx.grid().log();

        if (category != null)
            log = log.getLogger(category);

        Throwable err = errorInfo == null ? null : new IgniteException("Platform error:" + errorInfo);

        switch (level) {
            case PlatformLogger.LVL_TRACE:
                log.trace(message);
                break;
            case PlatformLogger.LVL_DEBUG:
                log.debug(message);
                break;
            case PlatformLogger.LVL_INFO:
                log.info(message);
                break;
            case PlatformLogger.LVL_WARN:
                log.warning(message, err);
                break;
            case PlatformLogger.LVL_ERROR:
                log.error(message, err);
                break;
            default:
                assert false;
        }
    }

    /** {@inheritDoc} */
    @Override public PlatformTarget binaryProcessor() {
        return new PlatformBinaryProcessor(platformCtx);
    }

    /**
     * Gets the near cache config.
     *
     * @param memPtr Memory pointer.
     * @return Near config.
     */
    private NearCacheConfiguration getNearCacheConfiguration(long memPtr) {
        assert memPtr != 0;

        BinaryRawReaderEx reader = platformCtx.reader(platformCtx.memory().get(memPtr));
        return PlatformConfigurationUtils.readNearConfiguration(reader);
    }

    /**
     * Internal store initialization routine.
     *
     * @param store Store.
     * @param convertBinary Convert binary flag.
     * @throws IgniteCheckedException If failed.
     */
    private void registerStore0(PlatformCacheStore store, boolean convertBinary) throws IgniteCheckedException {
        if (store instanceof PlatformDotNetCacheStore) {
            PlatformDotNetCacheStore store0 = (PlatformDotNetCacheStore)store;

            store0.initialize(ctx, convertBinary);
        }
        else
            throw new IgniteCheckedException("Unsupported interop store: " + store);
    }

    /**
     * Prepare cache extensions.
     *
     * @param cacheExts Original extensions.
     * @return Prepared extensions.
     */
    private static PlatformCacheExtension[] prepareCacheExtensions(Collection<PlatformCacheExtension> cacheExts) {
        if (!F.isEmpty(cacheExts)) {
            int maxExtId = 0;

            Map<Integer, PlatformCacheExtension> idToExt = new HashMap<>();

            for (PlatformCacheExtension cacheExt : cacheExts) {
                if (cacheExt == null)
                    throw new IgniteException("Platform cache extension cannot be null.");

                if (cacheExt.id() < 0)
                    throw new IgniteException("Platform cache extension ID cannot be negative: " + cacheExt);

                PlatformCacheExtension oldCacheExt = idToExt.put(cacheExt.id(), cacheExt);

                if (oldCacheExt != null)
                    throw new IgniteException("Platform cache extensions cannot have the same ID [" +
                        "id=" + cacheExt.id() + ", first=" + oldCacheExt + ", second=" + cacheExt + ']');

                if (cacheExt.id() > maxExtId)
                    maxExtId = cacheExt.id();
            }

            PlatformCacheExtension[] res = new PlatformCacheExtension[maxExtId + 1];

            for (PlatformCacheExtension cacheExt : cacheExts)
                res[cacheExt.id()]= cacheExt;

            return res;
        }
        else
            //noinspection ZeroLengthArrayAllocation
            return new PlatformCacheExtension[0];
    }

    /**
     * Store and manager pair.
     */
    private static class StoreInfo {
        /** Store. */
        private final PlatformCacheStore store;

        /** Convert binary flag. */
        private final boolean convertBinary;

        /**
         * Constructor.
         *
         * @param store Store.
         * @param convertBinary Convert binary flag.
         */
        private StoreInfo(PlatformCacheStore store, boolean convertBinary) {
            this.store = store;
            this.convertBinary = convertBinary;
        }
    }
}


text:
require 'bubble-wrap/loader'
BubbleWrap.require('motion/core/ns_url_request.rb')
BubbleWrap.require('motion/http.rb')


text:
#ifndef GS_MATRIX_H
#define GS_MATRIX_H

#include "Real.h"
#include "Assert.h"
#include "Macros.h"
#include "Tags.h"
#include "Rotate.h"
#include "MatrixInitializer.h"

#include <cmath>
#include <cstring>
#include <algorithm>
#include <cstdint>
#include <initializer_list>

namespace Gs
{

#define GS_ASSERT_NxN_MATRIX \
    static_assert(Rows == Cols, GS_FILE_LINE "function can only be used with NxN matrices")

#ifdef GS_ROW_MAJOR_STORAGE
#   define GS_FOREACH_ROW_COL(r, c)             \
        for (std::size_t r = 0; r < Rows; ++r)  \
        for (std::size_t c = 0; c < Cols; ++c)
#else
#   define GS_FOREACH_ROW_COL(r, c)             \
        for (std::size_t c = 0; c < Cols; ++c)  \
        for (std::size_t r = 0; r < Rows; ++r)
#endif

/**
\brief Base matrix class.
\tparam T Specifies the data type of the matrix components.
This should be a primitive data type such as float, double, int etc.
\remarks The macro GS_ROW_MAJOR_STORAGE can be defined, to use row-major storage layout.
By default column-major storage layout is used.
The macro GS_ROW_VECTORS can be defined, to use row vectors. By default column vectors are used.
Here is an example, how a 4x4 matrix is laid-out with column- and row vectors:
\code
// 4x4 matrix with column vectors:
// / x1 y1 z1 w1 \
// | x2 y2 z2 w2 |
// | x3 y3 z3 w3 |
// \ x4 y4 z4 w4 /

// 4x4 matrix with row vectors:
// / x1 x2 x3 x4 \
// | y1 y2 y3 y4 |
// | z1 z2 z3 z4 |
// \ w1 w2 w3 w4 /

// In both cases, (w1, w2, w3, w4) stores the position in an affine transformation.
\endcode
Matrix elements can be accessed by the bracket operator:
\code
Gs::Matrix4 A;
A(0, 0) = row0column0;
A(2, 1) = row2column1;
\endcode
This is independent of the matrix storage layout and independent of the usage of row- or column vectors.
But the following function is dependent of the usage of row- or column vectors:
\code
// For column vectors:
A.At(2, 1) = row2column1;

// For row vectors:
A.At(2, 1) = row1column2;
\endcode
This function is used for easier support between row- and column vectors.
*/
template <typename T, std::size_t Rows, std::size_t Cols>
class Matrix
{

    public:

        static_assert(Rows*Cols > 0, "matrices must consist of at least 1x1 elements");

        /* ----- Static members ----- */

        //! Number of rows of this matrix type.
        static const std::size_t rows       = Rows;

        //! Number of columns of this matrix type.
        static const std::size_t columns    = Cols;

        //! Number of scalar elements of this matrix type.
        static const std::size_t elements   = Rows*Cols;

        /* ----- Typenames ----- */

        //! Specifies the typename of the scalar components.
        using ScalarType        = T;

        //! Typename of this matrix type.
        using ThisType          = Matrix<T, Rows, Cols>;

        //! Typename of the transposed of this matrix type.
        using TransposedType    = Matrix<T, Cols, Rows>;

        /* ----- Functions ----- */

        /**
        \brief Default constructor.
        \remarks If the 'GS_DISABLE_AUTO_INIT' is NOT defined, the matrix elements will be initialized. Otherwise, the matrix is in an uninitialized state.
        */
        Matrix()
        {
            #ifndef GS_DISABLE_AUTO_INIT
            Details::MatrixDefaultInitializer<T, Rows, Cols>::Initialize(*this);
            #endif
        }

        //! Copy constructor.
        Matrix(const ThisType& rhs)
        {
            *this = rhs;
        }

        //! Initializes this matrix with the specified values (row by row, and column by column).
        Matrix(const std::initializer_list<T>& values)
        {
            std::size_t i = 0, n = values.size();
            for (auto it = values.begin(); i < n; ++i, ++it)
                (*this)(i / columns, i % columns) = *it;
            for (; i < elements; ++i)
                (*this)(i / columns, i % columns) = T(0);
        }

        /**
        \brief Explicitly uninitialization constructor.
        \remarks With this constructor, the matrix is always in an uninitialized state.
        */
        explicit Matrix(UninitializeTag)
        {
            // do nothing
        }

        /**
        \brief Returns a reference to a single matrix element at the specified location.
        \param[in] row Specifies the zero-based row index. Must be in the range [0, Rows).
        \param[in] col Specifies the zero-based column index. Must be in the range [0, Cols).
        \throws std::runtime_error If the macro 'GS_ENABLE_ASSERT' and the macro 'GS_ASSERT_EXCEPTION' are defined,
        and either the row or the column is out of range.
        */
        T& operator () (std::size_t row, std::size_t col)
        {
            GS_ASSERT(row < Rows);
            GS_ASSERT(col < Cols);
            #ifdef GS_ROW_MAJOR_STORAGE
            return m_[row*Cols + col];
            #else
            return m_[col*Rows + row];
            #endif
        }

        /**
        \brief Returns a constant reference to a single matrix element at the specified location.
        \param[in] row Specifies the zero-based row index. Must be in the range [0, Rows).
        \param[in] col Specifies the zero-based column index. Must be in the range [0, Cols).
        \throws std::runtime_error If the macro 'GS_ENABLE_ASSERT' and the macro 'GS_ASSERT_EXCEPTION' are defined,
        and either the row or the column is out of range.
        */
        const T& operator () (std::size_t row, std::size_t col) const
        {
            GS_ASSERT(row < Rows);
            GS_ASSERT(col < Cols);
            #ifdef GS_ROW_MAJOR_STORAGE
            return m_[row*Cols + col];
            #else
            return m_[col*Rows + row];
            #endif
        }

        T& operator [] (std::size_t element)
        {
            GS_ASSERT(element < ThisType::elements);
            return m_[element];
        }

        const T& operator [] (std::size_t element) const
        {
            GS_ASSERT(element < ThisType::elements);
            return m_[element];
        }

        ThisType& operator += (const ThisType& rhs)
        {
            for (std::size_t i = 0; i < ThisType::elements; ++i)
                m_[i] += rhs.m_[i];
            return *this;
        }

        ThisType& operator -= (const ThisType& rhs)
        {
            for (std::size_t i = 0; i < ThisType::elements; ++i)
                m_[i] -= rhs.m_[i];
            return *this;
        }

        ThisType& operator *= (const ThisType& rhs)
        {
            GS_ASSERT_NxN_MATRIX;
            *this = (*this * rhs);
            return *this;
        }

        ThisType& operator *= (const T& rhs)
        {
            for (std::size_t i = 0; i < ThisType::elements; ++i)
                m_[i] *= rhs;
            return *this;
        }

        ThisType& operator = (const ThisType& rhs)
        {
            for (std::size_t i = 0; i < ThisType::elements; ++i)
                m_[i] = rhs.m_[i];
            return *this;
        }

        #ifdef GS_ROW_VECTORS

        T& At(std::size_t col, std::size_t row)
        {
            return (*this)(row, col);
        }

        const T& At(std::size_t col, std::size_t row) const
        {
            return (*this)(row, col);
        }

        #else

        T& At(std::size_t row, std::size_t col)
        {
            return (*this)(row, col);
        }

        const T& At(std::size_t row, std::size_t col) const
        {
            return (*this)(row, col);
        }

        #endif

        //! Restes all matrix elements to zero.
        void Reset()
        {
            for (std::size_t i = 0; i < ThisType::elements; ++i)
                m_[i] = T(0);
        }

        //! Loads the identity for this matrix.
        void LoadIdentity()
        {
            GS_ASSERT_NxN_MATRIX;
            GS_FOREACH_ROW_COL(r, c)
            {
                (*this)(r, c) = (r == c ? T(1) : T(0));
            }
        }

        //! Returns an identity matrix.
        static ThisType Identity()
        {
            ThisType result;
            result.LoadIdentity();
            return result;
        }

        //! Returns a transposed copy of this matrix.
        TransposedType Transposed() const
        {
            TransposedType result;

            GS_FOREACH_ROW_COL(r, c)
            {
                result(c, r) = (*this)(r, c);
            }

            return result;
        }

        //! Transposes this matrix.
        void Transpose()
        {
            GS_ASSERT_NxN_MATRIX;

            for (std::size_t i = 0; i + 1 < Cols; ++i)
            {
                for (std::size_t j = 1; j + i < Cols; ++j)
                {
                    std::swap(
                        m_[i*(Cols + 1) + j],
                        m_[(j + i)*Cols + i]
                    );
                }
            }
        }

        /**
        \brief Returns the determinant of this matrix.
        \see Gs::Determinant
        */
        T Determinant() const
        {
            return Gs::Determinant(*this);
        }

        /**
        Returns the trace of this matrix: M(0, 0) + M(1, 1) + ... + M(N - 1, N - 1).
        \note This can only be used for squared matrices!
        */
        T Trace() const
        {
            static_assert(Rows == Cols, "traces can only be computed for squared matrices");

            T trace = T(0);

            for (std::size_t i = 0; i < Rows; ++i)
                trace += (*this)(i, i);

            return trace;
        }

        Matrix<T, Rows, Cols> Inverse() const
        {
            Matrix<T, Rows, Cols> inv { *this };
            inv.MakeInverse();
            return inv;
        }

        bool MakeInverse()
        {
            Matrix<T, Rows, Cols> in { *this };
            return Gs::Inverse(*this, in);
        }

        //! Returns a pointer to the first element of this matrix.
        T* Ptr()
        {
            return &(m_[0]);
        }

        //! Returns a constant pointer to the first element of this matrix.
        const T* Ptr() const
        {
            return &(m_[0]);
        }

        /**
        Returns a type casted instance of this matrix.
        \tparam C Specifies the static cast type.
        */
        template <typename C> Matrix<C, Rows, Cols> Cast() const
        {
            Matrix<C, Rows, Cols> result { UninitializeTag{} };

            for (std::size_t i = 0; i < ThisType::elements; ++i)
                result[i] = static_cast<C>(m_[i]);

            return result;
        }

    private:

        T m_[ThisType::elements];

};

/* --- Global Operators --- */

template <typename T, std::size_t Rows, std::size_t Cols>
Matrix<T, Rows, Cols> operator + (const Matrix<T, Rows, Cols>& lhs, const Matrix<T, Rows, Cols>& rhs)
{
    auto result = lhs;
    result += rhs;
    return result;
}

template <typename T, std::size_t Rows, std::size_t Cols>
Matrix<T, Rows, Cols> operator - (const Matrix<T, Rows, Cols>& lhs, const Matrix<T, Rows, Cols>& rhs)
{
    auto result = lhs;
    result -= rhs;
    return result;
}

template <typename T, std::size_t Rows, std::size_t Cols>
Matrix<T, Rows, Cols> operator * (const Matrix<T, Rows, Cols>& lhs, const T& rhs)
{
    auto result = lhs;
    result *= rhs;
    return result;
}

template <typename T, std::size_t Rows, std::size_t Cols>
Matrix<T, Rows, Cols> operator * (const T& lhs, const Matrix<T, Rows, Cols>& rhs)
{
    auto result = rhs;
    result *= lhs;
    return result;
}

template <typename T, std::size_t Rows, std::size_t ColsRows, std::size_t Cols>
Matrix<T, Rows, Cols> operator * (const Matrix<T, Rows, ColsRows>& lhs, const Matrix<T, ColsRows, Cols>& rhs)
{
    Matrix<T, Rows, Cols> result { UninitializeTag{} };

    GS_FOREACH_ROW_COL(r, c)
    {
        result(r, c) = T(0);
        for (std::size_t i = 0; i < ColsRows; ++i)
            result(r, c) += lhs(r, i)*rhs(i, c);
    }

    return result;
}

/* --- Type Alias --- */

#define GS_DEF_MATRIX_TYPES_MxN(m, n)                               \
    template <typename T> using Matrix##m##n##T = Matrix<T, m, n>;  \
    using Matrix##m##n      = Matrix##m##n##T<Real>;                \
    using Matrix##m##n##f   = Matrix##m##n##T<float>;               \
    using Matrix##m##n##d   = Matrix##m##n##T<double>;              \
    using Matrix##m##n##i   = Matrix##m##n##T<std::int32_t>;        \
    using Matrix##m##n##ui  = Matrix##m##n##T<std::uint32_t>;       \
    using Matrix##m##n##b   = Matrix##m##n##T<std::int8_t>;         \
    using Matrix##m##n##ub  = Matrix##m##n##T<std::uint8_t>

GS_DEF_MATRIX_TYPES_MxN(3, 4);
GS_DEF_MATRIX_TYPES_MxN(4, 3);

#define GS_DEF_MATRIX_TYPES_NxN(n)                              \
    template <typename T> using Matrix##n##T = Matrix<T, n, n>; \
    using Matrix##n     = Matrix##n##T<Real>;                   \
    using Matrix##n##f  = Matrix##n##T<float>;                  \
    using Matrix##n##d  = Matrix##n##T<double>;                 \
    using Matrix##n##i  = Matrix##n##T<std::int32_t>;           \
    using Matrix##n##ui = Matrix##n##T<std::uint32_t>;          \
    using Matrix##n##b  = Matrix##n##T<std::int8_t>;            \
    using Matrix##n##ub = Matrix##n##T<std::uint8_t>

GS_DEF_MATRIX_TYPES_NxN(2);
GS_DEF_MATRIX_TYPES_NxN(3);
GS_DEF_MATRIX_TYPES_NxN(4);

#undef GS_DEF_MATRIX_TYPES_MxN
#undef GS_DEF_MATRIX_TYPES_NxN

#undef GS_ASSERT_NxN_MATRIX
#undef GS_FOREACH_ROW_COL

} // /namespace Gs

#endif

// ================================================================================