text:
function [source] = ft_dipolefitting(cfg, data)

% FT_DIPOLEFITTING perform grid search and non-linear fit with one or multiple
% dipoles and try to find the location where the dipole model is best able
% to explain the measured EEG or MEG topography.
%
% This function will initially scan the whole brain with a single dipole on
% a regular coarse grid, and subsequently start at the most optimal location
% with a non-linear search. Alternatively you can specify the initial
% location of the dipole(s) and the non-linear search will start from there.
%
% Use as
%   [source] = ft_dipolefitting(cfg, data)
%
% The configuration has the following general fields
%   cfg.numdipoles  = number, default is 1
%   cfg.symmetry    = 'x', 'y' or 'z' symmetry for two dipoles, can be empty (default = [])
%   cfg.channel     = Nx1 cell-array with selection of channels (default = 'all'),
%                     see FT_CHANNELSELECTION for details
%   cfg.gridsearch  = 'yes' or 'no', perform global search for initial
%                     guess for the dipole parameters (default = 'yes')
%   cfg.nonlinear   = 'yes' or 'no', perform nonlinear search for optimal
%                     dipole parameters (default = 'yes')
%
% You should specify the volume conductor model, see FT_FETCH_VOL, and the
% sensor information, see FT_FETCH_SENS.
%
% If you start with a grid search, you should specify the grid locations at
% which a test dipole will be placed. The positions of the dipoles can be
% specified as a regular 3-D grid that is aligned with the axes of the head
% coordinate system
%   cfg.grid.xgrid      = vector (e.g. -20:1:20) or 'auto' (default = 'auto')
%   cfg.grid.ygrid      = vector (e.g. -20:1:20) or 'auto' (default = 'auto')
%   cfg.grid.zgrid      = vector (e.g.   0:1:20) or 'auto' (default = 'auto')
%   cfg.grid.resolution = number (e.g. 1 cm) for automatic grid generation
% Alternatively a complete grid with dipole positions and precomputed
% leadfields can be specified
%   cfg.grid            = structure, see FT_PREPARE_LEADFIELD
% or the position of a few dipoles at locations of interest can be
% specified, for example obtained from an anatomical or functional MRI
%   cfg.grid.pos        = Nx3 matrix with position of each source
%   cfg.grid.dim        = [Nx Ny Nz] vector with dimensions in case of 3-D grid (optional)
%   cfg.grid.inside     = vector with indices of the sources inside the brain (optional)
%   cfg.grid.outside    = vector with indices of the sources outside the brain (optional)
%
% If you do not start with a grid search, you have to give a starting location
% for the nonlinear search
%   cfg.dip.pos     = initial dipole position, matrix of Ndipoles x 3
%
% The conventional approach is to fit dipoles to event-related averages, which
% within fieldtrip can be obtained from the FT_TIMELOCKANALYSIS or from
% the FT_TIMELOCKGRANDAVERAGE function. This has the additional options
%   cfg.latency     = [begin end] in seconds or 'all' (default = 'all')
%   cfg.model       = 'moving' or 'regional'
% A moving dipole model has a different position (and orientation) for each
% timepoint, or for each component. A regional dipole model has the same
% position for each timepoint or component, and a different orientation.
%
% You can also fit dipoles to the spatial topographies of an independent
% component analysis, obtained from the FT_COMPONENTANALYSIS function.
% This has the additional options
%   cfg.component   = array with numbers (can be empty -> all)
%
% You can also fit dipoles to the spatial topographies that are present
% in the data in the frequency domain, which can be obtained using the
% FT_FREQANALYSIS function. This has the additional options
%   cfg.frequency   = single number (in Hz)
%
% Low level details of the fitting can be specified in the cfg.dipfit structure
%   cfg.dipfit.display  = level of display, can be 'off', 'iter', 'notify' or 'final' (default = 'iter')
%   cfg.dipfit.optimfun = function to use, can be 'fminsearch' or 'fminunc' (default is determined automatic)
%   cfg.dipfit.maxiter  = maximum number of function evaluations allowed (default depends on the optimfun)
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
%   cfg.inputfile   =  ...
%   cfg.outputfile  =  ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_SOURCEANALYSIS, FT_PREPARE_LEADFIELD, FT_FETCH_SENS

% TODO change the output format, more suitable would be something like:
% dip.label
% dip.time
% dip.avg (instead of Vdata)
% dip.dip.pos
% dip.dip.mom
% dip.dip.model, or dip.dip.avg
% dip.dimord

% Undocumented local options:
%   cfg.dipfit.constr   = Source model constraints, depends on cfg.symmetry
%
% This function depends on FT_PREPARE_DIPOLE_GRID which has the following options:
% cfg.grid.xgrid (default set in FT_PREPARE_DIPOLE_GRID: cfg.grid.xgrid = 'auto'), documented
% cfg.grid.ygrid (default set in FT_PREPARE_DIPOLE_GRID: cfg.grid.ygrid = 'auto'), documented
% cfg.grid.zgrid (default set in FT_PREPARE_DIPOLE_GRID: cfg.grid.zgrid = 'auto'), documented
% cfg.grid.resolution, documented
% cfg.grid.pos, documented
% cfg.grid.dim, documented
% cfg.grid.inside, documented
% cfg.grid.outside, documented
% cfg.symmetry, documented
% cfg.mri
% cfg.smooth
% cfg.sourceunits
% cfg.threshold
%
% This function depends on FT_PREPARE_VOL_SENS which has the following options:
% cfg.channel (default set in FT_DIPOLEFITTING: cfg.channel = 'all'), documented
% cfg.elec, documented
% cfg.elecfile, documented
% cfg.grad, documented
% cfg.gradfile, documented
% cfg.hdmfile, documented
% cfg.order
% cfg.vol, documented

% Copyright (C) 2004-2006, 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_dipolefitting.m 5439 2012-03-12 13:17:15Z giopia $

revision = '$Id: ft_dipolefitting.m 5439 2012-03-12 13:17:15Z giopia $';

% do the general setup of the function
ft_defaults
ft_preamble help
ft_preamble callinfo
ft_preamble trackconfig
ft_preamble loadvar data

% check if the input data is valid for this function
data = ft_checkdata(data, 'datatype', {'timelock', 'freq', 'comp'}, 'feedback', 'yes');

% set the defaults
if ~isfield(cfg, 'channel'),     cfg.channel = 'all';        end
if ~isfield(cfg, 'component'),   cfg.component = [];         end  % for comp input
if ~isfield(cfg, 'frequency'),   cfg.frequency = [];         end  % for freq input
if ~isfield(cfg, 'latency'),     cfg.latency = 'all';        end
if ~isfield(cfg, 'feedback'),    cfg.feedback = 'text';      end
if ~isfield(cfg, 'gridsearch'),  cfg.gridsearch = 'yes';     end
if ~isfield(cfg, 'nonlinear'),   cfg.nonlinear = 'yes';      end
if ~isfield(cfg, 'symmetry'),    cfg.symmetry = [];          end

% put the low-level options pertaining to the dipole grid (used for initial scanning) in their own field
cfg = ft_checkconfig(cfg, 'createsubcfg',  {'grid'});

% the default for this depends on the data type
if ~isfield(cfg, 'model'),
  if ~isempty(cfg.component)
    % each component is fitted independently
    cfg.model = 'moving';
  elseif ~isempty(cfg.latency)
    % fit the data with a dipole at one location
    cfg.model = 'regional';
  elseif ~isempty(cfg.latency)
    % fit the data with a dipole at one location
    cfg.model = 'regional';
  end
end

if ~isfield(cfg, 'numdipoles')
  if isfield(cfg, 'dip')
    cfg.numdipoles = size(cfg.dip(1).pos,1);
  else
    cfg.numdipoles = 1;
  end
end

% set up the symmetry constraints
if ~isempty(cfg.symmetry)
  if cfg.numdipoles~=2
    error('symmetry constraints are only supported for two-dipole models');
  elseif strcmp(cfg.symmetry, 'x')
    % this structure is passed onto the low-level ft_dipole_fit function
    cfg.dipfit.constr.reduce = [1 2 3];         % select the parameters [x1 y1 z1]
    cfg.dipfit.constr.expand = [1 2 3 1 2 3];   % repeat them as [x1 y1 z1 x1 y1 z1]
    cfg.dipfit.constr.mirror = [1 1 1 -1 1 1];  % multiply each of them with 1 or -1, resulting in [x1 y1 z1 -x1 y1 z1]
  elseif strcmp(cfg.symmetry, 'y')
    % this structure is passed onto the low-level ft_dipole_fit function
    cfg.dipfit.constr.reduce = [1 2 3];         % select the parameters [x1 y1 z1]
    cfg.dipfit.constr.expand = [1 2 3 1 2 3];   % repeat them as [x1 y1 z1 x1 y1 z1]
    cfg.dipfit.constr.mirror = [1 1 1 1 -1 1];  % multiply each of them with 1 or -1, resulting in [x1 y1 z1 x1 -y1 z1]
  elseif strcmp(cfg.symmetry, 'z')
    % this structure is passed onto the low-level ft_dipole_fit function
    cfg.dipfit.constr.reduce = [1 2 3];         % select the parameters [x1 y1 z1]
    cfg.dipfit.constr.expand = [1 2 3 1 2 3];   % repeat them as [x1 y1 z1 x1 y1 z1]
    cfg.dipfit.constr.mirror = [1 1 1 1 1 -1];  % multiply each of them with 1 or -1, resulting in [x1 y1 z1 x1 y1 -z1]
  else
    error('unrecognized symmetry constraint');
  end
elseif ~isfield(cfg, 'dipfit') || ~isfield(cfg.dipfit, 'constr')
  % no symmetry constraints have been specified
  cfg.dipfit.constr = [];
end

if isfield(data, 'topolabel')
  % this looks like a component analysis
  iscomp = 1;
  % transform the data into a representation on which the timelocked dipole fit can perform its trick
  data = comp2timelock(cfg, data);
else
  iscomp = 0;
end

if isfield(data, 'freq')
  % this looks like a frequency analysis
  isfreq = 1;
  % transform the data into a representation on which the timelocked dipole fit can perform its trick
  data = freq2timelock(cfg, data);
else
  isfreq = 0;
end

% prepare the volume conduction model and the sensor array
% this updates the configuration with the appropriate fields
[vol, sens, cfg] = prepare_headmodel(cfg, data);

