text:
function [data,indices] = bz_GetWidebandData(channels,varargin)

% bz_GetWidebandData - Get local field potentials.
%
%  Load wide band data from disk (unlike spikes or positions, raw data is way
%  too large to keep in memory).
%
%  USAGE
%
%    [data,indices] = bz_GetWidebandData(channels,<options>)
%
%    channels       optional list of channels to load (default = all)
%    <options>      optional list of property-value pairs (see table below)
%
%    =========================================================================
%     Properties    Values
%    -------------------------------------------------------------------------
%     'restrict'    list of time intervals to read from the data file
%     'intervals'   same as 'restrict' (for backwards compatibility)
%     'select'      select channel by ID ('id', counted from 0 a la NeuroScope)
%                   or by number ('number', counted from 1 a la Matlab)
%                   (default = 'id')
%    =========================================================================
%
%  OUTPUT
%
%    data           list of (time,voltage1,...,voltageN) tuples
%    indices        for each tuple, the index of the interval it falls in
%
%  EXAMPLES
%
%    % channel ID 5 (= # 6), from 0 to 120 seconds
%    data = bz_GetWidebandData(5,'intervals',[0 120]);
%    % same, plus from 240.2 to 265.23 seconds
%    data = bz_GetWidebandData(5,'intervals',[0 120;240.2 265.23]);
%    % multiple channels
%    data = bz_GetWidebandData([1 2 3 4 10 17],'intervals',[0 120]);
%    % channel # 3 (= ID 2), from 0 to 120 seconds
%    data = bz_GetWidebandData(3,'intervals',[0 120],'select','number');

% Copyright (C) 2004-2011 by Michaël Zugaro
%
% This program 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.

global DATA;
if isempty(DATA),
	error('No session defined (did you forget to call SetCurrentSession? Type ''help Data'' for details).');
end

% Default values
intervals = [0 Inf];
select = 'id';

% Optional parameter
if ischar(channels),
	varargin = {channels,varargin{:}};
	channels = []; % all
end

if nargin < 1 | mod(length(varargin),2) ~= 0,
  error('Incorrect number of parameters (type ''help bz_GetWidebandData'' for details).');
end

% Parse parameter list
for i = 1:2:length(varargin),
  if ~ischar(varargin{i}),
    error(['Parameter ' num2str(i+1) ' is not a property (type ''help bz_GetWidebandData'' for details).']);
  end
  switch(lower(varargin{i})),
    case {'intervals','restrict'},
      intervals = varargin{i+1};
      if ~isdmatrix(intervals) || size(intervals,2) ~= 2,
        error('Incorrect value for property ''intervals'' (type ''help bz_GetWidebandData'' for details).');
      end
    case 'select',
      select = lower(varargin{i+1});
      if ~isstring_FMAT(select,'id','number'),
        error('Incorrect value for property ''select'' (type ''help bz_GetWidebandData'' for details).');
      end
    otherwise,
      error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help bz_GetWidebandData'' for details).']);
  end
end

filename = [DATA.session.path '/' DATA.session.basename '.dat'];
nChannels = DATA.nChannels;
if isempty(channels),
	channels = 1:nChannels;
elseif strcmp(select,'id'),
	channels = channels + 1;
end

nIntervals = size(intervals,1);
data = [];
indices = [];
for i = 1:nIntervals,
	duration = (intervals(i,2)-intervals(i,1));
	start = intervals(i,1);
	% Load data
	d = bz_LoadBinary(filename,'duration',duration,'frequency',DATA.rates.wideband,'nchannels',nChannels,'start',start,'channels',channels);
	% The following two lines compensate for annoying numerical precision errors in Matlab, whereby the number of samples
	% read with LoadBinary is not always exactly that expected, depending on how accurately 'duration' is coded internally
	n = size(d,1);
	t = linspace(start,start+n/DATA.rates.wideband,n)';
	data = [data ; t d];
	indices = [indices ; i*ones(size(t))];
end

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
%kksync 'synchronize an objects database and any caches'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros ksync.pane file
%
% Parameters:
% String: tb 'Toolbox', default: ' ': 'toolbox name'
% String: oname 'Object ', default: ' ': 'name of object in toolbox'
%
% Example: kksync( {'tb',' ';'oname',' '})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% ksync - synchronize object database and any caches
%
%  DESCRIPTION
% .I ksync
% is used to synchronize an object with any cache held by kcms.
% There are two common situations where "ksync" would be used:
%
%  "o"
% When an object's database has been manually edited,
% using "kdbmedit",
% or some other utility.
%
%  "o"
% When a cache mechanism has been changed.
%
% For example, if kcms is changed to store a new field in the cache,
% then all caches must be updated.
% The example below shows how all objects in all toolboxes can
% be synchronized.
%
% In the future "ksync" will be updated to include options for
% synchronizing all objects within a given toolbox,
% and synchronizing all objects in all toolboxes.
%
%
%
%  EXAMPLES
% The following bourne shell script can be used to invoke ksync on
% all objects in all toolboxes
%
%
%     #!/bin/sh
%     for toolbox in `kecho -echo toolboxes`; do
%             for object in `kecho -tb $toolbox -echo objects`; do
%                     ksync -tb $toolbox -oname $object
%             done
%     done
%
%
%  "SEE ALSO"
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993 - 1997, Khoral Research, Inc. ("KRI")  All rights reserved.
%

function varargout = kksync(varargin)
Inputs={};
if nargin ==0
  arglist={'',''};
elseif nargin ==1
  arglist=varargin{1};
else error('Usage: [out1,..] = kksync(arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'tb', ' ';'oname', ' '};
maxval={0,0};
minval={0,0};
istoggle=[0,0];
was_set=istoggle * 0;
paramtype={'String','String'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=0; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

      nextoutput = nextoutput + 1;
      if (minval{jj} == 0)
         NumReqOutputs = NumReqOutputs - 1;
      end
     elseif isstr(arglist{ii,2})
      narglist{jj,2} = arglist{ii,2};
     else
        if strcmp(paramtype{jj}, 'Integer') & (round(arglist{ii,2}) ~= arglist{ii,2})
            error(['Argument ' arglist{ii,1} ' is of integer type but non-integer number ' arglist{ii,2} ' was supplied']);
        end
        if (minval{jj} ~= 0 | maxval{jj} ~= 0)
          if (minval{jj} == 1 & maxval{jj} == 1 & arglist{ii,2} < 0)
            error(['Argument ' arglist{ii,1} ' must be bigger or equal to zero!']);
          elseif (minval{jj} == -1 & maxval{jj} == -1 & arglist{ii,2} > 0)
            error(['Argument ' arglist{ii,1} ' must be smaller or equal to zero!']);
          elseif (minval{jj} == 2 & maxval{jj} == 2 & arglist{ii,2} <= 0)
            error(['Argument ' arglist{ii,1} ' must be bigger than zero!']);
          elseif (minval{jj} == -2 & maxval{jj} == -2 & arglist{ii,2} >= 0)
            error(['Argument ' arglist{ii,1} ' must be smaller than zero!']);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} < minval{jj})
            error(['Argument ' arglist{ii,1} ' must be bigger than ' num2str(minval{jj})]);
          elseif (minval{jj} ~= maxval{jj} & arglist{ii,2} > maxval{jj})
            error(['Argument ' arglist{ii,1} ' must be smaller than ' num2str(maxval{jj})]);
          end
        end
     end
     if ~strcmp(narglist{jj,2},'OK_out') &  ~strcmp(narglist{jj,2},'OK_in')
       narglist{jj,2} = arglist{ii,2};
     end
   end
   end
   if (wasmatched == 0 & ~strcmp(arglist{ii,1},''))
        error(['Argument ' arglist{ii,1} ' is not a valid argument for this function']);
   end
end
% match the remaining inputs/outputs to the unused arguments and test for missing required inputs
 for jj=1:size(narglist,1)
     if  strcmp(paramtype{jj}, 'Toggle')
        if (narglist{jj,2} ==0)
          narglist{jj,1} = '';
        end;
        narglist{jj,2} = '';
     end;
     if  ~strcmp(narglist{jj,2},'__input') && ~strcmp(narglist{jj,2},'__output') && istoggle(jj) && ~ was_set(jj)
          narglist{jj,1} = '';
          narglist{jj,2} = '';
     end;
     if strcmp(narglist{jj,2}, '__input')
      if (minval{jj} == 0)  % meaning this input is required
        if (nextinput > size(Inputs))
           error(['Required input ' narglist{jj,1} ' has no corresponding input in the list!']);
        else
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        end
      else  % this is an optional input
        if (nextinput <= length(Inputs))
          narglist{jj,2} = 'OK_in';
          nextinput = nextinput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end;
     else
     if strcmp(narglist{jj,2}, '__output')
      if (minval{jj} == 0) % this is a required output
        if (nextoutput > nargout & nargout > 1)
           error(['Required output ' narglist{jj,1} ' is not stated in the assignment list!']);
        else
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
          NumReqOutputs = NumReqOutputs-1;
        end
      else % this is an optional output
        if (nargout - nextoutput >= NumReqOutputs)
          narglist{jj,2} = 'OK_out';
          nextoutput = nextoutput + 1;
        else
          narglist{jj,1} = '';
          narglist{jj,2} = '';
        end;
      end
     end
  end
end
if nargout
   varargout = cell(1,nargout);
else
  varargout = cell(0);
end
global KhorosRoot
if exist('KhorosRoot') && ~isempty(KhorosRoot)
w=['"' KhorosRoot];
else
if ispc
  w='"C:\Program Files\dip\khorosBin\';
else
[s,w] = system('which cantata');
w=['"' w(1:end-8)];
end
end
callKhoros([w 'ksync"  '],Inputs,narglist);

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB


text:
function [net1, avgImg] = initVGG16Net( )
%VGG16
opts.gpus=1;
cold=true;
prepareGPUs(opts,cold);

net2=load('./exp/model/imagenet-vgg-verydeep-16.mat');
net2.layers(31:end) = [];

avgImg=net2.meta.normalization.averageImage;

net1=dagnn.DagNN();

