text:
function [ class, clsize, critvl, ntrans, ifault ] = swap ( varval, class, ...
  clsize, in, ik, iv, critvl, ntrans, ifault )

%*****************************************************************************80
%
%% SWAP interchanges objects between different classes to improve a criterion.
%
%  Discussion:
%
%    This routine is given a classification of objects, including the
%    number of objects in each class, and the current value of some criterion
%    which is desired to be minimized.
%
%    The routine calculates the change in criterion for all possible swaps,
%    that is, operations in which two objects in different classes exchange
%    places. Each swap that would result in a lowering of the criterion is
%    executed, and the related quantities are updated.
%
%    When no more advantageous swaps can be found, the routine returns.
%
%    The routine relies on a user-supplied routine, CRSWAP, to report the
%    expected change in the criterion for a given swap, and to carry
%    out that transfer if requested.
%
%    The variables CLASS and CRITVL have been added to the argument list
%    of CRSWAP.
%
%    Also, the order of the two classes "L" and "M" was interchanged in
%    the call to CRSWAP.  The original order was counterintuitive.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    18 February 2008
%
%  Author:
%
%    Original FORTRAN77 version by Banfield, Bassill.
%    MATLAB version by John Burkardt.
%
%  Reference:
%
%    Colin Banfield, LC Bassill,
%    Algorithm AS 113:
%    A transfer for non-hierarchichal classification,
%    Applied Statistics,
%    Volume 26, Number 2, 1977, pages 206-210.
%
%  Parameters:
%
%    Input, real VARVAL(IN,IV), the data values.  There are
%    IN objects, each having spatial dimension IV.
%
%    Input, integer CLASS(IN), the initial classification of
%    each object.
%
%    Input, integer CLSIZE(IK), the initial number of objects
%    in each class.
%
%    Input, integer IN, the number of objects.
%
%    Input, integer IK, the number of classes.
%
%    Input, integer IV, the number of spatial dimensions,
%    or variates, of the objects.
%
%    Input, real CRITVL, the initial value of the criterion.
%
%    Output, integer CLASS(IN), the classification of
%    each object.
%
%    Output, integer CLSIZE(IK), the number of objects
%    in each class.
%
%    Output, real CRITVL, the current value of the criterion.
%
%    Output, integer NTRANS, the number of transfers executed.
%
%    Output, integer IFAULT, error indicator.
%    0, no error detected.
%    1, the number of classes was less than 2.
%    2, the number of objects was less than the number of classes.
%
  eps = 1.0E-38;
  ntrans = 0;

  if ( ik <= 1 )
    ifault = 1
    return
  end

  if ( in <= ik )
    ifault = 2;
    return
  end

  ifault = 0;
  icount = 0;
  itop = ( in * ( in - 1 ) ) / 2;

  i = 1;

  while ( 1 )

    i = i + 1;

    if ( itop <= icount )
      break
    end

    if ( in < i )
      i = 1;
      continue
    end

    l = class(i);
    k = l;
    it = i - 1;
%
%  Test the swap of object I from class M to L,
%  and object J from class L to M.
%
    for j = 1 : it

      icount = icount + 1;
      m = class(j);

      if ( l ~= j )

        if ( clsize(l) ~= 1 | clsize(m) ~= 1 )

          iswitch = 1;
          inc = crswap ( varval, class, clsize, in, ik, iv, critvl, ...
            i, j, l, m, iswitch );

          if ( inc < - eps )

            critvl = critvl + inc;
            icount = 0;

            iswitch = 2;
            crswap ( varval, class, clsize, in, ik, iv, critvl, ...
              i, j, l, m, iswitch );

            ntrans = ntrans + 1;
            class(i) = m;
            class(j) = l;
            l = m;

          end

        end
      end

    end

  end

  return
end


text:
%TEST_TIMING_DGT_FAC  Test timing factorization DGTs
%
%   This script test the timing SPREADADJs by comparing the results to
%   spreadadj in the main toolbox. Therefore, the correctness of
%   spreadadj must be verified first.

routinemax=2;

spfraction=.1;

test_failed=0;

disp('--- Used subroutines ---');

for rtype=1:2

  if rtype==1
    rname='REAL ';
  else
    rname='CMPLX';
  end;

  for sptype=1:2

    if sptype==1
      spname='FULL  ';
    else
      spname='SPARSE';
    end;

    for L=12:13

      if rtype==1
        if sptype==1
          coef1=rand(L,L);
          coef2=rand(L,L);
        else
          coef1=sprand(L,L,spfraction);
          coef2=sprand(L,L,spfraction);
        end;
      else
        if sptype==1
          coef1=crand(L,L);
          coef2=crand(L,L);
        else
          coef1=spcrand(L,L,spfraction);
          coef2=spcrand(L,L,spfraction);
        end;
      end;

      ctwist=tconv(coef1,coef2);

      for rout=1:routinemax

        ctwist2=feval(['ref_tconv_',num2str(rout)],coef1,coef2);

        rdiff=ctwist-ctwist2;

        res=norm(rdiff(:));

        fail='';
        if res>10e-10
          fail='FAILED';
          test_failed=test_failed+1;
        end;

        s=sprintf('TWI %s %s %i L:%3i %0.5g %s',rname,spname,rout,L,res,fail);
        disp(s)
      end;

    end;

  end;

end;

test_failed

author: ltfat

repo: ltfat

save_path: github-repos/MATLAB/ltfat-ltfat


text:
function [slug] = amu2slug(amu)
% Convert mass from atomic mass units to slugs.
% Chad Greene 2012
slug = amu*(3.660864489409*1e-27)/32.17405;

author: Sable

repo: mcbench-benchmarks


text:
function [X,W]=simplexquad(varargin)

% simplexquad.m - Gaussian Quadrature for an n-dimensional simplex.
%
% Construct Gauss points and weights for a n-dimensional simplex
% domain with vertices specified by the n*(n-1) matrix vert. Where each
% row contains the coordinates (x1,...,xn) for a vertex. The order of
% the quadrature scheme in each dimension must be the same in this
% implementation.
%
% Sample Usage:
%
% [X,W]=simplexquad(n,vert); % Specify the vertices
% [X,W]=simplexquad(n,dim);  % Specify the dimension and use unit simplex
%
% X will be a matrix for which the jth column are the grid points in each
% coordinate xj.
%
% Note: The standard n-dimensional simplex has vertices specified
%       vert=eye(n+1,n).
%
% The first four simplexes are
%
% n | Domain
% --|------------
% 1 | Interval
% 2 | Triangle
% 3 | Tetrahedron
% 4 | Pentatope
%
% Written by: Greg von Winckel
% Contact: gregvw(at)math(dot)unm(dot)edu
% http://math.unm.edu/~gregvw

nargin=length(varargin);

if nargin~=2
    error('simplexquad takes two input arguments');
end

N=varargin{1};

if length(N)~=1
    error('First argument must be a scalar');
end