% select the desired channels, the order should be the same as in the sensor structure
[selsens, seldata] = match_str(sens.label, data.label);
Vdata = data.avg(seldata, :);

if iscomp
  % select the desired component topographies
  Vdata = Vdata(:, cfg.component);
elseif isfreq
  % the desired frequency topographies have already been selected
  Vdata = Vdata(:, :);
else
  % select the desired latencies
  if ischar(cfg.latency) && strcmp(cfg.latency, 'all')
    cfg.latency = data.time([1 end]);
  end
  tbeg = nearest(data.time, cfg.latency(1));
  tend = nearest(data.time, cfg.latency(end));
  cfg.latency = [data.time(tbeg) data.time(tend)];
  Vdata = Vdata(:, tbeg:tend);
end

nchans = size(Vdata,1);
ntime  = size(Vdata,2);
Vmodel = zeros(nchans, ntime);
fprintf('selected %d channels\n', nchans);
fprintf('selected %d topographies\n', ntime);

if nchans<cfg.numdipoles*3
  warning('not enough channels to perform a dipole fit');
end

if ntime<1
  error('no spatial topography selected');
end

% check whether EEG is average referenced
if ft_senstype(sens, 'eeg')
  if any(rv(Vdata, avgref(Vdata))>0.001)
    warning('the EEG data is not average referenced, correcting this');
  end
  Vdata = avgref(Vdata);
end

% set to zeros if no initial dipole was specified
if ~isfield(cfg, 'dip')
  cfg.dip.pos = zeros(cfg.numdipoles, 3);
  cfg.dip.mom = zeros(3*cfg.numdipoles, 1);
end

% set to zeros if no initial dipole position was specified
if ~isfield(cfg.dip, 'pos')
  cfg.dip.pos = zeros(cfg.numdipoles, 3);
end

% set to zeros if no initial dipole moment was specified
if ~isfield(cfg.dip, 'mom')
  cfg.dip.mom = zeros(3*cfg.numdipoles, 1);
end

% check the specified dipole model
if numel(cfg.dip.pos)~=cfg.numdipoles*3 || numel(cfg.dip.mom)~=cfg.numdipoles*3
  error('inconsistent number of dipoles in configuration')
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% perform the dipole scan, this is usefull for generating an initial guess
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(cfg.gridsearch, 'yes')
  % test whether we have a valid configuration for dipole scanning
  if cfg.numdipoles==1
    % this is ok
  elseif cfg.numdipoles==2 && ~isempty(cfg.dipfit.constr)
    % this is also ok
  else
    error('dipole scanning is only possible for a single dipole or a symmetric dipole pair');
  end

  % construct the dipole grid on which the gridsearch will be done
  tmpcfg = [];
  tmpcfg.vol  = vol;
  tmpcfg.grad = sens; % this can be electrodes or gradiometers
  % copy all options that are potentially used in ft_prepare_sourcemodel
  try, tmpcfg.grid        = cfg.grid;         end
  try, tmpcfg.mri         = cfg.mri;          end
  try, tmpcfg.headshape   = cfg.headshape;    end
  try, tmpcfg.tightgrid   = cfg.tightgrid;    end
  try, tmpcfg.symmetry    = cfg.symmetry;     end
  try, tmpcfg.smooth      = cfg.smooth;       end
  try, tmpcfg.threshold   = cfg.threshold;    end
  try, tmpcfg.spheremesh  = cfg.spheremesh;   end
  try, tmpcfg.inwardshift = cfg.inwardshift;  end
  try, tmpcfg.sourceunits = cfg.sourceunits;  end
  grid = ft_prepare_sourcemodel(tmpcfg);

  ft_progress('init', cfg.feedback, 'scanning grid');
  for i=1:length(grid.inside)
    ft_progress(i/length(grid.inside), 'scanning grid location %d/%d\n', i, length(grid.inside));
    indx = grid.inside(i);
    if isfield(grid, 'leadfield')
      % reuse the previously computed leadfield
      lf = grid.leadfield{indx};
    else
      lf = ft_compute_leadfield(grid.pos(indx,:), sens, vol);
    end
    % the model is V=lf*mom+noise, therefore mom=pinv(lf)*V estimates the
    % dipole moment this makes the model potential U=lf*pinv(lf)*V and the
    % model error is norm(V-U) = norm(V-lf*pinv(lf)*V) = norm((eye-lf*pinv(lf))*V)
    if any(isnan(lf(:)))
        % this might happen if one of the dipole locations of the grid is
        % outside the brain compartment
        lf(:) = 0;
    end
    switch cfg.model
      case 'regional'
        % sum the error over all latencies
        grid.error(indx,1) = sum(sum(((eye(nchans)-lf*pinv(lf))*Vdata).^2));
      case 'moving'
        % remember the error for each latency independently
        grid.error(indx,:) = sum(((eye(nchans)-lf*pinv(lf))*Vdata).^2);
      otherwise
        error('unsupported cfg.model');
    end % switch model
  end % looping over the grid
  ft_progress('close');

  switch cfg.model
    case 'regional'
      % find the grid point(s) with the minimum error
      [err, indx] = min(grid.error(grid.inside));
      dip.pos = grid.pos(grid.inside(indx),:);          % note that for a symmetric dipole pair this results in a vector
      dip.pos = reshape(dip.pos,3,cfg.numdipoles)';    % convert to a Nx3 array
      dip.mom = zeros(cfg.numdipoles*3,1);              % set the dipole moment to zero
      if cfg.numdipoles==1
        fprintf('found minimum after scanning on grid point [%g %g %g]\n', dip.pos(1), dip.pos(2), dip.pos(3));
      elseif cfg.numdipoles==2
        fprintf('found minimum after scanning on grid point [%g %g %g; %g %g %g]\n', dip.pos(1), dip.pos(2), dip.pos(3), dip.pos(4), dip.pos(5), dip.pos(6));
      end
    case 'moving'
      for t=1:ntime
        % find the grid point(s) with the minimum error
        [err, indx] = min(grid.error(grid.inside,t));
        dip(t).pos = grid.pos(grid.inside(indx),:);           % note that for a symmetric dipole pair this results in a vector
        dip(t).pos = reshape(dip(t).pos,3,cfg.numdipoles)';  % convert to a Nx3 array
        dip(t).mom = zeros(cfg.numdipoles*3,1);               % set the dipole moment to zero
        if cfg.numdipoles==1
          fprintf('found minimum after scanning for topography %d on grid point [%g %g %g]\n', t, dip(t).pos(1), dip(t).pos(2), dip(t).pos(3));
        elseif cfg.numdipoles==2
          fprintf('found minimum after scanning for topography %d on grid point [%g %g %g; %g %g %g]\n', t, dip(t).pos(1), dip(t).pos(2), dip(t).pos(3), dip(t).pos(4), dip(t).pos(5), dip(t).pos(6));
        end
      end
    otherwise
      error('unsupported cfg.model');
  end % switch model
end % if gridsearch

if strcmp(cfg.gridsearch, 'no')
  % use the initial guess supplied in the configuration for the remainder
  switch cfg.model
    case 'regional'
      dip = struct(cfg.dip);
    case 'moving'
      for t=1:ntime
        dip(t) = struct(cfg.dip);
      end
    otherwise
      error('unsupported cfg.model');
  end % switch model
end

% multiple dipoles can be represented either as a 1x(N*3) vector or as a  Nx3 matrix,
% i.e. [x1 y1 z1 x2 y2 z2] or [x1 y1 z1; x2 y2 z2]
switch cfg.model
  case 'regional'
    dip = fixdipole(dip);
  case 'moving'
    for t=1:ntime
      dip(t) = fixdipole(dip(t));
    end
  otherwise
    error('unsupported cfg.model');
end % switch model

if isfield(cfg, 'dipfit')
  % convert the structure with the additional low-level options into key-value pairs
  optarg = ft_cfg2keyval(getfield(cfg, 'dipfit'));
else
  % no additional low-level options were specified
  optarg = {};
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% perform the non-linear fit
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(cfg.nonlinear, 'yes')
  switch cfg.model
    case 'regional'
      % perform the non-linear dipole fit for all latencies together
      % catch errors due to non-convergence
      try
        dip = dipole_fit(dip, sens, vol, Vdata, optarg{:});
        success = 1;
        if cfg.numdipoles==1
          fprintf('found minimum after non-linear optimization on [%g %g %g]\n', dip.pos(1), dip.pos(2), dip.pos(3));
        elseif cfg.numdipoles==2
          fprintf('found minimum after non-linear optimization on [%g %g %g; %g %g %g]\n', dip.pos(1,1), dip.pos(1,2), dip.pos(1,3), dip.pos(2,1), dip.pos(2,2), dip.pos(2,3));
        end
      catch
        success = 0;
        disp(lasterr);
      end
    case 'moving'
      % perform the non-linear dipole fit for each latency independently
      % instead of using dip(t) =  ft_dipole_fit(dip(t),...), I am using temporary variables dipin and dipout
      % this is to prevent errors of the type "Subscripted assignment between dissimilar structures"
      dipin = dip;
      for t=1:ntime
        % catch errors due to non-convergence
        try
          dipout(t) = dipole_fit(dipin(t), sens, vol, Vdata(:,t), optarg{:});
          success(t) = 1;
          if cfg.numdipoles==1
            fprintf('found minimum after non-linear optimization for topography %d on [%g %g %g]\n', t, dipout(t).pos(1), dipout(t).pos(2), dipout(t).pos(3));
          elseif cfg.numdipoles==2
            fprintf('found minimum after non-linear optimization for topography %d on [%g %g %g; %g %g %g]\n', t, dipout(t).pos(1,1), dipout(t).pos(1,2), dipout(t).pos(1,3), dipout(t).pos(2,1), dipout(t).pos(2,2), dipout(t).pos(2,3));
          end
        catch
          dipout(t).pos = dipin(t).pos;
          dipout(t).mom = dipin(t).mom;
          success(t) = 0;
          disp(lasterr);
        end
      end
      dip = dipout;
      clear dipin dipout
    otherwise
      error('unsupported cfg.model');
  end % switch model
end % if nonlinear