net1.addLayer('conv1_1', dagnn.Conv('size', [3,3,3,64],...
    'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'input', 'conv_11', {'conv11_f', 'conv11_b'});
net1.addLayer('relu1_1', dagnn.ReLU(),'conv_11','relu_11');

f = net1.getParamIndex('conv11_f') ;
net1.params(f).value=net2.layers{1}.weights{1};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1e3;

f = net1.getParamIndex('conv11_b') ;
net1.params(f).value=net2.layers{1}.weights{2};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1;

net1.addLayer('conv1_2', dagnn.Conv('size', [3,3,64,64],...
    'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_11', 'conv_12', {'conv12_f', 'conv12_b'});
net1.addLayer('relu1_2', dagnn.ReLU(),'conv_12','relu_12');
net1.addLayer('pool1', dagnn.Pooling('poolSize', [2,2], 'pad',...
    [0,1,0,1], 'stride', [2,2]),'relu_12','pool_1');

f = net1.getParamIndex('conv12_f') ;
net1.params(f).value=net2.layers{3}.weights{1};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1e3;

f = net1.getParamIndex('conv12_b') ;
net1.params(f).value=net2.layers{3}.weights{2};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1;

%-------------------------covn 2--------------------
net1.addLayer('conv2_1', dagnn.Conv('size', [3,3,64,128],...
    'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'pool_1', 'conv_21', {'conv21_f', 'conv21_b'});
net1.addLayer('relu2_1', dagnn.ReLU(),'conv_21','relu_21');

f = net1.getParamIndex('conv21_f') ;
net1.params(f).value=net2.layers{6}.weights{1};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1e3;

f = net1.getParamIndex('conv21_b') ;
net1.params(f).value=net2.layers{6}.weights{2};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1;

net1.addLayer('conv2_2', dagnn.Conv('size', [3,3,128,128],...
    'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_21', 'conv_22', {'conv22_f', 'conv22_b'});
net1.addLayer('relu2_2', dagnn.ReLU(),'conv_22','relu_22');
net1.addLayer('pool2', dagnn.Pooling('poolSize', [2,2], 'pad',...
    [0,1,0,1], 'stride', [2,2]),'relu_22','pool_2');

f = net1.getParamIndex('conv22_f') ;
net1.params(f).value=net2.layers{8}.weights{1};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1e3;

f = net1.getParamIndex('conv22_b') ;
net1.params(f).value=net2.layers{8}.weights{2};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1;

%-------------------------covn 3--------------------
net1.addLayer('conv3_1', dagnn.Conv('size', [3,3,128,256],...
    'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'pool_2', 'conv_31', {'conv31_f', 'conv31_b'});
net1.addLayer('relu3_1', dagnn.ReLU(),'conv_31','relu_31');

f = net1.getParamIndex('conv31_f') ;
net1.params(f).value=net2.layers{11}.weights{1};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1e3;

f = net1.getParamIndex('conv31_b') ;
net1.params(f).value=net2.layers{11}.weights{2};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1;

net1.addLayer('conv3_2', dagnn.Conv('size', [3,3,256,256],...
    'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_31', 'conv_32', {'conv32_f', 'conv32_b'});
net1.addLayer('relu3_2', dagnn.ReLU(),'conv_32','relu_32');

f = net1.getParamIndex('conv32_f') ;
net1.params(f).value=net2.layers{13}.weights{1};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1e3;

f = net1.getParamIndex('conv32_b') ;
net1.params(f).value=net2.layers{13}.weights{2};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1;

net1.addLayer('conv3_3', dagnn.Conv('size', [3,3,256,256],...
    'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_32', 'conv_33', {'conv33_f', 'conv33_b'});
net1.addLayer('relu3_3', dagnn.ReLU(),'conv_33','relu_33');

f = net1.getParamIndex('conv33_f') ;
net1.params(f).value=net2.layers{15}.weights{1};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1e3;

f = net1.getParamIndex('conv33_b') ;
net1.params(f).value=net2.layers{15}.weights{2};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1;

%-------------------------covn 4--------------------
net1.addLayer('conv4_1', dagnn.Conv('size', [3,3,256,512],...
    'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_33', 'conv_41', {'conv41_f', 'conv41_b'});
net1.addLayer('relu4_1', dagnn.ReLU(),'conv_41','relu_41');

f = net1.getParamIndex('conv41_f') ;
net1.params(f).value=net2.layers{18}.weights{1};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1e3;

f = net1.getParamIndex('conv41_b') ;
net1.params(f).value=net2.layers{18}.weights{2};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1;

net1.addLayer('conv4_2', dagnn.Conv('size', [3,3,512,512],...
    'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_41', 'conv_42', {'conv42_f', 'conv42_b'});
net1.addLayer('relu4_2', dagnn.ReLU(),'conv_42','relu_42');

f = net1.getParamIndex('conv42_f') ;
net1.params(f).value=net2.layers{20}.weights{1};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1e3;

f = net1.getParamIndex('conv42_b') ;
net1.params(f).value=net2.layers{20}.weights{2};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1;

net1.addLayer('conv4_3', dagnn.Conv('size', [3,3,512,512],...
    'hasBias', true, 'pad',...
    [1,1,1,1], 'stride', [1,1]), 'relu_42', 'conv_43', {'conv43_f', 'conv43_b'});
net1.addLayer('relu4_3', dagnn.ReLU(),'conv_43','relu_43');

f = net1.getParamIndex('conv43_f') ;
net1.params(f).value=net2.layers{22}.weights{1};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1e3;

f = net1.getParamIndex('conv43_b') ;
net1.params(f).value=net2.layers{22}.weights{2};
net1.params(f).learningRate=0;
net1.params(f).weightDecay=1;

% net1.addLayer('pool2_show', dagnn.Crop('crop',[1,1]),...
%     {'pool_2','pool_2'}, 'pool2show');
% net1.addLayer('relu33_show', dagnn.Crop('crop',[1,1]),...
%     {'relu_33','relu_33'}, 'relu33_show');

net1.move('gpu');
clear net2;
end

% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
clear vl_tflow vl_imreadjpeg ;
end

% -------------------------------------------------------------------------
function prepareGPUs(opts, cold)
% -------------------------------------------------------------------------
numGpus = numel(opts.gpus) ;
if numGpus > 1
  % check parallel pool integrity as it could have timed out
  pool = gcp('nocreate') ;
  if ~isempty(pool) && pool.NumWorkers ~= numGpus
    delete(pool) ;
  end
  pool = gcp('nocreate') ;
  if isempty(pool)
    parpool('local', numGpus) ;
    cold = true ;
  end

end
if numGpus >= 1 && cold
  fprintf('%s: resetting GPU\n', mfilename)
  clearMex() ;
  if numGpus == 1
    gpuDevice(opts.gpus)
  else
    spmd
      clearMex() ;
      gpuDevice(opts.gpus(labindex))
    end
  end
end
end

repo: CREST-Release


text:
function evalRP_multicut_waf(expidxs,bSave)

fprintf('evalRP_multicut()\n');

if (nargin < 2)
    bSave = true;
end

fontSize = 18;
% figure(100); clf; hold on;
legendName = cell(0);
set(0,'DefaultAxesFontSize', fontSize)
set(0,'DefaultTextFontSize', fontSize)

prefix = 'pck-head-rpc-';
[~,parts] = util_get_parts24();
nJoints = 14;
pck_thresh = 0.5;

% clusSizeThresh = 15;

rootDir = '/BS/leonid-people-3d/work/data/WeAreFamily_Stickmen_v1.02';
addpath([rootDir '/code']);
addpath([rootDir '/code/utils']);

GTWAF = ReadStickmenAnnotationTxtMulti('/BS/leonid-people-3d/work/data/WeAreFamily_Stickmen_v1.02//data/waf_sticks_all.txt');
annolistWAF_gt = GTWAF(351:end);

for expidx = expidxs
    fprintf('**********************************************************************************\n');
    % load experiment parameters
    p = rcnn_exp_params(expidx);

    if (isfield(p,'nms_thresh_det'))
        nms_thresh_det = p.nms_thresh_det;
    else
        nms_thresh_det = 0.5;
    end

    load(p.testGT);
    annolist_gt = annolist%(1:300);

    mkdir_if_missing(p.latexDir);
    mkdir_if_missing(p.plotsDir);

    assert(length(p.pidxs) == nJoints);

    if (isfield(p,'clusSizeThresh'))
        clusSizeThresh = p.clusSizeThresh;
    else
        clusSizeThresh = 1;
    end

    % load keypoints
    if (isfield(p,'multicut') && p.multicut == true)
        [keypointsAll,imgidxs_missing] = det2keypointsImgMulticutMulti(expidx,parts,annolist_gt,clusSizeThresh);
        annolistWAF_det = backproject_waf(expidx,keypointsAll,annolistWAF_gt);
    end

    annolist_gt(imgidxs_missing) = [];
    keypointsAll(imgidxs_missing) = [];

    assert(length(annolist_gt) == length(keypointsAll));
    [scoresAll, labelsAll, nGTall] = assignGTMulticutMulti(keypointsAll,annolist_gt,p.pidxs,parts,pck_thresh);

%     groups = {0,2,4,5,7,9,12,14,16,17,19,21,22,23};
    partLabels = {'rankle','rknee','rhip','lhip','lknee','lankle','rwrist','relbow','rshoulder','lshoulder','lelbow','lwrist','neck','tophead'};

    apAll = zeros(length(p.pidxs),1);
%     figure(100); clf;

    for i = 1:length(p.pidxs)
        scores = [];
        labels = [];
        for imgidx = 1:length(annolist_gt)
            scores = [scores; scoresAll{i}{imgidx}];
            labels = [labels; labelsAll{i}{imgidx}];
        end
        [precision,recall,sorted_scores,sortidx,sorted_labels] = getRPC(scores,labels,sum(nGTall(i,:)));
        ap = VOCap(recall,precision)*100;
        apAll(i) = ap;
        legendName = sprintf('%s, AP: %1.1f%%', p.name, ap);
        fprintf('%s\n',legendName);

%         plotRPC(precision,recall,p.colorName,'-',partLabels{i});
%         legend(legendName,'Location','NorthWest');
%         if (bSave)
%             print(gcf, '-dpng', [p.plotsDir '/' prefix partLabels{i} '-' 'expidx' num2str(expidx) '.png']);
%             printpdf([p.plotsDir '/' prefix partLabels{i} '-' 'expidx' num2str(expidx) '.pdf']);
%         end
    end
    if (bSave)
        tableFilename = [p.latexDir '/ap-expidx' num2str(expidx) '.tex'];
        apAll(15,:) = mean(apAll(7:14));
        apAll(16,:) = mean(apAll);
        [row, header] = genTable(apAll,p.name);
        fid = fopen(tableFilename,'wt');assert(fid ~= -1);
        fprintf(fid,'%s\n',row{1});fclose(fid);
        fid = fopen([p.latexDir '/ap-header.tex'],'wt');assert(fid ~= -1);
        fprintf(fid,'%s\n',header);fclose(fid);
    end
end
end

author: eldar

repo: deepcut

save_path: github-repos/MATLAB/eldar-deepcut


text:
function y = minter_xls(Y,x,z,ta,sc,f,type,d,flax1,flax2)
% PURPOSE: Interface via Excel Link for multivariate temporal disaggregation
% -----------------------------------------------------------------------
% SYNTAX: y = minter_xls(Y,x,z,ta,sc,f,type,d,flax1,flax2);
% -----------------------------------------------------------------------
% INPUT
%           SELECTION OF THE METHOD
%
% Common parameters:
%        ta: type of disaggregation
%            ta=1 ---> sum (flow)
%            ta=2 ---> average (index)
%            ta=3 ---> last element (stock) ---> interpolation
%            ta=4 ---> first element (stock) ---> interpolation
%        sc: number of high frequency data points for each low frequency data point
%            sc= 4 ---> annual to quarterly
%            sc=12 ---> annual to monthly
%            sc= 3 ---> quarterly to monthly
%
% Specific parameters:
%
% ==> Rossi:
%        opMethod = type: preliminary univariate disaggregation = 1
%            = 1 ---> Fernandez
%            = 2 ---> Chow-Lin
%            = 3 ---> Litterman
%        In all cases, estimation is performed by Maximum Likelihood
%
% ==> Denton:
%        d: objective function to be minimized: volatility of ...
%            d=0 ---> levels
%            d=1 ---> first differences
%            d=2 ---> second differences
%
% ==> di Fonzo:
%        type: model for the innovations
%            = 0 ---> white noise
%            = 1 ---> random walk
%
% INPUT DATA:
%         Y : NxM
%         x : nxMM
%         z : nxnz
%
% -----------------------------------------------------------------------
% OUTPUT: y: nxi
%       i=M  brief --> only temporally disaggregated series (all procedures)
%       i=2M detailed --> temporally disaggregated series + standard errors of estimates
%                  Available for Di Fonzo.
% -----------------------------------------------------------------------
% LIBRARY: rossi, denton, difonzo

% written by:
% Ana Abad(*) & Enrique M. Quilis(**)
%   (*) National Statistical Institute
%   (**) Macroeconomic Research Department
%        Ministry of Economy and Competitiveness
%        <enrique.quilis@mineco.es>

% Version 2.2 (January, 2013)

% -----------------------------------------------------------------------
% SELECTION OF THE METHOD

switch flax1
case 1
   % Rossi
   opMethod = type;
   res = rossi(Y,x,z,ta,sc,opMethod,1);
case 2
   % Denton
   op1 = 1; %Additive variant
   res = denton(Y,x,z,ta,sc,d,op1);
case 3
   % di Fonzo
   res = difonzo(Y,x,z,ta,sc,type,f);
end

% -----------------------------------------------------------------------
% SELECTION OF OUTPUT

 switch flax2
     case 0
         % Brief output
         y = res.y;
     case 1
         % Normal output
         switch res.meth
             case {'Multivariate Denton','Multivariate Rossi'}
                 y = res.y;
             case {'Multivariate Di Fonzo'}
                  y   = [res.y res.d_y];
          end
 end

author: Sable

repo: mcbench-benchmarks


text:
function DBAddFigure(f,eid,name,comments,parameters,mfiles,varargin)

%DBAddFigure - Save figure in current database.
%
% Save figure as MATLAB fig and PNG image. Also save code used to generate it
% (although not required, installing export_fig will yield better PNG images).
%
%  USAGE
%
%    DBAddFigure(f,eid,name,comments,parameters,mfiles,<options>)
%
%    f              figure handle
%    eid            experiment ID (identifier string)
%    name           descriptive name
%    comments       comment string
%    parameters     figure parameters
%    mfiles         cell array of m-file names (used to generate the figure)
%    <options>      optional list of property-value pairs (see table below)
%
%    =========================================================================
%     Properties    Values
%    -------------------------------------------------------------------------
%     'onlyPNG'     skip fig and only store png capture (use this to avoid
%                   storing very large figures into the database,
%                   default = 'off')
%    =========================================================================
%
%  NOTE
%
%    The pair (eid,name) must uniquely define the figure (they are used as
%    primary keys in the database).
%
%  SEE
%
%    See also DBAddVariable, DBGetFigures, DBExportGallery.
%

% Copyright (C) 2007-2013 by Michaël Zugaro
%
% This program 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.

global dbUser;

% Make sure MyM is installed and functional
CheckMyM;

% Check number of parameters
if nargin < 6,
	error('Incorrect number of parameters (type ''help DBAddFigure'' for details).');
end

% Default values
onlyPNG = 'off';

% Check parameters
if ~ishandle(f),
	error('Incorrect figure handle (type ''help DBAddFigure'' for details).');
end
if ~ischar(eid),
	error('Incorrect EID string (type ''help DBAddFigure'' for details).');
end
if ~ischar(name),
	error('Incorrect figure name (type ''help DBAddFigure'' for details).');
end
if ~isempty(strfind(eid,'/')) || ~isempty(strfind(name,'/')),
	error('EIDs and names should not contain ''/'' (type ''help DBAddFigure'' for details).');
end
if ~ischar(comments),
	error('Incorrect comment string (type ''help DBAddFigure'' for details).');
end
if ~ischar(parameters),
	error('Incorrect figure parameters (type ''help DBAddFigure'' for details).');
end
if ~ischar(mfiles) && ~iscell(mfiles),
	error('Incorrect list of m-files (type ''help DBAddFigure'' for details).');
end
if ischar(mfiles),
	mfiles = {mfiles};
end

% Parse options
for i = 1:2:length(varargin),
	if ~ischar(varargin{i}),
		error(['Parameter ' num2str(i+firstIndex) ' is not a property (type ''help DBAddFigure'' for details).']);
	end
	switch(lower(varargin{i})),
		case 'onlypng',
			onlyPNG = lower(varargin{i+1});
			if ~isstring_FMAT(onlyPNG,'on','off'),
				error('Incorrect value for property ''onlypng'' (type ''help DBAddFigure'' for details).');
			end
		otherwise,
			error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help DBAddFigure'' for details).']);
	end
end

onlyPNG = strcmp(onlyPNG,'on');

basename = tempname;
figName = [basename '.fig'];
pngName = [basename '.png'];
if ~onlyPNG,
	try
		% Create temporary fig file
		saveas(f,figName);
	catch
		error('Could not create temporary file for fig figure.');
	end
end
try
	% Create temporary png file
	if ~isempty(which('export_fig')),
		export_fig(f,pngName,'-png','-a1');
	else
		saveas(f,pngName);
	end
catch
	error('Could not create temporary file for png figure.');
end

% M-Files
for i = 1:length(mfiles),
	mfileName = which(mfiles{i});
	if isempty(mfileName),
		error(['M-File for function ''' mfiles{i} ''' not found.']);
	end
	fid = fopen(mfileName);
	code{i} = fread(fid);
	fclose(fid);
end

% Date and md5
d = datestr(now);
md5 = CalcMD5(pngName);

% Execute SQL query command
if onlyPNG,
	h = mym(['insert into figures (eid,name,comments,parameters,mfiles,code,date,user,md5,png) values ("{S}","{S}","{S}","{S}","{M}","{M}","{S}","{S}","{Si}","{uF}")'],eid,name,comments,parameters,mfiles,code,d,dbUser,md5,pngName);
else
	h = mym(['insert into figures (eid,name,comments,parameters,mfiles,code,date,user,md5,fig,png) values ("{S}","{S}","{S}","{S}","{M}","{M}","{S}","{S}","{Si}","{F}","{uF}")'],eid,name,comments,parameters,mfiles,code,d,dbUser,md5,figName,pngName);
end

% Delete temporary files
if ~onlyPNG,
	delete(figName);
end
delete(pngName);


text:
classdef ThinPlate < Kernel
    % Object of type kernel but optimized for ThinPlate so that the computation of the
    % radial quadrature goes faster
    properties (Access = public)
        C = 1;  %such that G(r) = C*r^2*log(R*r)
        R = 1;
    end

    methods
        function[kernel] = ThinPlate(CC,RR)
            if nargin == 0
                CC = 1;
            end
            if nargin <= 1
                RR = 1;
            end
            kernel@Kernel(@(x)(CC*x.^2.*log(RR*x)),@(x)(2*CC*x.*log(RR*x) + CC*x))
            kernel.scalFunc = @(a,b,rho)(CC*thinPlateSP([a,b],rho,RR));
            kernel.normFunc = @(a,b)(abs(CC)*ThinPlate.norm_func(a,b,RR));
            kernel.gamma_est = @ThinPlate.gamma_est;
            kernel.C = CC;
            kernel.R = RR;
            kernel.singular = false;
        end
    end
    methods (Access = public)
        function[out] = dilatation(this,lambda)
            CC = this.C;
            RR = this.R;
            out = ThinPlate(lambda^2*CC,lambda*RR);
        end
        function[out] = mtimes(this,mu)
            if isa(this,'Kernel')
                assert(and(isa(mu,'double'),isscalar(mu)));
                out = ThinPlate(mu*this.C);
            else
                out = mtimes(mu,this);
            end
        end
        function[out] = radialQuadKernel(this,a,tol,varargin)
            Cmem = this.C;
            this = (1/Cmem)*this;
            rq = RadialQuadrature(a,this,tol/abs(Cmem),varargin{:});
            out = Cmem*rq;
        end
        function[onlineEBD,rq,loc] = offlineEBD(this,X,Y,a,tol)
            % Special way to handle the radial quadrature : we add a term
            % in r^2 to enforce multi-Dirichlet condition.
            rMax = rMaxCalc(X,Y);
            x = X/rMax;
            y = Y/rMax;
            k1 = ThinPlate(this.C*rMax^2,this.R*rMax) +...
                X2kKernel(1,-this.C*(1+log(rMax*this.R))*rMax^2); % adjust multi-Dirichlet condition.
            rq = RadialQuadrature(a,k1,tol);
            q2d = Quad2D(rq);
            loc = localCorrections(x,y,a,k1,rq,tol,false);
            onlineEBD = @(v)(q2d.conv(x,y,v) + loc*v + suppTerm(v));

            % We remove the added r^2 term by computing the convolution as
            % follows:
            function[res] = suppTerm(alpha)
                alphay = [alpha alpha].*y;
                x2 = x(:,1).^2 + x(:,2).^2;
                y2 = y(:,1).^2 + y(:,2).^2;
                alphay2 = alpha.*y2;
                res = this.C*rMax^2*(log(rMax*this.R)+1)*(...
                    x2*sum(alpha)...
                    - 2*x(:,1)*sum(alphay(:,1)) - 2*x(:,2)*sum(alphay(:,2))...
                    + sum(alphay2));
            end
        end
    end
    methods (Static, Access = protected)
        function[res] = norm_func(a,b,R)
            % Found with Maple
            if a==0
                res = sqrt(2*pi*(...
                    b ^ 4 * log(R * b) ^ 2 +...
                    b ^ 4 * log(R * b) / 0.2e1 + b ^ 4 / 0.8e1));

            else
                res = sqrt(2*pi*(...
                    -a ^ 4 * log(R * a) ^ 2 - a ^ 4 * log(R * a) / 0.2e1 ...
                    - a ^ 4 / 0.8e1 + b ^ 4 * log(R * b) ^ 2 +...
                    b ^ 4 * log(R * b) / 0.2e1 + b ^ 4 / 0.8e1));
            end
        end
        function[low,up] = gamma_est(~)
            % Helps the radial quadrature to guess the number of components
            up = 7;
            low= 0;
        end

    end

end

author: SwanLab

repo: Swan

save_path: github-repos/MATLAB/SwanLab-Swan


text:
function [sys,x0,str,ts]=ESO_2rd(t,x,u,flag,d,bet,b)

switch flag
    case 0
        [sys,x0,str,ts]=mdlInitializeSizes;
    case 1
        sys=mdlDerivatives(x,u,d,bet,b);
    case 3
        sys=mdlOutputs(x);
    case {2,4,9}
        sys=[];
    otherwise
        error(['Unhandled flag=',num2str(flag)]);
end
function [sys,x0,str,ts]=mdlInitializeSizes
    sizes=simsizes;
    sizes.NumContStates=3;
    sizes.NumDiscStates=0;
    sizes.NumOutputs=3;
    sizes.NumInputs=2;
    sizes.DirFeedthrough=1;
    sizes.NumSampleTimes=1;
    sys=simsizes(sizes);
    x0=[0;0;0];
    str=[];
    ts=[-1 0];
function sys=mdlDerivatives(x,u,d,bet,b)
    e=x(1)-u(2);
    sys(1,1)=x(2)-bet(1)*e;
    sys(2,1)=x(3)-bet(2)*fal(e,0.5,d)+b*u(1);
    sys(3,1)=-bet(3)*fal(e,0.25,d);
function sys=mdlOutputs(x)
    sys=x;
function f=fal(e,a,d)
    if abs(e)<d
        f=e*d^(a-1);
    else f=(abs(e))^a*sign(e);
    end

author: TianfaYao

repo: ADRC

save_path: github-repos/MATLAB/TianfaYao-ADRC


text:
function r8cc_write ( col_file, row_file, a_file, m, n, nz_num, col, row, a )

%*****************************************************************************80
%
%% R8CC_WRITE writes a R8CC matrix to three files.
%
%  Discussion:
%
%    The R8CC format is the double precision sparse compressed column
%    format.  Associated with this format, we have an M by N matrix
%    with NZ_NUM nonzero entries.  We construct the column pointer
%    vector COL of length N+1, such that entries of column J will be
%    stored in positions COL(J) through COL(J+1)-1.  This indexing
%    refers to both the ROW and A vectors, which store the row indices
%    and the values of the nonzero entries.  The entries of the
%    ROW vector corresponding to each column are assumed to be
%    ascending sorted.
%
%    The R8CC format is equivalent to the MATLAB "sparse" format,
%    and the Harwell Boeing "real unsymmetric assembled" (RUA) format.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    02 September 2006
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Iain Duff, Roger Grimes, John Lewis,
%    User's Guide for the Harwell-Boeing Sparse Matrix Collection,
%    October 1992
%
%  Parameters:
%
%    Input, string COL_FILE, ROW_FILE, A_FILE, the names of the
%    files containing the column pointers, row entries, and matrix entries.
%
%    Input, integer M, N, the number of rows and columns in the matrix.
%
%    Input, integer NZ_NUM, the number of nonzero elements in the matrix.
%
%    Input, integer COL(N+1), the column pointers.
%
%    Input, integer ROW(NZ_NUM), the row indices.
%
%    Input, real A(NZ_NUM), the nonzero elements
%    of the matrix.
%

%
%  Write the column information.
%
  output_unit = fopen ( col_file, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8CC_WRITE - Fatal error!\n' );
    fprintf ( 1, '  Could not open the output file "%s".\n', col_file );
    error ( 'R8CC_WRITE - Fatal error!' );
  end

  for k = 1 : n + 1

    fprintf ( output_unit, '%8d\n', col(k) );

  end

  fclose ( output_unit );
%
%  Write the row information.
%
  output_unit = fopen ( row_file, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8CC_WRITE - Fatal error!\n' );
    fprintf ( 1, '  Could not open the output file "%s".\n', row_file );
    error ( 'R8CC_WRITE - Fatal error!' );
  end

  for k = 1 : nz_num

    fprintf ( output_unit, '%8d\n', row(k) );

  end

  fclose ( output_unit );
%
%  Write the value information.
%
  output_unit = fopen ( a_file, 'wt' );

  if ( output_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'R8CC_WRITE - Fatal error!\n' );
    fprintf ( 1, '  Could not open the output file "%s".\n', a_file );
    error ( 'R8CC_WRITE - Fatal error!' );
  end

  for k = 1 : nz_num

    fprintf ( output_unit, '%14f\n', a(k) );

  end

  fclose ( output_unit );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function pathNameFix=pathSepFix(pathName)

fileSepString=filesep;

switch fileSepString
    case '/' %i.e. PC so fix to MAC type
        pathNameFix=regexprep(pathName,'\','/');
    case'\' %i.e. LINUX or MAC so fix to PC type
        pathNameFix=regexprep(pathName,'/','\');
end

%%
% _*GIBBON footer text*_
%
% License: <https://github.com/gibbonCode/GIBBON/blob/master/LICENSE>
%
% GIBBON: The Geometry and Image-based Bioengineering add-On. A toolbox for
% image segmentation, image-based modeling, meshing, and finite element
% analysis.
%
% Copyright (C) 2006-2022 Kevin Mattheus Moerman and the GIBBON contributors
%
% This program 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.
%
% This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

author: gibbonCode

repo: GIBBON

save_path: github-repos/MATLAB/gibbonCode-GIBBON


text:
%
%   This .m file creates a rectangular grid and calculates the
%   cumulative number curve at each grid point. The grid is
%   saved in the file "cumugrid.mat".
%                        Operates on catalogue "a"
%
% define size of the area
%
% ________________________________________________________________________
%  Please use the left mouse button or the cursor to select the lower
%  left corner of the area of investigation. Please use the left
%  mouse again to select the upper right corner. The calculation might take
%  some time. This time can be reduced by using a smaller area and/or
%  a larger grid-spacing! The amount of calculation done will be displayed
%  in percent of the total time.
%
%_________________________________________________________________________

report_this_filefun(mfilename('fullpath'));

selgp

itotal = length(newgri(:,1));
if length(gx) < 2  ||  length(gy) < 2
    errordlg('Selection too small! (not a matrix)');
    return
end

close(gpf)
zmap_message_center.clear_message();;think
%  make grid, calculate start- endtime etc.  ...
%
t0b = min(a.Date)  ;
n = a.Count;
teb = a(n,3) ;
tdiff = round((teb - t0b)*365/par1);
cumu = zeros(length(t0b:par1/365:teb)+2);
ncu = length(cumu);
cumuall = zeros(ncu,length(newgri(:,1)));
loc = zeros(3,length(newgri(:,1)));

% loop over  all points
%
i2 = 0.;
i1 = 0.;
allcount = 0.;
%
% loop for all grid points
wai = waitbar(0,' Please Wait ...  ');
set(wai,'NumberTitle','off','Name','Makegrid - Percent completed');;
drawnow

x = newgri(:,1);y = newgri(:,2);
% calculate distance from center point and sort wrt distance
%
lea = a.Count;
lex = length(x(:,1));
al  = a.Longitude * ones(1,lex);
ala = a.Latitude * ones(1,lex);
alt = a.Date * ones(1,lex);
al  = (al' - x * ones(1,lea)) * cos(pi/180*mean(y)*111);
ala  = (ala' - y * ones(1,lea)) * 111;
l = sqrt(al.^2 + ala.^2);
[s,is] = sort(l);
l2 = is <= ni;
alt = reshape(alt(l2),ni,lea);
cumuall = [histogram(alt,t0b:par1/365:teb) ];

%cumuall(:,allcount) = [cumu';  x; l(ni,:)];
loc= [x ; y; s(:,ni)];

waitbar(allcount/itotal)

%
% save data
%
%  set(txt1,'String', 'Saving data...')
close(wai)
drawnow
%save cumugrid.mat cumuall par1 ni dx dy gx gy tdiff t0b teb loc

catSave3 =...
    [ 'zmap_message_center.set_info(''Save Grid'',''  '');think;',...
    ' [file1,path1] = uiputfile(fullfile(hodi, ''eq_data'', ''*.mat''), ''Grid Datafile'');',...
    ' sapa2 = [''save '' path1 file1 '' x y tmpgri newgri xvect yvect ll cumuall par1 ni dx dy gx gy tdiff t0b teb loc a main faults mainfault coastline''];',...
    ' if length(file1) > 1, eval(sapa2),end , done'];

eval(catSave3)

watchoff
zmapmenu
return

figure_w_normalized_uicontrolunits(mess)
clf
set(gca,'visible','off')

te = text(0.01,0.95,'The cumulative number array \newlinehas been saved in \newlinefile cumugrid.mat \newlinePlease rename it \newlineto protect if from overwriting.');
set(te,'FontSize',ZmapGlobal.Data.fontsz.m,'FontWeight','bold')

uicontrol('Units','normal','Position',...
    [.7 .10 .2 .12],'String','Options ', 'Callback','zmapmenu')

uicontrol('Units','normal','Position',...
    [.3 .10 .2 .12],'String','Back', 'Callback','welcome')

author: CelsoReyes


text:
function [OverviewName, phdmeta, overviewmeta] = CreateImageOverview(filename,Prefs)
%CREATEIMAGEOVERVIEW Creates an image overview from CPHD data at the
%specified resolution

%generate overview name
[pathstr, fname] = fileparts(filename);
if strcmpi(Prefs.SICDLocation,'Colocated')
    OverviewName = [pathstr filesep fname '_Overview.nitf'];
else
    OverviewName = [Prefs.SICDLocation filesep fname '_Overview.nitf'];
end

ph_reader = open_ph_reader(filename);
phdmeta = ph_reader.get_meta();
ph_reader.close();

%if specified, use existing Overview file
if Prefs.UseOverview
    if ~isempty(dir(OverviewName))
        reader_obj = open_reader(OverviewName);
        overviewmeta = reader_obj.get_meta();
        reader_obj.close;
        return;
    end
end

%form image at specified resolution
overviewmeta = pfa_file(filename,OverviewName,'Resolution',[Prefs.MaxResolution Prefs.MaxResolution]);

end

author: ngageoint


text:
%computes an array of DetectionResults (which contain arrays of labeled events: goodEvents, missedEvents, badEvents) per
%file
classdef DetectionResultsComputer < handle
    properties (Access = public)
        tolerance = 10;
    end

    methods (Access = public)
        function obj = DetectionResultsComputer()
        end

        %returns an array of DetectionResults (one for each cell)
        function detectionResults = computeDetectionResults(obj,eventsCellArray,annotationsArray)

            nCells = length(eventsCellArray);
            detectionResults = repmat(DetectionResult,1,nCells);
            for i = 1 : nCells
                annotationSet = annotationsArray(i);
                detectedEvents = eventsCellArray{i};
                detectionResults(i) = obj.computeDetectionResult(detectedEvents,annotationSet.eventAnnotations);
            end
        end
    end

    methods (Access = private)
        function r = isRelevantEvents(obj,detectedEvents)
            if isempty(detectedEvents)
                r = [];
            else
                labels = [detectedEvents.label];
                nLabels = length(labels);
                r = false(1,nLabels);
                for i = 1 : nLabels
                    r(i) = obj.isRelevantLabel(labels(i));
                end
            end
        end

        function b = isRelevantLabel(~,label)
            b = label > 0;
        end

        function detectionResult = computeDetectionResult(obj,detectedEvents,eventAnnotations)

            isGoodEvent = obj.isRelevantEvents(detectedEvents);
            goodEvents = obj.computeGoodEvents(detectedEvents,isGoodEvent);
            badEvents = obj.computeBadEvents(detectedEvents,isGoodEvent);

            eventAnnotations = obj.removeIgnoredAnnotations(eventAnnotations);

            missedEvents = obj.computeMissedEventAnnotations(detectedEvents,eventAnnotations);
            detectionResult = DetectionResult(goodEvents,missedEvents,badEvents);
        end

        function eventAnnotations = removeIgnoredAnnotations(~, eventAnnotations)
            isValidLabel = ~Labeling.ShouldIgnoreLabels([eventAnnotations.label]);
            eventAnnotations = eventAnnotations(isValidLabel);
        end

        function goodEvents = computeGoodEvents(~,detectedEvents, isGoodEvent)
            nGoodEvents = sum(isGoodEvent);
            goodEvents = [];
            if nGoodEvents > 0
                goodEvents = repmat(Event(),1,nGoodEvents);
                goodEventCount = 1;
                for i = 1 : length(detectedEvents)
                    if isGoodEvent(i)
                        goodEvents(goodEventCount) = detectedEvents(i);
                        goodEventCount = goodEventCount + 1;
                    end
                end
            end
        end

        function badEvents = computeBadEvents(~,detectedEvents,isGoodEvent)
            nBadEvents = sum(~isGoodEvent);
            badEvents = [];
            if nBadEvents > 0
                badEvents = repmat(Event(),1,nBadEvents);
                eventCount = 1;
                for i = 1 : length(detectedEvents)
                    if ~isGoodEvent(i)
                        badEvents(eventCount) = detectedEvents(i);
                        eventCount = eventCount + 1;
                    end
                end
            end
        end

        function missedEvents = computeMissedEventAnnotations(obj,detectedEvents,eventAnnotations)
            didMissEvent = obj.computeDidMissEvent(detectedEvents,eventAnnotations);
            missedEvents = [];
            nMissedEvents = sum(didMissEvent);
            if nMissedEvents > 0
                missedEvents = repmat(EventAnnotation,1,nMissedEvents);
                missedEventCounter = 1;
                for i = 1 : length(didMissEvent)
                    if didMissEvent(i)
                        missedEvents(missedEventCounter) = eventAnnotations(i);
                        missedEventCounter = missedEventCounter + 1;
                    end
                end
            end
        end

        function didMissEvent = computeDidMissEvent(obj,detectedEvents,annotations)
            nEvents = length(annotations);
            if isempty(detectedEvents)
                didMissEvent = true(1,nEvents);
            else

                didMissEvent = false(1,nEvents);

                detectedEventLocations = [detectedEvents.sample];

                segmentStartings = detectedEventLocations - obj.tolerance;
                segmentEndings = detectedEventLocations + obj.tolerance;

                for i = 1 : length(annotations)
                    if obj.isRelevantLabel(annotations(i).label)
                        eventLocation = annotations(i).sample;
                        contained = DetectionResultsComputer.IsPointContainedInSegments(eventLocation,segmentStartings,segmentEndings);
                        if ~contained
                            didMissEvent(i) = true;
                        end
                    end
                end
            end
        end
    end

    methods (Access = private, Static)
        %returns true if an event value is contained within a range
        function b = IsPointContainedInSegment(point, segmentStarting, segmentEnding)
            b = (point <= segmentEnding && point >= segmentStarting);
        end

        %segments and points should be sorted
        function contained = IsPointContainedInSegments(point,segmentStartings,segmentEndings)
            contained = false;
            for i = 1 : length(segmentStartings)
                segmentStarting = segmentStartings(i);
                segmentEnding = segmentEndings(i);
                if DetectionResultsComputer.IsPointContainedInSegment(point,segmentStarting,segmentEnding)
                    contained = true;
                end
                if point < segmentStarting
                    break;
                end
            end
        end
    end

end

author: avenix

repo: WDK

save_path: github-repos/MATLAB/avenix-WDK


text:
function prob_test162 ( )

%*****************************************************************************80
%
%% TEST162 tests ZIPF_SAMPLE.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  nsample = 1000;
  seed = 123456789;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST162\n' );
  fprintf ( 1, '  For the Zipf PDF:\n' );
  fprintf ( 1, '  ZIPF_SAMPLE samples.\n' );

  a = 4.0;

  check = zipf_check ( a );

  if ( ~check );
    fprintf ( 1, '\n' );
    fprintf ( 1, 'TEST162 - Fatal error!\n' );
    fprintf ( 1, '  The parameters are not legal.\n' );
    return
  end

  mean = zipf_mean ( a );
  variance = zipf_variance ( a );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  PDF parameter A =             %14f\n', a );
  fprintf ( 1, '  PDF mean =                    %14f\n', mean );
  fprintf ( 1, '  PDF variance =                %14f\n', variance );

  for i = 1 : nsample
    [ x(i), seed ] = zipf_sample ( a, seed );
  end

  mean = i4vec_mean ( nsample, x );
  variance = i4vec_variance ( nsample, x );
  xmax = max ( x(1:nsample) );
  xmin = min ( x(1:nsample) );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Sample size =     %6d\n', nsample );
  fprintf ( 1, '  Sample mean =     %14f\n', mean );
  fprintf ( 1, '  Sample variance = %14f\n', variance );
  fprintf ( 1, '  Sample maximum =  %6d\n', xmax );
  fprintf ( 1, '  Sample minimum =  %6d\n', xmin );

  return
end


text:
function [ x, y ] = p06_dat ( data_num )

%*****************************************************************************80
%
%% P06_DAT returns the data vector for problem 6.
%
%  Discussion:
%
%    The X data is equally spaced.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    12 August 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer DATA_NUM, the number of data points.
%
%    Output, real X(DATA_NUM,1), the abscissa data.
%
%    Output, real Y(DATA_NUM,1), the ordinate data.
%
  x = zeros ( data_num, 1 );
  y = zeros ( data_num, 1 );

  num_int = 5;

  n = 1;
  x(n,1) = 0.0;
  y(n,1) = 0.0;

  for i = 1 : num_int

    for j = 1 : i
      n = n + 1;
      x(n,1) = ( i - 1 ) + 0.5 * j /i;
      y(n,1) = j / i;
    end

    for j = 1 : i
      n = n + 1;
      x(n,1) = i - 1 + 0.5 + 0.5 * j / i;
      y(n,1) = 1.0 - j / i;
    end

  end

  return
end


text:
function problem = gen_category_registration(problem)
%% Generate random category registration problem
%% Heng Yang, July 04, 2021

if ~isfield(problem,'N'); error('Please use problem.N to specify number of keypoints.'); end
if ~isfield(problem,'K'); problem.K = 2; end
if ~isfield(problem,'noiseSigma'); problem.noiseSigma = 0.01; end
if ~isfield(problem,'outlierRatio'); problem.outlierRatio = 0.0; end
if ~isfield(problem,'intraRadius'); problem.intraRadius = 0.2; end
if ~isfield(problem,'translationBound'); problem.translationBound = 10.0; end

N               = problem.N;
K               = problem.K;
noiseSigma      = problem.noiseSigma;
outlierRatio    = problem.outlierRatio;
intraRadius     = problem.intraRadius;
translationBound= problem.translationBound;

% generate a mean shape centered at zero
mean_shape = randn(3,N);
mean_shape = mean_shape - mean(mean_shape,2);

shapes     = zeros(3,N,K);
for k = 1:K
    shapes(:,:,k)  = mean_shape + intraRadius * randn(3,N);
end

% ground truth c, R, t
c_gt           = rand(K,1);
c_gt           = c_gt/sum(c_gt); % c sum up to one
R_gt           = rand_rotation;
t_gt           = randn(3,1); t_gt = t_gt/norm(t_gt);
t_gt           = translationBound * rand * t_gt;

% generate a noisy scene
shape          = combine_shapes(shapes,c_gt);
scene          = R_gt * shape + t_gt + noiseSigma * randn(3,N);

% generate outliers
nrOutliers     = round(N*outlierRatio);
if nrOutliers > 0
    fprintf('Category registration: generate %d outliers.\n',nrOutliers);
    outlierIDs  = N-nrOutliers+1:N;
    outliers    = randn(3,nrOutliers);
    scene(:,outlierIDs) = outliers;
else
    outlierIDs   = [];
end

theta_gt   = ones(N,1);
theta_gt(outlierIDs) = -1;

problem.type                = 'category registration';
problem.shape               = shape;
problem.shapes              = shapes;
problem.scene               = scene;
problem.nrOutliers          = nrOutliers;
problem.outlierIDs          = outlierIDs;
problem.c_gt                = c_gt;
problem.R_gt                = R_gt;
problem.t_gt                = t_gt;
problem.cBound              = 1.0;
problem.theta_gt            = theta_gt;

noiseBoundSq                = max(4e-2, noiseSigma^2 * chi2inv(0.99,3));
problem.noiseBoundSq        = noiseBoundSq;
problem.noiseBound          = sqrt(problem.noiseBoundSq);

fprintf('N: %d, num outliers: %d, noise bound: %g, translation bound: %g, c bound: %g\n',...
    problem.N,problem.nrOutliers,problem.noiseBound,problem.translationBound,problem.cBound);
end

author: MIT-SPARK

repo: CertifiablyRobustPerception


text:
function [ a, seed ] = r8cc_random ( m, n, nz_num, colptr, rowind, seed )

%*****************************************************************************80
%
%% R8CC_RANDOM randomizes a R8CC matrix.
%
%  Discussion:
%
%    The R8CC format is the double precision sparse compressed column
%    format.  Associated with this format, we have an M by N matrix
%    with NZ_NUM nonzero entries.  We construct the column pointer
%    vector COL of length N+1, such that entries of column J will be
%    stored in positions COL(J) through COL(J+1)-1.  This indexing
%    refers to both the ROW and A vectors, which store the row indices
%    and the values of the nonzero entries.  The entries of the
%    ROW vector corresponding to each column are assumed to be
%    ascending sorted.
%
%    The R8CC format is equivalent to the MATLAB "sparse" format,
%    and the Harwell Boeing "real unsymmetric assembled" (RUA) format.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    01 September 2006
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Iain Duff, Roger Grimes, John Lewis,
%    User's Guide for the Harwell-Boeing Sparse Matrix Collection,
%    October 1992
%
%  Parameters:
%
%    Input, integer M, the number of rows of the matrix.
%
%    Input, integer N, the number of columns of the matrix.
%
%    Input, integer NZ_NUM, the number of nonzero elements in A.
%
%    Input, integer COLPTR(N+1), points to the first element of each column.
%
%    Input, integer ROWIND(NZ_NUM), contains the row indices of the elements.
%
%    Input, integer SEED, a seed for the random number generator.
%
%    Output, real A(NZ_NUM), the matrix.
%
%    Output, integer SEED, an updated seed for the random number generator.
%
  for j = 1 : n
    for k = colptr(j) : colptr(j+1) - 1
      [ a(k), seed ] = r8_uniform_01 ( seed );
    end
  end

  return
end


text:
function b=isequal(f, g)
%ISEQUAL Equality test for BALLFUNV.
%   ISEQUAL(F, G) returns 1 then F and G are the same
%   BALLFUNV and 0 otherwise.
%
%   See also ISZERO.

% Copyright 2019 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

b = iszero(f-g);
end

author: chebfun

repo: chebfun

save_path: github-repos/MATLAB/chebfun-chebfun


text:
function plot_selectProfile(~, eventObj)

hFig = gcf;
idxPC = eventObj.Source.Parent.Parent.UserData.idxPC; % index of PC(s)

hAxes = gca;

try

    % Get new value
    view(2);
    hRotate = rotate3d;
    if strcmpi(hRotate.Enable, 'On'), reactivateRotate3d = true; else reactivateRotate3d = false; end

    % Var1: Select profile
    % [x, y] = ginput_2016a_mod(2);
    % lineStart = [x(1) y(1)];
    % lineEnd   = [x(2) y(2)];

    % Var2: Select profile
    [lineStart(1), lineStart(2)] = ginput_2016a_mod(1); % get start point
    zMax = max(get(gca, 'ZLim'));
    hStart = plot3(lineStart(1), lineStart(2), zMax, 'o', 'Color', 'r', 'MarkerSize', 5, 'LineWidth', 2);
    [lineEnd(1), lineEnd(2)] = ginput_2016a_mod(1); % get end point
    hEnd = plot3(lineEnd(1), lineEnd(2), zMax, 'o', 'Color', 'r', 'MarkerSize', 5, 'LineWidth', 2);
    hLine1 = plot3([lineStart(1); lineEnd(1)], [lineStart(2); lineEnd(2)], [zMax; zMax], '-', 'LineWidth', 3, 'Color', 'k');
    hLine2 = plot3([lineStart(1); lineEnd(1)], [lineStart(2); lineEnd(2)], [zMax; zMax], ':', 'LineWidth', 3, 'Color', 'w');

    % Define width
    prompt = {'Profile width:'};
    dlgTitle = '';
    noLines = 1;
    defaultAnswer = {'1'};
    answer = inputdlg(prompt, dlgTitle, noLines, defaultAnswer);
    delete(hStart); delete(hEnd); delete(hLine1); delete(hLine2); % delete points and line
    if ~isempty(answer{1})
        lineWidth = str2num(answer{1});
    else
        return;
    end

    if reactivateRotate3d, hRotate.Enable  = 'On'; end

catch

    error('Error selecting ''Profile''!'); return;

end

% Select profile
for i = 1:numel(idxPC)

    if i == 1, logLevelOrig = msg('O', 'GetLogLevel'); end
    msg('O', 'SetLogLevel', 'off');

    % Select profile!
    hFig.UserData.PC{idxPC(i)}.select('All');
    az = hFig.UserData.PC{idxPC(i)}.select('Profile', lineStart, lineEnd, lineWidth);

    msg('O', 'SetLogLevel', logLevelOrig);

end

view(az, 0);

% Update plot!
for i = 1:numel(idxPC)
    plot_setPrmAndPlot(hFig, idxPC(i));
end

end

author: pglira


text:
%% This function will generate the simulation data of an ODE function.
%You could determine the noise level by input variable "Noise". If you do
%not want any noise, set noise to zero. Please indicate whether your ODE
%function have control input, if the answer is yes, please set the
%"Control" as 1.

% Last Update: 2019/04/21
% Coded By: K

function [d_Data,Data]=Get_Sim_Data(ODE,state0,u,tspan,Noise,Control,Shuffle)
%% Get the size of the state and control
[N1,M1]=size(state0);
[N2,M2]=size(u);

%% Get simulation data by simulating the system using ODE113

% Determine the left hand side derivative
if Control==1
    y_list(1,:)=state0;
    d_y_list(1,:)=ODE(0,y_list(1,:),u(1,:));
    for i=2:length(u)
        [t_1,y_1] = ode113(@(t_1,y_1)ODE(t_1,y_1,u(i-1,:)),tspan(1,i-1:i),state0);
        y_list(i,:)=y_1(end,:);
        d_y_list(i,:)=ODE(0,y_list(i,:),u(i,:));
        state0=y_list(i,:)';
    end
else
    %Simulate the system ODE
    [t,y]=ode45(@(t,y)ODE(t,y),tspan,state0);
    y_list=y;
    % Get the derivative data
    d_y_list=ODE(0,y_list')';
end

%% Add some noise to the system
for i=1:N1
    Data(:,i)=y_list(:,i)+Noise*randn(size(y_list(:,i)));
end
%
for i=1:N1
    d_Data(:,i)=d_y_list(:,i)+Noise*randn(size(d_y_list(:,i)));
end

%% Shuffle the data
if Shuffle==1
    Sequence=randperm(size(Data,1));
    Data=Data(Sequence,:);
    d_Data=d_Data(Sequence,:);
end

author: dynamicslab

repo: SINDy-PI


text:
% LFUtilProcessCalibrations - process a folder/tree of camera calibrations
%
% Usage:
%
%     LFUtilProcessCalibrations
%     LFUtilProcessCalibrations( CalibrationsPath )
%     LFUtilProcessCalibrations( CalibrationsPath, FileOptions )
%     LFUtilProcessCalibrations( [], FileOptions )
%
% All parameters are optional and take on default values as set in the "Defaults" section at the top
% of the implementation. As such, this can be called as a function or run directly by editing the
% code. When calling as a function, pass an empty array "[]" to omit a parameter.
%
% This function recursively crawls through a folder identifying camera "calibration info" files and
% building a database for use in selecting a calibration appropriate to a light field. An example
% usage is in the image rectification code in LFUtilDecodeLytroFolder / LFSelectFromDatabase.
%
% Inputs -- all are optional, see code below for default values :
%
%    CalibrationsPath : Path to folder containing calibrations -- note the function operates
%                       recursively, i.e. it will search sub-folders. The calibration database will
%                       be created at the top level of this path. A typical configuration is to
%                       create a "Cameras" folder with a separate subfolder of calibrations for each
%                       camera in use. The appropriate path to pass to this function is the top
%                       level of that cameras folder.
%
%
%     FileOptions : struct controlling file naming and saving
%                       .SaveResult : Set to false to perform a "dry run"
%         .CalibrationDatabaseFname : Name of file to which white image database is saved
%           .CalInfoFilenamePattern : File search pattern for finding calibrations
%
% Output takes the form of a saved calibration database.
%
% User guide: LFToolbox.pdf
% See also: LFUtilDecodeLytroFolder, LFCalRectifyLF, LFSelectFromDatabase, LFUtilCalLensletCam,
% LFUtilProcessWhiteImages

% Copyright (c) 2013-2020 Donald G. Dansereau

function LFUtilProcessCalibrations( CalibrationsPath, FileOptions )

%---Defaults---
CalibrationsPath = LFDefaultVal( 'CalibrationsPath', 'Cameras' );

FileOptions = LFDefaultField( 'FileOptions', 'SaveResult', true );
FileOptions = LFDefaultField( 'FileOptions', 'CalibrationDatabaseFname', 'CalibrationDatabase.mat' );
FileOptions = LFDefaultField( 'FileOptions', 'CalInfoFilenamePattern', 'CalInfo*.json' );

%---Crawl folder structure locating calibrations---
fprintf('Building database of calibrations in %s\n', CalibrationsPath);
CamInfo = LFGatherCamInfo( CalibrationsPath, FileOptions.CalInfoFilenamePattern );

%---Optionally save---
if( FileOptions.SaveResult )
    SaveFpath = fullfile(CalibrationsPath, FileOptions.CalibrationDatabaseFname);
    fprintf('Saving to %s\n', SaveFpath);

    TimeStamp = datestr(now,'ddmmmyyyy_HHMMSS');
    GeneratedByInfo = struct('mfilename', mfilename, 'time', TimeStamp, 'VersionStr', LFToolboxVersion);
    save(SaveFpath, 'GeneratedByInfo', 'CamInfo');
end

repo: LFToolbox


text:
function channels = EPW(N, beta)
m = log2(N);
channels = zeros(N, 1);
for i = 0 : N - 1
    bin_seq_str = dec2bin(i, m);
    bin_seq = zeros(m, 1);
    for j = 1 : m
        if bin_seq_str(j) == '1'
            bin_seq(j) = 1;
        end
    end
    bin_seq = bin_seq(m : -1 : 1);
    sum = 0;
    for j = 1 : m
        if m >= 9
            sum = sum + bin_seq(j) * (beta^(j - 1) + 0.221 * 0.9889^(j - 1) - bin_seq(9) * 0.0371 * 0.5759^(j - 1) - bin_seq(8) * 0.047 * 0.4433^(j - 1));
        else
            if m == 8
                sum = sum + bin_seq(j) * (beta^(j - 1) + 0.221 * 0.9889^(j - 1) - bin_seq(8) * 0.047 * 0.4433^(j - 1));
            else
                sum = sum + bin_seq(j) * (beta^(j - 1) + 0.221 * 0.9889^(j - 1));
            end
        end
    end
    channels(i + 1) = sum;
end
end

author: YuYongRun

repo: PolarCodeDecodersInMatlab


text:
% book : Signals and Systems Laboratory with MATLAB
% authors : Alex Palamides & Anastasia Veloni
%
%
%
% problem 5 - convolution of x(t) and h(t)

t1=0:.1:.9;
t2=1:.1:3;
t3=3.1:.1:5;
x1=zeros(size(t1));
x2=t2;
x3=ones(size(t3));
x=[x1 x2 x3];
h1=zeros(size(t1));
h2=exp(-t2);
h3=zeros(size(t3));
h=[h1 h2 h3];
y=conv(x,h)*0.1;
plot(0:.1:10,y);
legend('y(t)')

figure
th=1:.01:3;
h=exp(-th);
tx1=1:.01:3;
x1=tx1;
tx2=3.01:.01:5;
x2=ones(size(tx2));
x=[x1 x2];
y=conv(x,h)*0.01;
plot(2:.01:8,y);
legend('y(t)')


text:
function varargout = main_edit_video(varargin)
% MAIN_EDIT_VIDEO MATLAB code for main_edit_video.fig
%      MAIN_EDIT_VIDEO, by itself, creates a new MAIN_EDIT_VIDEO or raises the existing
%      singleton*.
%
%      H = MAIN_EDIT_VIDEO returns the handle to a new MAIN_EDIT_VIDEO or the handle to
%      the existing singleton*.
%
%      MAIN_EDIT_VIDEO('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in MAIN_EDIT_VIDEO.M with the given input arguments.
%
%      MAIN_EDIT_VIDEO('Property','Value',...) creates a new MAIN_EDIT_VIDEO or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before main_edit_video_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to main_edit_video_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help main_edit_video

% Last Modified by GUIDE v2.5 28-May-2014 22:09:41

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @main_edit_video_OpeningFcn, ...
                   'gui_OutputFcn',  @main_edit_video_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before main_edit_video is made visible.
function main_edit_video_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to main_edit_video (see VARARGIN)

% Choose default command line output for main_edit_video
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes main_edit_video wait for user response (see UIRESUME)
% uiwait(handles.figure1);

clc;
lrs_load_conf;

set(hObject,'Name','Video editor','NumberTitle','off');

set(handles.edit_input_video,'string',fullfile(lrs_conf.lrs_dir,'dataset','demo.avi'));
set(handles.edit_output_video,'string',fullfile(lrs_conf.lrs_dir,'dataset','demo_out.avi'));

img = imread(fullfile(lrs_conf.lrs_dir,'figs','no-available-image.png'));
imshow(img,'parent',handles.axes_input);

% --- Outputs from this function are returned to the command line.
function varargout = main_edit_video_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

function edit_input_video_Callback(hObject, eventdata, handles)
% hObject    handle to edit_input_video (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_input_video as text
%        str2double(get(hObject,'String')) returns contents of edit_input_video as a double

% --- Executes during object creation, after setting all properties.
function edit_input_video_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_input_video (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton_show_input_video.
function pushbutton_show_input_video_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_show_input_video (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global runningFlag;
if(runningFlag == false)
    inputVideoHandle = handles.edit_input_video;
    axesInputHandle = handles.axes_input;
    textLogMessageHandle = handles.text_log_message;
    gui_show_video(inputVideoHandle,axesInputHandle,textLogMessageHandle);
else
    disp('Stop video first!');
end

% --- Executes on button press in pushbutton_close_window.
function pushbutton_close_window_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_close_window (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in pushbutton_select_input.
function pushbutton_select_input_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_select_input (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
lrs_load_conf;
[filename, pathname] = uigetfile({'*.avi';'*.mpg';'*.mp4';'*.*'},'File Selector',fullfile(lrs_conf.lrs_dir,'dataset'));
if(~isequal(filename,0) && ~isequal(pathname,0))
  inputVideoHandle = handles.edit_input_video;
  fullpath = fullfile(pathname, filename);
  set(inputVideoHandle,'String',fullpath);
end

% --- Executes on button press in pushbutton_stop.
function pushbutton_stop_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_stop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global stopFlag;
stopFlag = true;

function edit_crop_begin_Callback(hObject, eventdata, handles)
% hObject    handle to edit_crop_begin (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_crop_begin as text
%        str2double(get(hObject,'String')) returns contents of edit_crop_begin as a double

% --- Executes during object creation, after setting all properties.
function edit_crop_begin_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_crop_begin (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function edit_crop_end_Callback(hObject, eventdata, handles)
% hObject    handle to edit_crop_end (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_crop_end as text
%        str2double(get(hObject,'String')) returns contents of edit_crop_end as a double

% --- Executes during object creation, after setting all properties.
function edit_crop_end_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_crop_end (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function edit_resize_factor_Callback(hObject, eventdata, handles)
% hObject    handle to edit_resize_factor (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_resize_factor as text
%        str2double(get(hObject,'String')) returns contents of edit_resize_factor as a double

% --- Executes during object creation, after setting all properties.
function edit_resize_factor_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_resize_factor (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in checkbox_resize.
function checkbox_resize_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox_resize (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox_resize

% --- Executes on button press in checkbox_crop.
function checkbox_crop_Callback(hObject, eventdata, handles)
% hObject    handle to checkbox_crop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox_crop

% --- Executes on button press in pushbutton_process.
function pushbutton_process_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_process (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

inputVideoHandle = handles.edit_input_video;
inputFileName = get(inputVideoHandle,'String');
disp(['Input video: ' inputFileName]);

outputVideoHandle = handles.edit_output_video;
outputFileName = get(outputVideoHandle,'String');
disp(['Output video: ' outputFileName]);

if exist(inputFileName, 'file')
  displog('Loading video...');
  video_struct = load_video_file(inputFileName);
  video = convert_video_to_4d(video_struct); % show_4dvideo(video);
  video_aux = video;

  checkboxCropHandle = handles.checkbox_crop;
  if (get(checkboxCropHandle,'Value') == get(checkboxCropHandle,'Max'))
    displog('Cropping video...');

    r = str2double(get(handles.edit_crop_begin,'String'));
    s = str2double(get(handles.edit_crop_end,'String'));

    disp(['Begin: ', num2str(r)]);
    disp(['End: ', num2str(s)]);

    [video_aux] = crop_4dvideo(video,r,s);
  end

  checkboxResizeHandle = handles.checkbox_resize;
  if (get(checkboxResizeHandle,'Value') == get(checkboxResizeHandle,'Max'))
    displog('Resizing video...');

    f = str2double(get(handles.edit_resize_factor,'String'));

    disp(['Factor: ', num2str(f)]);

    [video_aux] = resize_4dvideo(video_aux,f);
  end

  displog('Saving video...');
  convert_video4d_to_avi(video_aux,outputFileName);
  displog('OK');
else
  % File does not exist.
  warningMessage = sprintf('Warning: file does not exist:\n%s', inputFileName);
  uiwait(msgbox(warningMessage));
end

function edit_output_video_Callback(hObject, eventdata, handles)
% hObject    handle to edit_output_video (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit_output_video as text
%        str2double(get(hObject,'String')) returns contents of edit_output_video as a double

% --- Executes during object creation, after setting all properties.
function edit_output_video_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit_output_video (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton_show_output_video.
function pushbutton_show_output_video_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton_show_output_video (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global runningFlag;
if(runningFlag == false)
    gui_show_video(handles.edit_output_video,handles.axes_input,handles.text_log_message);
else
    disp('Stop video first!');
end

author: andrewssobral

repo: lrslibrary


text:
function [ml] = ft32ml(ft3)
% Convert volume from cubic feet to milliliters.
% Chad Greene 2012
ml = ft3*28316.846592;


text:
function strat = randomBetStrategy_timeseries(dat_dir, files, bet, hours, nValidOdds, nGamesStrategy, nSamps, preload, s1)

% 1- Select random sample of games, same number as number of games in Beat
% the Bookie strategy
% For each game, select random time before the game, random outcome (home, draw, away)
% bet on the maximum odds for that outcome at that time
% calculate returns

% Proportion of Home, Draw or away that our strategy employed
pHome = s1.pHome;
pDraw = s1.pDraw;
pAway = s1.pAway;

% preload all files for speed
if preload
   all_data = nan(32,length(cell2mat(hours)),size(files,1));
   for fi = 1 : size(files,1)
       if mod(fi,1000) == 0
          fprintf('Preloading Game #%d \n', fi)
       end
       fid = fopen([dat_dir files(fi).name], 'r');
       C = textscan(fid, repmat('%f ' , [1,72*3]), 'delimiter', ',');
       fclose(fid);
       aux = cell2mat(C);
       all_data(:,:,fi) =  aux(:,cell2mat(hours));
   end
   hours{1} = hours{1} - hours{1}(1) + 1;
   hours{2} = hours{2} - hours{2}(1) + 1 + length(hours{1});
   hours{3} = hours{3} - hours{3}(1) + 1 + length(hours{1}) + length(hours{3});
end

% Pre-allocate matrixes
money = nan(nSamps, nGamesStrategy);
money(:,1) = 0;
accuracy = nan(nSamps, nGamesStrategy);
ids = nan(nSamps, nGamesStrategy);
c = 1;
wodds = 1;
wZeros = 1;

for samp = 1 : nSamps

    fprintf('Sample #%d \n', samp);
    dat_rnd = randperm(size(files,1));
    m = 1; % counter for money (returns always start at '0')

    fi = 1;
    while 1

        % Loop through until we get all valid games for the strategy
        if (m) > nGamesStrategy
            break
        end

        if mod(fi,1000) == 0
            fprintf('Game #%d \n', fi);
        end

        if preload
            data = squeeze(all_data(:,:,dat_rnd(fi)));
        else
            fid = fopen([dat_dir files(dat_rnd(fi)).name], 'r');
            C = textscan(fid, repmat('%f ' , [1,72*3]), 'delimiter', ',');
            fclose(fid);
            data = cell2mat(C);
        end

        % sanity check: there are some games that had odds more than 8
        % hours away from the beginning of the game and then got cancelled.
        % We discard those few games here.
        if sum(isnan(data(:))) == (32 * 216)
            fprintf('Skip Game number %d, %s \n', dat_rnd(fi), files(dat_rnd(fi)).name);
            fi = fi + 1;
            continue;
        end

        % get result of the game
        name = strrep(files(dat_rnd(fi)).name, '.txt', '');
        C = strsplit(name, '_');
        score_home = str2double(C{end-1});
        score_away = str2double(C{end});
        if score_home > score_away
            result = 1;
        elseif score_home == score_away
            result = 2;
        else
            result = 3;
        end

        % Select what to bet (Home, Draw or away) according to the
        % respective probabilities. These probabilities come from
        % the results of our strategy.
        bet_result = sum(rand >= cumsum([0, pHome, pDraw, pAway]));

        % Choose time randomly
        randomTimeOutcome = randsample(hours{bet_result},1);

         % Check that there are at least nValidOdds in the selected hour
        if sum(~isnan(data(:, randomTimeOutcome))) < nValidOdds
%             fprintf('Game without odds')
            wodds = wodds + 1;
            fi = fi + 1;
            continue
        end

        if any(data(:, randomTimeOutcome)) == 0
%             fprintf('Game with odds 0')
            wZeros = wZeros + 1;
            fi = fi + 1;
            continue
        end

        % select max odds at time/outcome
        max_odds(samp, m) = nanmax(data(:, randomTimeOutcome));
        mean_odds(samp, m) = nanmean(data(:, randomTimeOutcome));

        % Estimate return for each game
        if (~isnan(max_odds(samp, m)))
            aux_possible_earn = bet  * (max_odds(samp, m) - 1);

            % calculate loss / earning
            if isequal(bet_result, result)
                money(samp, m + 1) = money(samp, m) + aux_possible_earn;
                accuracy(samp, m) = 1;
                ids(samp, m) = bet_result;
                m = m + 1;
            else
                money(samp, m + 1) = money(samp, m) - bet;
                accuracy(samp, m) = 0;
                ids(samp, m) = bet_result;
                m = m + 1;
            end

        % Some games have bookies with very few valid odds. Skip them
        else
            c = c + 1;
            fi = fi + 1;
            continue;
        end

        fi = fi + 1;
    end
end

% sprintf('There were %d games with invalid / insufficient number of odds', c)
strat.money = money;
strat.name = 'RandomStrategy';
strat.max_odds = max_odds;
strat.mean_odds = mean_odds;
strat.accuracy = accuracy;
strat.ids = ids;
strat.wodds = wodds;
strat.wZeros = wZeros;

end

repo: BeatTheBookie


text:
function view=mrv_dilateCurrentROI(view,iterations)
% function d=mrv_dilateCurrentROI(view)
% PURPOSE: Dilates the current ROI in the Gray view.
% HISTORY: 100704: ARW: Wrote it.
% Note: Large numbers of iterations can result in long processing times.
if (~exist('iterations','var'))
    iterations=1;
end
if ~(strcmp(view.viewType,'Gray') | strcmp(view.viewType,'Volume'))
    error('This routine requires you to be in the Gray view');
end

thisROI=view.ROIs(view.selectedROI);
if(~isfield(view,'grayConMat') | isempty(view.grayConMat));
    disp('Computing connection matrix...');
    view.grayConMat = makeGrayConMat(view.nodes,view.edges,0);
end
thisROI.coords=mrv_dilateGrayROI(view,thisROI.coords,iterations);
thisROI.name=[thisROI.name,'_dilated'];
view=addROI(view,thisROI);
return;

author: vistalab

repo: vistasoft

save_path: github-repos/MATLAB/vistalab-vistasoft


text:
function samplingPoints = index2sample(this, arrayIndices, iDims)
% Returns index (coordinate) as given by dim-info for specific voxel samplingPoints
%
%   Y = MrDimInfo()
%   samplingPoints = Y.index2sample(arrayIndices, iDims)
%
% If the samplingPoints-arrays are filled explicitly, these values are taken. If
% not, then labelIndex = range(1) + (arrayIndex-1)*resolution is returned
% for the respective dimension
%
% This is a method of class MrDimInfo.
%
% IN
%   arrayIndices        matrix [nVoxels, nDims] of absolute
%                       voxel samplingPoints (one per row) within array
%   iDims               if specified, arrayIndices are assumed to be subset
%                       of all dimensions only
% OUT
%   samplingPoints      matrix [nVoxels, nDims] of voxel
%                       samplingPoints in coordinate system given by dimInfo
%
% EXAMPLE
%   index2sample([3 4 5])
%       => returns
%
%   See also MrDimInfo demo_dim_info MrImageGeometry MrDimInfo.get_voxels

% Author:   Saskia Bollmann & Lars Kasper
% Created:  2016-01-23
% Copyright (C) 2016 Institute for Biomedical Engineering
%                    University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC Toolbox, which is released
% under the terms of the GNU General Public License (GPL), version 3.
% You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version).
% For further details, see the file COPYING or
%  <http://www.gnu.org/licenses/>.

if nargin < 3
    iDims = 1:this.nDims;
end

nDimsSubset = numel(iDims);

isRowVector = nDimsSubset == 1 && size(arrayIndices,1) == 1;

if isRowVector
   arrayIndices = arrayIndices(:); % allows row/column vectors as input for 1-dim trafo
end

nVoxels = size(arrayIndices,1);

samplingPoints = zeros(nVoxels,nDimsSubset);

for v = 1:nVoxels
    % for each dimension, take explicit samplingPoints
    for d = 1:nDimsSubset
        iDim = iDims(d);
        samplingPoints(v,d) = this.samplingPoints{iDim}(arrayIndices(v,d));
    end
end

if isRowVector % transform back to row vector for output
    samplingPoints = reshape(samplingPoints, 1, []);
end

author: translationalneuromodeling

repo: tapas


text:
function test_bug1248

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_preprocessing preproc

for samp=[25 98 999]
  for fs=[235 943]
    data = [];
    data.hdr.Fs     = fs;
    data.hdr.label  = {'fakechan1','fakechan2','fakechan3'};
    data.fsample    = fs;
    data.label      = {'fakechan1','fakechan2','fakechan3'};
    data.trial      = {rand(3,samp),rand(3,samp+1),rand(3,samp+2)};
    data.time       = {1/fs:1/fs:samp/fs,1/fs:1/fs:(samp+1)/fs,1/fs:1/fs:(samp+2)/fs};

    cfg = [];
    cfg.hpfreq     = 2;
    cfg.hpfiltord  = [];
    cfg.hpfilter   = 'yes';
    cfg.hpfilttype = 'fir';
    data = ft_preprocessing(cfg,data);

    cfg = [];
    cfg.hpfreq     = 2;
    cfg.hpfiltord  = [];
    cfg.hpfilter   = 'yes';
    cfg.hpfilttype = 'firls';
    data = ft_preprocessing(cfg,data);

    % no problem originally here
    cfg = [];
    cfg.lpfreq     = 20;
    cfg.lpfiltord  = [];
    cfg.lpfilter   = 'yes';
    cfg.lpfilttype = 'fir';
    data = ft_preprocessing(cfg,data);

    cfg = [];
    cfg.bpfreq     = [2 20];
    cfg.bpfiltord  = [];
    cfg.bpfilter   = 'yes';
    cfg.bpfilttype = 'fir';
    data = ft_preprocessing(cfg,data);

    cfg = [];
    cfg.bsfreq     = [2 20];
    cfg.bsfiltord  = [];
    cfg.bsfilter   = 'yes';
    cfg.bsfilttype = 'fir';
    data = ft_preprocessing(cfg,data);

    cfg = [];
    cfg.bsfreq     = [2 20];
    cfg.bsfiltord  = [];
    cfg.bsfilter   = 'yes';
    cfg.bsfilttype = 'firls';
    data = ft_preprocessing(cfg,data);

  end
end

author: fieldtrip

repo: fieldtrip

save_path: github-repos/MATLAB/fieldtrip-fieldtrip


text:
function ChanceConstraint = le(level,P)

if isa(P,'double') & isa(level,'probability')
    error('Currently only supports level <= p(F)')
    temp = P;
    P = level;
    level = temp;
end

if level < 0 | level > 1
    error('The confidence level must be between 0 and 1');
end
ChanceConstraint = chance(P.Constraint,level);

author: yalmip

repo: YALMIP

save_path: github-repos/MATLAB/yalmip-YALMIP


text:
function Q = makeQForWeightedCorr(UniqueNumBins, numPlaces)
%function Q = makeQForWeightedCorr(UniqueNumBins, numPlaces)

a1 = repmat((1:max(UniqueNumBins))', [1, numPlaces]);
b1 = repmat(1:numPlaces, [max(UniqueNumBins), 1]);
Q = {};
for i = 1:length(UniqueNumBins)

    Q{UniqueNumBins(i)} = [reshape(a1(1:UniqueNumBins(i), :), [], 1), reshape(b1(1:UniqueNumBins(i), :), [], 1)];
end

author: buzsakilab

repo: buzcode


text:
function run_training ( )

%% loading the setup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
options = setup( );

%% learning other requirements %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if options.learningShape == 1
    disp('Learning shap model...');
    do_learn_shape( options );
end

if options.learningVariation == 1
    disp('Learning data variation...');
    do_learn_variation( options );
end

load( ['model/' options.datasetName '_ShapeModel.mat']    );
load( ['model/' options.datasetName '_DataVariation.mat'] );

%% learn cascaded regression %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

imgDir = options.trainingImageDataPath;
ptsDir = options.trainingTruthDataPath;

%% loading data
disp('Loading training data...');
Data = load_all_data2( imgDir, ptsDir, options );

n_cascades = options.n_cascades;
LearnedCascadedModel{n_cascades}.R = [];

rms = zeros(n_cascades,1);

for icascade = 1 : n_cascades

    options.current_cascade = icascade;

    %% learning single regressors
    if icascade == 1

        new_init_shape = [];
        [R,new_init_shape,rms(icascade)] = learn_single_regressor( ...
            ShapeModel, DataVariation, Data, new_init_shape, options );

        LearnedCascadedModel{icascade}.R = R;

        %% save other parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        LearnedCascadedModel{icascade}.n_cascades = n_cascades;
        LearnedCascadedModel{icascade}.descSize   = options.descSize;
        LearnedCascadedModel{icascade}.descBins   = options.descBins;

    else

        [R, new_init_shape,rms(icascade)] = learn_single_regressor( ...
            ShapeModel, DataVariation, Data, new_init_shape, options );

        LearnedCascadedModel{icascade}.R = R;

    end

end

%save('result/Trained_RMS.mat' , 'rms');

save([options.modelPath options.slash ...
    'LearnedCascadedModel.mat'],'LearnedCascadedModel');
clear;

author: tntrung


text:
function M=movsp2wv(N,Np);
%MOVSP2WV Movie illustrating the passage from the spectrogram to the WVD.
%	M=MOVSP2WV(N,Np) generates the movie frames illustrating the passage
%	from the spectrogram to the WVD using different smoothing gaussian
%	windows in the smoothed pseudo-WVD.
%
%	N : number of points for the signal;
%	Np : number of snapshots (default : 8)
%	M : matrix of movie frames.
%
%	Example :
%	 M=movsp2wv(128,15); movie(M,5);

%	O. Lemoine - June 1996.
%	Copyright (c) 1996 by CNRS (France).
%
%  This program 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 2 of the License, or
%  (at your option) any later version.
%
%  This program 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 this program; if not, write to the Free Software
%  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

if nargin<1,
 error('At least one argument required');
elseif nargin==1,
 Np=8;
end
Np=odd(Np)-1;

M  = moviein(Np);

t1=N/4; t2=3*N/4; t3=t1; t4=t2;
f1=0.125; f2=f1; f3=0.375; f4=f3;
t=1:N;
T=sqrt(2*N);

sig1=amgauss(N,t1,T).*fmconst(N,f1,t1);
sig2=amgauss(N,t2,T).*fmconst(N,f2,t2);
sig3=amgauss(N,t3,T).*fmconst(N,f3,t3);
sig4=amgauss(N,t4,T).*fmconst(N,f4,t4);

sig=sig1+sig2+sig3+sig4;

h=tftb_window(49,'gauss');
[tfr,t,f]=tfrsp(sig,t,N,h); tfr=tfr(1:N/2,:); f=f(1:N/2);
Max=max(max(tfr)); V=[0.1 0.3 0.5 0.7 0.9]*Max;
contour(t,f,tfr,V);
xlabel('Time'); ylabel('Frequency'); axis('xy')
M(:,1) = getframe;

Ng0=odd(fliplr(linspace(3,N/4,Np/2-1)));
Nh0=odd(linspace(N/2,9*N/10,Np/2-1));

for k=2:Np/2,
 g=tftb_window(Ng0(k-1),'gauss');
 h=tftb_window(Nh0(k-1),'gauss');
 [tfr,t,f]=tfrspwv(sig,t,N,g,h);
 Max=max(max(tfr)); V=[0.1 0.3 0.5 0.7 0.9]*Max;
 contour(t,f,tfr,V);
 xlabel('Time'); ylabel('Frequency'); axis('xy')
 M(:,k) = getframe;
end

[tfr,t,f]=tfrwv(sig);
Max=max(max(tfr)); V=[0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]*Max;
contour(t,f,tfr,V);
xlabel('Time'); ylabel('Frequency'); axis('xy')
M(:,Np/2+1) = getframe;

for k=Np/2+2:Np,
 M(:,k) =M(:,Np+2-k);
end

author: HeLiangHIT


text:
% A demo how to run a multi-face face tracker

clear;

if(isunix)
    executable = '"../../build/bin/FaceLandmarkVidMulti"';
else
    executable = '"../../x64/Release/FaceLandmarkVidMulti.exe"';
end

in_files = dir('../../samples/multi_face.avi');

model = 'model/main_ceclm_general.txt'; % Trained on in the wild, menpo and multi-pie data (a CE-CLM model)

% Uncomment the below models if you want to try them
%model = 'model/main_clnf_general.txt'; % Trained on in the wild and multi-pie data (a CLNF model)

% Uncomment the below models if you want to try them
%model = 'model/main_clnf_wild.txt'; % Trained on in-the-wild data only

%model = 'model/main_clm_general.txt'; % Trained on in the wild and multi-pie data (less accurate SVR/CLM model)
%model = 'model/main_clm_wild.txt'; % Trained on in-the-wild

% Create a command that will run the tracker on set of videos and display the output
command = sprintf('%s -mloc "%s" -verbose ', executable, model);

% add all videos to single argument list (so as not to load the model anew
% for every video)
for i=1:numel(in_files)
    inputFile = ['../../samples/', in_files(i).name];
    command = cat(2, command, [' -f "' inputFile '" ']);
end

% Call the executable
if(isunix)
    unix(command);
else
    dos(command);
end

author: TadasBaltrusaitis

repo: OpenFace


text:
filename='Bridge_quad_coarse';
 ptype = 'MACRO';
method = 'SIMPALL';
materialType = 'ISOTROPIC';
initial_case = 'full';
cost = {'compliance';'perimeter'};
weights = [1, 0.1];
constraint = {'volumeConstraint'};
optimizer = 'MMA'; incrementFactor = 1;
filterType = 'P1';

nsteps = 5;
Vfrac_final = 0.2;
Perimeter_target = 1;
optimality_final = 1e-3;
constr_final =1e-3;

Vfrac_initial = 1;
optimality_initial = 1e-2;
constr_initial = 1e-3;
TOL.rho_plus = 1;
TOL.rho_minus = 0;
TOL.E_plus = 1;
TOL.E_minus = 1e-3;
TOL.nu_plus = 1/3;
TOL.nu_minus = 1/3;

author: SwanLab

repo: Swan


text:
function [mel,mr] = frq2mel(frq)
%FRQ2ERB  Convert Hertz to Mel frequency scale MEL=(FRQ)
%	[mel,mr] = frq2mel(frq) converts a vector of frequencies (in Hz)
%	to the corresponding values on the Mel scale which corresponds
%	to the perceived pitch of a tone.
%   mr gives the corresponding gradients in Hz/mel.

%	The relationship between mel and frq is given by:
%
%	m = ln(1 + f/700) * 1000 / ln(1+1000/700)
%
%  	This means that m(1000) = 1000
%
%	References:
%
%	  [1] S. S. Stevens & J. Volkman "The relation of pitch to
%		frequency", American J of Psychology, V 53, p329 1940
%	  [2] C. G. M. Fant, "Acoustic description & classification
%		of phonetic units", Ericsson Tchnics, No 1 1959
%		(reprinted in "Speech Sounds & Features", MIT Press 1973)
%	  [3] S. B. Davis & P. Mermelstein, "Comparison of parametric
%		representations for monosyllabic word recognition in
%		continuously spoken sentences", IEEE ASSP, V 28,
%		pp 357-366 Aug 1980
%	  [4] J. R. Deller Jr, J. G. Proakis, J. H. L. Hansen,
%		"Discrete-Time Processing of Speech Signals", p380,
%		Macmillan 1993
%	  [5] HTK Reference Manual p73
%

%      Copyright (C) Mike Brookes 1998
%      Version: $Id: frq2mel.m,v 1.7 2010/08/01 08:41:57 dmb Exp $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program 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 2 of the License, or
%   (at your option) any later version.
%
%   This program 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 can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
persistent k
if isempty(k)
    k=1127.01048;
end
af=abs(frq);
mel = sign(frq).*log(1+af/700)*k;
mr=(700+af)/k;
if ~nargout
    plot(frq,mel,'-x');
    xlabel(['Frequency (' xticksi 'Hz)']);
    ylabel(['Frequency (' yticksi 'Mel)']);
end

author: decouples


text:
function [tcorr,rho,X_ECEF] = get_rho(tR_RAW,pseudorange,Eph,X_receiver)
%GET_RHO  Calculation of distance in ECEF system between
%	      satellite and receiver at time tR_RAW given the
%	      ephemeris Eph.

%Kai Borre 04-01-96
%Copyright (c) by Kai Borre
%$Revision: 1.0 $  $Date: 1997/09/23  $

% Initial assigment of constants
vlight = 299792458;	         % vacuum speed of light in m/s
Omegae = 7.292115147e-5;	 % rotation rate of the earth in rad/s

%signal sended time=signal received time-signal transmission time
tx_RAW = tR_RAW-pseudorange/vlight;

%time correction acording to system time
toc = Eph(21);
      dt = check_t(tx_RAW-toc);
      tcorr = (Eph(2)*dt + Eph(20))*dt + Eph(19);
      tx_GPS = tx_RAW-tcorr;
      dt = check_t(tx_GPS-toc);
      tcorr = (Eph(2)*dt + Eph(20))*dt + Eph(19);
      tx_GPS = tx_RAW-tcorr;

% satellite position
X = satpos(tx_GPS, Eph);

%geometric range
rho = norm(X-X_receiver(1:3));

%satellite coordinates into inertial coordinate system
omegatau = Omegae*rho/vlight;
R3 = [ cos(omegatau) sin(omegatau) 0;
      -sin(omegatau) cos(omegatau) 0;
              0	       0	     1];
X_ECEF = R3*X;

%geometric range acording to inertial coordinate system
rho = norm(X_ECEF-X_receiver(1:3));
%%%%%%%%% end get_rho.m %%%%%%%%%

author: yandld