if N~=abs(round(N-1))+1;
    error('Number of Gauss points must be a natural number');
end

if length(varargin{2})==1  % Dimension specified
    n=varargin{2};

    if n~=abs(round(n-1))+1;
        error('Dimension must be a natural number');
    end

    m=n+1; vert=eye(m,n);
else                      % Vertices specified
    vert=varargin{2};
    [m,n]=size(vert);

    if m~=n+1
        error('The matrix of vertices must have n+1 rows and n columns');
    end
end

Nn=N^n;

if n==1 % The 1-D simplex is only an interval
    [q,w]=rquad(N,0); len=diff(vert);
    X=vert(1)+len*q;  W=abs(len)*w;

else % Find quadrature rules for higher dimensional domains

    for k=1:n
        [q{k},w{k}]=rquad(N,n-k);
    end

    [Q{1:n}]=ndgrid(q{:}); q=reshape(cat(n,Q{:}),Nn,n);
    [W{1:n}]=ndgrid(w{:}); w=reshape(cat(n,W{:}),Nn,n);

    map=eye(m); map(2:m,1)=-1; c=map*vert;
    W=abs(det(c(2:m,:)))*prod(w,2);

    qp=cumprod(q,2); e=ones(Nn,1);
    X=[e [(1-q(:,1:n-1)),e].*[e,qp(:,1:n-2),qp(:,n)]]*c;
end

function [x,w]=rquad(N,k)

k1=k+1; k2=k+2; n=1:N;  nnk=2*n+k;
A=[k/k2 repmat(k^2,1,N)./(nnk.*(nnk+2))];
n=2:N; nnk=nnk(n);
B1=4*k1/(k2*k2*(k+3)); nk=n+k; nnk2=nnk.*nnk;
B=4*(n.*nk).^2./(nnk2.*nnk2-nnk2);
ab=[A' [(2^k1)/k1; B1; B']]; s=sqrt(ab(2:N,2));
[V,X]=eig(diag(ab(1:N,1),0)+diag(s,-1)+diag(s,1));
[X,I]=sort(diag(X));
x=(X+1)/2; w=(1/2)^(k1)*ab(1,2)*V(1,I)'.^2;