if strcmp(cfg.nonlinear, 'no')
  % the optimal dipole positions are either obrained from scanning or from the initial configured seed
  switch cfg.model
    case 'regional'
      success = 1;
    case 'moving'
      success = ones(1,ntime);
    otherwise
      error('unsupported cfg.model');

  end % switch model
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute the model potential distribution and the residual variance
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch cfg.model
  case 'regional'
    if success
      % re-compute the leadfield in order to compute the model potential and dipole moment
      lf = ft_compute_leadfield(dip.pos, sens, vol);
      % compute all details of the final dipole model
      dip.mom = pinv(lf)*Vdata;
      dip.pot = lf*dip.mom;
      dip.rv  = rv(Vdata, dip.pot);
      Vmodel  = dip.pot;
    end
  case 'moving'
    for t=1:ntime
      if success(t)
        % re-compute the leadfield in order to compute the model potential and dipole moment
        lf = ft_compute_leadfield(dip(t).pos, sens, vol);
        % compute all details of the final dipole model
        dip(t).mom = pinv(lf)*Vdata(:,t);
        dip(t).pot = lf*dip(t).mom;
        dip(t).rv  = rv(Vdata(:,t), dip(t).pot);
        Vmodel(:,t) = dip(t).pot;
      end
    end
  otherwise
    error('unsupported cfg.model');
end % switch model

switch cfg.model
  case 'regional'
    if isfreq
      % the matrix with the dipole moment is encrypted and cannot be interpreted straight away
      % reconstruct the frequency representation of the data at the source level
      [dip.pow, dip.csd, dip.fourier] = timelock2freq(dip.mom);
    end
  case 'moving'
    if isfreq
      % although this is technically possible so far, it does not make any sense
      warning('a moving dipole model in the frequency domain is not supported');
    end
  otherwise
    error('unsupported cfg.model');
end % switch model

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% collect the results
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
source.label  = cfg.channel; % these channels were used in fitting
source.dip    = dip;
source.Vdata  = Vdata;  % FIXME this should be renamed (if possible w.r.t. EEGLAB)
source.Vmodel = Vmodel; % FIXME this should be renamed (if possible w.r.t. EEGLAB)

% assign a latency, frequeny or component axis to the output
if iscomp
  source.component = cfg.component;
  % FIXME assign Vdata to an output variable, idem for the model potential
elseif isfreq
  source.freq   = cfg.frequency;
  source.dimord = 'chan_freq';
  % FIXME assign Vdata to an output variable, idem for the model potential
else
  tbeg = nearest(data.time, cfg.latency(1));
  tend = nearest(data.time, cfg.latency(end));
  source.time   = data.time(tbeg:tend);
  source.dimord = 'chan_time';
end

% FIXME why would this be done?
if isfield(data, 'grad')
  % copy the gradiometer array along
  source.grad = data.grad;
end
if isfield(data, 'elec')
  % copy the electrode array along
  source.elec = data.elec;
end

% do the general cleanup and bookkeeping at the end of the function
ft_postamble trackconfig
ft_postamble callinfo
ft_postamble previous data
ft_postamble history source
ft_postamble savevar source


text:
package com.p1.mobile.p1android.content;

import android.util.Log;

public class Message extends Content {
    public static final String TAG = Message.class.getSimpleName();
    public static final String TYPE = "message";

    private String ownerId;
    private String value;

    protected Message(String id) {
        super(id);
        IOSession = new MessageIOSession();
        Log.d(TAG, "Tag " + id + " created");
    }

    @Override
    public MessageIOSession getIOSession() {
        return (MessageIOSession) super.getIOSession();
    }

    public class MessageIOSession extends ContentIOSession {

        @Override
        public String getType(){
            return TYPE;
        }

        @Override
        public void replaceFakeId(String oldId, String newId) {
            if (getId().equals(oldId)) {
                setId(newId);
                ContentHandler.getInstance().changeMessageId(oldId, newId);
                Log.d(TAG, "Id replaced from " + oldId + " to " + newId);
            }
            if (ownerId.equals(oldId)) {
                ownerId = newId;
            }
        }

        public String getOwnerId() {
            return ownerId;
        }

        public void setOwnerId(String ownerId) {
            Message.this.ownerId = ownerId;
        }

        /**
         * @return the actual message
         */
        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            Message.this.value = value;
        }

        public boolean isSending() {
            return !hasFailedNetworkOperation() && getEtag() == null;
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
local cFunc = {};		-- Local Functions
local cSetting = {};	-- Local Settings

AnimationManager = {};
AnimationManager.__index = AnimationManager;

--[[

]]

-- ///////////////////////////////
-- ///// New 				//////
-- ///// Returns: Object	//////
-- ///////////////////////////////

function AnimationManager:New(...)
	local obj = setmetatable({}, {__index = self});
	if obj.Constructor then
		obj:Constructor(...);
	end
	return obj;
end

-- ///////////////////////////////
-- ///// StopAnimation 		//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function AnimationManager:StopAnimation(player)
	return setPedAnimation(player)
end

-- ///////////////////////////////
-- ///// ShowAnimations		//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function AnimationManager:ShowAnimations(player)
	outputConsole("Available Animations:", player);
	local string = "";
	for index, object in pairs(self.animations) do
		string = string.."/"..object.sCommand.." - ";
	end
	outputConsole(string, player)
end

-- ///////////////////////////////
-- ///// Constructor 		//////
-- ///// Returns: void		//////
-- ///////////////////////////////

function AnimationManager:Constructor(...)
	-- Klassenvariablen --

	-- bDoCommand, sCommand, sBlock, sAnim, iTime, bLoop, bUpdatePosition, bInterruptable
	-- Interruptable nie auf false!

	self.animations =
	{
		Animation:New(true, "handsup", "shop", "SHP_Rob_HandsUp", 0, false, false),
		Animation:New(true, "drunk", "ped", "WALK_drunk", 0, true, true),
		Animation:New(true, "walk", "ped", "WALK_civi", 0, true, true),
		Animation:New(true, "jog", "ped", "JOG_maleA", 0, true, true),
		Animation:New(true, "bomb", "bomber", "BOM_Plant_Loop", 0, true, false),
		Animation:New(true, "robman", "shop", "ROB_Loop_Threat", 0, true, false),
		Animation:New(true, "getarrested", "ped", "ARRESTgun", 1000, false, false),
		Animation:New(true, "laught", "rapping", "Laugh_01", 0, true, false),
		Animation:New(true, "lookout", "shop", "ROB_Shifty", 0, true, false),
		Animation:New(true, "crossarms", "cop_ambient", "Coplook_loop", 0, true, false),
		Animation:New(true, "crossarms2", "cop_ambient", "Coplook_think", 0, true, false),
		Animation:New(true, "lay", "beach", "bather", 0, true, false),
		Animation:New(true, "hide", "ped", "cower", 0, true, false),
		Animation:New(true, "vomit", "food", "EAT_Vomit_P", 0, true, false),
		Animation:New(true, "wave", "ON_LOOKERS", "wave_loop", 0, true, false),
		Animation:New(true, "slapass", "sweet", "sweet_ass_slap", 0, true, false),
		Animation:New(true, "deal", "dealer", "dealer_deal", 0, true, false),
		Animation:New(true, "crack", "crack", "crckdeth2", 0, true, false),
		Animation:New(true, "ground", "beach", "ParkSit_M_loop", 0, true, false),
		Animation:New(true, "fucku", "ped", "fucku", 0, true, false),
		Animation:New(true, "chat", "ped", "IDLE_chat", 0, true, false),
		Animation:New(true, "taijiquan", "park", "Tai_Chi_Loop", 0, true, false),
		Animation:New(true, "chairsit", "beach", "SitnWait_loop_W", 0, true, false),
		Animation:New(true, "piss", "PAULNMAC", "Piss_loop", 0, true, false),
		Animation:New(true, "wank", "PAULNMAC", "wank_loop", 0, true, false),
		Animation:New(true, "tired", "PAULNMAC", "PnM_Loop_A", 0, true, false),
		Animation:New(true, "dance", "DANCING", "dance_loop", 0, false, false, true, "dance"),
		Animation:New(true, "scratchballs", "MISC", "Scratchballs_01", 0, true, false),
		Animation:New(true, "scratchhead", "MISC", "plyr_shkhead", 0, true, false),
		Animation:New(true, "bitchslap", "MISC", "bitchslap", 0, true, false),
		Animation:New(true, "smoking", "SMOKING", "M_smk_loop", 0, true, false),
		Animation:New(true, "crossarms3", "MTB", "wtchrace_loop", 0, true, false),
		Animation:New(true, "swingarms", "RAPPING", "RAP_B_Loop", 0, true, false),

	}

	-- Methoden --
	self.stopAnimationFunc = function(...) self:StopAnimation(...) end;
	self.showAnimationFunc = function(...) self:ShowAnimations(...) end;

	-- Events --
	addCommandHandler("anims", self.showAnimationFunc);

	--logger:OutputInfo("[CALLING] AnimationManager: Constructor");
end

-- EVENT HANDLER --


text:
package org.xtreemfs.flink.benchmark;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.operators.Order;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.io.CsvReader;
import org.apache.flink.api.java.tuple.Tuple10;
import org.apache.flink.api.java.tuple.Tuple7;
import org.apache.flink.api.java.tuple.Tuple8;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.fs.FileSystem.WriteMode;

public class TPCH1Benchmark extends AbstractBenchmark {

	@Override
	public void execute() {
		if (noJob) {
			return;
		}

		// select
		// l_returnflag,
		// l_linestatus,
		// sum(l_quantity) as sum_qty,
		// sum(l_extendedprice) as sum_base_price,
		// sum(l_extendedprice * (1 - l_discount)) as sum_disc_price,
		// sum(l_extendedprice * (1 - l_discount) * (1 + l_tax)) as sum_charge,
		// avg(l_quantity) as avg_qty,
		// avg(l_extendedprice) as avg_price,
		// avg(l_discount) as avg_disc,
		// count(*) as count_order
		// from
		// lineitem
		// where
		// l_shipdate <= date '1998-12-01' - interval ':1' day (3)
		// group by
		// l_returnflag,
		// l_linestatus
		// order by
		// l_returnflag,
		// l_linestatus;

		JobExecutionResult jobExecResult = null;
		long jobMillis = -1L;
		try {
			ExecutionEnvironment env = ExecutionEnvironment
					.getExecutionEnvironment();

			Configuration parameters = new Configuration();

			// 11111110000 in binary, indicate to skip the first four fields and
			// include the following seven fields.
			// 4: l_quantity, decimal
			// 5: l_extendedprice, decimal
			// 6: l_discount, decimal
			// 7: l_tax, decimal
			// 8: l_returnflag, 1-char string
			// 9: l_linestatus, 1-char string
			// 10: l_shipdate, date
			List<CsvReader> readers = new ArrayList<CsvReader>();
			if (inputChunks == 0) {
				readers.add(env
						.readCsvFile(dfsWorkingDirectoryUri + "lineitem.tbl")
						.fieldDelimiter("|").includeFields(0x7F0));
			} else {
				for (int i = 0; i < inputChunks; ++i) {
					readers.add(env
							.readCsvFile(
									dfsWorkingDirectoryUri + "lineitem.tbl."
											+ i).fieldDelimiter("|")
							.includeFields(0x7F0));
				}
			}

			final SimpleDateFormat dateParser = new SimpleDateFormat(
					"yyyy-MM-dd");
			final long referenceDate = dateParser.parse("1998-12-01").getTime();

			// 86400000 milliseconds in a day, 90 is the TPC-H Q1 validation
			// value.
			final long delta = 90 * 86400000; // (new Random().nextInt(61) + 60)
												// * 86400000;

			DataSet<Tuple7<Float, Float, Float, Float, String, String, String>> lineItems = readers
					.get(0)
					.types(Float.class, Float.class, Float.class, Float.class,
							String.class, String.class, String.class)
					.withParameters(parameters);
			for (int i = 1; i < inputChunks; ++i) {
				lineItems = lineItems.union(readers
						.get(i)
						.types(Float.class, Float.class, Float.class,
								Float.class, String.class, String.class,
								String.class).withParameters(parameters));
			}

			// Filter on date.
			DataSet<Tuple7<Float, Float, Float, Float, String, String, String>> filteredLineItems = lineItems
					.filter(new FilterFunction<Tuple7<Float, Float, Float, Float, String, String, String>>() {

						private static final long serialVersionUID = -818134663949093125L;

						@Override
						public boolean filter(
								Tuple7<Float, Float, Float, Float, String, String, String> tuple)
								throws Exception {
							Date date = dateParser.parse(tuple.f6);
							return date.getTime() <= referenceDate - delta;
						}
					});

			// Map for calculations.
			DataSet<Tuple8<String, String, Float, Float, Float, Float, Float, Long>> mappedLineItems = filteredLineItems
					.map(new MapFunction<Tuple7<Float, Float, Float, Float, String, String, String>, Tuple8<String, String, Float, Float, Float, Float, Float, Long>>() {

						private static final long serialVersionUID = 8021849053433646399L;

						@Override
						public Tuple8<String, String, Float, Float, Float, Float, Float, Long> map(
								Tuple7<Float, Float, Float, Float, String, String, String> tuple)
								throws Exception {
							float discountedPrice = tuple.f1
									* (1.0f - tuple.f2);
							return new Tuple8<String, String, Float, Float, Float, Float, Float, Long>(
									tuple.f4, tuple.f5, tuple.f0, tuple.f1,
									discountedPrice, discountedPrice
											* (1.0f + tuple.f3), tuple.f2, 1L);
						}
					});

			DataSet<Tuple10<String, String, Float, Float, Float, Float, Float, Float, Float, Long>> result = mappedLineItems
					.groupBy(0, 1)
					.sum(2)
					.andSum(3)
					.andSum(4)
					.andSum(5)
					.andSum(6)
					.andSum(7)
					.map(new MapFunction<Tuple8<String, String, Float, Float, Float, Float, Float, Long>, Tuple10<String, String, Float, Float, Float, Float, Float, Float, Float, Long>>() {

						private static final long serialVersionUID = -6596407623350163628L;

						@Override
						public Tuple10<String, String, Float, Float, Float, Float, Float, Float, Float, Long> map(
								Tuple8<String, String, Float, Float, Float, Float, Float, Long> tuple)
								throws Exception {
							return new Tuple10<String, String, Float, Float, Float, Float, Float, Float, Float, Long>(
									tuple.f0, tuple.f1, tuple.f2, tuple.f3,
									tuple.f4, tuple.f5, tuple.f2 / tuple.f7,
									tuple.f3 / tuple.f7, tuple.f6 / tuple.f7,
									tuple.f7);
						}
					}).sortPartition(0, Order.ASCENDING).setParallelism(1)
					.sortPartition(1, Order.ASCENDING).setParallelism(1);

			result.writeAsCsv(dfsWorkingDirectoryUri + "tpchq1.csv", "\n", "|",
					WriteMode.OVERWRITE);

			// print triggers program execution
			jobMillis = System.currentTimeMillis();
			result.print();
			jobMillis = System.currentTimeMillis() - jobMillis;

			jobExecResult = env.getLastJobExecutionResult();

			copyFromWorkingDirectory(outputDirectory.getAbsolutePath(),
					"tpchq1.csv");

			if (verifyResults) {
				// Output according to dbgen (factor 1.0):
				// l|l|sum_qty|sum_base_price|sum_disc_price|sum_charge|avg_qty|avg_price|avg_disc|count_order
				// A|F|37734107.00|56586554400.73|53758257134.87|55909065222.83|25.52|38273.13|0.05|1478493
				// N|F|991417.00|1487504710.38|1413082168.05|1469649223.19|25.52|38284.47|0.05|38854
				// N|O|74476040.00|111701729697.74|106118230307.61|110367043872.50|25.50|38249.12|0.05|2920374
				// R|F|37719753.00|56568041380.90|53741292684.60|55889619119.83|25.51|38250.85|0.05|1478870

				// So we cannot test the sums and counts, but we can check the
				// averages and the order.
				List<Tuple10<String, String, Float, Float, Float, Float, Float, Float, Float, Long>> results = result
						.collect();
				if (results.size() != 4) {
					System.out.println("Incorrect number of results: "
							+ results.size() + ", expected 4.");
				} else {
					checkResult(results.get(0), "A", "F", 25.52f, 38273.13f,
							0.05f, 0.002f);
					checkResult(results.get(1), "N", "F", 25.52f, 38284.47f,
							0.05f, 0.002f);
					checkResult(results.get(2), "N", "O", 25.50f, 38249.12f,
							0.05f, 0.002f);
					checkResult(results.get(3), "R", "F", 25.51f, 38250.85f,
							0.05f, 0.002f);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("Error during execution: "
					+ e.getMessage(), e);
		}

		System.out.println("job (wall): " + jobMillis + "ms, job (flink): "
				+ jobExecResult.getNetRuntime() + "ms");
	}

	private static void checkResult(
			Tuple10<String, String, Float, Float, Float, Float, Float, Float, Float, Long> result,
			String returnFlag, String lineStatus, float avgQty, float avgPrice,
			float avgDisc, float tolerance) {
		if (!returnFlag.equals(result.f0) || !lineStatus.equals(result.f1)) {
			System.out.print("Element is in the wrong order: " + result.f0
					+ "|" + result.f1 + ", expecting " + returnFlag + "|"
					+ lineStatus);
		} else {
			System.out.print("Order is fine");
		}

		float difference = Math.abs(result.f6 - avgQty) / avgQty;
		if (difference > tolerance) {
			System.out.print("; Avg. Qty. is over tolerance: " + difference
					+ ", expecting " + tolerance);
		} else {
			System.out.print("; Avg. Qty. is fine (" + difference + ")");
		}

		difference = Math.abs(result.f7 - avgPrice) / avgPrice;
		if (difference > tolerance) {
			System.out.print("; Avg. Price is over tolerance: " + difference
					+ ", expecting " + tolerance);
		} else {
			System.out.print("; Avg. Price is fine (" + difference + ")");
		}

		difference = Math.abs(result.f8 - avgDisc) / avgDisc;
		if (difference > tolerance) {
			System.out.println("; Avg. Disc. is over tolerance: " + difference
					+ ", expecting " + tolerance + ".");
		} else {
			System.out.println("; Avg. Disc. is fine (" + difference + ").");
		}
	}

	@Override
	public String getName() {
		return "tpch1";
	}

}


text:
<?php

namespace Magento\ConfigurableProduct\Test\Unit\Model\Plugin;

use Magento\ConfigurableProduct\Model\Plugin\AroundProductRepositorySave;

class AroundProductRepositorySaveTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var AroundProductRepositorySave
     */
    protected $plugin;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $productRepositoryMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $productOptionRepositoryMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $productFactoryMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $productMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $productExtensionMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $configurableTypeFactoryMock;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $productInterfaceMock;

    /**
     * @var \Closure
     */
    protected $closureMock;

    protected function setUp()
    {
        $this->productRepositoryMock = $this->getMock('Magento\Catalog\Api\ProductRepositoryInterface');
        $this->productOptionRepositoryMock = $this->getMock(
            'Magento\ConfigurableProduct\Api\OptionRepositoryInterface'
        );
        $this->configurableTypeFactoryMock = $this->getMock(
            '\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\ConfigurableFactory',
            ['create'],
            [],
            '',
            false
        );
        $this->productInterfaceMock = $this->getMock('\Magento\Catalog\Api\Data\ProductInterface');
        $this->productMock = $this->getMock(
            'Magento\Catalog\Model\Product',
            ['getExtensionAttributes', 'getTypeId', 'getSku', 'getStoreId', 'getId', 'getTypeInstance'],
            [],
            '',
            false
        );
        $this->closureMock = function () {
            return $this->productMock;
        };

        $this->productFactoryMock = $this->getMockBuilder('\Magento\Catalog\Model\ProductFactory')
            ->setMethods(['create'])
            ->disableOriginalConstructor()
            ->getMock();
        $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $this->plugin = $objectManager->getObject(
            'Magento\ConfigurableProduct\Model\Plugin\AroundProductRepositorySave',
            [
                'optionRepository' => $this->productOptionRepositoryMock,
                'productFactory' => $this->productFactoryMock,
                'typeConfigurableFactory' => $this->configurableTypeFactoryMock
            ]
        );

        $this->productExtensionMock = $this->getMock(
            'Magento\Catalog\Api\Data\ProductExtension',
            [
                'getConfigurableProductOptions',
                'getConfigurableProductLinks',
                'setConfigurableProductOptions',
                'setConfigurableProductLinks',
            ],
            [],
            '',
            false
        );
    }

    public function testAroundSaveWhenProductIsSimple()
    {
        $this->productMock->expects($this->once())->method('getTypeId')->willReturn('simple');
        $this->productMock->expects($this->never())->method('getExtensionAttributes');

        $this->assertEquals(
            $this->productMock,
            $this->plugin->aroundSave($this->productRepositoryMock, $this->closureMock, $this->productMock)
        );
    }

    public function testAroundSaveWithoutOptions()
    {
        $this->productInterfaceMock->expects($this->once())->method('getTypeId')
            ->willReturn(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE);
        $this->productInterfaceMock->expects($this->once())
            ->method('getExtensionAttributes')
            ->willReturn($this->productExtensionMock);
        $this->productExtensionMock->expects($this->once())
            ->method('getConfigurableProductOptions')
            ->willReturn(null);
        $this->productExtensionMock->expects($this->once())
            ->method('getConfigurableProductLinks')
            ->willReturn(null);

        $this->assertEquals(
            $this->productMock,
            $this->plugin->aroundSave($this->productRepositoryMock, $this->closureMock, $this->productInterfaceMock)
        );
    }

    protected function setupProducts($productIds, $attributeCode, $additionalProductId = null)
    {
        $count = 0;
        $products = [];
        foreach ($productIds as $productId) {
            $productMock = $this->getMockBuilder('\Magento\Catalog\Model\Product')
                ->disableOriginalConstructor()
                ->getMock();
            $productMock->expects($this->once())
                ->method('load')
                ->with($productId)
                ->willReturnSelf();
            $productMock->expects($this->once())
                ->method('getId')
                ->willReturn($productId);
            $productMock->expects($this->any())
                ->method('getData')
                ->with($attributeCode)
                ->willReturn($productId);
            $this->productFactoryMock->expects($this->at($count))
                ->method('create')
                ->willReturn($productMock);
            $products[] = $productMock;
            $count++;
        }

        if ($additionalProductId) {
            $nonExistingProductMock = $this->getMockBuilder('\Magento\Catalog\Model\Product')
                ->disableOriginalConstructor()
                ->getMock();
            $nonExistingProductMock->expects($this->once())
                ->method('load')
                ->with($additionalProductId)
                ->willReturnSelf();
            $this->productFactoryMock->expects($this->at($count))
                ->method('create')
                ->willReturn($nonExistingProductMock);
            $products[] = $nonExistingProductMock;
        }
        return $products;
    }

    protected function setupConfigurableProductAttributes($attributeCodes)
    {
        $configurableProductTypeMock = $this->getMockBuilder(
            '\Magento\ConfigurableProduct\Model\Product\Type\Configurable'
        )->disableOriginalConstructor()->getMock();

        $this->productMock->expects($this->once())
            ->method('getTypeInstance')
            ->willReturn($configurableProductTypeMock);

        $configurableAttributes = [];
        foreach ($attributeCodes as $attributeCode) {
            $configurableAttribute = $this->getMockBuilder(
                '\Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute'
            )->setMethods(['getProductAttribute'])
                ->disableOriginalConstructor()
                ->getMock();
            $productAttributeMock = $this->getMockBuilder('\Magento\Catalog\Model\ResourceModel\Eav\Attribute')
                ->disableOriginalConstructor()
                ->getMock();
            $productAttributeMock->expects($this->once())
                ->method('getAttributeCode')
                ->willReturn($attributeCode);
            $configurableAttribute->expects($this->once())
                ->method('getProductAttribute')
                ->willReturn($productAttributeMock);
            $configurableAttributes[] = $configurableAttribute;
        }

        $configurableProductTypeMock->expects($this->once())
            ->method('getConfigurableAttributes')
            ->with($this->productMock)
            ->willReturn($configurableAttributes);

        return $this;
    }

    public function testAroundSaveWithLinks()
    {
        $links = [4, 5];
        $configurableAttributeCode = 'color';
        $this->productMock->expects($this->once())->method('getTypeId')
            ->willReturn(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE);
        $this->productMock->expects($this->once())
            ->method('getExtensionAttributes')
            ->willReturn($this->productExtensionMock);
        $this->productExtensionMock->expects($this->once())
            ->method('getConfigurableProductOptions')
            ->willReturn(null);
        $this->productExtensionMock->expects($this->once())
            ->method('getConfigurableProductLinks')
            ->willReturn($links);

        $this->setupConfigurableProductAttributes([$configurableAttributeCode]);
        $this->setupProducts($links, $configurableAttributeCode);

        $configurableTypeMock = $this->getMockBuilder(
            '\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable'
        )->disableOriginalConstructor()->getMock();
        $this->configurableTypeFactoryMock->expects($this->once())
            ->method('create')
            ->willReturn($configurableTypeMock);
        $configurableTypeMock->expects($this->once())
            ->method('saveProducts')
            ->with($this->productMock, $links);

        $productSku = 'configurable-sku';
        $this->productMock->expects($this->any())
            ->method('getSku')
            ->willReturn($productSku);
        $newProductMock = $this->setupReload($productSku);

        $this->assertEquals(
            $newProductMock,
            $this->plugin->aroundSave($this->productRepositoryMock, $this->closureMock, $this->productMock)
        );
    }

    /**
     * @expectedException \Magento\Framework\Exception\InputException
     * @expectedExceptionMessage Product with id "6" does not exist.
     */
    public function testAroundSaveWithNonExistingLinks()
    {
        $links = [4, 5];
        $nonExistingId = 6;
        $configurableAttributeCode = 'color';

        $this->setupConfigurableProductAttributes([$configurableAttributeCode]);
        $productMocks = $this->setupProducts($links, $configurableAttributeCode, $nonExistingId);
        $nonExistingProductMock = $productMocks[2];
        $nonExistingProductMock->expects($this->once())
            ->method('getId')
            ->willReturn(null);
        $links[] = $nonExistingId;

        $this->productMock->expects($this->once())->method('getTypeId')
            ->willReturn(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE);
        $this->productMock->expects($this->once())
            ->method('getExtensionAttributes')
            ->willReturn($this->productExtensionMock);
        $this->productExtensionMock->expects($this->once())
            ->method('getConfigurableProductOptions')
            ->willReturn(null);
        $this->productExtensionMock->expects($this->once())
            ->method('getConfigurableProductLinks')
            ->willReturn($links);

        $configurableTypeMock = $this->getMockBuilder(
            '\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable'
        )->disableOriginalConstructor()->getMock();
        $this->configurableTypeFactoryMock->expects($this->once())
            ->method('create')
            ->willReturn($configurableTypeMock);
        $configurableTypeMock->expects($this->never())
            ->method('saveProducts')
            ->with($this->productMock, $links);

        $this->plugin->aroundSave($this->productRepositoryMock, $this->closureMock, $this->productMock);
    }

    /**
     * @expectedException \Magento\Framework\Exception\InputException
     * @expectedExceptionMessage Product with id "6" does not contain required attribute "color".
     */
    public function testAroundSaveWithLinksWithMissingAttribute()
    {
        $links = [4, 5];
        $simpleProductId = 6;
        $configurableAttributeCode = 'color';

        $this->setupConfigurableProductAttributes([$configurableAttributeCode]);
        $productMocks = $this->setupProducts($links, $configurableAttributeCode, $simpleProductId);
        $simpleProductMock = $productMocks[2];
        $simpleProductMock->expects($this->once())
            ->method('getId')
            ->willReturn($simpleProductId);
        $simpleProductMock->expects($this->any())
            ->method('getData')
            ->with($configurableAttributeCode)
            ->willReturn(null);

        $links[] = $simpleProductId;

        $this->productMock->expects($this->once())->method('getTypeId')
            ->willReturn(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE);
        $this->productMock->expects($this->once())
            ->method('getExtensionAttributes')
            ->willReturn($this->productExtensionMock);
        $this->productExtensionMock->expects($this->once())
            ->method('getConfigurableProductOptions')
            ->willReturn(null);
        $this->productExtensionMock->expects($this->once())
            ->method('getConfigurableProductLinks')
            ->willReturn($links);

        $configurableTypeMock = $this->getMockBuilder(
            '\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable'
        )->disableOriginalConstructor()->getMock();
        $this->configurableTypeFactoryMock->expects($this->once())
            ->method('create')
            ->willReturn($configurableTypeMock);
        $configurableTypeMock->expects($this->never())
            ->method('saveProducts')
            ->with($this->productMock, $links);

        $this->plugin->aroundSave($this->productRepositoryMock, $this->closureMock, $this->productMock);
    }

    /**
     * @expectedException \Magento\Framework\Exception\InputException
     * @expectedExceptionMessage Products "6" and 4 have the same set of attribute values.
     */
    public function testAroundSaveWithLinksWithDuplicateAttributes()
    {
        $links = [4, 5];
        $simpleProductId = 6;
        $configurableAttributeCode = 'color';

        $this->setupConfigurableProductAttributes([$configurableAttributeCode]);
        $productMocks = $this->setupProducts($links, $configurableAttributeCode, $simpleProductId);
        $simpleProductMock = $productMocks[2];
        $simpleProductMock->expects($this->once())
            ->method('getId')
            ->willReturn($simpleProductId);
        $simpleProductMock->expects($this->any())
            ->method('getData')
            ->with($configurableAttributeCode)
            ->willReturn(4);

        $links[] = $simpleProductId;

        $this->productMock->expects($this->once())->method('getTypeId')
            ->willReturn(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE);
        $this->productMock->expects($this->once())
            ->method('getExtensionAttributes')
            ->willReturn($this->productExtensionMock);
        $this->productExtensionMock->expects($this->once())
            ->method('getConfigurableProductOptions')
            ->willReturn(null);
        $this->productExtensionMock->expects($this->once())
            ->method('getConfigurableProductLinks')
            ->willReturn($links);

        $configurableTypeMock = $this->getMockBuilder(
            '\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable'
        )->disableOriginalConstructor()->getMock();
        $this->configurableTypeFactoryMock->expects($this->once())
            ->method('create')
            ->willReturn($configurableTypeMock);
        $configurableTypeMock->expects($this->never())
            ->method('saveProducts')
            ->with($this->productMock, $links);

        $this->plugin->aroundSave($this->productRepositoryMock, $this->closureMock, $this->productMock);
    }

    /**
     * @expectedException \Magento\Framework\Exception\InputException
     * @expectedExceptionMessage The configurable product does not have any variation attribute.
     */
    public function testAroundSaveWithLinksWithoutVariationAttributes()
    {
        $links = [4, 5];

        $this->setupConfigurableProductAttributes([]);

        $this->productMock->expects($this->once())->method('getTypeId')
            ->willReturn(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE);
        $this->productMock->expects($this->once())
            ->method('getExtensionAttributes')
            ->willReturn($this->productExtensionMock);
        $this->productExtensionMock->expects($this->once())
            ->method('getConfigurableProductOptions')
            ->willReturn(null);
        $this->productExtensionMock->expects($this->once())
            ->method('getConfigurableProductLinks')
            ->willReturn($links);

        $this->plugin->aroundSave($this->productRepositoryMock, $this->closureMock, $this->productMock);
    }

    public function testAroundSaveWithOptions()
    {
        $productSku = "configurable_sku";
        $this->productInterfaceMock->expects($this->once())->method('getTypeId')
            ->willReturn(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE);
        //two options with id 5 and 6
        $options = $this->setupOptions([5, 6]);
        //two existing options with id 4 and 5
        $this->setupExistingOptions([4, 5]);

        $this->productMock->expects($this->any())->method('getSku')
            ->will($this->returnValue($productSku));

        $this->productOptionRepositoryMock->expects($this->at(0))
            ->method('save')
            ->with($productSku, $options[0]);
        $this->productOptionRepositoryMock->expects($this->at(1))
            ->method('save')
            ->with($productSku, $options[1]);
        $this->productOptionRepositoryMock->expects($this->at(2))
            ->method('deleteById')
            ->with($productSku, 4);

        $configurableProductTypeMock = $this->getMockBuilder(
            '\Magento\ConfigurableProduct\Model\Product\Type\Configurable'
        )->disableOriginalConstructor()->getMock();
        $configurableProductTypeMock->expects($this->once())
            ->method('resetConfigurableAttributes')
            ->with($this->productMock)
            ->willReturnSelf();
        $this->productMock->expects($this->any())
            ->method('getTypeInstance')
            ->willReturn($configurableProductTypeMock);

        $newProductMock = $this->setupReload($productSku);

        $this->assertEquals(
            $newProductMock,
            $this->plugin->aroundSave($this->productRepositoryMock, $this->closureMock, $this->productInterfaceMock)
        );
    }

    protected function setupReload($productSku)
    {
        $newProductMock = $this->getMockBuilder('Magento\Catalog\Api\Data\ProductInterface')
            ->disableOriginalConstructor()->getMock();
        $this->productRepositoryMock->expects($this->once())
            ->method('get')
            ->with($productSku, false, null, true)
            ->willReturn($newProductMock);
        return $newProductMock;
    }

    protected function setupExistingOptions(array $existingOptionIds)
    {
        $options = [];
        foreach ($existingOptionIds as $existingOptionId) {
            $optionMock = $this->getMock('\Magento\ConfigurableProduct\Api\Data\OptionInterface');
            $optionMock->expects($this->any())
                ->method('getId')
                ->willReturn($existingOptionId);
            $options[] = $optionMock;
        }

        $productExtensionMock = $this->getMockBuilder('Magento\Catalog\Api\Data\ProductExtension')
            ->disableOriginalConstructor()
            ->setMethods(['getConfigurableProductOptions'])
            ->getMock();
        $productExtensionMock->expects($this->any())
            ->method('getConfigurableProductOptions')
            ->willReturn($options);

        $this->productMock->expects($this->any())
            ->method('getExtensionAttributes')
            ->willReturn($productExtensionMock);
    }

    protected function setupOptions(array $optionIds)
    {
        $options = [];
        foreach ($optionIds as $optionId) {
            $optionMock = $this->getMock('\Magento\ConfigurableProduct\Api\Data\OptionInterface');
            $optionMock->expects($this->any())
                ->method('getId')
                ->willReturn($optionId);
            $options[] = $optionMock;
        }

        $productExtensionMock = $this->getMockBuilder('Magento\Catalog\Api\Data\ProductExtension')
            ->disableOriginalConstructor()
            ->setMethods(['getConfigurableProductOptions', 'getConfigurableProductLinks'])
            ->getMock();
        $productExtensionMock->expects($this->any())
            ->method('getConfigurableProductOptions')
            ->willReturn($options);
        $productExtensionMock->expects($this->any())
            ->method('getConfigurableProductLinks')
            ->willReturn(null);

        $this->productInterfaceMock->expects($this->once())
            ->method('getExtensionAttributes')
            ->willReturn($productExtensionMock);
        return $options;
    }
}


text:
defineSuite([
        'Core/queryToObject'
    ], function(
        queryToObject) {
    'use strict';

    it('can decode data', function() {
        var str = 'key1=some%20value&key2=a%2Fb';
        var obj = queryToObject(str);

        expect(obj).toEqual({
            key1 : 'some value',
            key2 : 'a/b'
        });

        str = 'spec=Core%2FobjectToQuery%20can%20encode%20data.&debug=Core%2FobjectToQuery%20can%20encode%20data.';
        obj = queryToObject(str);

        expect(obj).toEqual({
            spec : 'Core/objectToQuery can encode data.',
            debug : 'Core/objectToQuery can encode data.'
        });

        str = 'q=query+string';
        obj = queryToObject(str);

        expect(obj).toEqual({
            q : 'query string'
        });
    });

    it('can decode arrays of data', function() {
        var str = 'key=a&key=b';
        var obj = queryToObject(str);

        expect(obj).toEqual({
            key : ['a', 'b']
        });
    });

    it('can decode blank', function() {
        expect(queryToObject('')).toEqual({});
    });

    it('requires queryString', function() {
        expect(function() {
            queryToObject();
        }).toThrowDeveloperError();
    });
});


text:
<?php

declare(strict_types = 1);

namespace Nepttune\Model;

use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;

class PushNotificationModel
{
    use \Nette\SmartObject;

    /** @var SubscriptionTable */
    protected $subscriptionTable;

    /** @var  WebPush */
    protected $webPush;

    /** @var  \Nette\Http\Request */
    protected $request;

    public function __construct(
        array $parameters,
        SubscriptionTable $subscriptionTable,
        \Nette\Http\Request $request
    )
    {
        $this->subscriptionTable = $subscriptionTable;
        $this->webPush = new WebPush(['VAPID' => $parameters]);
        $this->request = $request;
    }

    public function __destruct()
    {
        $this->flush();
    }

    /**
     * Output msg queue
     */
    public function flush() : void
    {
        $this->webPush->flush();
    }

    /**
     * Send notification to all active subscriptions.
     * @param string $msg
     */
    public function sendAll($msg) : void
    {
        foreach ($this->subscriptionTable->findActive() as $row)
        {
            $this->sendNotification($row, $msg, false);
        }

        if ($flush)
        {
            $this->flush();
        }
    }

    /**
     * Send notification to all subscriptions paired with specific user.
     * @param int $userId
     * @param string $msg
     * @param string $dest
     * @param bool $flush
     */
    public function sendByUserId(int $userId, string $msg, ?string $dest = null, bool $flush = false) : void
    {
        $msg = $this->composeMsg($msg, $dest);

        foreach ($this->subscriptionTable->findActive()->where('user_id', $userId) as $row)
        {
            $this->sendNotification($row, $msg, false);
        }

        if ($flush)
        {
            $this->flush();
        }
    }

    /**
     * Send notification to all users subscribed to specific type.
     * @param int $typeId
     * @param string $msg
     * @param string $dest
     * @param bool $flush
     */
    public function sendByType(int $typeId, string $msg, ?string $dest = null, bool $flush = false) : void
    {
        $msg = $this->composeMsg($msg, $dest);

        $subscriptions = $this->subscriptionTable->findAll()
            ->where('subscription.active', 1)
            ->where('user.active', 1)
            ->where('user:user_subscription_type.subscription_type_id', $typeId);

        foreach ($subscriptions as $row)
        {
            $this->sendNotification($row, $msg, false);
        }

        if ($flush)
        {
            $this->flush();
        }
    }

    /**
     * Save or update subscriber information.
     * @throws \Nette\Application\BadRequestException
     * @param int $userId
     */
    public function saveSubscription(int $userId = null) : void
    {
        $json = \file_get_contents('php://input');

        if (!$json) {
            return;
        }

        $data = \json_decode($json, true);

        if (!$data || empty($data['endpoint']) || empty($data['publicKey']) || empty($data['authToken'])) {
            return;
        }

        $row = $this->subscriptionTable->findActive()->where('endpoint', $data['endpoint'])->fetch();

        switch ($this->request->getMethod()) {
            case 'POST':
            case 'PUT':
            {
                if ($row instanceof \Nette\Database\Table\ActiveRow) {
                    $row->update([
                        'user_id' => $userId ?: $row->user_id ?: null,
                        'key' => $data['publicKey'],
                        'token' => $data['authToken'],
                        'encoding' => $data['contentEncoding']
                    ]);

                    return;
                }

                $rowId = $this->subscriptionTable->insert([
                    'user_id' => $userId,
                    'endpoint' => $data['endpoint'],
                    'key' => $data['publicKey'],
                    'token' => $data['authToken'],
                    'encoding' => $data['contentEncoding']
                ]);
                $row = $this->subscriptionTable->getRow($rowId);
                $this->sendNotification($row, 'Notifications enabled!', true);

                return;
            }
            case 'DELETE':
            {
                if ($row instanceof \Nette\Database\Table\ActiveRow) {
                    $row->update([
                        'active' => 0
                    ]);
                }

                return;
            }
            default:
                throw new \Nette\Application\BadRequestException();
        }
    }

    private function sendNotification($row, string $msg, bool $flush = false) : void
    {
        $subscription = Subscription::create([
            'endpoint' => $row->endpoint,
            'publicKey' => $row->key,
            'authToken' => $row->token,
            'contentEncoding' => $row->encoding
        ]);

        $this->webPush->sendNotification($subscription, $msg, $flush);
    }

    private function composeMsg(string $msg, ?string $dest) : string
    {
        return $dest ? \json_encode(['text' => $msg, 'destination' => $dest]) : $msg;
    }
}


text:
<?php

namespace TelegramBot\Types;

/**
 * Represents a link to a voice message stored on the Telegram servers.
 * By default, this voice message will be sent by the user.
 * Alternatively, you can use input_message_content to send a message with the specified content instead of the voice
 * message.
 *
 * Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them.
 * @see https://core.telegram.org/bots/api#inlinequeryresultcachedvoice
 */
class InlineQueryResultCachedVoice
{
    /**
     * Type of the result, must be voice
     * @var string $type
     */
    public $type;

    /**
     * Unique identifier for this result, 1-64 bytes
     * @var string $id
     */
    public $id;

    /**
     * A valid file identifier for the voice message
     * @var string $voice_file_id
     */
    public $voice_file_id;

    /**
     * Voice message title
     * @var string $title
     */
    public $title;

    /**
     * Optional. Caption, 0-1024 characters
     * @var string $caption
     */
    public $caption;

    /**
     * Optional. Send {@see https://core.telegram.org/bots/api#markdown-style Markdown} or
     * {@see https://core.telegram.org/bots/api#html-style HTML},
     * if you want Telegram apps to show
     * {@see https://core.telegram.org/bots/api#formatting-options bold, italic, fixed-width text or inline URLs}
     * in your bot's message.
     * @var string $parse_mode
     */
    public $parse_mode;

    /**
     * Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode
     * @var MessageEntity[] $caption_entities
     */
    public $caption_entities;

    /**
     * Optional.
     * {@see https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating Inline keyboard}
     * attached to the message
     * @var InlineKeyboardMarkup $reply_markup
     */
    public $reply_markup;

    /**
     * Optional. Content of the message to be sent instead of the voice message
     * @var InputTextMessageContent|InputLocationMessageContent|InputVenueMessageContent|InputContactMessageContent $input_message_content
     */
    public $input_message_content;
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Message\Admin\Account;

class ResetPassword
{
    public function __construct(
        public string $resetPasswordToken,
        public ?string $newPassword = null,
        public ?string $confirmNewPassword = null,
    ) {
    }
}


text:
"""
Functions
---------
.. autosummary::
   :toctree: generated/

    fmin_l_bfgs_b

"""

## License for the Python wrapper
## ==============================

## Copyright (c) 2004 David M. Cooke <cookedm@physics.mcmaster.ca>

## Permission is hereby granted, free of charge, to any person obtaining a
## copy of this software and associated documentation files (the "Software"),
## to deal in the Software without restriction, including without limitation
## the rights to use, copy, modify, merge, publish, distribute, sublicense,
## and/or sell copies of the Software, and to permit persons to whom the
## Software is furnished to do so, subject to the following conditions:

## The above copyright notice and this permission notice shall be included in
## all copies or substantial portions of the Software.

## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
## DEALINGS IN THE SOFTWARE.

## Modifications by Travis Oliphant and Enthought, Inc. for inclusion in SciPy

import numpy as np
from numpy import array, asarray, float64, zeros
from . import _lbfgsb
from ._optimize import (MemoizeJac, OptimizeResult,
                       _check_unknown_options, _prepare_scalar_function)
from ._constraints import old_bound_to_new

from scipy.sparse.linalg import LinearOperator

__all__ = ['fmin_l_bfgs_b', 'LbfgsInvHessProduct']

def fmin_l_bfgs_b(func, x0, fprime=None, args=(),
                  approx_grad=0,
                  bounds=None, m=10, factr=1e7, pgtol=1e-5,
                  epsilon=1e-8,
                  iprint=-1, maxfun=15000, maxiter=15000, disp=None,
                  callback=None, maxls=20):
    """
    Minimize a function func using the L-BFGS-B algorithm.

    Parameters
    ----------
    func : callable f(x,*args)
        Function to minimize.
    x0 : ndarray
        Initial guess.
    fprime : callable fprime(x,*args), optional
        The gradient of `func`. If None, then `func` returns the function
        value and the gradient (``f, g = func(x, *args)``), unless
        `approx_grad` is True in which case `func` returns only ``f``.
    args : sequence, optional
        Arguments to pass to `func` and `fprime`.
    approx_grad : bool, optional
        Whether to approximate the gradient numerically (in which case
        `func` returns only the function value).
    bounds : list, optional
        ``(min, max)`` pairs for each element in ``x``, defining
        the bounds on that parameter. Use None or +-inf for one of ``min`` or
        ``max`` when there is no bound in that direction.
    m : int, optional
        The maximum number of variable metric corrections
        used to define the limited memory matrix. (The limited memory BFGS
        method does not store the full hessian but uses this many terms in an
        approximation to it.)
    factr : float, optional
        The iteration stops when
        ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``,
        where ``eps`` is the machine precision, which is automatically
        generated by the code. Typical values for `factr` are: 1e12 for
        low accuracy; 1e7 for moderate accuracy; 10.0 for extremely
        high accuracy. See Notes for relationship to `ftol`, which is exposed
        (instead of `factr`) by the `scipy.optimize.minimize` interface to
        L-BFGS-B.
    pgtol : float, optional
        The iteration will stop when
        ``max{|proj g_i | i = 1, ..., n} <= pgtol``
        where ``pg_i`` is the i-th component of the projected gradient.
    epsilon : float, optional
        Step size used when `approx_grad` is True, for numerically
        calculating the gradient
    iprint : int, optional
        Controls the frequency of output. ``iprint < 0`` means no output;
        ``iprint = 0``    print only one line at the last iteration;
        ``0 < iprint < 99`` print also f and ``|proj g|`` every iprint iterations;
        ``iprint = 99``   print details of every iteration except n-vectors;
        ``iprint = 100``  print also the changes of active set and final x;
        ``iprint > 100``  print details of every iteration including x and g.
    disp : int, optional
        If zero, then no output. If a positive number, then this over-rides
        `iprint` (i.e., `iprint` gets the value of `disp`).
    maxfun : int, optional
        Maximum number of function evaluations. Note that this function
        may violate the limit because of evaluating gradients by numerical
        differentiation.
    maxiter : int, optional
        Maximum number of iterations.
    callback : callable, optional
        Called after each iteration, as ``callback(xk)``, where ``xk`` is the
        current parameter vector.
    maxls : int, optional
        Maximum number of line search steps (per iteration). Default is 20.

    Returns
    -------
    x : array_like
        Estimated position of the minimum.
    f : float
        Value of `func` at the minimum.
    d : dict
        Information dictionary.

        * d['warnflag'] is

          - 0 if converged,
          - 1 if too many function evaluations or too many iterations,
          - 2 if stopped for another reason, given in d['task']

        * d['grad'] is the gradient at the minimum (should be 0 ish)
        * d['funcalls'] is the number of function calls made.
        * d['nit'] is the number of iterations.

    See also
    --------
    minimize: Interface to minimization algorithms for multivariate
        functions. See the 'L-BFGS-B' `method` in particular. Note that the
        `ftol` option is made available via that interface, while `factr` is
        provided via this interface, where `factr` is the factor multiplying
        the default machine floating-point precision to arrive at `ftol`:
        ``ftol = factr * numpy.finfo(float).eps``.

    Notes
    -----
    License of L-BFGS-B (FORTRAN code):

    The version included here (in fortran code) is 3.0
    (released April 25, 2011). It was written by Ciyou Zhu, Richard Byrd,
    and Jorge Nocedal <nocedal@ece.nwu.edu>. It carries the following
    condition for use:

    This software is freely available, but we expect that all publications
    describing work using this software, or all commercial products using it,
    quote at least one of the references given below. This software is released
    under the BSD License.

    References
    ----------
    * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound
      Constrained Optimization, (1995), SIAM Journal on Scientific and
      Statistical Computing, 16, 5, pp. 1190-1208.
    * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B,
      FORTRAN routines for large scale bound constrained optimization (1997),
      ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560.
    * J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B,
      FORTRAN routines for large scale bound constrained optimization (2011),
      ACM Transactions on Mathematical Software, 38, 1.

    """
    # handle fprime/approx_grad
    if approx_grad:
        fun = func
        jac = None
    elif fprime is None:
        fun = MemoizeJac(func)
        jac = fun.derivative
    else:
        fun = func
        jac = fprime

    # build options
    opts = {'disp': disp,
            'iprint': iprint,
            'maxcor': m,
            'ftol': factr * np.finfo(float).eps,
            'gtol': pgtol,
            'eps': epsilon,
            'maxfun': maxfun,
            'maxiter': maxiter,
            'callback': callback,
            'maxls': maxls}

    res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds,
                           **opts)
    d = {'grad': res['jac'],
         'task': res['message'],
         'funcalls': res['nfev'],
         'nit': res['nit'],
         'warnflag': res['status']}
    f = res['fun']
    x = res['x']

    return x, f, d

def _minimize_lbfgsb(fun, x0, args=(), jac=None, bounds=None,
                     disp=None, maxcor=10, ftol=2.2204460492503131e-09,
                     gtol=1e-5, eps=1e-8, maxfun=15000, maxiter=15000,
                     iprint=-1, callback=None, maxls=20,
                     finite_diff_rel_step=None, **unknown_options):
    """
    Minimize a scalar function of one or more variables using the L-BFGS-B
    algorithm.

    Options
    -------
    disp : None or int
        If `disp is None` (the default), then the supplied version of `iprint`
        is used. If `disp is not None`, then it overrides the supplied version
        of `iprint` with the behaviour you outlined.
    maxcor : int
        The maximum number of variable metric corrections used to
        define the limited memory matrix. (The limited memory BFGS
        method does not store the full hessian but uses this many terms
        in an approximation to it.)
    ftol : float
        The iteration stops when ``(f^k -
        f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= ftol``.
    gtol : float
        The iteration will stop when ``max{|proj g_i | i = 1, ..., n}
        <= gtol`` where ``pg_i`` is the i-th component of the
        projected gradient.
    eps : float or ndarray
        If `jac is None` the absolute step size used for numerical
        approximation of the jacobian via forward differences.
    maxfun : int
        Maximum number of function evaluations. Note that this function
        may violate the limit because of evaluating gradients by numerical
        differentiation.
    maxiter : int
        Maximum number of iterations.
    iprint : int, optional
        Controls the frequency of output. ``iprint < 0`` means no output;
        ``iprint = 0``    print only one line at the last iteration;
        ``0 < iprint < 99`` print also f and ``|proj g|`` every iprint iterations;
        ``iprint = 99``   print details of every iteration except n-vectors;
        ``iprint = 100``  print also the changes of active set and final x;
        ``iprint > 100``  print details of every iteration including x and g.
    maxls : int, optional
        Maximum number of line search steps (per iteration). Default is 20.
    finite_diff_rel_step : None or array_like, optional
        If `jac in ['2-point', '3-point', 'cs']` the relative step size to
        use for numerical approximation of the jacobian. The absolute step
        size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
        possibly adjusted to fit into the bounds. For ``method='3-point'``
        the sign of `h` is ignored. If None (default) then step is selected
        automatically.

    Notes
    -----
    The option `ftol` is exposed via the `scipy.optimize.minimize` interface,
    but calling `scipy.optimize.fmin_l_bfgs_b` directly exposes `factr`. The
    relationship between the two is ``ftol = factr * numpy.finfo(float).eps``.
    I.e., `factr` multiplies the default machine floating-point precision to
    arrive at `ftol`.

    """
    _check_unknown_options(unknown_options)
    m = maxcor
    pgtol = gtol
    factr = ftol / np.finfo(float).eps

    x0 = asarray(x0).ravel()
    n, = x0.shape

    if bounds is None:
        bounds = [(None, None)] * n
    if len(bounds) != n:
        raise ValueError('length of x0 != length of bounds')

    # unbounded variables must use None, not +-inf, for optimizer to work properly
    bounds = [(None if l == -np.inf else l, None if u == np.inf else u) for l, u in bounds]
    # LBFGSB is sent 'old-style' bounds, 'new-style' bounds are required by
    # approx_derivative and ScalarFunction
    new_bounds = old_bound_to_new(bounds)

    # check bounds
    if (new_bounds[0] > new_bounds[1]).any():
        raise ValueError("LBFGSB - one of the lower bounds is greater than an upper bound.")

    # initial vector must lie within the bounds. Otherwise ScalarFunction and
    # approx_derivative will cause problems
    x0 = np.clip(x0, new_bounds[0], new_bounds[1])

    if disp is not None:
        if disp == 0:
            iprint = -1
        else:
            iprint = disp

    sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,
                                  bounds=new_bounds,
                                  finite_diff_rel_step=finite_diff_rel_step)

    func_and_grad = sf.fun_and_grad

    fortran_int = _lbfgsb.types.intvar.dtype

    nbd = zeros(n, fortran_int)
    low_bnd = zeros(n, float64)
    upper_bnd = zeros(n, float64)
    bounds_map = {(None, None): 0,
                  (1, None): 1,
                  (1, 1): 2,
                  (None, 1): 3}
    for i in range(0, n):
        l, u = bounds[i]
        if l is not None:
            low_bnd[i] = l
            l = 1
        if u is not None:
            upper_bnd[i] = u
            u = 1
        nbd[i] = bounds_map[l, u]

    if not maxls > 0:
        raise ValueError('maxls must be positive.')

    x = array(x0, float64)
    f = array(0.0, float64)
    g = zeros((n,), float64)
    wa = zeros(2*m*n + 5*n + 11*m*m + 8*m, float64)
    iwa = zeros(3*n, fortran_int)
    task = zeros(1, 'S60')
    csave = zeros(1, 'S60')
    lsave = zeros(4, fortran_int)
    isave = zeros(44, fortran_int)
    dsave = zeros(29, float64)

    task[:] = 'START'

    n_iterations = 0

    while 1:
        # x, f, g, wa, iwa, task, csave, lsave, isave, dsave = \
        _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr,
                       pgtol, wa, iwa, task, iprint, csave, lsave,
                       isave, dsave, maxls)
        task_str = task.tobytes()
        if task_str.startswith(b'FG'):
            # The minimization routine wants f and g at the current x.
            # Note that interruptions due to maxfun are postponed
            # until the completion of the current minimization iteration.
            # Overwrite f and g:
            f, g = func_and_grad(x)
        elif task_str.startswith(b'NEW_X'):
            # new iteration
            n_iterations += 1
            if callback is not None:
                callback(np.copy(x))