text:
function [d rt]=corenums(A)
% CORENUMS Compute the core number for each vertex in the graph.
%
% [cn rt]=corenums(A) returns the core numbers for each vertex of the graph
% A along with the removal order of the vertex.  The core number is the
% largest integer c such that vertex v exists in a graph where all
% vertices have degree >= c.  The vector rt returns the removal time
% for each vertex.  That is, vertex vi was removed at step rt[vi].
%
% This method works on directed graphs but gives the in-degree core number.
% To get the out-degree core numbers, call corenums(A').
%
% The linear algorithm comes from:
% Vladimir Batagelj and Matjaz Zaversnik, "An O(m) Algorithm for Cores
% Decomposition of Networks."  Sept. 1 2002.
%
% Example:
%   load_gaimc_graph('cores_example'); % the graph A has three components
%   corenums(A)
%

% See also WCORENUMS

% David F. Gleich
% Copyright, Stanford University, 2008-2009

% History
% 2008-04-21: Initial Coding

if isstruct(A), rp=A.rp; ci=A.ci; %ofs=A.offset;
else [rp ci]=sparse_to_csr(A);
end
n=length(rp)-1;
nz=length(ci);

% the algorithm removes vertices by computing bucket sort on the degrees of
% all vertices and removing the smallest.

% compute in-degrees and maximum indegree
d=zeros(n,1); maxd=0; rt=zeros(n,1);
for k=1:nz, newd=d(ci(k))+1; d(ci(k))=newd; if newd>maxd; maxd=newd; end, end

% compute the bucket sort
dp=zeros(maxd+2,1); vs=zeros(n,1); vi=zeros(n,1); % degree position, vertices
for i=1:n, dp(d(i)+2)=dp(d(i)+2)+1; end % plus 2 because degrees start at 0
dp=cumsum(dp); dp=dp+1;
for i=1:n, vs(dp(d(i)+1))=i; vi(i)=dp(d(i)+1); dp(d(i)+1)=dp(d(i)+1)+1; end
for i=maxd:-1:1, dp(i+1)=dp(i); end

% start the algorithm
t=1;
for i=1:n
    v = vs(i); dv = d(v); rt(v)=t; t=t+1;
    for rpi=rp(v):rp(v+1)-1
        w=ci(rpi); dw=d(w);
        if dw<=dv, % we already removed w
        else % need to remove edge (v,w), which decreases d(w)
            % swap w with the vertex at the head of its degree
            pw=vi(w); % get the position of w
            px=dp(dw+1); % get the pos of the vertex at the head of dw list
            x=vs(px);
            % swap w, x
            vs(pw)=x; vs(px)=w; vi(w)=px; vi(x)=pw;
            % decrement the degree of w and increment the start of dw
            d(w)=dw-1;
            dp(dw+1)=px+1;
        end
    end
end

author: luanfujun

repo: deep-photo-styletransfer


text:
function DoPostScan(Simuh)

global VCtl
global VImg
global VCoi

DoUpdateInfo(Simuh,'Scan is complete!');
set(Simuh.TimeWait_text,'String', ['Est. Time Left :  ' '~' ' : ' '~' ' : ' '~']);

%% Signal Post-Processing
%  Add noise
DoAddNoise;

%% Image reconstruction
if strcmp(VCtl.AutoRecon,'on')

    %  Do image reconstruction
    DoUpdateInfo(Simuh,'Reconstructing images...');
    ExecFlag=DoImgRecon(Simuh);
    if ExecFlag==0
        error('Image recon is incomplete!');
    end
    DoUpdateInfo(Simuh,'Image recon is complete.');

    %  Enable channel selection
    channel = {'SumofMagn';'SumofCplx'};
    for i = 1:VCoi.RxCoilNum
        channel{i+2} = i;
    end
    set(Simuh.Channel_popupmenu,'String',channel);
    set(Simuh.Channel_popupmenu,'Enable','on');

    %  Enable echo selection
    echo = {};
    for i = 1:size(VImg.Mag,5)
        echo{i} = i;
    end
    set(Simuh.Echo_popupmenu,'String',echo);
    set(Simuh.Echo_popupmenu,'Enable','on');

    %  Output image display
    set(Simuh.Channel_popupmenu,'Value', 1);
    set(Simuh.Echo_popupmenu,'Value', 1);
    Simuh=guidata(Simuh.SimuPanel_figure);
    Img = sum(VImg.Mag, 4); % show SumofMagn
    Simuh.Img = Img(:,:,:,1); % show first echo
    Simuh.IV=struct(...
        'Slice',ceil(VCtl.SliceNum/2),...
        'C_lower',min(min(min(Simuh.Img))),...
        'C_upper',max(max(max(Simuh.Img))),...
        'Axes','off',...
        'Grid','off',...
        'Color_map','Gray'...
        );
    DoUpdateImage(Simuh.Preview_axes,Simuh.Img,Simuh.IV);
    set(Simuh.Preview_uipanel,'Title',['Preview : Series' num2str(Simuh.ScanSeriesInd)]);
    [row,col,layer]=size(Simuh.Img);
    if layer==1
        set(Simuh.Preview_slider,'Enable','off');
    else
        set(Simuh.Preview_slider,'Enable','on');
        set(Simuh.Preview_slider,'Min',1,'Max',layer,'SliderStep',[1/layer, 4/layer],'Value',ceil(layer/2));
    end
    guidata(Simuh.SimuPanel_figure, Simuh);

    % Saving output
    DoUpdateInfo(Simuh,'Saving recon images & data & info...');
    DoSaveOutput(Simuh);
    DoUpdateInfo(Simuh,'Image data saving is complete!');

else
    % Saving output
    TmpVImg = VImg;
    VImg = []; % clear VImg
    DoUpdateInfo(Simuh,'Saving signal data & info...');
    DoSaveOutput(Simuh);
    DoUpdateInfo(Simuh,'Signal data saving is complete!');
    VImg = TmpVImg;

end

end

author: leoliuf

repo: MRiLab

save_path: github-repos/MATLAB/leoliuf-MRiLab


text:
function y = tapas_boltzmann(x, beta)
% --------------------------------------------------------------------------------------------------
% Copyright (C) 2016 Christoph Mathys, TNU, UZH & ETHZ
%
% This file is part of the HGF toolbox, which is released under the terms of the GNU General Public
% Licence (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/>.

q = exp(beta.*x);
Z = sum(q);
y = q./Z;

return;

author: translationalneuromodeling

repo: tapas


text:
function [z,I,J] = joinvars(x,y)
%JOINVARS     joins sets of variables x and y into one set z
%
%   [z,I,J] = joinvars(x,y)
%
%On entry, string or string cell array x is a set of mutually disjoint variables,
%  and string or string cell array y is a set of mutually disjoint variables.
%On return, variables x and y are merged into z such that
%  z(I) corresponds to the set x, and z(J) corresponds to the set y.
%

% written  08/28/00     S.M. Rump
%

  % make sure, variables are stored in cell arrays (covers univariate case)
  if ~iscell(x)
    x = {x};
  end
  if ~iscell(y)
    y = {y};
  end

  nx = length(x);
  [z,dummy,IJ] = unique([x y]);
  I = IJ(1:nx);
  J = IJ(nx+1:end);

repo: OpenMAS


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   Q = T2quaternion(T)
%   Returns the quaternion corresponding to an homogeneous transformation
%   matrix T. Only the 3x3 rotation matrix in T is used.
%
%   See also QPROD, QUATERNION2T.
%
%   Author: Arturo Gil. Universidad Miguel Hern�ndez de Elche. email:
%   arturo.gil@umh.es date:   21/04/2012
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Copyright (C) 2012, by Arturo Gil Aparicio
%
% This file is part of ARTE (A Robotics Toolbox for Education).
%
% ARTE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% ARTE 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with ARTE.  If not, see <http://www.gnu.org/licenses/>.
function Q = T2quaternion(T)
% use only the orientation
R = T(1:3, 1:3);

Q = zeros(1,4);
Q(1) = sqrt(trace(R))/2;
Q(1) = real(Q(1));

Lx = R(3,2) - R(2,3);
Ly = R(1,3) - R(3,1);
Lz = R(2,1) - R(1,2);

if (R(1,1) >= R(2,2)) && (R(1,1) >= R(3,3))
    Lx1 = R(1,1) - R(2,2) - R(3,3) + 1;
    Ly1 = R(2,1) + R(1,2);
    Lz1 = R(3,1) + R(1,3);
elseif (R(2,2) >= R(3,3))
    Lx1 = R(2,1) + R(1,2);
    Ly1 = R(2,2) - R(1,1) - R(3,3) + 1;
    Lz1 = R(3,2) + R(2,3);
else
    Lx1 = R(3,1) + R(1,3);
    Ly1 = R(3,2) + R(2,3);
    Lz1 = R(3,3) - R(1,1) - R(2,2) + 1;
end

if (Lx >= 0) || (Ly >= 0) || (Lz >= 0)
    Lx = Lx + Lx1;
    Ly = Ly + Ly1;
    Lz = Lz + Lz1;
else
    Lx = Lx - Lx1;
    Ly = Ly - Ly1;
    Lz = Lz - Lz1;
end

if norm([Lx Ly Lz]) == 0
    Q = [1 0 0 0];
else
    s = sqrt(1-Q(1)^2)/norm([Lx Ly Lz]);
    Q(2:4) = s*[Lx Ly Lz];
end

repo: ARTE


text:
function varargout = dctool(varargin)
% DCTOOL Graphical interface for displaying the status of a distributed
% computing network.
%
%      DCTOOL, by itself, creates a new DCTOOL or raises the existing
%      singleton.
%
%      H = DCTOOL returns the handle to a new DCTOOL or the handle to
%      the existing singleton.
%
%  Tim Farajian 7/11/2005

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @dctool_OpeningFcn, ...
    'gui_OutputFcn',  @dctool_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

%----------------------------------------------%
%----------------------------------------------%

% GUI Output function
function varargout = dctool_OutputFcn(ignore, ignore2, handles)
varargout{1} = handles.output;

%----------------------------------------------%

function Figure_CloseRequestFcn(hObject, ignore, handles)
if strcmp(get(handles.updatetimer,'Running'),'on')
    stop(handles.updatetimer)
end
delete([handles.updatetimer handles.starttimer])
delete(hObject);

%----------------------------------------------%

function dctool_OpeningFcn(hObject, ignore, handles)
% Choose default command line output for dctool
handles.output = hObject;
% Initialize distributed computing network info
handles.jm = [];handles.Workers = [];handles.Jobs = [];handles.Tasks = [];
handles.cjm = [];handles.cWorker = [];handles.cJob = [];handles.cTask = [];
%%% Create update timer %%%
% Specify timer period
SecPerUpdate =  get(handles.RateSlider,'Value');
set(handles.RateText,'String',sprintf('%0.1f',SecPerUpdate))
oldwarn = warning('off','MATLAB:TIMER:RATEPRECISION');
handles.updatetimer = timer('busymode','queue',...
    'ExecutionMode','fixedSpacing',...
    'Period',SecPerUpdate,'startdelay',0,...
    'TimerFcn',@(a,b)Update(a,b,hObject),...
    'TasksToExecute',1e6);
% Create timer to start populating listboxes after figure is shown
handles.starttimer = timer('startdelay',0.1,...
    'TimerFcn',@PopulateJobManagers,'UserData',handles.Figure);

warning(oldwarn); % Reset warning state
guidata(hObject, handles); % Save handles
start(handles.starttimer); % Start timer to initiate populating listboxes

%----------------------------------------------%
%----------------------------------------------%

%%%%%%%%%%%%%%%%%%%%%
% Listbox Callbacks %
%%%%%%%%%%%%%%%%%%%%%

%%% Job manager changed by user %%%
function jmbox_Callback(hObject, ignore, handles)
if isempty(handles.jm)
    % Currently no job manager in listbox
    return
end
jm = handles.jm(get(handles.jmbox,'Value')); % Get currently selected manager
if ~isequal(handles.cjm,jm)
    % Job manager has changed
    handles.cjm = jm; % Reassign current job manager
    % Stop update timer
    if strcmp(handles.updatetimer.Running,'on')
        stop(handles.updatetimer)
    end
    % Clear list boxes
    h = [handles.workerbox handles.jobbox handles.taskbox];
    set(h,'String',{})
    % Reset current worker, job, and task
    handles.cWorker = [];  handles.cJob = [];  handles.cTask = [];
    handles.Workers = [];  handles.Jobs = [];  handles.Tasks = [];
    guidata(hObject,handles);
    % Populate list boxes
    Populate([],[],hObject);
    % Restart the update timer
    if strcmp(handles.updatetimer.Running,'off')
        start(handles.updatetimer)
    end
end

%----------------------------------------------%

%%% Job changed by user %%%
function jobbox_Callback(hObject, ignore, handles)
if isempty(handles.Jobs)
    % Currently no jobs in listbox
    return
end
job = handles.Jobs(get(handles.jobbox,'Value')); % Selected job
if ~isequal(handles.cJob,job)
    % Job changed
    handles.cJob = job; % Reassign current job
    set(handles.taskbox,'String',{}) % Clear task listbox
    handles.cTask = []; % Reset current task
    guidata(hObject,handles);
    PopulateTasks([],[],hObject);
end
% Submit menu item is disabled if current job is not pending
state = job.state;
if strcmp(state,'pending')
    set(handles.MenuSubmit,'Enable','on');
else
    set(handles.MenuSubmit,'Enable','off')
end
% JobReport menu item is disabled if current job is pending or queued
if strcmp(state,'pending') || strcmp(state,'queued')
    set(handles.MenuReport,'Enable','off');
else
    set(handles.MenuReport,'Enable','on')
end

%----------------------------------------------%

%%% Task changed by user %%%
function taskbox_Callback(hObject, ignore, handles)
if isempty(handles.Tasks)
    % Currently no tasks in listbox
    return
end
% Reassign current task
handles.cTask = handles.Tasks(get(handles.taskbox,'Value')); % Selected task
guidata(hObject,handles);

% Worker changed by user
function workerbox_Callback(hObject, ignore, handles)
if isempty(handles.Workers)
    % Currently no workers in listbox
    return
end
% Reassign current worker
handles.cWorker = handles.Workers(get(handles.workerbox,'Value'));
guidata(hObject,handles);

%----------------------------------------------%
%----------------------------------------------%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Context Menu Item Callbacks %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%% Job Manager menu callbacks %%%

%%% Export manager to base workspace
function MenuExportJm_Callback(ignore, ignore2, handles)
jm = inputdlg('Export handle to job manager as name:','Export Job Manager');
assignin('base',jm{1},handles.cjm);
disp('Variables created in the workspace.');

%----------------------------------------------%

%%% Remove manager from manager list
function MenuRemove_Callback(hObject, ignore, handles)
cval = get(handles.jmbox, 'Value'); % Index of selected manager
handles.jm(cval) = []; % Remove handle from list
fv = get(handles.jmbox,'String'); % Get string
fv(cval) = []; % Remove string from list
if isempty(handles.jm)
    % No more managers
    handles.cjm = []; % Indicate no selected manager
    stop(handles.updatetimer); % Stop the update timer
    % Disable manager menu items
    hMenu = get(get(handles.jmbox,'uiContextMenu'),'Children');
    set(hMenu,'Enable','off');
elseif cval > length(handles.jm)
    % Current manager index now greater than number of managers -> reduce
    cval = length(handles.jm);
    handles.cjm = handles.jm(cval);
else
    % Indicate current manager is now the next one
    handles.cjm = handles.jm(cval);
end
guidata(hObject,handles);
% Update manager listbox
set(handles.jmbox,{'Value','String'},{cval,fv});
% Populate remaining listboxes
Populate([],[],hObject);

%----------------------------------------------%

% Display property inspector
function MenuPropsJM_Callback(ignore, ignore2, handles)
inspect(handles.jm(get(handles.jmbox,'Value')))

%----------------------------------------------%

function MenuBench_Callback(hObject, eventdata, handles)
distcomp_bench_dist(length(handles.Workers), get(handles.cjm,'Name'));

%----------------------------------------------%

%%% Worker menu callbacks %%%

% Export handle to worker to base workspace
function MenuExportWorker_Callback(ignore, ignore2, handles)
name = inputdlg('Export handle to worker as name:','Export Worker');
assignin('base',name{1},handles.cWorker);
disp('Variables created in the workspace.');

%----------------------------------------------%

% VNC into current worker
function MenuVNC_Callback(ignore, ignore2, handles)
VncDir = 'D:\Applications\TightVnc\vncviewer.exe ';
str = [VncDir handles.cWorker.Hostname];
system(str);

%----------------------------------------------%

function MenuPropsWorker_Callback(ignore, ignore2, handles)
inspect(handles.Workers(get(handles.workerbox,'Value')))

%----------------------------------------------%

%%% Job menu callbacks %%%

% Export current job to base workspace
function MenuExportJob_Callback(ignore, ignore2, handles)
name = inputdlg('Export handle to job as name:','Export Job');
if isempty(name)
    return
end
assignin('base',name{1},handles.cJob);
disp('Variables created in the workspace.');

%----------------------------------------------%

% Submit current job
function MenuSubmit_Callback(ignore, ignore2, handles)
job = handles.Jobs(get(handles.jobbox,'Value'));
submit(job)

%----------------------------------------------%

% Destroy current job
function MenuDestroy_Callback(ignore, ignore2, handles)
job = handles.Jobs(get(handles.jobbox,'Value'));
if ishandle(job)
    destroy(job)
end

%----------------------------------------------%

function MenuReport_Callback(ignore, ignore2, handles)
JobReport(handles.cJob)

%----------------------------------------------%

function MenuPropsJob_Callback(ignore, ignore2, handles)
inspect(handles.Jobs(get(handles.jobbox,'Value')))

%----------------------------------------------%

%%% Task menu callbacks %%%

% Export current task to workspace
function MenuExportTask_Callback(ignore, ignore2, handles)
name = inputdlg('Export handle to task as name:','Export Task');
assignin('base',name{1},handles.cTask);
disp('Variables created in the workspace.');

%----------------------------------------------%

% Cancel current task
function MenuCancel_Callback(ignore, ignore2, handles)
if ishandle(handles.cTask)
    cancel(handles.cTask)
end

%----------------------------------------------%

% Destroy current task
function MenuDestroyTask_Callback(ignore, ignore2, handles)
if ishandle(handles.cTask)
    destroy(handles.cTask)
end

%----------------------------------------------%

function MenuPropsTask_Callback(ignore, ignore2, handles)
inspect(handles.Tasks(get(handles.taskbox,'Value')))

%----------------------------------------------%
%----------------------------------------------%

%%%%%%%%%%%%%%%%%%%%%%
% Menu Bar Callbacks %
%%%%%%%%%%%%%%%%%%%%%%

function MenuClose_Callback(ignore, ignore2, handles)
close(handles.Figure)

%----------------------------------------------%

function DemoCallback(hObject,ignore)
data = get(hObject,'UserData');
handles = guidata(data{1});
fcn = data{2};
fcn(handles.cjm);

%----------------------------------------------%
%----------------------------------------------%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Functions to populate list boxes %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% For performance reasons, certain operations are performed when the
% listboxes are first populated.  Then, Update* performs fewer operations to
% keep them updated.

% Populates all listboxes for the first time (Update keeps t
function Populate(tmr,data,hObject)
if ~ishandle(hObject)
    % Figure has been closed -> Stop the timer
    stop(tmr);
    delete(tmr);
    return
end
PopulateWorkers(tmr,data,hObject);
PopulateJobs(tmr,data,hObject);
PopulateTasks(tmr,data,hObject);

%----------------------------------------------%

% Populate manager list with all managers on network
function PopulateJobManagers(tmr, ignore)
hObject = get(tmr,'Userdata');
handles = guidata(hObject);
set(handles.JmUpdateText,'Visible','on'); % Turn on "updating" text
% Clear list boxes
h = [handles.jmbox handles.workerbox handles.jobbox handles.taskbox];
set(h,'String',{})
drawnow
% Reset current worker, job, and task
handles.cWorker = [];  handles.cJob = [];  handles.cTask = [];
handles.Jobs = [];  handles.Tasks = [];
% Get all job managers
handles.jm = findResource('jobmanager');
jmstr = get(handles.jm,{'Name'}); % Get names
set(handles.jmbox,{'value','String'},{1,jmstr}); % Fill manager listbox

% Get handles to manager menu items
hMenu = get(get(handles.jmbox,'uiContextMenu'),'Children');
if isempty(handles.jm)
    handles.cjm = []; % Indicate there is no current job manager
    set(hMenu,'Enable','off');
else
    set(hMenu,'Enable','on');
    handles.cjm = handles.jm(1); % Set current job manager
end
guidata(hObject,handles)
set(handles.JmUpdateText,'Visible','off'); % Turn off "update" text
% Populate the list boxes
PopulateWorkers([],[],hObject);
PopulateJobs([],[],hObject);
PopulateTasks([],[],hObject);
% If update timer is not already started -> start it
if strcmp(get(handles.updatetimer,'Running'),'off')
    start(handles.updatetimer)
end

%----------------------------------------------%

% Populate worker list box
function PopulateWorkers(ignore, ignore2, hObject)
if ~ishandle(hObject)
    % Figure already closed
    return
end
handles = guidata(hObject);
set(handles.WorkerUpdateText,'Visible','on'); % Turn on "updating" text
drawnow
% Things may have changed from the drawnow
if ~ishandle(hObject)
    return
end
handles = guidata(hObject);

workerstr = {}; workerloc = 1; % Initialize variables
% Get handles to all workers
handles.Workers = [get(handles.cjm,'IdleWorkers');get(handles.cjm,'BusyWorkers')];
% Get handles to all worker menu items
hMenu = get(get(handles.workerbox,'uiContextMenu'),'Children');
if isempty(handles.Workers)
    % No workers -> disable menu
    handles.cWorker = [];
    set(hMenu,'Enable','off');
else
    set(hMenu,'Enable','on');
    handles.cWorker = handles.Workers(workerloc);
end
handles.WorkerData = get(handles.Workers,{'Name'});
data = get(handles.Workers,{'CurrentTask'});
guidata(hObject,handles)
for n = 1:length(handles.Workers)
    if isempty(data) || isempty(data{n})
        str = 'Idle';
    else
        str = 'Busy';
    end
    workerstr{n} = sprintf('%s - %s',handles.WorkerData{n},str);
end
set(handles.workerbox,{'value','String'},{workerloc,workerstr});
set(handles.WorkerUpdateText,'Visible','off');

%----------------------------------------------%

% Populate job list
function PopulateJobs(ignore, ignore2,hObject)
if ~ishandle(hObject)
    % Figure already closed
    return
end
handles = guidata(hObject);
set(handles.JobUpdateText,'Visible','on'); % Turn on "updating" text
drawnow
% Things may have changed from the drawnow
if ~ishandle(hObject)
    % Figure already closed
    return
end
handles = guidata(hObject);

jobstr = {};jobloc = 1; % Initialize variables
handles.Jobs = get(handles.cjm,'Jobs'); % Get handles to all jobs
% Get handles to all job menu items
hMenu = get(get(handles.jobbox,'uiContextMenu'),'Children');
if isempty(handles.Jobs)
    % No jobs -> disable menu
    handles.cJob = [];
    set(hMenu,'Enable','off');
else
    set(hMenu,'Enable','on');
    handles.cJob = handles.Jobs(jobloc);
end
handles.JobData = get(handles.Jobs,{'Name','UserName'});
state = get(handles.Jobs,{'State'});

guidata(hObject,handles)
if ~ishandle(hObject),return,end % In case figure was closed by now
for n = 1:length(handles.Jobs)
    jobstr{n} = sprintf('%s - %s - %s',handles.JobData{n,:},state{n});
end
set(handles.jobbox,{'Value','String'},{jobloc,jobstr});
if isempty(state) || ~strcmp(state{jobloc},'pending')
    set(handles.MenuSubmit,'Enable','on');
else
    set(handles.MenuSubmit,'Enable','off');
end
set(handles.JobUpdateText,'Visible','off');

%----------------------------------------------%

%%% Populate task list box %%%
function PopulateTasks(ignore, ignore2,hObject)
if ~ishandle(hObject)
    % Figure already closed
    return
end
handles = guidata(hObject);
set(handles.TaskUpdateText,'Visible','on');
drawnow
% Things may have changed from the drawnow
if ~ishandle(hObject)
    % Figure already closed
    return
end
handles = guidata(hObject);

taskstr = {};taskloc = 1; % Initialize variables
handles.Tasks = get(handles.cJob,'Tasks'); % Get handles to all tasks
% Get handles to all task menu items
hMenu = get(get(handles.taskbox,'uiContextMenu'),'Children');
if isempty(handles.Tasks)
    % No tasks -> disable menu
    handles.cTask = [];
    set(hMenu,'Enable','off');
else
    set(hMenu,'Enable','on');
    handles.cTask = handles.Tasks(taskloc); % Specify current task
end
handles.TaskData = get(handles.Tasks,{'ID'});
state = get(handles.Tasks,{'State'});
guidata(hObject,handles)
for n = 1:length(handles.Tasks)
    taskstr{n} = sprintf('Task%d - %s',handles.TaskData{n,:},state{n});
end
set(handles.taskbox,{'value','String'},{taskloc,taskstr});
set(handles.TaskUpdateText,'Visible','off');

%----------------------------------------------%
%----------------------------------------------%

%%%%%%%%%%%%%%%%%%%%
% Update listboxes %
%%%%%%%%%%%%%%%%%%%%
% These keep the listboxes updated.  Different operations are performed to
% initially populate the listboxes using the Populate* functions.

function Update(ignore,ignore2,hObject)
% Timer callback - Updates all listboxes with current info from job manager
% Each function is similar.  Each is organized to minimize the number of
% times the job manager is queried for information, which is expensive.
UpdateWorkers(hObject);
UpdateJobs(hObject);
UpdateTasks(hObject);

%----------------------------------------------%

function UpdateWorkers(hObject)
handles = guidata(hObject);
% Check if update checkbox is off
if ~get(handles.MasterUpdate,'Value') || ~get(handles.WorkerUpdate,'Value')
    return
end
set(handles.WorkerUpdateText,'Visible','on'); % Turn on "Updating" text
drawnow % Allow text to be shown - Other callbacks may occur
if ~ishandle(hObject)
    return % Figure has been closed
end
handles = guidata(hObject); % Handles may have changed

% Find manager's associated workers
workers = [get(handles.cjm,'IdleWorkers'); get(handles.cjm,'BusyWorkers')];

% Remove workers that are no longer there
stillthere = ismember(handles.Workers, workers);
handles.Workers(~stillthere) = [];
handles.WorkerData(~stillthere) = [];
if size(handles.Workers,2)==0 % Ensure empty is 0-by-n rather than n-by-0
    handles.Workers = handles.Workers.';
    handles.WorkerData = handles.WorkerData.';
end
% Add new workers
notnew = ismember(workers, handles.Workers);
handles.Workers = [handles.Workers(:); workers(~notnew)];

tname = get(workers(~notnew),{'Name'}); % Get new worker's names
handles.WorkerData = [handles.WorkerData; tname]; % Add name to data list
if length(handles.Workers) == 1 && ~iscell(handles.WorkerData)
    % Happens when only one worker
    handles.WorkerData = {handles.WorkerData};
end

% Read the current task of all workers
ctask = get(handles.Workers,{'CurrentTask'});

nWorkers = length(handles.Workers); workerstr = {}; % Initialize variables
for n = 1:nWorkers
    if isempty(ctask{n})
        str = 'Idle';
    else
        str = 'Busy';
    end
    workerstr{n} = sprintf('%s - %s',handles.WorkerData{n},str);
end

hMenu = get(get(handles.workerbox,'uiContextMenu'),'Children');
if nWorkers == 0
    % No workers in list
    workerloc = 1; % Listbox value
    handles.cWorker = []; % Assign current worker
    set(hMenu,'Enable','off');  % Disable context menu items
else
    workerloc = min(nWorkers,get(handles.workerbox,'Value')); % Listbox value
    handles.cWorker = handles.Workers(workerloc); % Assign current worker
    set(hMenu,'Enable','on'); % Enable context menu items
end
guidata(hObject,handles)
set(handles.workerbox,{'value','String'},{workerloc,workerstr});
set(handles.WorkerUpdateText,'Visible','off');

%----------------------------------------------%

%%% Updates current job info from the job manager
function UpdateJobs(hObject)
if ~ishandle(hObject) % Check if figure has closed
    return
end
handles = guidata(hObject);
% Check if update checkbox is off
if ~get(handles.MasterUpdate,'Value') || ~get(handles.JobUpdate,'Value')
    return
end
set(handles.JobUpdateText,'Visible','on'); % Show "Updating" text
drawnow % Allow text to be shown - Other callbacks may occur
if ~ishandle(hObject) % Check if figure has closed
    return
end
handles = guidata(hObject); % Handles may have changed

jobs = get(handles.cjm,'Jobs'); % Read all jobs in current job manager
% Remove jobs that are no longer there
stillthere = ismember(handles.Jobs, jobs);
handles.Jobs(~stillthere) = [];
handles.JobData(~stillthere,:) = [];
if size(handles.Jobs,2)==0 % Ensure empty is 0-by-n rather than n-by-0
    handles.Jobs = handles.Jobs.';
end
if size(handles.JobData,2)==0 % Ensure empty is 0-by-n rather than n-by-0
    handles.JobData = handles.JobData.';
end
% Add new jobs
notnew = ismember(jobs, handles.Jobs);
handles.Jobs = [handles.Jobs; jobs(~notnew)];

% Get data about new jobs
r = get(jobs(~notnew),{'Name','UserName'}); % Only need to obtain when new
state = get(handles.Jobs,{'State'}); % Need to obtain every time
handles.JobData = [handles.JobData; r]; % Include new data in list

nJobs = length(handles.Jobs);
jobstr = cell(nJobs,1);
for n = 1:nJobs
    jobstr{n} = sprintf('%s - %s - %s',handles.JobData{n,:},state{n});
end
% Get handles to all context menu items
hMenu = get(get(handles.jobbox,'uiContextMenu'),'Children');
if nJobs == 0
    % No jobs in list
    jobloc = 1; % Listbox value
    handles.cJob = []; % Assign current job
    set(hMenu,'Enable','off');  % Disable context menu items
else
    jobloc = min(nJobs,get(handles.jobbox,'Value')); % Listbox value
    handles.cJob = handles.Jobs(jobloc); % Assign current job
    set(hMenu,'Enable','on'); % Enable context menu items
end
set(handles.jobbox,{'Value','String'},{jobloc,jobstr});
% Disable Submit menu item if job is not pending
if isempty(state) || ~strcmp(state{jobloc},'pending')
    set(handles.MenuSubmit,'Enable','off');
else
    set(handles.MenuSubmit,'Enable','on');
end
guidata(hObject,handles)
set(handles.JobUpdateText,'Visible','off');
drawnow

%----------------------------------------------%

function UpdateTasks(hObject)

if ~ishandle(hObject) % Check if figure has closed
    return
end
handles = guidata(hObject);
% Check if update checkbox is off
if ~get(handles.MasterUpdate,'Value') || ~get(handles.TaskUpdate,'Value')
    return
end
set(handles.TaskUpdateText,'Visible','on'); % Show "Updating" text
drawnow % Allow text to be shown - Other callbacks may occur
if ~ishandle(hObject) % Check if figure has closed
    return
end
handles = guidata(hObject); % Handles may have changed

% Find all tasks associated with current job
tasks = get(handles.cJob,'Tasks');

% Remove tasks from list that are no longer there
stillthere = ismember(handles.Tasks, tasks);
handles.Tasks(~stillthere) = [];
handles.TaskData(~stillthere) = [];
if size(handles.Tasks,2)==0 % Ensure empty is 0-by-n rather than n-by-0
    handles.Tasks = handles.Tasks.';
    handles.TaskData = handles.TaskData.';
end
% Add new tasks to list
notnew = ismember(tasks, handles.Tasks);
handles.Tasks = [handles.Tasks; tasks(~notnew)];

ID = get(tasks(~notnew),{'ID'}); % Only need to obtain when new
state = get(handles.Tasks,{'State'}); % Need to obtain every time
handles.TaskData = [handles.TaskData; ID];
if length(handles.TaskData) == 1
    if ~iscell(handles.TaskData)
        handles.TaskData = {handles.TaskData};
    end
end
nTasks = length(handles.Tasks);
taskstr = {};
for n = 1:length(handles.Tasks)
    taskstr{n} = sprintf('Task%d - %s',handles.TaskData{n},state{n});
end
hMenu = get(get(handles.taskbox,'uiContextMenu'),'Children');
if nTasks == 0
    % No tasks in list
    taskloc = 1; % Listbox value
    handles.cTask = []; % Assign current task
    set(hMenu,'Enable','off');  % Disable context menu items
else
    taskloc = min(nTasks,get(handles.taskbox,'Value')); % Listbox value
    handles.cTask = handles.Tasks(taskloc); % Assign current task
    set(hMenu,'Enable','on'); % Enable context menu items
end
set(handles.taskbox,{'value','String'},{taskloc,taskstr});
set(handles.TaskUpdateText,'Visible','off');
guidata(hObject,handles)

%----------------------------------------------%
%----------------------------------------------%

%%%%%%%%%%%%%%%%%%%%%%%
% Uicontrol Callbacks %
%%%%%%%%%%%%%%%%%%%%%%%

function MasterUpdate_Callback(hObject, ignore, handles)
h = [handles.WorkerUpdate handles.JobUpdate handles.TaskUpdate];
v = get(hObject,'Value');
if v
    set(h,'Enable','on')
else
    set(h,'Enable','off')
end

%----------------------------------------------%

% Change the rate at which the interface is refreshed
function RateSlider_Callback(hObject, ignore, handles)
% Stop timer if running
state = strcmp(handles.updatetimer.Running,'on');
if state
    stop(handles.updatetimer)
end
% Change timer period - Want smaller values on right of slider
SecPerUpdate =  get(hObject,'Value');
set(handles.RateText,'String',sprintf('%0.1f',SecPerUpdate))
oldwarn = warning('off','MATLAB:TIMER:RATEPRECISION');
set(handles.updatetimer,'Period', SecPerUpdate);
warning(oldwarn);
%drawnow
if state
    start(handles.updatetimer)
end

%----------------------------------------------%
%----------------------------------------------%

%%%%%%%%%%%%%%
% Job Report %
%%%%%%%%%%%%%%

function varargout = JobReport(varargin)
% JOBREPORT generates a graphical representation of the progress of the
% tasks of a specified job.
%
%   JOBREPORT(JOB) generates a plot where the horizontal axis indicates the
%   different workers used throughout the job JOB, and the vertical axis
%   indicates the starting and finishing times of each task
%
%   JOBREPORT(AX,...) plots into the axes with handle AX.
%
%   H = JOBREPORT(...) returns a handle to the patch objects.
%
%   5/2005 Tim Farajian

if nargin==1
    % Only 1 input
    job = varargin{1};
    f = figure;
    AX = gca;
    hold(AX,'on'); % Set hold state
    ylabel('Time')
    title(['Job report for ' get(job,'Name')],'interpreter','none');
    datetick('y');
else
    % Axis was specified
    [AX job] = deal(varargin{1:2});
    if ~ishandle(AX) || ~strcmp(get(AX,'type'),'axes')
        error('AX must be a handle to a valid axis object')
    end
    f = get(AX,'Parent');
end
set(f,'Pointer','watch')
drawnow

if ~ishandle(job) || ~isa(job,'distcomp.job')
    error('JOB must be a handle to a valid job object')
else
    jobstate = get(job,'State');
    if ismember(jobstate,{'pending','queued'})
        error('Job has not yet started.')
    end
end

tasks = job.Tasks; % Get handles to all tasks in job
if isempty(tasks)
    error(['No tasks in ' get(job,'Name')],'Job Report Error');
end

taskstates = get(tasks,'State'); % Get state of all tasks
if length(tasks)==1 && ~iscell(taskstates)
    % Ensure its a cell array
    taskstates = {taskstates};
end
unavailable = strcmp(taskstates,'unavailable'); % Check if unavailable
tasks(unavailable) = []; % Remove unavailable tasks
taskstates(unavailable) = []; % Remove unavailable taskstates

IDs = get(tasks,'ID'); % Get IDs of all tasks
if length(tasks)==1 && ~iscell(IDs)
    % Ensure its a cell array
    IDs = {IDs};
end

workers = get(tasks,'Worker'); % Get handle to all workers used by tasks
if iscell(workers)
    % Ensure its not a cell array
    workers = [workers{:}];
end
% Find the unique workers
[workers ignore wkrnums] = unique(workers);
wkrnames = get(workers,'Name'); % Get names of all workers
if length(workers)==1 && ~iscell(wkrnames)
    % Ensure its a cell array
    wkrnames = {wkrnames};
end

ax(1:2) = [0 1+length(workers)]; % Set x-axis limits

% Get job start time
JobStart = TaskTime(job,'StartTime');
plot(ax, [JobStart JobStart],'k--')

% Get job finish time and set axes limits
if strcmp(jobstate,{'finished'})
    JobFinish = TaskTime(job,'FinishTime');
    if JobFinish == JobStart,
        JobFinish = JobFinish + 5e-6;
    end
    dy = max(7e-5,0.6*(JobFinish-JobStart));
    my = (JobStart + JobFinish)/2;
    plot(ax, [JobFinish JobFinish],'k--')
    ax(3:4) =  my + dy*[-1 1];
else
    JobFinish = now;
    jobdiff = max(2e-4,1.1*(JobFinish-JobStart));
    ax(3:4) =  JobFinish + [-jobdiff 0];
end

% Set figure and axis
axis(ax)
datetick('y')
set(gca,'Xtick',1:length(workers));
set(gca,'XtickLabel',wkrnames);

nTasks = length(tasks);
TaskStart = zeros(nTasks,1);
TaskFinish = zeros(nTasks,1);
h = zeros(nTasks,1); % Preallocate
set(f,'Pointer','arrow')
drawnow
for n = 1:nTasks
    task = tasks(n);
    switch taskstates{n}
        case {'pending'}
            continue
        case {'running'}
            TaskStart(n) = TaskTime(task,'StartTime');
            TaskFinish(n) = JobFinish+1e-6;
            colr = 'c';
        case {'finished'}
            TaskStart(n) = TaskTime(task,'StartTime');
            TaskFinish(n) = TaskTime(task,'FinishTime');
            if isempty(task.ErrorMessage)
                colr = 'b';
            else
                colr = 'r';
            end
    end

    timediff = TaskFinish(n)-TaskStart(n); % Time difference
    if timediff<=0
        % Ensure time difference is positive
        timediff = 5e-6;
        TaskFinish(n)=TaskStart(n) + timediff;
    end
    px = wkrnums(n) - 0.5+[0 0 1 1]; % x-coords of patch
    py = TaskStart(n)+timediff*[0 1 1 0]; % y-coords of patch
    h(n) = patch(px,py, colr); % Create patch
    % Create task text label
    text(mean(px),mean(py),...
        sprintf('Task%d',IDs{n}),'horizontal','center');
    axis(ax)
    drawnow
end
if nargout>0
    varargout = h;
end

%----------------------------------------------%

function time = TaskTime(obj, prop)
% Subfunction for use with JobReport
timestr = get(obj,prop);
timestr = timestr(5:end);timestr(17:20)=[];
time = datenum(timestr);

function MenuBarHelp_Callback(hObject, eventdata, handles)
fid = fopen('dctool_help.txt');
str = fread(fid,inf,'*char').';
fclose(fid);
f = figure('menubar','none','NumberTitle','off','Name','About DCTOOL');
h=uicontrol('style','edit','parent',f,'min',0,'max',2,'enable','inactive'...
    ,'units','normalized','position',[0 0 1 1],'string',str,...
    'horizontalalignment','left','fontsize',10);
drawnow

%%% Workaround for g271589 %%%
found = false;
jf = get(f, 'javaframe');
ac = jf.getAxisComponent;
cc = ac.getParent.getComponent(0);
if ~isa(cc, 'com.mathworks.hg.peer.FigureComponentContainer')
    cc = ac.getParent.getComponent(1);
end
for i=1:cc.getComponentCount
    if isa(cc.getComponent(i-1).getComponent(0), 'com.mathworks.hg.peer.utils.UIScrollPane')
        s = cc.getComponent(i-1).getComponent(0);
        found = true;
    end
end
if (found)
    e = s.getViewport.getView;
    awtinvoke(e, 'scrollRectToVisible(Ljava.awt.Rectangle;)V', ...
        java.awt.Rectangle(0, 0, 1, 1));
end


text:
if(exist('E:\datasets\FERA_2015\semaine/SEMAINE-Sessions/', 'file'))
    SEMAINE_dir = 'E:\datasets\FERA_2015\semaine/SEMAINE-Sessions/';
elseif(exist('I:\datasets\FERA_2015\Semaine\SEMAINE-Sessions/', 'file'))
    SEMAINE_dir = 'I:\datasets\FERA_2015\Semaine\SEMAINE-Sessions/';
elseif(exist('C:\tadas\face_datasets\fera_2015\semaine/SEMAINE-Sessions/', 'file'))
    SEMAINE_dir = 'C:\tadas\face_datasets\fera_2015\semaine/SEMAINE-Sessions/';
elseif(exist('D:\datasets\face_datasets\fera_2015\semaine\SEMAINE-Sessions/', 'file'))
    SEMAINE_dir = 'D:\datasets\face_datasets\fera_2015\semaine\SEMAINE-Sessions/';
elseif(exist('D:\Datasets\FERA_2015\semaine\SEMAINE-Sessions/', 'file'))
    SEMAINE_dir = 'D:\Datasets\FERA_2015\semaine\SEMAINE-Sessions/';
elseif(exist('D:/fera_2015/semaine/SEMAINE-Sessions/', 'file'))
    SEMAINE_dir = 'D:/fera_2015/semaine/SEMAINE-Sessions/';
elseif(exist('/multicomp/datasets/face_datasets/FERA_2015/Semaine/SEMAINE-Sessions/', 'file'))
    SEMAINE_dir = '/multicomp/datasets/face_datasets/FERA_2015/Semaine/SEMAINE-Sessions/';
elseif(exist('/media/tadas/2EBEA130BEA0F20F/datasets/FERA_2015/semaine/SEMAINE-Sessions/', 'file'))
    SEMAINE_dir = '/media/tadas/2EBEA130BEA0F20F/datasets/FERA_2015/semaine/SEMAINE-Sessions/';
else
    fprintf('SEMAINE location not found (or not defined)\n');
end

if(exist('SEMAINE_dir', 'var'))
    hog_data_dir = [SEMAINE_dir, '../processed_data/'];
end

train_recs = {'rec1', 'rec12', 'rec14', 'rec19', 'rec23', 'rec25', 'rec37', 'rec39', 'rec43', 'rec45', 'rec48', 'rec50', 'rec52', 'rec54', 'rec56', 'rec60'};
devel_recs = {'rec9', 'rec13', 'rec15', 'rec20', 'rec24', 'rec26', 'rec38', 'rec42', 'rec44', 'rec46', 'rec49', 'rec51', 'rec53', 'rec55', 'rec58'};

aus_SEMAINE = [2 12 17 25 28 45];

author: TadasBaltrusaitis

repo: OpenFace


text:
%kcxvisualHSV 'create visually a HSV constant image '
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros cxvisualHSV.pane file
%
% Parameters:
% Integer: width 'Width', default: 100: 'width of the image'
% Integer: height 'Height', default: 100: 'height of the image'
% Integer: hue 'Initial Hue value', default: 0: 'initial hue'
% Integer: saturation 'Initial Saturation value', default: 100: 'initial saturation'
% Integer: value 'Initial Value value', default: 100: 'initial value'
% OutputFile: o 'Output', required: 'Resulting output data object'
%
% Example: o = kcxvisualHSV( {'width',100;'height',100;'hue',0;'saturation',100;'value',100;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% cxvisualHSV - create visually a HSV constant image
%
%  DESCRIPTION
% Allows the user to visually create an 3-band RGB image with Hue, Saturation and Value values specified via the user interface (values are shown in RGB too). Shows an area with the selected color while interacting.
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
% cxvisualRGB
%
%  RESTRICTIONS
%
%  REFERENCES
% All references for the toolbox COLOR are on the file $COLOR/Readme.html
%
%  COPYRIGHT
% Copyright (C) 1997 Rafael Santos. Khoros (C) Khoral Research, Inc.
%

function varargout = kcxvisualHSV(varargin)
Inputs={};
if nargin ==0
  arglist={'',''};
elseif nargin ==1
  arglist=varargin{1};
else error('Usage: [out1,..] = kcxvisualHSV(arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'width', 100;'height', 100;'hue', 0;'saturation', 100;'value', 100;'o', '__output'};
maxval={2,2,359,100,100,0};
minval={2,2,0,0,0,0};
istoggle=[0,0,0,0,0,0];
was_set=istoggle * 0;
paramtype={'Integer','Integer','Integer','Integer','Integer','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; 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(1,1);
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
[varargout{:}]=callKhoros([w 'cxvisualHSV"  '],Inputs,narglist);

author: aludnam

repo: MATLAB

save_path: github-repos/MATLAB/aludnam-MATLAB