            if n_iterations >= maxiter:
                task[:] = 'STOP: TOTAL NO. of ITERATIONS REACHED LIMIT'
            elif sf.nfev > maxfun:
                task[:] = ('STOP: TOTAL NO. of f AND g EVALUATIONS '
                           'EXCEEDS LIMIT')
        else:
            break

    task_str = task.tobytes().strip(b'\x00').strip()
    if task_str.startswith(b'CONV'):
        warnflag = 0
    elif sf.nfev > maxfun or n_iterations >= maxiter:
        warnflag = 1
    else:
        warnflag = 2

    # These two portions of the workspace are described in the mainlb
    # subroutine in lbfgsb.f. See line 363.
    s = wa[0: m*n].reshape(m, n)
    y = wa[m*n: 2*m*n].reshape(m, n)

    # See lbfgsb.f line 160 for this portion of the workspace.
    # isave(31) = the total number of BFGS updates prior the current iteration;
    n_bfgs_updates = isave[30]

    n_corrs = min(n_bfgs_updates, maxcor)
    hess_inv = LbfgsInvHessProduct(s[:n_corrs], y[:n_corrs])

    task_str = task_str.decode()
    return OptimizeResult(fun=f, jac=g, nfev=sf.nfev,
                          njev=sf.ngev,
                          nit=n_iterations, status=warnflag, message=task_str,
                          x=x, success=(warnflag == 0), hess_inv=hess_inv)

class LbfgsInvHessProduct(LinearOperator):
    """Linear operator for the L-BFGS approximate inverse Hessian.

    This operator computes the product of a vector with the approximate inverse
    of the Hessian of the objective function, using the L-BFGS limited
    memory approximation to the inverse Hessian, accumulated during the
    optimization.

    Objects of this class implement the ``scipy.sparse.linalg.LinearOperator``
    interface.

    Parameters
    ----------
    sk : array_like, shape=(n_corr, n)
        Array of `n_corr` most recent updates to the solution vector.
        (See [1]).
    yk : array_like, shape=(n_corr, n)
        Array of `n_corr` most recent updates to the gradient. (See [1]).

    References
    ----------
    .. [1] Nocedal, Jorge. "Updating quasi-Newton matrices with limited
       storage." Mathematics of computation 35.151 (1980): 773-782.

    """

    def __init__(self, sk, yk):
        """Construct the operator."""
        if sk.shape != yk.shape or sk.ndim != 2:
            raise ValueError('sk and yk must have matching shape, (n_corrs, n)')
        n_corrs, n = sk.shape

        super().__init__(dtype=np.float64, shape=(n, n))

        self.sk = sk
        self.yk = yk
        self.n_corrs = n_corrs
        self.rho = 1 / np.einsum('ij,ij->i', sk, yk)

    def _matvec(self, x):
        """Efficient matrix-vector multiply with the BFGS matrices.

        This calculation is described in Section (4) of [1].

        Parameters
        ----------
        x : ndarray
            An array with shape (n,) or (n,1).

        Returns
        -------
        y : ndarray
            The matrix-vector product

        """
        s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
        q = np.array(x, dtype=self.dtype, copy=True)
        if q.ndim == 2 and q.shape[1] == 1:
            q = q.reshape(-1)

        alpha = np.empty(n_corrs)

        for i in range(n_corrs-1, -1, -1):
            alpha[i] = rho[i] * np.dot(s[i], q)
            q = q - alpha[i]*y[i]

        r = q
        for i in range(n_corrs):
            beta = rho[i] * np.dot(y[i], r)
            r = r + s[i] * (alpha[i] - beta)

        return r

    def todense(self):
        """Return a dense array representation of this operator.

        Returns
        -------
        arr : ndarray, shape=(n, n)
            An array with the same shape and containing
            the same data represented by this `LinearOperator`.

        """
        s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
        I = np.eye(*self.shape, dtype=self.dtype)
        Hk = I

        for i in range(n_corrs):
            A1 = I - s[i][:, np.newaxis] * y[i][np.newaxis, :] * rho[i]
            A2 = I - y[i][:, np.newaxis] * s[i][np.newaxis, :] * rho[i]

            Hk = np.dot(A1, np.dot(Hk, A2)) + (rho[i] * s[i][:, np.newaxis] *
                                                        s[i][np.newaxis, :])
        return Hk


text:
package com.intellij.slicer;

import com.intellij.ide.util.treeView.AbstractTreeStructure;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public interface SliceLanguageSupportProvider {

  @NotNull
  SliceUsage createRootUsage(@NotNull PsiElement element, @NotNull SliceAnalysisParams params) ;

  @Nullable
  PsiElement getExpressionAtCaret(PsiElement atCaret, boolean dataFlowToThis);

  @NotNull
  PsiElement getElementForDescription(@NotNull PsiElement element);

  @NotNull
  SliceUsageCellRendererBase getRenderer();

  void startAnalyzeLeafValues(AbstractTreeStructure structure, Runnable finalRunnable);

  void startAnalyzeNullness(AbstractTreeStructure structure, Runnable finalRunnable);

  void registerExtraPanelActions(DefaultActionGroup group, SliceTreeBuilder builder);
}


text:
/**
 * Created by 15061857 on 2017/4/21.
 */
var http = require('http');
const querystring = require('querystring');
const postData = querystring.stringify({
    'msg': 'Hello World!'
});
var dataString = null;
const options = {
    hostname: 'minos2sit.cnsuning.com',
    port: 9080,
    path: '/minos2-admin/menu/queryCurUser.htm',
    method: 'GET',
    /*headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData)
    }*/
    headers:{
        Cookie:'idsLoginUserIdLastTime=15061857',
        'Content-Length': Buffer.byteLength(postData)
    },
    agent:false
};

const req = http.request(options, (res) => {
    console.log(`STATUS: ${res.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
    });
    res.on('end', () => {
        console.log('No more data in response.');
    });
});

req.on('error', (e) => {
    console.error(`problem with request: ${e.message}`);
});

// write data to request body
req.write(postData);
req.end();


text:
/*
 retrieve forwarded url from header,
 save for use in target flow to set target url.
 additionally parse url into components and set
 request.uri to allow path/queryparam variable
 references to work as expected
*/
var cfurl = context.getVariable('request.header.X-Cf-Forwarded-Url')
// TODO: update this if/when route services change made on CF side
// var cfurl = context.getVariable('proxy.pathsuffix')
// cfurl = decodeURIComponent(cfurl.slice(1))
// TODO: Update zip file

context.setVariable('cf-url', cfurl)

var r = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/
var parts = r.exec(cfurl)
context.setVariable('cf-path', parts[5])
if (parts[6]) {
    context.setVariable('cf-querystring', parts[6])
    context.setVariable('request.uri', parts[5] + parts[6])
} else {
    context.setVariable('request.uri', parts[5])
}