code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
function [P, K] = svm_dual(S, K)
%SVM_DUAL Dual QP Problem of SVM Learning
%
% P = svm_dual(S);
%
% constructs a QP problem corresponding to the dual formulation
% of the SVM problem given by S.
%
% P = svm_dual(S, K);
%
% performs the construction using the pre-computed kernel matrix
% K as the kernel matrix. If K is not provided, it will be computed
% by the function.
%
% [P, K] = svm_dual( ... );
%
% additionally returns the kernel matrix.
%
% Note that the solution to a dual problem is the vector of the alpha
% coefficients.
%
% Created by Dahua Lin, on Jan 18, 2012
%
%% verify inputs
if ~is_svm_problem(S)
error('svm_dual:invalidarg', 'S should be a svm-problem struct.');
end
n = S.n;
if nargin < 2 || isempty(K)
K = [];
else
if ~(isfloat(K) && isreal(K) && isequal(size(K), [n n]))
error('svm_dual:invalidarg', 'K should be an n x n real matrix.');
end
end
%% main
% get kernel matrix
if isempty(K)
K = svm_kernel(S);
end
% construct problem
switch S.type
case 'class'
sdim = n;
y = S.y;
H = (y' * y) .* K;
f = -ones(n, 1);
Aeq = y;
beq = 0;
c = S.C.';
case 'regress'
sdim = 2 * n;
e = S.tol;
y = S.y.';
H = [K -K; -K K];
f = [e - y; e + y];
Aeq = [ones(1, n), -ones(1, n)];
beq = 0;
c = S.C.';
if ~isscalar(c)
c = [c; c];
end
case 'rank'
[I, J, c] = find(S.G);
sdim = numel(I);
H = K(I, I) + K(J, J) - (K(I, J) + K(J, I));
f = -ones(sdim, 1);
Aeq = [];
beq = [];
otherwise
error('svm_dual:invalidarg', ...
'Unsupported SVM problem type %s', S.type);
end
if isscalar(c)
c = c * ones(sdim, 1);
end
P = qp_problem(H, f, [], [], Aeq, beq, zeros(sdim, 1), c);
| zzhangumd-smitoolbox | classics/svm/svm_dual.m | MATLAB | mit | 1,940 |
function svc_rbf_demo(n, solver)
%SVC_RBF_DEMO The Demo of RBF kernel SVM for classification
%
% SVC_RBF_DEMO;
% SVC_RBF_DEMO(n);
%
% Here, n is the number of samples per class. By default it is
% set to 100.
%
% SVC_RBF_DEMO(n, solver);
%
% User can also specifies a customized solver function handle.
% (default is @mstd_solve using interior-point-convex)
%
% Created by Dahua Lin, on Jan 18, 2012
%
%% prepare data
if nargin < 1
n = 100;
end
if nargin < 2
solver = svm_default_solver();
end
r0 = 2;
r1 = 12;
r1w = 1;
X0 = randn(2, n) * r0;
t1 = rand(1, n) * (2 * pi);
rho1 = randn(1, n) * r1w + r1;
X1 = [rho1 .* cos(t1); rho1 .* sin(t1)];
%% train svm
X = [X0 X1];
y = [-1 * ones(1, n), ones(1, n)];
C = 10;
sigma = 6;
S = svm_problem('class', X, y, C, {'gauss', sigma});
tic;
R = svm_dual_train(S, [], solver);
elapsed_t = toc;
fprintf('Training time on %d samples = %f sec.\n', size(X,2), elapsed_t);
%% visualize
% data points
figure;
plot(X0(1,:), X0(2,:), 'c.'); hold on;
plot(X1(1,:), X1(2,:), 'g.');
% range
xmin = min(X(1,:));
xmax = max(X(1,:));
ymin = min(X(2,:));
ymax = max(X(2,:));
xm0 = xmin - (xmax - xmin) * 0.05;
xm1 = xmax + (xmax - xmin) * 0.05;
ym0 = ymin - (ymax - ymin) * 0.05;
ym1 = ymax + (ymax - ymin) * 0.05;
% prediction contours
[xx, yy] = meshgrid(linspace(xm0, xm1, 300), linspace(ym0, ym1, 300));
gpts = [xx(:)'; yy(:)'];
p = svm_dual_predict(R, gpts);
p = reshape(p, size(xx));
contour(xx, yy, p, [-1, 0, 1]);
% support vectors
hold on;
plot(R.X(1,:), R.X(2,:), 'mo', 'LineWidth', 1, 'MarkerSize', 10);
axis([xm0, xm1, ym0, ym1]);
axis equal;
| zzhangumd-smitoolbox | classics/svm/svc_rbf_demo.m | MATLAB | mit | 1,643 |
function [w, b, xi] = svm_primal_train(S, solver)
%SVM_PRIMAL_TRAIN Train Support Vector Machine using Primal formulation
%
% [w, b] = SVM_PRIMAL_TRAIN(S);
% [w, b] = SVM_PRIMAL_TRAIN(S, solver);
% [w, b, xi] = SVM_PRIMAL_TRAIN( ... );
%
% trains a linear SVM using primal QP formulation.
%
% Input arguments:
% - S: The SVM problem struct.
% Note S.kernel_type must be 'linear'.
%
% - solver: The solver function handle.
% If omitted, the function by default uses mstd_solve,
% which invokes MATLAB's built-in interior-point solver.
%
% Output arguments:
% - w: The weight vector [d x 1].
% - b: The offset scalar.
% - xi: The vector of slack variables
%
% The linear prediction is then given by w'*x+b.
%
% Created by Dahua Lin, on Jan 18, 2012
%
%% Prepare solver
if nargin < 2
solver = svm_default_solver();
else
if ~isa(solver, 'function_handle')
error('svm_primal_train:invalidarg', ...
'solver must be a function handle.');
end
end
%% main
P = svm_primal(S);
sol = solver(P);
d = size(S.X, 1);
switch S.type
case {'class', 'regress'}
w = sol(1:d);
b = sol(d+1);
if nargout >= 3
xi = sol(d+2:end);
end
case 'rank'
w = sol(1:d);
b = 0;
if nargout >= 3
xi = sol(d+1:end);
end
end
| zzhangumd-smitoolbox | classics/svm/svm_primal_train.m | MATLAB | mit | 1,475 |
function svc_linear_demo(n, solver)
%SVC_LINEAR_DEMO Demo of linear SVM classification
%
% SVC_LINEAR_DEMO;
% SVC_LINEAR_DEMO(n);
% SVC_LINEAR_DEMO(n, solver);
%
% Here, n is the number of samples per class. By default it is
% set to 100.
%
% User can also specifies a customized solver function handle.
%
% SVC_LINEAR_DEMO(n, 'dlm');
%
% Uses lsvm_dlm_train to perform the training.
%
% Created by Dahua Lin, on Jan 18, 2012
%
%% process inputs
if nargin < 1
n = 100;
end
if nargin < 2
solver = svm_default_solver();
end
use_dlm = ischar(solver) && strcmpi(solver, 'dlm');
%% prepare data
t = rand() * (2 * pi);
tc = t + pi/2 + randn() * 0.5;
d = 6;
c0 = [cos(tc) sin(tc)] * d;
c1 = -c0;
X0 = gen_data(n, c0(1), c0(2), 3, 1, t);
X1 = gen_data(n, c1(1), c1(2), 3, 1, t);
%% training
X = [X0 X1];
y = [-1 * ones(1, n), ones(1, n)];
C = 5;
S = svm_problem('class', X, y, C);
tic;
if ~use_dlm
[w, b] = svm_primal_train(S, solver);
else
hw = 0.1;
[w, b] = lsvm_dlm_train(S, hw, [], 'Display', 'iter');
end
elapsed_t = toc;
fprintf('Training time on %d points = %f sec\n', size(X, 2), elapsed_t);
%% visualize
% data points
figure;
plot(X0(1,:), X0(2,:), 'c.'); hold on;
plot(X1(1,:), X1(2,:), 'g.');
% range
xmin = min(X(1,:));
xmax = max(X(1,:));
ymin = min(X(2,:));
ymax = max(X(2,:));
xm0 = xmin - (xmax - xmin) * 0.05;
xm1 = xmax + (xmax - xmin) * 0.05;
ym0 = ymin - (ymax - ymin) * 0.05;
ym1 = ymax + (ymax - ymin) * 0.05;
rgn = [xm0, xm1, ym0, ym1];
% margin lines
impline(w(1), w(2), b-1, rgn, 'Color', 'b');
impline(w(1), w(2), b+1, rgn, 'Color', 'b');
axis([xm0, xm1, ym0, ym1]);
axis equal;
%% Auxiliary functions
function X = gen_data(n, x0, y0, a, b, t)
X = randn(2, n);
X = bsxfun(@times, [a; b], X);
R = [cos(t) -sin(t); sin(t) cos(t)];
X = bsxfun(@plus, R * X, [x0; y0]);
| zzhangumd-smitoolbox | classics/svm/svc_linear_demo.m | MATLAB | mit | 1,871 |
function tf = is_svm_problem(S)
%IS_SVM_PROBLEM Whether the input argument is an SVM problem struct
%
% tf = is_svm_problem(S);
% returns whether S is a valid SVM problem struct.
%
% Created by Dahua Lin, on Jan 17, 2012
%
%% main
tf = isstruct(S) && numel(S) == 1 && isfield(S, 'tag') && ...
strcmp(S.tag, 'svm-problem'); | zzhangumd-smitoolbox | classics/svm/is_svm_problem.m | MATLAB | mit | 337 |
function svr_rbf_demo(n, solver)
%SVR_RBF_DEMO The Demo of RBF kernel SVM for regression
%
% SVR_RBF_DEMO;
% SVR_RBF_demo(n);
%
% Here, n is the number of samples. By default it is set to 200.
%
% SVR_RBF_DEMO(n, solver);
%
% User can also specifies a customized solver function handle.
% (default is @mstd_solve using interior-point-convex)
%
% Created by Dahua Lin, on Jan 18, 2012
%
%% process inputs
if nargin < 2
n = 200;
end
if nargin < 3
solver = svm_default_solver();
end
%% prepare data
noise_sig = 0.2;
x = sort(rand(1, n) * (2 * pi));
y = sin(x) + randn(1, n) * noise_sig;
%% train SVM
tol = noise_sig;
C = 20;
sigma = 1;
S = svm_problem('regress', x, y, C, {'gauss', sigma}, tol);
R = svm_dual_train(S, [], solver);
% predict
yp = svm_dual_predict(R, x);
%% visualization
figure;
plot(x, y, 'b.');
hold on;
plot(x, yp, 'r-', 'LineWidth', 2);
plot(x, yp + tol, 'm-', 'LineWidth', 1);
plot(x, yp - tol, 'm-', 'LineWidth', 1);
| zzhangumd-smitoolbox | classics/svm/svr_rbf_demo.m | MATLAB | mit | 987 |
function v = svm_dual_predict(R, X)
%SVM_DUAL_PREDICT SVM prediction based on dual formulation solution
%
% v = SVM_DUAL_PREDICT(R, X);
%
% Evaluates the prediction values based on the solution to the
% dual QP problem, using the following formula
%
% v = w' * x + b
% = sum_i a_i * k(sv_i, x) + b
%
% Input arguments:
% - R: The svm-dual-sol struct that captures the SVM dual
% problem solution.
%
% - X: The testing samples upon which the predicted values
% are to be evaluated.
%
% Output arguments:
% - v: The predicted values: size 1 x N.
%
% Created by Dahua Lin, on Jan 18, 2012
%% main
v = R.a * svm_kernel(R, X);
b = R.b;
if ~isequal(b, 0)
v = v + b;
end
| zzhangumd-smitoolbox | classics/svm/svm_dual_predict.m | MATLAB | mit | 799 |
function svmrank_rbf_demo(n, solver)
%SVMRANK_RBF_DEMO Demo of ranking using linear SVM
%
% SVMRANK_RBF_DEMO(n);
%
% Here, n is the number of samples. By default it is set to 200.
%
% SVMRANK_RBF_DEMO(n, solver);
%
% User can also specifies a customized solver function handle.
% (default is @mstd_solve using interior-point-convex)
%
% Created by Dahua Lin, on Jan 18, 2012
%
%% process input
if nargin < 1
n = 200;
end
if nargin < 2
solver = svm_default_solver();
end
%% prepare data
t = sort(rand(1, n));
t = t(end:-1:1);
X = [t - 0.5; 3 * (t - 0.5).^2];
%% train SVM
C = 50;
G = sparse(1:n-1, 2:n, 1, n, n);
sigma = 0.5;
S = svm_problem('rank', X, G, C, {'gauss', sigma});
tic;
R = svm_dual_train(S, [], solver);
elapsed_t = toc;
fprintf('Training time on %d points = %f sec\n', size(X, 2), elapsed_t);
%% visualize
x = X(1, :);
y = X(2, :);
figure;
scatter(x, y, 400 * (t.^2) );
axis equal;
xlim = get(gca, 'XLim'); x0 = xlim(1); x1 = xlim(2);
ylim = get(gca, 'YLim'); y0 = ylim(1); y1 = ylim(2);
xs = linspace(x0, x1, 200);
ys = linspace(y0, y1, 200);
[xx, yy] = meshgrid(xs, ys);
gpts = [xx(:) yy(:)]';
scores = svm_dual_predict(R, gpts);
scores = reshape(scores, size(xx));
hold on;
contour(xs, ys, scores, 50);
colorbar;
| zzhangumd-smitoolbox | classics/svm/svmrank_rbf_demo.m | MATLAB | mit | 1,286 |
function P = svm_primal(S)
%SVM_PRIMAL Primal QP Problem of SVM Learning
%
% P = SVM_PRIMAL(S);
%
% constructs a QP problem corresponding to the primal formulation
% of the SVM problem represented by S.
%
% The solution composition for different types of problems are
% different.
%
% - 'class': sol = [w; b; xi]
% - 'regress': sol = [w; b; xi]
% - 'rank': sol = [w; xi]
%
% Note this function only applies to the problem using linear kernel.
%
% Created by Dahua Lin, on Jan 17, 2012
%
%% verify input
if ~is_svm_problem(S)
error('svm_primal:invalidarg', 'S should be a svm-problem struct.');
end
if ~strcmp(S.kernel_type, 'linear')
error('svm_primal:invalidarg', ...
'S.kernel_type must be linear for svm_primal.');
end
%% main
n = S.n;
d = size(S.X, 1);
% generate constraints
switch S.type
case 'class'
X = S.X;
y = S.y;
A = [bsxfun(@times, y, X).', y.'];
b = ones(n, 1);
c = S.C;
case 'regress'
X = S.X.';
y = S.y.';
tol = S.tol;
A = [-X, -ones(n, 1); X, ones(n, 1)];
b = [-(y + tol); y - tol];
c = S.C;
if ~isscalar(c)
c = [c c];
end
case 'rank'
[I, J, c] = find(S.G);
X = S.X;
A = (X(:, I) - X(:, J)).';
b = ones(size(A,1), 1);
otherwise
error('svm_primal:invalidarg', ...
'Unsupported SVM model type %s', S.type);
end
% generate constraint matrix
cdim = size(A, 1);
if issparse(A) || 5 * d < cdim
A = [A, speye(cdim)];
else
A = [A, eye(cdim)];
end
sdim = size(A, 2);
% quadratic coefficient matrix
wdim = d;
H = sparse(1:wdim, 1:wdim, 1, sdim, sdim);
% linear coefficient vector
f = zeros(sdim, 1);
f(end-cdim+1:end) = c;
% lower-bound
lb = zeros(sdim, 1);
lb(1:end-cdim) = -inf;
% make problem struct
P = qp_problem(H, f, -A, -b, [], [], lb, []);
| zzhangumd-smitoolbox | classics/svm/svm_primal.m | MATLAB | mit | 2,022 |
function [R, alpha] = svm_dual_train(S, K, solver)
%SVM_DUAL_TRAIN SVM training based on dual QP formulation
%
% R = SVM_DUAL_TRAIN(S);
% R = SVM_DUAL_TRAIN(S, K);
% R = SVM_DUAL_TRAIN(S, [], solver);
% R = SVM_DUAL_TRAIN(S, K, solver);
%
% Trains a support vector machine (SVM) based on the dual QP
% formulation of the problem given in S.
%
% Input arguments:
% - S: The struct representing the SVM problem
%
% - K: The pre-computed kernel matrix. If not available,
% one can input K as an empty array.
%
% - solver: User-supplied solver (in form of a function handle).
% If omitted, the default solver that invokes MATLAB
% quadprog will be used.
%
% In output, R is a struct that represents the solution, which
% has the following fields:
%
% - tag: a fixed string: 'svm-dual-sol';
% - type: The problem type;
% - n: The number of support vectors
% - X: The matrix comprised of support vectors [d x n]
% - a: The coefficient on the support vectors. [1 x n]
% - b: The offset scalar
% - kernel_type
% - kernel_params
%
% [R, alpha] = SVM_DUAL_TRAIN( ... );
%
% additionally returns the original QP solution alpha.
%
% With the solution R, the prediction on a given set of samples X can
% be made by
%
% v = R.a * svm_kernel(R, X) + R.b;
%
% This can also be accomplished by invoking svm_dual_predict.
%
% Created by Dahua Lin, on Jan 18, 2012
%
%% process inputs
if nargin < 2
K = [];
end
if nargin < 3
solver = svm_default_solver();
else
if ~isa(solver, 'function_handle')
error('svm_dual_train:invalidarg', ...
'solver must be a function handle.');
end
end
%% main
% construct and solve QP
[P, K] = svm_dual(S, K);
alpha = solver(P);
% select support vectors
rtol = 1e-8;
switch S.type
case 'class'
si = find(alpha > rtol * max(alpha));
a = S.y(si) .* alpha(si).';
case 'regress'
n = S.n;
a1 = alpha(1:n);
a2 = alpha(n+1:2*n);
a = a1 - a2;
aa = abs(a);
si = find(aa > rtol * max(aa));
a = a(si).';
case 'rank'
n = S.n;
[I, J] = find(S.G);
a1 = aggreg(alpha, n, I, 'sum');
a2 = aggreg(alpha, n, J, 'sum');
a = a1 - a2;
aa = abs(a);
si = find(aa > rtol * max(aa));
a = a(si).';
end
% solve offset (b)
b = svm_dual_offset(S, K, alpha, si);
% make solution
R.tag = 'svm-dual-sol';
R.type = S.type;
R.n = numel(si);
R.X = S.X(:, si);
R.a = a;
R.b = b;
R.kernel_type = S.kernel_type;
R.kernel_params = S.kernel_params;
| zzhangumd-smitoolbox | classics/svm/svm_dual_train.m | MATLAB | mit | 2,823 |
function S = svm_problem(type, X, Y, C, kernel, tol)
%SVM_PROBLEM Support Vector Machine (SVM) Learning Problem
%
% S = SVM_PROBLEM('class', X, y, C);
% S = SVM_PROBLEM('class', X, y, C, kernel);
%
% Constructs the problem struct for learning a binary SVM classifier.
%
% The primal formulation is given by
%
% minimize (1/2) * ||w||^2 + sum_i C_i * xi_i
%
% with xi_i = max(0, 1 - y_i * (w' * x_i + b))
%
% Here, if kernel is omitted, the problem is to learn a linear SVM,
% otherwise, it is to learn a kernel SVM.
%
%
% S = SVM_PROBLEM('regress', X, y, C, [], tol);
% S = SVM_PROBLEM('regress', X, y, C, kernel, tol);
%
% Constructs the problem struct for SVM regression.
%
% The primal formulation is given by
%
% minimize (1/2) * ||w||^2 + sum_i C_i * xi_i
%
% with xi_i = max(0, abs(w' * x_i + b - y_i) - tol).
%
%
% S = SVM_PROBLEM('rank', X, G);
% S = SVM_PROBLEM('rank', X, G, [], kernel);
%
% Constructs the problem struct for SVM ranking.
%
% The primal formulation is given by
%
% minimize (1/2) * ||w||^2 + sum_{ij} G_{ij} xi_{ij}
%
% with xi_{ij} = max(0, 1 - w' * (x_i - x_j))
%
% The greater the value of G_{ij} is, the more efforts the
% optimization process devotes to enforcing that
% w' * x_i > w' * x_j.
%
% Input arguments:
% - X: The feature matrix, of size d x n.
%
% - y: The vector of labels (for classification) or
% responses (for ranking), of size 1 x n.
% For multi-class problem, the number of classes m
% are set to max(y).
%
% - C: The weights of slack variables, which can be
% either a scalar, or a vector of size 1 x n to
% assign sample-specific weights.
%
% - kernel: The kernel, which can be in either of the following
% form:
%
% - 'linear': Linear kernel: k(x,y) = x' * y.
% - {'gauss', sigma}: Gaussian kernel:
% k(x,y) = exp(-||x - y||^2/(2*sigma^2)).
% - {'poly', [a, b, d]}: Polynomial kernel:
% k(x,y) = (a * (x'*y) + b)^d
% - {'invmq', [a, b]}: Inverse multiquadratic kernel:
% k(x,y) = 1 / (a*||x-y||^2 + b)
% - {'sigmoid', [a, b]}: Sigmoid kernel:
% k(x,y) = tanh(a * (x'*y) + b)
%
% Or it can be a function handle, such that
% kernel(X, Y) returns an m x n matrix K with
% K(i, j) being the kernel value of X(:,i) and Y(:,j).
%
% If kernel is omitted, then the linear kernel is
% assumed.
%
% Note that if a pre-computed kernel is provided, the sample matrix
% X can be input as an empty array.
%
% The output S is a struct with the following fields:
%
% - tag: A fixed string: 'svm-problem'.
%
% - type: The problem type, whose value can be either of:
% 'class', 'multi-class', 'regress', and 'rank'.
%
% - n: The number of training samples
%
% - m: The number of classes.
%
% - X: The sample matrix.
%
% - y: The vector of labels or responses.
%
% - G: The ranking coefficient matrix. (G is empty, if
% S is not a ranking problem)
%
% - C: The slack weight (a scalar or a 1 x n vector).
%
% - tol: The tolerance for regression
%
% - kernel_type: The type of kernel, which can be either of:
% 'linear', 'gauss', 'poly', 'invmq', or 'custom'.
% ('custom' means using user-supplied function).
%
% - kernel_params: depends on the kernel type:
% - for linear kernel, it is empty.
% - for gauss kernel, it has a field sigma
% - for poly kernel, it has fields: a, b, d
% - for invmq kernel, it has fields: a, b
% - for sigmoid kernel, it has fields: a, b
% - for custom kernel, it is the function handle.
%
% Created by Dahua Lin, on Jan 17, 2012
%
%% verify inputs
if ~ischar(type)
error('svm_problem:invalidarg', 'The SVM type should be a string.');
end
if ~(isnumeric(X) && ndims(X) == 2)
error('svm_problem:invalidarg', 'X should be a numeric matrix.');
end
n = size(X, 2);
switch type
case 'class'
if isfloat(Y) && isreal(Y) && isequal(size(Y), [1 n])
m = 2;
y = Y;
G = [];
else
error('svm_problem:invalidarg', 'y should be an 1 x n real vector.');
end
case 'regress'
if isfloat(Y) && isreal(Y) && isequal(size(Y), [1 n])
m = 1;
y = Y;
G = [];
else
error('svm_problem:invalidarg', 'y should be an 1 x n real vector.');
end
case 'rank'
if isfloat(Y) && isreal(Y) && isequal(size(Y), [n n])
m = 1;
y = [];
G = Y;
else
error('svm_problem:invalidarg', 'G should be an n x n real matrix.');
end
otherwise
error('svm_problem:invalidarg', 'The SVM type is invalid.');
end
if ~(isfloat(C) && ((isscalar(C) && C >= 0) || ...
(isvector(C) && numel(C) == n)))
error('svm_problem:invalidarg', ...
'C should be either a positive scalar or a real vector of length n.');
end
if nargin < 5 || isempty(kernel)
kertype = 'linear';
kerparam = [];
else
[kertype, kerparam] = check_kernel(kernel);
end
if strcmp(type, 'regress')
if ~(isfloat(tol) && isreal(tol) && isscalar(tol) && tol > 0)
error('svm_problem:invalidarg', 'tol is invalid.');
end
else
tol = [];
end
%% make output
S.tag = 'svm-problem';
S.type = type;
S.n = n;
S.m = m;
S.X = X;
S.y = y;
S.G = G;
S.C = C;
S.tol = tol;
S.kernel_type = kertype;
S.kernel_params = kerparam;
if strcmp(kertype, 'pre')
S.kermat = kernel;
end
%% kernel checking
function [kt, kp] = check_kernel(kernel)
% verify kernels
if strcmpi(kernel, 'linear')
kt = 'linear';
kp = [];
elseif iscell(kernel)
kt = lower(kernel{1});
r = kernel{2};
switch kt
case 'gauss'
if isfloat(r) && isscalar(r) && r > 0
kp.sigma = r;
else
error('svm_problem:invalidarg', ...
'The parameter for the gauss kernel is invalid.');
end
case 'poly'
if isfloat(r) && numel(r) == 3 && all(r >= 0)
kp.a = r(1);
kp.b = r(2);
kp.d = r(3);
else
error('svm_problem:invalidarg', ...
'The parameter for the poly kernel is invalid.');
end
case 'invmq'
if isfloat(r) && numel(r) == 2 && all(r >= 0)
kp.a = r(1);
kp.b = r(2);
else
error('svm_problem:invalidarg', ...
'The parameter for the invmq kernel is invalid.');
end
case 'sigmoid'
if isfloat(r) && numel(r) == 2 && all(r >= 0)
kp.a = r(1);
kp.b = r(2);
else
error('svm_problem:invalidarg', ...
'The parameter for the sigmoid kernel is invalid.');
end
end
elseif isa(kernel, 'function_handle')
kt = 'custom';
kp = kernel;
else
error('svm_problem:invalidarg', ...
'The input kernel is invalid.');
end
| zzhangumd-smitoolbox | classics/svm/svm_problem.m | MATLAB | mit | 7,995 |
function K = svm_kernel(S, X)
%SVM_KERNEL SVM Kernel evaluation
%
% K = SVM_KERNEL(S);
%
% Evaluates the kernel matrix (i.e. Gram matrix) for the given
% SVM problem or solution.
%
% Here, S should be either a svm-problem or a svm-dual-sol struct.
%
% In the output, K is a matrix of size S.n x S.n.
%
% K = SVM_KERNEL(S, X);
%
% Evaluates the kernel matrix between S.X and X. The output
% matrix K is of size S.n x size(X,2).
%
% Created by Dahua Lin, on Jan 18, 2011
%
%% verify input arguments
if ~(is_svm_problem(S) || is_svm_dual_sol(S))
error('svm_kernel:invalidarg', ...
'S should be a svm-problem or svm-dual-sol struct.');
end
if nargin < 2
X = [];
else
d = size(S.X, 1);
if ~(isnumeric(X) && ndims(X) == 2 && size(X,1) == d)
error('svm_kernel:invalidarg', 'The input matrix X is invalid.');
end
end
%% main
kp = S.kernel_params;
switch S.kernel_type
case 'linear'
if isempty(X)
X = S.X;
K = X' * X;
else
K = S.X' * X;
end
case 'gauss'
K = gausskernel(S.X, X, kp.sigma);
case 'poly'
K = polykernel(S.X, X, kp.a, kp.b, kp.d);
case 'invmq'
K = invmqkernel(S.X, X, kp.a, kp.b);
case 'sigmoid'
K = sigmoidkernel(S.X, X, kp.a, kp.b);
otherwise
error('svm_kernel:invalidarg', ...
'Unsupported kernel type %s', S.kernel_type);
end
| zzhangumd-smitoolbox | classics/svm/svm_kernel.m | MATLAB | mit | 1,510 |
function [v, d1, d2] = svm_huber_loss(z, h)
% Compute the Huber loss with margin 1 as follows
%
% f(z) =
% 0, if z >= 1 + h
% (1+h-z)^2/4h, if |1 - z| < h
% 1 - z, if z <= 1 - h
%
% [v, d1, d2] = svm_huber_loss(z, h);
%
% Inputs:
% - z: the array of input values
% - h: the quadratic band-width [scalar]
% if h = 0, it reduces to hinge loss
%
% Outputs:
% - v: the function values
% - d1: the first derivative values
% - d2: the second derivative values
%
% Created by Dahua Lin, on Apr 21, 2011
%
%% main
u = 1 - z;
if h > 0
sq = find(abs(u) < h);
s1 = find(u >= h);
else
s1 = find(u > h);
end
v = zeros(size(u));
if h > 0
v(sq) = ((u(sq) + h).^2 / (4*h));
end
v(s1) = u(s1);
if nargout >= 1
d1 = zeros(size(u));
if h > 0
d1(sq) = - ((u(sq) + h) / (2*h));
end
d1(s1) = -1;
end
if nargout >= 2
d2 = zeros(size(u));
if h > 0
d2(sq) = 1 / (2*h);
end
end
| zzhangumd-smitoolbox | classics/svm/private/svm_huber_loss.m | MATLAB | mit | 1,039 |
function solver = svm_default_solver()
% Returns the default QP solver for SVM training
%
% solver = svm_default_solver();
%
optim_ver = ver('optim');
optim_ver = str2double(optim_ver.Version);
if optim_ver >= 6
alg = 'interior-point-convex';
else
alg = 'interior-point';
end
opts = optimset('Algorithm', alg, 'Display', 'off');
solver = @(pb) mstd_solve(pb, opts);
| zzhangumd-smitoolbox | classics/svm/private/svm_default_solver.m | MATLAB | mit | 379 |
function [v, g, H] = primal_svm_obj(sol, Q, F, y, c, lof, rb, op)
% The uniform objective function of primal linear/kernel svm training
%
% The objective is given by
%
% minimize (1/2) w' * Q * w + (rb/2) * b^2
% + sum_j c_j L(y_j * (w' * f_j + b))
%
% w.r.t. (w, b)
%
% For linear SVM: Q = I (input 1), and F = X
% For kernel SVM: Q = K, and F = K
%
% [v, g, H] = primal_svm(sol, Q, F, y, c, lof, rb);
% [v, dx] = primal_svm(sol, Q, F, y, c, lof, rb, 'd');
%
% Inputs:
% sol: the solution at which the objective is to be evaluated
% sol(1:d) - w
% sol(d+1) - b
%
% Q: The quadratic matrix on w [scalar or d x d]
% F: The feature matrix [d x n], f_j is given by F(:,j).
% when F is Q, it is input as empty to note this fact.
% y: The label vector [1 x n]
% c: The loss coefficients [scalar or 1 x n]
% lof: The loss function handle
% rb: The regularization coefficient of b [1 x n]
% dx: The Newton direction vector: -(H \ g),
% which is directly computed in an efficient way
%
% Note for kernel matrix, d = n here.
%
% Outputs:
% v: the objective value [scalar]
% g: the gradient vector [(d+1) x 1]
% H: the Hessian matrix [(d+1) x (d+1)]
%
% Created by Dahua Lin, on Apr 21, 2011
%
%% parse input
if nargin >= 8 && op(1) == 'd'
odir = true;
else
odir = false;
end
%% main
% extract solution
if isempty(F)
d = numel(y);
else
d = size(F,1);
end
w = sol(1:d);
b = sol(d+1);
% prediction and derivative evaluation
if isempty(F)
z = y .* (w' * Q + b);
else
z = y .* (w' * F + b);
end
if nargout <= 1
Lv = lof(z);
elseif nargout == 2
if odir
[Lv, Lg, Lh] = lof(z);
else
[Lv, Lg] = lof(z);
end
else
[Lv, Lg, Lh] = lof(z);
end
% evaluate objective
v = eval_objv(Q, rb, w, b, c, Lv);
if odir
% evaluate Newton direction
if nargout >= 2
tg = (c .* Lg) .* y;
th = c .* Lh;
g = eval_dir(Q, F, rb, w, b, tg, th);
end
else
% evaluate gradient
if nargout >= 2
tg = (c .* Lg) .* y;
g = eval_grad(Q, F, rb, w, b, tg);
end
% evaluate Hessian
if nargout >= 3
th = c .* Lh;
H = eval_Hess(Q, F, rb, th);
end
end
%% Sub functions
function v = eval_objv(Q, rb, w, b, c, Lv)
if isscalar(Q)
vw = (w' * w) * (Q / 2);
else
vw = (w' * Q * w) / 2;
end
vb = b^2 * (rb / 2);
if isscalar(c)
v = vw + vb + c * sum(Lv);
else
v = vw + vb + c * Lv';
end
function g = eval_grad(Q, F, rb, w, b, tg)
gb = rb * b + sum(tg);
if isempty(F)
g = [Q * (w + tg'); gb];
else
if isequal(Q, 1)
Qw = w;
else
Qw = Q * w;
end
g = [Qw + F * tg'; gb];
end
function H = eval_Hess(Q, F, rb, th)
if isempty(F)
F = Q;
end
d = size(F, 1);
Hw = F * bsxfun(@times, F, th)';
if isscalar(Q)
dind = 1 + (0:d-1) * (d+1);
Hw(dind) = Hw(dind) + Q;
else
Hw = Hw + Q;
end
Hw = (Hw + Hw') / 2;
Hwb = F * th';
H = zeros(d+1, d+1);
H(1:d, 1:d) = Hw;
H(1:d, d+1) = Hwb;
H(d+1, 1:d) = Hwb';
H(d+1, d+1) = sum(th) + rb;
function dx = eval_dir(Q, F, rb, w, b, tg, th)
if isempty(F) % F == Q
n = size(Q, 1);
ii = [w + tg', th'];
gw_and_f = Q * ii;
gw = gw_and_f(:,1);
f = gw_and_f(:,2);
do_fast = nnz(th) < 0.7 * n;
if do_fast
% compute M0
hnz = find(th ~= 0);
hz = find(th == 0);
dhnz = th(hnz);
dhnz = dhnz(:);
M0 = bsxfun(@times, dhnz, Q(hnz, hnz));
m = size(M0, 1);
dind = 1 + (0:m-1) * (m+1);
M0(dind) = M0(dind) + 1;
% compute IA_gw and u
pre_rr = ii(hnz, :);
pre_rr(:, 1) = pre_rr(:, 1) - bsxfun(@times, dhnz, Q(hnz, hz) * ii(hz, 1));
rr = M0 \ pre_rr;
IA_gw = ii(:, 1);
IA_gw(hnz) = rr(:,1);
u = ii(:, 2);
u(hnz) = rr(:,2);
else
% compute M
M = bsxfun(@times, th(:), Q);
dind = 1 + (0:n-1) * (n+1);
M(dind) = M(dind) + 1;
% compute IA_gw and u
rr = M \ ii;
IA_gw = rr(:, 1);
u = rr(:, 2);
end
else % F != Q
d = size(F, 1);
A = F * bsxfun(@times, F, th)';
if isscalar(Q)
dind = 1 + (0:d-1) * (d+1);
A(dind) = A(dind) + Q;
else
A = A + Q;
end
A = (A + A') * 0.5;
f = F * th';
u = A \ f;
gw = Q * w + F * tg';
IA_gw = A \ gw;
end
gb = rb * b + sum(tg);
hb = rb + sum(th);
s = 1 ./ (hb - f' * u);
db = u' * gw - gb;
dx = [- (IA_gw + (s * db) * u); s * db];
| zzhangumd-smitoolbox | classics/svm/private/primal_svm_obj.m | MATLAB | mit | 4,832 |
function [w, b] = lsvm_dlm_train(S, hw, initsol, varargin)
%LSVM_DLM_TRAIN Linear SVM training via direct loss minimization
%
% [w, b] = LSVM_DLM_TRAIN(S, hw, initsol, ...);
%
% Learns a linear SVM model via direct minimization of an
% approximate regularized loss function, as
%
% (1/2) ||w||^2 + sum_i c_i L( y_i * (w'*x_i+b) ).
%
% Here, L is an approximate hinge loss, defined by
%
% L(u) = 0 when u >= 1 + h
% = (1 + h - u)^2 / (4*h) when 1 - h < u < 1 + h
% = 1 - u when u <= 1 - h
%
% Here, h is called the hinge transition width.
%
% Input arguments:
%
% - S: The svm-problem struct
% - hw: The hinge transition width [0 < hw < 1]
% - initsol: Initial guess of the solution, in form of [w; b]
% One can set initsol to [], then the function will
% be zeros(d+1, 1) as initial guess by default.
%
% Output arguments:
%
% - w: The weight vector, size: d x 1
% - b: The offset scalar
%
% One can control the optimization procedure, by specifying the
% following options in form of name/value pairs. See the help
% of newtonfmin for detailed information on what options are
% available.
%
% Created by Dahua Lin, on Jan 19, 2011
%
%% verify input arguments
if ~(is_svm_problem(S) && strcmp(S.type, 'class') && ...
strcmp(S.kernel_type, 'linear'))
error('lsvm_dlm_train:invalidarg', ...
'S should be an svm-problem for classification using linear kernel.');
end
if ~(isfloat(hw) && isreal(hw) && hw > 0 && hw < 1)
error('lsvm_dlm_train:invalidarg', ...
'hw should be a real scalar in (0, 1).');
end
d = size(S.X, 1);
if nargin < 3 || isempty(initsol)
s0 = zeros(d+1, 1);
else
if ~(isfloat(initsol) && isreal(initsol) && isequal(size(initsol), [d 1]))
error('lsvm_dlm_train:invalidarg', ...
'initsol should be a real vector of size d x 1.');
end
s0 = initsol;
end
%% main
Xa = [S.X; ones(1, S.n)];
y = S.y;
c = S.C;
f = @(s) lsvm_dlm_objfun(s, Xa, y, c, hw);
sol = newtonfmin(f, s0, varargin{:});
w = sol(1:d);
b = sol(d+1);
%% objective function
function [v, g, H] = lsvm_dlm_objfun(s, Xa, y, c, h)
d = size(Xa, 1) - 1;
w = s(1:d);
b = s(d+1);
b_reg = 1e-9;
c_sca = isscalar(c);
% evaluate linear predictor
u = y .* (s' * Xa);
% categorize samples
ti = find(abs(u - 1) < h);
wi = find(u <= 1 - h);
has_t = ~isempty(ti);
has_w = ~isempty(wi);
% objective value
if has_t
ut = u(ti);
rt = 1 + h - ut;
if c_sca
Lt = (1/(4*h)) * ( sum(rt.^2) * c );
else
ct = c(ti);
Lt = (1/(4*h)) * ( (rt.^2) * ct );
end
else
Lt = 0;
end
if has_w
uw = u(wi);
if c_sca
Lw = sum(1 - uw) * c;
else
cw = c(wi);
Lw = (1 - uw) * cw;
end
else
Lw = 0;
end
v = 0.5 * ((w' * w) + b_reg * (b^2)) + (Lt + Lw);
% gradient
if nargout < 2; return; end
g = [w; b_reg * b];
if has_t
gt = (1 / (2*h)) * rt;
Xt = Xa(:, ti);
if c_sca
g = g - Xt * (c * (y(ti) .* gt).');
else
g = g - Xt * (ct .* (y(ti) .* gt).');
end
end
if has_w
Xw = Xa(:, wi);
if c_sca
g = g - Xw * (c * y(wi)).';
else
g = g - Xw * (cw .* y(wi).');
end
end
% Hessian
if nargout < 3; return; end
H = diag([ones(d, 1); b_reg]);
if has_t
if c_sca
H = H + (c/(2*h)) * (Xt * Xt');
else
H2 = Xt * bsxfun(@times, Xt', ct);
H2 = 0.5 * (H2 + H2');
H = H + (1/(2*h)) * H2;
end
end
| zzhangumd-smitoolbox | classics/svm/lsvm_dlm_train.m | MATLAB | mit | 3,692 |
function svmrank_linear_demo(n, solver)
%SVMRANK_LINEAR_DEMO Demo of ranking using linear SVM
%
% SVMRANK_LINEAR_DEMO(n);
%
% Here, n is the number of samples. By default it is set to 100.
%
% SVMRANK_LINEAR_DEMO(n, solver);
%
% User can also specifies a customized solver function handle.
% (default is @mstd_solve using interior-point-convex)
%
% Created by Dahua Lin, on Jan 18, 2012
%
%% process input
if nargin < 1
n = 100;
end
if nargin < 2
solver = svm_default_solver();
end
%% prepare data
A = randn(2, 1);
t = sort(rand(1, n));
t = t(end:-1:1);
X = A * t;
%% train SVM
C = 5;
G = sparse(1:n-1, 2:n, 1, n, n);
S = svm_problem('rank', X, G, C, 'linear');
tic;
w = svm_primal_train(S, solver);
elapsed_t = toc;
fprintf('Training time on %d points = %f sec\n', size(X, 2), elapsed_t);
%% visualize
x = X(1, :);
y = X(2, :);
figure;
scatter(x, y, 400 * (t.^2) );
axis equal;
xlim = get(gca, 'XLim'); x0 = xlim(1); x1 = xlim(2);
ylim = get(gca, 'YLim'); y0 = ylim(1); y1 = ylim(2);
xs = linspace(x0, x1, 200);
ys = linspace(y0, y1, 200);
[xx, yy] = meshgrid(xs, ys);
gpts = [xx(:) yy(:)]';
scores = w' * gpts;
scores = reshape(scores, size(xx));
hold on;
contour(xs, ys, scores, 20);
colorbar;
| zzhangumd-smitoolbox | classics/svm/svmrank_linear_demo.m | MATLAB | mit | 1,254 |
function svr_linear_demo(n, solver)
%SVR_LINEAR_DEMO Demo of SVM for linear regression
%
% SVR_LINEAR_DEMO;
% SVR_LINEAR_DEMO(n);
% SVR_LINEAR_DEMO(n, solver);
%
% Conducts the demo of SVM for linear regression.
%
% n is the number of samples (default = 200, if omitted).
%
% User can also supply a customized solver.
%
% Created by Dahua Lin, on Jan 18, 2011
%
%% process inputs
if nargin < 1
n = 200;
end
if nargin < 2
solver = svm_default_solver();
end
%% prepare data
noise_sig = 0.3;
x = rand(1, n) * (2 * pi);
a0 = randn();
b0 = randn();
y = (a0 * x + b0) + randn(1, n) * noise_sig;
%% train SVM
tol = noise_sig;
C = 20;
S = svm_problem('regress', x, y, C, 'linear', tol);
[a, b] = svm_primal_train(S, solver);
%% visualization
figure;
plot(x, y, 'b.');
x0 = 0;
x1 = 2 * pi;
y0 = a * x0 + b;
y1 = a * x1 + b;
hold on;
plot([x0, x1], [y0, y1], 'r-', 'LineWidth', 2);
plot([x0, x1], [y0, y1] + tol, 'm-', 'LineWidth', 1);
plot([x0, x1], [y0, y1] - tol, 'm-', 'LineWidth', 1);
| zzhangumd-smitoolbox | classics/svm/svr_linear_demo.m | MATLAB | mit | 1,037 |
function [R, A] = knnc(D, M, L, K, wfun, op)
%KNNC K-nearest-neighbor classification
%
% R = KNNC(D, M, L, K);
% R = KNNC(D, M, L, K, wfun);
% R = KNNC(D, M, L, K, [], 'dis');
% R = KNNC(D, M, L, K, wfun, 'dis');
% R = KNNC(D, M, L, K, [], 'sim');
% R = KNNC(D, M, L, K, wfun, 'sim');
%
% Performs K-nearest-neighbor classification.
%
% Input arguments:
% - D: The matrix of distances or similarities.
%
% Suppose there are n query samples and m reference
% samples, then D should have size m x n. Particularly,
% D(i, j) is the distance between the j-th query to
% the i-th reference.
%
% If the 6th argument is omited or set to 'dis', then
% D contains distances (i.e. smaller values indicate
% closer). If the 6th argument is set to 'sim', then
% D contains similarities (i.e. higher values indiate
% closer).
%
% - M: The number of distinct classes.
%
% - L: The labels of reference samples, which should be
% a numeric vector of length m. The values in L should
% be integers in {1, ..., M}.
%
% - K: The number of neighbors for each sample.
%
% - wfun: The weighting function, which, if given, will be
% invoked as
%
% W = wfun(Dr);
%
% Here, Dr is the matrix of sorted distance or
% similarity values (from the closest to the K-th
% closest). The size of Dr is K x n. In the output,
% W should also be a matrix of size K x n.
%
% If wfun is omitted or input as [], then all the K
% neighbors have equal contribution.
%
% Output arguments:
% - R: The resultant vector of class labels, of size 1 x n.
%
%
% [R, A] = KNNC( ... );
%
% Additionally returns A, the class-wise accumulated scores for
% each pair of class/sample.
%
% Here, A is a matrix of size K x n. A(k, i) is the number of
% neighbors of sample i that belong to class k (if wfun is not used),
% or the total neighbor weights associated with class k.
%
% Created by Dahua Lin, on Jan 21, 2012
%
%% verify input
if ~(isfloat(D) && isreal(D) && ndims(D) == 2)
error('knnc:invalidarg', 'D should be a real matrix.');
end
[m, n] = size(D);
if m < 2
error('knnc:invalidarg', 'D should contain at least two rows.');
end
if ~(isnumeric(M) && isscalar(M) && M == fix(M) && M >= 1)
error('knnc:invalidarg', 'M should be a positive integer.');
end
if ~(isnumeric(L) && isvector(L) && numel(L) == m)
error('knnc:invalidarg', 'L should be a vector of length m.');
end
if ~(isnumeric(K) && isscalar(K) && K == fix(K) && K >= 1 && K <= n)
error('knnc:invalidarg', 'K should be a positive integer in [1, n].');
end
if nargin < 5 || isempty(wfun)
use_wfun = 0;
else
if ~isa(wfun, 'function_handle')
error('knnc:invalidarg', 'wfun should be a function handle.');
end
use_wfun = 1;
end
if nargin < 6
dir = 'min';
else
if strcmpi(op, 'dis')
dir = 'min';
elseif strcmpi(op, 'sim')
dir = 'max';
else
error('knnc:invalidarg', 'The 6th argument is invalid.');
end
end
%% main
[Dr, I] = top_k(D, dir, K);
Lr = L(I);
if ~use_wfun
A = intcount(M, Lr, 1);
else
W = wfun(Dr);
assert(isequal(size(W), [K n]));
if ~isa(W, 'double')
W = double(W);
end
A = aggreg_percol(W, M, Lr, 'sum');
end
[~, R] = max(A, [], 1);
| zzhangumd-smitoolbox | classics/classification/knnc.m | MATLAB | mit | 3,721 |
function [L, v] = sclassify(D, op)
%SCLASSIFY Standard Nearest Neighbor Classification
%
% L = SCLASSIFY(D, 'dis');
% L = SCLASSIFY(D, 'sim');
%
% Classifies each sample to a particular class that is closest to it.
%
% Suppose there are K class and n testing samples. Then D should be
% matrix of size K x n, and D(k, i) is the distance (2nd arg being
% 'dis') or similarity (2nd arg being 'sim') between the i-th sample
% and the k-th class.
%
% L is a vector of size 1 x n, whose values are integers in
% {1, ..., K}.
%
%
% [L, v] = SCLASSIFY( ... );
%
% Additionally returns the distance/similarity value between each
% sample to the selected class.
%
%
% Created by Dahua Lin, on Jun 6, 2010
% Modifued by Dahua Lin, on Jan 21, 2012
%
%% verify input
if ~(isnumeric(D) && ndims(D) == 2)
error('sclassify:invalidarg', 'D should be a numeric matrix.');
end
if strcmp(op, 'dis')
is_dis = true;
elseif strcmp(op, 'sim')
is_dis = false;
else
error('sclassify:invalidarg', ...
'The second arg should be either ''dis'' or ''sim''.');
end
%% main
if is_dis
[v, L] = min(D, [], 1);
else
[v, L] = max(D, [], 1);
end
| zzhangumd-smitoolbox | classics/classification/sclassify.m | MATLAB | mit | 1,232 |
function [x, y, thres] = roc_curve(scores, L0, xname, yname, varargin)
% Computes the ROC curve from prediction results
%
% [x, y, thres] = roc_curve(scores, L0, xname, yname, ...);
%
% Computes the ROC curve from scores.
%
% Input arguments:
% - scores: The prediction scores.
% - L0: The ground-truth label of the scores. [logical]
% - xname: The name of quantity for x-axis
% - yname: The name of quantity for y-axis
%
% Output arguments:
% - x: The x-coordinates of the sampled points at curve
% - y: The y-coordinates of the sampled points at curve
% - thres: The corresponding thresholds
%
% Here, xname and yname can be chosen from either of the following:
% - 'tp': true-positive ratio = #[1->1] / #[*->1]
% - 'fp': false-positive ratio = #[0->1] / #[*->1]
% - 'tn': true-negative ratio = #[0->0] / #[*->0]
% - 'fn': false-negative ratio = #[1->0] / #[*->0]
% - 'precision': the retrieval precision = #[1->1] / #[*->1]
% - 'recall': the retrieval recall rate = #[1->1] / #[1->*]
%
% Here, #[i->j] means the number of samples whose ground-truth
% label is i and predicted label is j. i and j here can be either
% 0 (negative), 1 (positive), and * (both).
%
% Procedure description:
% - A sequence of thresholds are set up, with each threshold,
% the score above it is considered as positive, and the remaining
% are considered as negative. This procedure is implemented in
% an efficient way through a multi-bin histogram of scores.
% - According to these results, we compute the quantity specified
% by xname and yname respectively.
% - Via (linear) interpolation, we produce the y-values for the
% given x-values.
%
% One can specify following options to customize the behavior:
% - 'pred': How to make the prediction, which can be
% 'gt': predict 1 when score > threshold; (default)
% 'ge': predict 1 when score >= threshold;
% 'lt': predict 1 when score < threshold;
% 'le': predict 1 when score <= threshold;
%
% - 'sdensity': The sample density: the number of thresholds
% to sample. (default = 100).
% It can also be a sorted vector that explicitly
% gives the sequence of thresholds.
%
% Note the number of thresholds must be at least 3.
%
% History
% -------
% - Created by Dahua Lin, on April 24, 2011
%
%% verify input arguments
% basic args
if ~(isnumeric(scores) && isreal(scores))
error('roc_curve:invalidarg', 'scores should be a numeric array.');
end
if ~(islogical(L0) && isequal(size(L0), size(scores)))
error('roc_curve:invalidarg', ...
'L0 should be a logical array of the same size as scores.');
end
if ~(ischar(xname) && ischar(yname))
error('roc_curve:invalidarg', ...
'xname and yname should be both strings.');
end
xfunc = name_to_cfunc(xname);
yfunc = name_to_cfunc(yname);
% options
opts.pred = 'gt';
opts.sdensity = 100;
if ~isempty(varargin)
onames = varargin(1:2:end);
ovals = varargin(2:2:end);
if ~(numel(onames) == numel(ovals) && iscellstr(onames))
error('roc_curve:invalidarg', 'The options are not correctly given.');
end
for i = 1 : numel(onames)
cn = onames{i};
cv = ovals{i};
switch lower(cn)
case 'pred'
if ~(ischar(cv) && ismember(cv, {'gt', 'ge', 'lt', 'le'}))
error('roc_curve:invalidarg', ...
'The option pred is invalid.');
end
case 'interp'
if ~(ischar(cv) && ...
ismember(cv, {'cubic', 'spline', 'linear', 'nearest'}))
error('roc_curve:invalidarg', ...
'The option interp is invalid.');
end
case 'sdensity'
if (isnumeric(cv) && isreal(cv) && ...
(isscalar(cv) || isvector(cv)))
if isscalar(cv)
if cv < 3
error('roc_curve:invalidarg', ...
'sdensity must be at least 3.');
end
end
else
error('roc_curve:invalidarg', ...
'The option sdensity is invalid.');
end
otherwise
error('roc_curve:invalidarg', ...
'The option name %s is unknown', cn);
end
opts.(cn) = cv;
end
end
%% main
% sort and categorize score values
if ~(isvector(scores) && size(scores, 2) == 1)
scores = scores(:);
L0 = L0(:);
end
[scores, sord] = sort(scores);
L0 = L0(sord);
scores_t = scores(L0);
scores_f = scores(~L0);
clear sord;
% delimit scores into threshold bins
if isscalar(opts.sdensity)
thres = linspace(scores(1), scores(end), opts.sdensity);
else
thres = opts.sdensity;
end
switch opts.pred
case 'gt'
hdir = 'R';
cdir = 1;
case 'ge'
hdir = 'L';
cdir = 1;
case 'lt'
hdir = 'L';
cdir = -1;
case 'le'
hdir = 'R';
cdir = -1;
end
H_t = intcount([0, numel(thres)], pieces(scores_t, thres, hdir, 'sorted'));
H_f = intcount([0, numel(thres)], pieces(scores_f, thres, hdir, 'sorted'));
% calculate desired quantities
x = xfunc(H_t, H_f, cdir);
y = yfunc(H_t, H_f, cdir);
to_retain = ~isnan(x) & ~isnan(y);
x = x(to_retain);
y = y(to_retain);
thres = thres(to_retain);
%% Calculation functions
function f = name_to_cfunc(name)
switch lower(name)
case 'tp'
f = @calc_tp;
case 'tn'
f = @calc_tn;
case 'fp'
f = @calc_fp;
case 'fn'
f = @calc_fn;
case 'precision'
f = @calc_precision;
case 'recall'
f = @calc_recall;
otherwise
error('roc_curve:invalidarg', ...
'The quantity name %s is invalid', name);
end
function v = calc_tp(H_t, H_f, cdir)
v = csum(H_t, cdir) ./ csum(H_t + H_f, cdir);
function v = calc_tn(H_t, H_f, cdir)
v = csum(H_f, -cdir) ./ csum(H_t + H_f, -cdir);
function v = calc_fp(H_t, H_f, cdir)
v = csum(H_f, cdir) ./ csum(H_t + H_f, cdir);
function v = calc_fn(H_t, H_f, cdir)
v = csum(H_t, -cdir) ./ csum(H_t + H_f, -cdir);
function v = calc_precision(H_t, H_f, cdir)
v = csum(H_t, cdir) ./ csum(H_t + H_f, cdir);
function v = calc_recall(H_t, H_f, cdir) %#ok<INUSL>
v = csum(H_t, cdir) / sum(H_t);
function cs = csum(h, dir)
if dir > 0
cs = cumsum(h(end:-1:1));
cs = cs(end-1:-1:1);
else
cs = cumsum(h);
cs = cs(1:end-1);
end
| zzhangumd-smitoolbox | classics/classification/roc_curve.m | MATLAB | mit | 7,035 |
// WorldEditor.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "afxwinappex.h"
#include "WorldEditor.h"
#include "MainFrm.h"
#include "WorldEditorDoc.h"
#include "WorldEditorView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CWorldEditorApp
BEGIN_MESSAGE_MAP(CWorldEditorApp, CWinAppEx)
ON_COMMAND(ID_APP_ABOUT, &CWorldEditorApp::OnAppAbout)
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen)
END_MESSAGE_MAP()
// CWorldEditorApp construction
CWorldEditorApp::CWorldEditorApp()
{
m_bHiColorIcons = TRUE;
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CWorldEditorApp object
CWorldEditorApp theApp;
// CWorldEditorApp initialization
BOOL CWorldEditorApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinAppEx::InitInstance();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettings(4); // Load standard INI file options (including MRU)
InitContextMenuManager();
InitKeyboardManager();
InitTooltipManager();
CMFCToolTipInfo ttParams;
ttParams.m_bVislManagerTheme = TRUE;
theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL,
RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams);
// Register the application's document templates. Document templates
// serve as the connection between documents, frame windows and views
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CWorldEditorDoc),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CWorldEditorView));
if (!pDocTemplate)
return FALSE;
AddDocTemplate(pDocTemplate);
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Dispatch commands specified on the command line. Will return FALSE if
// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// The one and only window has been initialized, so show and update it
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
// call DragAcceptFiles only if there's a suffix
// In an SDI app, this should occur after ProcessShellCommand
return TRUE;
}
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// App command to run the dialog
void CWorldEditorApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CWorldEditorApp customization load/save methods
void CWorldEditorApp::PreLoadState()
{
BOOL bNameValid;
CString strName;
bNameValid = strName.LoadString(IDS_EDIT_MENU);
ASSERT(bNameValid);
GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT);
}
void CWorldEditorApp::LoadCustomState()
{
}
void CWorldEditorApp::SaveCustomState()
{
}
// CWorldEditorApp message handlers
| zz3d | WorldEditor/Src/MFCUI/WorldEditor.cpp | C++ | art | 4,363 |
// stdafx.cpp : source file that includes just the standard includes
// WorldEditor.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| zz3d | WorldEditor/Src/MFCUI/stdafx.cpp | C++ | art | 213 |
// WorldEditorDoc.h : interface of the CWorldEditorDoc class
//
#pragma once
class CWorldEditorDoc : public CDocument
{
protected: // create from serialization only
CWorldEditorDoc();
DECLARE_DYNCREATE(CWorldEditorDoc)
// Attributes
public:
// Operations
public:
// Overrides
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
// Implementation
public:
virtual ~CWorldEditorDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
DECLARE_MESSAGE_MAP()
};
| zz3d | WorldEditor/Src/MFCUI/WorldEditorDoc.h | C++ | art | 648 |
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by WorldEditor.rc
//
#define IDD_ABOUTBOX 100
#define IDR_POPUP_EDIT 119
#define ID_STATUSBAR_PANE1 120
#define ID_STATUSBAR_PANE2 121
#define IDS_STATUS_PANE1 122
#define IDS_STATUS_PANE2 123
#define IDS_TOOLBAR_STANDARD 124
#define IDS_TOOLBAR_CUSTOMIZE 125
#define ID_VIEW_CUSTOMIZE 126
#define IDR_MAINFRAME 128
#define IDR_MAINFRAME_256 129
#define IDR_WorldEditorTYPE 130
#define ID_VIEW_PROPERTIESWND 150
#define ID_SORTPROPERTIES 151
#define ID_PROPERTIES1 152
#define ID_PROPERTIES2 153
#define ID_EXPAND_ALL 154
#define IDS_PROPERTIES_WND 158
#define IDI_PROPERTIES_WND 167
#define IDI_PROPERTIES_WND_HC 168
#define IDR_PROPERTIES 183
#define IDB_PROPERTIES_HC 184
#define IDR_THEME_MENU 200
#define ID_SET_STYLE 201
#define ID_VIEW_APPLOOK_WIN_2000 210
#define ID_VIEW_APPLOOK_OFF_XP 211
#define ID_VIEW_APPLOOK_WIN_XP 212
#define ID_VIEW_APPLOOK_OFF_2003 213
#define ID_VIEW_APPLOOK_VS_2005 214
#define ID_VIEW_APPLOOK_OFF_2007_BLUE 215
#define ID_VIEW_APPLOOK_OFF_2007_BLACK 216
#define ID_VIEW_APPLOOK_OFF_2007_SILVER 217
#define ID_VIEW_APPLOOK_OFF_2007_AQUA 218
#define IDS_EDIT_MENU 306
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 310
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 310
#define _APS_NEXT_COMMAND_VALUE 32771
#endif
#endif
| zz3d | WorldEditor/Src/MFCUI/Resource.h | C | art | 1,555 |
// WorldEditor.h : main header file for the WorldEditor application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CWorldEditorApp:
// See WorldEditor.cpp for the implementation of this class
//
class CWorldEditorApp : public CWinAppEx
{
public:
CWorldEditorApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
UINT m_nAppLook;
BOOL m_bHiColorIcons;
virtual void PreLoadState();
virtual void LoadCustomState();
virtual void SaveCustomState();
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CWorldEditorApp theApp;
| zz3d | WorldEditor/Src/MFCUI/WorldEditor.h | C++ | art | 718 |
// MainFrm.h : interface of the CMainFrame class
//
#pragma once
#include "PropertiesWnd.h"
class CMainFrame : public CFrameWndEx
{
protected: // create from serialization only
CMainFrame();
DECLARE_DYNCREATE(CMainFrame)
// Attributes
public:
// Operations
public:
// Overrides
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual BOOL LoadFrame(UINT nIDResource, DWORD dwDefaultStyle = WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, CWnd* pParentWnd = NULL, CCreateContext* pContext = NULL);
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // control bar embedded members
CMFCMenuBar m_wndMenuBar;
CMFCToolBar m_wndToolBar;
CMFCStatusBar m_wndStatusBar;
CMFCToolBarImages m_UserImages;
CPropertiesWnd m_wndProperties;
// Generated message map functions
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnViewCustomize();
afx_msg LRESULT OnToolbarCreateNew(WPARAM wp, LPARAM lp);
afx_msg void OnApplicationLook(UINT id);
afx_msg void OnUpdateApplicationLook(CCmdUI* pCmdUI);
DECLARE_MESSAGE_MAP()
BOOL CreateDockingWindows();
void SetDockingWindowIcons(BOOL bHiColorIcons);
};
| zz3d | WorldEditor/Src/MFCUI/MainFrm.h | C++ | art | 1,325 |
// MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "WorldEditor.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWndEx)
const int iMaxUserToolbars = 10;
const UINT uiFirstUserToolBarId = AFX_IDW_CONTROLBAR_FIRST + 40;
const UINT uiLastUserToolBarId = uiFirstUserToolBarId + iMaxUserToolbars - 1;
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWndEx)
ON_WM_CREATE()
ON_COMMAND(ID_VIEW_CUSTOMIZE, &CMainFrame::OnViewCustomize)
ON_REGISTERED_MESSAGE(AFX_WM_CREATETOOLBAR, &CMainFrame::OnToolbarCreateNew)
ON_COMMAND_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_OFF_2007_AQUA, &CMainFrame::OnApplicationLook)
ON_UPDATE_COMMAND_UI_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_OFF_2007_AQUA, &CMainFrame::OnUpdateApplicationLook)
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
// TODO: add member initialization code here
theApp.m_nAppLook = theApp.GetInt(_T("ApplicationLook"), ID_VIEW_APPLOOK_VS_2005);
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWndEx::OnCreate(lpCreateStruct) == -1)
return -1;
BOOL bNameValid;
// set the visual manager and style based on persisted value
OnApplicationLook(theApp.m_nAppLook);
if (!m_wndMenuBar.Create(this))
{
TRACE0("Failed to create menubar\n");
return -1; // fail to create
}
m_wndMenuBar.SetPaneStyle(m_wndMenuBar.GetPaneStyle() | CBRS_SIZE_DYNAMIC | CBRS_TOOLTIPS | CBRS_FLYBY);
// prevent the menu bar from taking the focus on activation
CMFCPopupMenu::SetForceMenuFocus(FALSE);
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
CString strToolBarName;
bNameValid = strToolBarName.LoadString(IDS_TOOLBAR_STANDARD);
ASSERT(bNameValid);
m_wndToolBar.SetWindowText(strToolBarName);
CString strCustomize;
bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
ASSERT(bNameValid);
m_wndToolBar.EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
// Allow user-defined toolbars operations:
InitUserToolbars(NULL, uiFirstUserToolBarId, uiLastUserToolBarId);
if (!m_wndStatusBar.Create(this))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}
m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT));
// TODO: Delete these five lines if you don't want the toolbar and menubar to be dockable
m_wndMenuBar.EnableDocking(CBRS_ALIGN_ANY);
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockPane(&m_wndMenuBar);
DockPane(&m_wndToolBar);
// enable Visual Studio 2005 style docking window behavior
CDockingManager::SetDockingMode(DT_SMART);
// enable Visual Studio 2005 style docking window auto-hide behavior
EnableAutoHidePanes(CBRS_ALIGN_ANY);
// create docking windows
if (!CreateDockingWindows())
{
TRACE0("Failed to create docking windows\n");
return -1;
}
m_wndProperties.EnableDocking(CBRS_ALIGN_ANY);
DockPane(&m_wndProperties);
// Enable toolbar and docking window menu replacement
EnablePaneMenu(TRUE, ID_VIEW_CUSTOMIZE, strCustomize, ID_VIEW_TOOLBAR);
// enable quick (Alt+drag) toolbar customization
CMFCToolBar::EnableQuickCustomization();
if (CMFCToolBar::GetUserImages() == NULL)
{
// load user-defined toolbar images
if (m_UserImages.Load(_T(".\\UserImages.bmp")))
{
m_UserImages.SetImageSize(CSize(16, 16), FALSE);
CMFCToolBar::SetUserImages(&m_UserImages);
}
}
// enable menu personalization (most-recently used commands)
// TODO: define your own basic commands, ensuring that each pulldown menu has at least one basic command.
CList<UINT, UINT> lstBasicCommands;
lstBasicCommands.AddTail(ID_FILE_NEW);
lstBasicCommands.AddTail(ID_FILE_OPEN);
lstBasicCommands.AddTail(ID_FILE_SAVE);
lstBasicCommands.AddTail(ID_FILE_PRINT);
lstBasicCommands.AddTail(ID_APP_EXIT);
lstBasicCommands.AddTail(ID_EDIT_CUT);
lstBasicCommands.AddTail(ID_EDIT_PASTE);
lstBasicCommands.AddTail(ID_EDIT_UNDO);
lstBasicCommands.AddTail(ID_APP_ABOUT);
lstBasicCommands.AddTail(ID_VIEW_STATUS_BAR);
lstBasicCommands.AddTail(ID_VIEW_TOOLBAR);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2003);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_VS_2005);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_BLUE);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_SILVER);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_BLACK);
lstBasicCommands.AddTail(ID_VIEW_APPLOOK_OFF_2007_AQUA);
CMFCToolBar::SetBasicCommands(lstBasicCommands);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWndEx::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return TRUE;
}
BOOL CMainFrame::CreateDockingWindows()
{
BOOL bNameValid;
// Create properties window
CString strPropertiesWnd;
bNameValid = strPropertiesWnd.LoadString(IDS_PROPERTIES_WND);
ASSERT(bNameValid);
if (!m_wndProperties.Create(strPropertiesWnd, this, CRect(0, 0, 200, 200), TRUE, ID_VIEW_PROPERTIESWND, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | CBRS_RIGHT | CBRS_FLOAT_MULTI))
{
TRACE0("Failed to create Properties window\n");
return FALSE; // failed to create
}
SetDockingWindowIcons(theApp.m_bHiColorIcons);
return TRUE;
}
void CMainFrame::SetDockingWindowIcons(BOOL bHiColorIcons)
{
HICON hPropertiesBarIcon = (HICON) ::LoadImage(::AfxGetResourceHandle(), MAKEINTRESOURCE(bHiColorIcons ? IDI_PROPERTIES_WND_HC : IDI_PROPERTIES_WND), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), 0);
m_wndProperties.SetIcon(hPropertiesBarIcon, FALSE);
}
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWndEx::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWndEx::Dump(dc);
}
#endif //_DEBUG
// CMainFrame message handlers
void CMainFrame::OnViewCustomize()
{
CMFCToolBarsCustomizeDialog* pDlgCust = new CMFCToolBarsCustomizeDialog(this, TRUE /* scan menus */);
pDlgCust->EnableUserDefinedToolbars();
pDlgCust->Create();
}
LRESULT CMainFrame::OnToolbarCreateNew(WPARAM wp,LPARAM lp)
{
LRESULT lres = CFrameWndEx::OnToolbarCreateNew(wp,lp);
if (lres == 0)
{
return 0;
}
CMFCToolBar* pUserToolbar = (CMFCToolBar*)lres;
ASSERT_VALID(pUserToolbar);
BOOL bNameValid;
CString strCustomize;
bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
ASSERT(bNameValid);
pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
return lres;
}
void CMainFrame::OnApplicationLook(UINT id)
{
CWaitCursor wait;
theApp.m_nAppLook = id;
switch (theApp.m_nAppLook)
{
case ID_VIEW_APPLOOK_WIN_2000:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManager));
break;
case ID_VIEW_APPLOOK_OFF_XP:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOfficeXP));
break;
case ID_VIEW_APPLOOK_WIN_XP:
CMFCVisualManagerWindows::m_b3DTabsXPTheme = TRUE;
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
break;
case ID_VIEW_APPLOOK_OFF_2003:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2003));
CDockingManager::SetDockingMode(DT_SMART);
break;
case ID_VIEW_APPLOOK_VS_2005:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2005));
CDockingManager::SetDockingMode(DT_SMART);
break;
default:
switch (theApp.m_nAppLook)
{
case ID_VIEW_APPLOOK_OFF_2007_BLUE:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_LunaBlue);
break;
case ID_VIEW_APPLOOK_OFF_2007_BLACK:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_ObsidianBlack);
break;
case ID_VIEW_APPLOOK_OFF_2007_SILVER:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Silver);
break;
case ID_VIEW_APPLOOK_OFF_2007_AQUA:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Aqua);
break;
}
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2007));
CDockingManager::SetDockingMode(DT_SMART);
}
RedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_FRAME | RDW_ERASE);
theApp.WriteInt(_T("ApplicationLook"), theApp.m_nAppLook);
}
void CMainFrame::OnUpdateApplicationLook(CCmdUI* pCmdUI)
{
pCmdUI->SetRadio(theApp.m_nAppLook == pCmdUI->m_nID);
}
BOOL CMainFrame::LoadFrame(UINT nIDResource, DWORD dwDefaultStyle, CWnd* pParentWnd, CCreateContext* pContext)
{
// base class does the real work
if (!CFrameWndEx::LoadFrame(nIDResource, dwDefaultStyle, pParentWnd, pContext))
{
return FALSE;
}
// enable customization button for all user toolbars
BOOL bNameValid;
CString strCustomize;
bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE);
ASSERT(bNameValid);
for (int i = 0; i < iMaxUserToolbars; i ++)
{
CMFCToolBar* pUserToolbar = GetUserToolBarByIndex(i);
if (pUserToolbar != NULL)
{
pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize);
}
}
return TRUE;
}
| zz3d | WorldEditor/Src/MFCUI/MainFrm.cpp | C++ | art | 9,911 |
// WorldEditorView.cpp : implementation of the CWorldEditorView class
//
#include "stdafx.h"
#include "WorldEditor.h"
#include "WorldEditorDoc.h"
#include "WorldEditorView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CWorldEditorView
IMPLEMENT_DYNCREATE(CWorldEditorView, CView)
BEGIN_MESSAGE_MAP(CWorldEditorView, CView)
END_MESSAGE_MAP()
// CWorldEditorView construction/destruction
CWorldEditorView::CWorldEditorView()
{
// TODO: add construction code here
}
CWorldEditorView::~CWorldEditorView()
{
}
BOOL CWorldEditorView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
// CWorldEditorView drawing
void CWorldEditorView::OnDraw(CDC* /*pDC*/)
{
CWorldEditorDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: add draw code for native data here
}
void CWorldEditorView::OnRButtonUp(UINT nFlags, CPoint point)
{
ClientToScreen(&point);
OnContextMenu(this, point);
}
void CWorldEditorView::OnContextMenu(CWnd* pWnd, CPoint point)
{
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE);
}
// CWorldEditorView diagnostics
#ifdef _DEBUG
void CWorldEditorView::AssertValid() const
{
CView::AssertValid();
}
void CWorldEditorView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CWorldEditorDoc* CWorldEditorView::GetDocument() const // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CWorldEditorDoc)));
return (CWorldEditorDoc*)m_pDocument;
}
#endif //_DEBUG
// CWorldEditorView message handlers
| zz3d | WorldEditor/Src/MFCUI/WorldEditorView.cpp | C++ | art | 1,728 |
#pragma once
class CPropertiesToolBar : public CMFCToolBar
{
public:
virtual void OnUpdateCmdUI(CFrameWnd* /*pTarget*/, BOOL bDisableIfNoHndler)
{
CMFCToolBar::OnUpdateCmdUI((CFrameWnd*) GetOwner(), bDisableIfNoHndler);
}
virtual BOOL AllowShowOnList() const { return FALSE; }
};
class CPropertiesWnd : public CDockablePane
{
// Construction
public:
CPropertiesWnd();
void AdjustLayout();
// Attributes
public:
void SetVSDotNetLook(BOOL bSet)
{
m_wndPropList.SetVSDotNetLook(bSet);
m_wndPropList.SetGroupNameFullWidth(bSet);
}
protected:
CFont m_fntPropList;
CComboBox m_wndObjectCombo;
CPropertiesToolBar m_wndToolBar;
CMFCPropertyGridCtrl m_wndPropList;
// Implementation
public:
virtual ~CPropertiesWnd();
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnExpandAllProperties();
afx_msg void OnUpdateExpandAllProperties(CCmdUI* pCmdUI);
afx_msg void OnSortProperties();
afx_msg void OnUpdateSortProperties(CCmdUI* pCmdUI);
afx_msg void OnProperties1();
afx_msg void OnUpdateProperties1(CCmdUI* pCmdUI);
afx_msg void OnProperties2();
afx_msg void OnUpdateProperties2(CCmdUI* pCmdUI);
afx_msg void OnSetFocus(CWnd* pOldWnd);
afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection);
DECLARE_MESSAGE_MAP()
void InitPropList();
void SetPropListFont();
};
| zz3d | WorldEditor/Src/MFCUI/PropertiesWnd.h | C++ | art | 1,445 |
#include "stdafx.h"
#include "PropertiesWnd.h"
#include "Resource.h"
#include "MainFrm.h"
#include "WorldEditor.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
/////////////////////////////////////////////////////////////////////////////
// CResourceViewBar
CPropertiesWnd::CPropertiesWnd()
{
}
CPropertiesWnd::~CPropertiesWnd()
{
}
BEGIN_MESSAGE_MAP(CPropertiesWnd, CDockablePane)
ON_WM_CREATE()
ON_WM_SIZE()
ON_COMMAND(ID_EXPAND_ALL, OnExpandAllProperties)
ON_UPDATE_COMMAND_UI(ID_EXPAND_ALL, OnUpdateExpandAllProperties)
ON_COMMAND(ID_SORTPROPERTIES, OnSortProperties)
ON_UPDATE_COMMAND_UI(ID_SORTPROPERTIES, OnUpdateSortProperties)
ON_COMMAND(ID_PROPERTIES1, OnProperties1)
ON_UPDATE_COMMAND_UI(ID_PROPERTIES1, OnUpdateProperties1)
ON_COMMAND(ID_PROPERTIES2, OnProperties2)
ON_UPDATE_COMMAND_UI(ID_PROPERTIES2, OnUpdateProperties2)
ON_WM_SETFOCUS()
ON_WM_SETTINGCHANGE()
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CResourceViewBar message handlers
void CPropertiesWnd::AdjustLayout()
{
if (GetSafeHwnd() == NULL)
{
return;
}
CRect rectClient,rectCombo;
GetClientRect(rectClient);
m_wndObjectCombo.GetWindowRect(&rectCombo);
int cyCmb = rectCombo.Size().cy;
int cyTlb = m_wndToolBar.CalcFixedLayout(FALSE, TRUE).cy;
m_wndObjectCombo.SetWindowPos(NULL, rectClient.left, rectClient.top, rectClient.Width(), 200, SWP_NOACTIVATE | SWP_NOZORDER);
m_wndToolBar.SetWindowPos(NULL, rectClient.left, rectClient.top + cyCmb, rectClient.Width(), cyTlb, SWP_NOACTIVATE | SWP_NOZORDER);
m_wndPropList.SetWindowPos(NULL, rectClient.left, rectClient.top + cyCmb + cyTlb, rectClient.Width(), rectClient.Height() -(cyCmb+cyTlb), SWP_NOACTIVATE | SWP_NOZORDER);
}
int CPropertiesWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDockablePane::OnCreate(lpCreateStruct) == -1)
return -1;
CRect rectDummy;
rectDummy.SetRectEmpty();
// Create combo:
const DWORD dwViewStyle = WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST | WS_BORDER | CBS_SORT | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
if (!m_wndObjectCombo.Create(dwViewStyle, rectDummy, this, 1))
{
TRACE0("Failed to create Properties Combo \n");
return -1; // fail to create
}
m_wndObjectCombo.AddString(_T("Application"));
m_wndObjectCombo.AddString(_T("Properties Window"));
m_wndObjectCombo.SetFont(CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)));
m_wndObjectCombo.SetCurSel(0);
if (!m_wndPropList.Create(WS_VISIBLE | WS_CHILD, rectDummy, this, 2))
{
TRACE0("Failed to create Properties Grid \n");
return -1; // fail to create
}
InitPropList();
m_wndToolBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_PROPERTIES);
m_wndToolBar.LoadToolBar(IDR_PROPERTIES, 0, 0, TRUE /* Is locked */);
m_wndToolBar.CleanUpLockedImages();
m_wndToolBar.LoadBitmap(theApp.m_bHiColorIcons ? IDB_PROPERTIES_HC : IDR_PROPERTIES, 0, 0, TRUE /* Locked */);
m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() | CBRS_TOOLTIPS | CBRS_FLYBY);
m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() & ~(CBRS_GRIPPER | CBRS_SIZE_DYNAMIC | CBRS_BORDER_TOP | CBRS_BORDER_BOTTOM | CBRS_BORDER_LEFT | CBRS_BORDER_RIGHT));
m_wndToolBar.SetOwner(this);
// All commands will be routed via this control , not via the parent frame:
m_wndToolBar.SetRouteCommandsViaFrame(FALSE);
AdjustLayout();
return 0;
}
void CPropertiesWnd::OnSize(UINT nType, int cx, int cy)
{
CDockablePane::OnSize(nType, cx, cy);
AdjustLayout();
}
void CPropertiesWnd::OnExpandAllProperties()
{
m_wndPropList.ExpandAll();
}
void CPropertiesWnd::OnUpdateExpandAllProperties(CCmdUI* pCmdUI)
{
}
void CPropertiesWnd::OnSortProperties()
{
m_wndPropList.SetAlphabeticMode(!m_wndPropList.IsAlphabeticMode());
}
void CPropertiesWnd::OnUpdateSortProperties(CCmdUI* pCmdUI)
{
pCmdUI->SetCheck(m_wndPropList.IsAlphabeticMode());
}
void CPropertiesWnd::OnProperties1()
{
// TODO: Add your command handler code here
}
void CPropertiesWnd::OnUpdateProperties1(CCmdUI* /*pCmdUI*/)
{
// TODO: Add your command update UI handler code here
}
void CPropertiesWnd::OnProperties2()
{
// TODO: Add your command handler code here
}
void CPropertiesWnd::OnUpdateProperties2(CCmdUI* /*pCmdUI*/)
{
// TODO: Add your command update UI handler code here
}
void CPropertiesWnd::InitPropList()
{
SetPropListFont();
m_wndPropList.EnableHeaderCtrl(FALSE);
m_wndPropList.EnableDescriptionArea();
m_wndPropList.SetVSDotNetLook();
m_wndPropList.MarkModifiedProperties();
CMFCPropertyGridProperty* pGroup1 = new CMFCPropertyGridProperty(_T("Appearance"));
pGroup1->AddSubItem(new CMFCPropertyGridProperty(_T("3D Look"), (_variant_t) false, _T("Specifies the window's font will be non-bold and controls will have a 3D border")));
CMFCPropertyGridProperty* pProp = new CMFCPropertyGridProperty(_T("Border"), _T("Dialog Frame"), _T("One of: None, Thin, Resizable, or Dialog Frame"));
pProp->AddOption(_T("None"));
pProp->AddOption(_T("Thin"));
pProp->AddOption(_T("Resizable"));
pProp->AddOption(_T("Dialog Frame"));
pProp->AllowEdit(FALSE);
pGroup1->AddSubItem(pProp);
pGroup1->AddSubItem(new CMFCPropertyGridProperty(_T("Caption"), (_variant_t) _T("About"), _T("Specifies the text that will be displayed in the window's title bar")));
m_wndPropList.AddProperty(pGroup1);
CMFCPropertyGridProperty* pSize = new CMFCPropertyGridProperty(_T("Window Size"), 0, TRUE);
pProp = new CMFCPropertyGridProperty(_T("Height"), (_variant_t) 250l, _T("Specifies the window's height"));
pProp->EnableSpinControl(TRUE, 50, 300);
pSize->AddSubItem(pProp);
pProp = new CMFCPropertyGridProperty( _T("Width"), (_variant_t) 150l, _T("Specifies the window's width"));
pProp->EnableSpinControl(TRUE, 50, 200);
pSize->AddSubItem(pProp);
m_wndPropList.AddProperty(pSize);
CMFCPropertyGridProperty* pGroup2 = new CMFCPropertyGridProperty(_T("Font"));
LOGFONT lf;
CFont* font = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT));
font->GetLogFont(&lf);
lstrcpy(lf.lfFaceName, _T("Arial"));
pGroup2->AddSubItem(new CMFCPropertyGridFontProperty(_T("Font"), lf, CF_EFFECTS | CF_SCREENFONTS, _T("Specifies the default font for the window")));
pGroup2->AddSubItem(new CMFCPropertyGridProperty(_T("Use System Font"), (_variant_t) true, _T("Specifies that the window uses MS Shell Dlg font")));
m_wndPropList.AddProperty(pGroup2);
CMFCPropertyGridProperty* pGroup3 = new CMFCPropertyGridProperty(_T("Misc"));
pProp = new CMFCPropertyGridProperty(_T("(Name)"), _T("Application"));
pProp->Enable(FALSE);
pGroup3->AddSubItem(pProp);
CMFCPropertyGridColorProperty* pColorProp = new CMFCPropertyGridColorProperty(_T("Window Color"), RGB(210, 192, 254), NULL, _T("Specifies the default window color"));
pColorProp->EnableOtherButton(_T("Other..."));
pColorProp->EnableAutomaticButton(_T("Default"), ::GetSysColor(COLOR_3DFACE));
pGroup3->AddSubItem(pColorProp);
static TCHAR BASED_CODE szFilter[] = _T("Icon Files(*.ico)|*.ico|All Files(*.*)|*.*||");
pGroup3->AddSubItem(new CMFCPropertyGridFileProperty(_T("Icon"), TRUE, _T(""), _T("ico"), 0, szFilter, _T("Specifies the window icon")));
pGroup3->AddSubItem(new CMFCPropertyGridFileProperty(_T("Folder"), _T("c:\\")));
m_wndPropList.AddProperty(pGroup3);
CMFCPropertyGridProperty* pGroup4 = new CMFCPropertyGridProperty(_T("Hierarchy"));
CMFCPropertyGridProperty* pGroup41 = new CMFCPropertyGridProperty(_T("First sub-level"));
pGroup4->AddSubItem(pGroup41);
CMFCPropertyGridProperty* pGroup411 = new CMFCPropertyGridProperty(_T("Second sub-level"));
pGroup41->AddSubItem(pGroup411);
pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("Item 1"), (_variant_t) _T("Value 1"), _T("This is a description")));
pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("Item 2"), (_variant_t) _T("Value 2"), _T("This is a description")));
pGroup411->AddSubItem(new CMFCPropertyGridProperty(_T("Item 3"), (_variant_t) _T("Value 3"), _T("This is a description")));
pGroup4->Expand(FALSE);
m_wndPropList.AddProperty(pGroup4);
}
void CPropertiesWnd::OnSetFocus(CWnd* pOldWnd)
{
CDockablePane::OnSetFocus(pOldWnd);
m_wndPropList.SetFocus();
}
void CPropertiesWnd::OnSettingChange(UINT uFlags, LPCTSTR lpszSection)
{
CDockablePane::OnSettingChange(uFlags, lpszSection);
SetPropListFont();
}
void CPropertiesWnd::SetPropListFont()
{
::DeleteObject(m_fntPropList.Detach());
LOGFONT lf;
afxGlobalData.fontRegular.GetLogFont(&lf);
NONCLIENTMETRICS info;
info.cbSize = sizeof(info);
afxGlobalData.GetNonClientMetrics(info);
lf.lfHeight = info.lfMenuFont.lfHeight;
lf.lfWeight = info.lfMenuFont.lfWeight;
lf.lfItalic = info.lfMenuFont.lfItalic;
m_fntPropList.CreateFontIndirect(&lf);
m_wndPropList.SetFont(&m_fntPropList);
}
| zz3d | WorldEditor/Src/MFCUI/PropertiesWnd.cpp | C++ | art | 9,058 |
// WorldEditorView.h : interface of the CWorldEditorView class
//
#pragma once
class CWorldEditorView : public CView
{
protected: // create from serialization only
CWorldEditorView();
DECLARE_DYNCREATE(CWorldEditorView)
// Attributes
public:
CWorldEditorDoc* GetDocument() const;
// Operations
public:
// Overrides
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
// Implementation
public:
virtual ~CWorldEditorView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
afx_msg void OnFilePrintPreview();
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in WorldEditorView.cpp
inline CWorldEditorDoc* CWorldEditorView::GetDocument() const
{ return reinterpret_cast<CWorldEditorDoc*>(m_pDocument); }
#endif
| zz3d | WorldEditor/Src/MFCUI/WorldEditorView.h | C++ | art | 1,086 |
#pragma once
// The following macros define the minimum required platform. The minimum required platform
// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
// your application. The macros work by enabling all features available on platform versions up to and
// including the version specified.
// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER // Specifies that the minimum required platform is Windows Vista.
#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif
#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0.
#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE.
#endif
| zz3d | WorldEditor/Src/MFCUI/targetver.h | C | art | 1,432 |
// WorldEditorDoc.cpp : implementation of the CWorldEditorDoc class
//
#include "stdafx.h"
#include "WorldEditor.h"
#include "WorldEditorDoc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CWorldEditorDoc
IMPLEMENT_DYNCREATE(CWorldEditorDoc, CDocument)
BEGIN_MESSAGE_MAP(CWorldEditorDoc, CDocument)
END_MESSAGE_MAP()
// CWorldEditorDoc construction/destruction
CWorldEditorDoc::CWorldEditorDoc()
{
// TODO: add one-time construction code here
}
CWorldEditorDoc::~CWorldEditorDoc()
{
}
BOOL CWorldEditorDoc::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;
// TODO: add reinitialization code here
// (SDI documents will reuse this document)
return TRUE;
}
// CWorldEditorDoc serialization
void CWorldEditorDoc::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
// TODO: add storing code here
}
else
{
// TODO: add loading code here
}
}
// CWorldEditorDoc diagnostics
#ifdef _DEBUG
void CWorldEditorDoc::AssertValid() const
{
CDocument::AssertValid();
}
void CWorldEditorDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
// CWorldEditorDoc commands
| zz3d | WorldEditor/Src/MFCUI/WorldEditorDoc.cpp | C++ | art | 1,212 |
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently,
// but are changed infrequently
#pragma once
#ifndef _SECURE_ATL
#define _SECURE_ATL 1
#endif
#ifndef VC_EXTRALEAN
#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
#endif
#include "targetver.h"
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
// turns off MFC's hiding of some common and often safely ignored warning messages
#define _AFX_ALL_WARNINGS
#include <afxwin.h> // MFC core and standard components
#include <afxext.h> // MFC extensions
#ifndef _AFX_NO_OLE_SUPPORT
#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls
#endif
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT
#include <afxcontrolbars.h> // MFC support for ribbons and control bars
#ifdef _UNICODE
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_IA64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
#endif
| zz3d | WorldEditor/Src/MFCUI/stdafx.h | C | art | 1,974 |
#pragma once
#ifdef ZZ3D_EXPORTS
#define ZZ3D_API __declspec(dllexport)
#else
#define ZZ3D_API __declspec(dllimport)
#endif
#include <D3D9.h>
#include <d3dx9math.h>
#pragma comment(lib,"d3d9.lib")
#pragma comment(lib,"d3dx9.lib")
#include <Windows.h> | zz3d | Kernel/Src/Kernel.h | C | art | 266 |
#include "CameraBase.h"
CameraBase::CameraBase()
{
}
CameraBase::~CameraBase()
{
}
void CameraBase::setCamera( D3DXVECTOR3 from,D3DXVECTOR3 to,D3DXVECTOR3 up )
{
} | zz3d | Kernel/Src/Camera/CameraBase.cpp | C++ | art | 186 |
#pragma once
#include "D3dx9math.h"
class CameraBase
{
public:
CameraBase();
virtual ~CameraBase();
void setCamera(D3DXVECTOR3 from,D3DXVECTOR3 to,D3DXVECTOR3 up);
protected:
D3DXVECTOR3 mPos;
D3DXVECTOR3 mLookAt;
D3DXVECTOR3 mUp;
D3DXMATRIX mMatView;
D3DXMATRIX mMatProj;
}; | zz3d | Kernel/Src/Camera/CameraBase.h | C++ | art | 309 |
#pragma once
#include "../Kernel.h"
struct DeviceCfg
{
DeviceCfg()
{
memset(this,0,sizeof(DeviceCfg));
mIsWindowed = true;
mMultiSampleType = D3DMULTISAMPLE_NONE;
}
bool mIsWindowed;
unsigned int mWidth;
unsigned int mHeight;
unsigned int mFullScreenHZ;
HWND mWnd;
bool mIsVerticalSync;
D3DMULTISAMPLE_TYPE mMultiSampleType;
};
class D3Device
{
public:
D3Device();
~D3Device();
static const DWORD MINI_VSVERSION=D3DVS_VERSION(1,1); //vertex shader version required
static const DWORD MINI_PSVERSION=D3DPS_VERSION(1,4); //pixel shader version required
public:
IDirect3DDevice9* createDevice(const DeviceCfg& cfg);
private:
DWORD findBestBehaviorFlags();
void findBestPresentParam(const DeviceCfg& cfg,D3DPRESENT_PARAMETERS& pParam);
private:
IDirect3D9* mDevice;
IDirect3DDevice9* mD3DDevice;
}; | zz3d | Kernel/Src/Device/D3D9Device.h | C++ | art | 899 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package res;
/**
*
* @author EnzoZhong
*/
public class Res {
}
| zzblog | src/java/res/Res.java | Java | asf20 | 189 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back;
import e.z.blog.back.setup.IntallSetup;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Encoding;
import org.nutz.mvc.annotation.IocBy;
import org.nutz.mvc.annotation.Modules;
import org.nutz.mvc.annotation.SetupBy;
import org.nutz.mvc.ioc.provider.ComboIocProvider;
/**
*
* @author EnzoZhong
*/
@At("/back")
@SetupBy( IntallSetup.class )
@Modules( scanPackage = true )
@Encoding( input = "utf-8" , output = "utf-8" )
@IocBy( type = ComboIocProvider.class ,
args = { "*org.nutz.ioc.loader.json.JsonLoader" ,
"dao.json" ,
"service.json" ,
"*org.nutz.ioc.loader.annotation.AnnotationIocLoader" ,
"e.z"
} )
public class Mvc {
}
| zzblog | src/java/e/z/blog/back/Mvc.java | Java | asf20 | 878 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com;
import javax.servlet.http.HttpServletRequest;
/**
*
* @author EnzoZhong
*/
public interface ComGetIpApi {
/**
*
* @param request
* @return
*/
String getIP(HttpServletRequest request);
}
| zzblog | src/java/e/z/blog/back/com/ComGetIpApi.java | Java | asf20 | 393 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com;
import e.z.blog.back.bean.base.Tag;
/**
*
* @author EnzoZhong
*/
public interface DaoTagApi extends DaoBaseApi<Tag> {
}
| zzblog | src/java/e/z/blog/back/com/DaoTagApi.java | Java | asf20 | 266 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com;
import e.z.blog.back.bean.base.Tab;
/**
*
* @author EnzoZhong
*/
public interface DaoTabApi extends DaoBaseApi<Tab> {
}
| zzblog | src/java/e/z/blog/back/com/DaoTabApi.java | Java | asf20 | 266 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com;
import java.util.List;
/**
*
* @param <Type> < p/> thor Enzo
*/
public interface DaoBaseApi<Type> {
/**
*
*/
String CREATE = "create";
/**
*
*/
String READ_ALL = "read";
/**
*
*/
String READ_BY_ID = "readById";
/**
*
*/
String READ_SON_BY_ID = "readSonById";
/**
*
*/
String UPDATE = "update";
/**
*
*/
String DELETE = "delete";
//状态
/**
*
*/
String SUCCESS = "成功";
/**
*
*/
String FAIL = "失败";
Type create ( Type type );
Type read ( Type type );
List<Type> readAll ();
Type update ( Type type );
Type delete ( Type type );
}
| zzblog | src/java/e/z/blog/back/com/DaoBaseApi.java | Java | asf20 | 1,054 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com.impl;
import e.z.blog.back.com.ComNavTreeApi;
import java.util.HashMap;
import java.util.Map;
import org.nutz.ioc.loader.annotation.IocBean;
import z.h.w.jar.data.tree.ReferTree;
import z.h.w.jar.kit.To;
/**
* 该类暂时输出固定的树,以后实现了权限管理后,就实现根据角色不同,分发不同的目录资源
*
* @author EnzoZhong
*/
@IocBean
public class ComNavTree implements ComNavTreeApi {
/**
* 暂时这是管理员的树目录,以后写了权限系统后,就根据权限不同分发不同的资源
*
* @return
*/
@Override
public ReferTree<Map<String , String>> getNavTree () {
Map<String , String> ROOT = createMap( "ROOT" );
ReferTree<Map<String , String>> tree = new ReferTree( ROOT );
tree.add( To.objs2Array(
createMap( "首页" , "/back/index" , "_self" ) ,
createMap( "Blog操控" ) ,
createMap( "系统操控" ) ,
createMap( "退出" , "/back" , "_self" ) ) , ROOT );
tree.add( To.objs2Array(
createMap( "语言管理" ) ,
createMap( "目录管理" ) ,
createMap( "标签管理" ) ,
createMap( "文章管理" ) ,
createMap( "留言管理" ) ) , createMap( "Blog操控" ) );
tree.add( To.objs2Array(
createMap( "语言Crud" , "/back/lan" ) ) , createMap( "语言管理" ) );
tree.add( To.objs2Array(
createMap( "目录Crud" , "/back/tab" ) ) , createMap( "目录管理" ) );
tree.add( To.objs2Array(
createMap( "标签Crud" , "/back/tag" ) ) , createMap( "标签管理" ) );
tree.add( To.objs2Array(
createMap( "文章Crud" , "/back/essay" ) ) , createMap( "文章管理" ) );
tree.add( To.objs2Array(
createMap( "留言Crud" , "/back/remark" ) ) , createMap( "留言管理" ) );
/*
* -----------------------------------------系统目录类--------------------------------------
*/
tree.add( To.objs2Array(
createMap( "模板管理" ) ) , createMap( "系统操控" ) );
return tree;
}
/**
*
* @param name < p/>
* <p/>
* @return
*/
public static Map<String , String> createMap ( String name ) {
return createMap( name , "" , "" );
}
/**
*
* @param name param href
* <p/>
* @return
*/
public static Map<String , String> createMap ( String name , String href ) {
return createMap( name , href , "" );
}
/**
*
* @param name param href param target
* <p/>
* @return
*/
public static Map<String , String> createMap ( String name , String href , String target ) {
Map<String , String> re = new HashMap();
re.put( "name" , name );
re.put( "url" , href );
if ( target.equalsIgnoreCase( "" ) ) {
re.put( "target" , "myFrame" );
} else {
re.put( "target" , target );
}
return re;
}
}
| zzblog | src/java/e/z/blog/back/com/impl/ComNavTree.java | Java | asf20 | 3,823 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com.impl;
import e.z.blog.back.com.ComDataTableApi;
import java.lang.reflect.Field;
import java.util.*;
import org.nutz.dao.entity.annotation.Comment;
import org.nutz.ioc.loader.annotation.IocBean;
import z.h.w.jar.kit.Self;
import z.h.w.jar.kit.Text;
import z.h.w.jar.kit.To;
/**
*
* @author EnzoZhong
*/
@IocBean( singleton = false )
public class ComDataTable implements ComDataTableApi {
private Map<String , Field> fieldMap;
@Override
public Map<String , Field> ini ( Class clazz , String... fieldNameArray ) {
fieldMap = new LinkedHashMap();
Stack<String> nameStack = To.objs2Stack( fieldNameArray );
Stack<Field> fieldStack = Self.getFieldStack( clazz );
while ( !fieldStack.isEmpty() ) {
Field field = fieldStack.pop();
for ( String name : nameStack ) {
String fieldName = field.getName().toLowerCase();
if ( fieldName.equalsIgnoreCase( name.toLowerCase() ) ) {
field.setAccessible( true );
fieldMap.put( name , field );
}
}
}
return fieldMap;
}
@Override
public List<String> getValueList ( Object obj , String... fieldName ) {
if ( fieldMap == null ) {
fieldMap = ini( obj.getClass() , fieldName );
}
List<String> stringList = new ArrayList();
for ( String name : fieldName ) {
Field field = fieldMap.get( name );
System.out.println( name );
System.out.println( field );
String string;
try {
Object value = field.get( obj );
string = value.toString();
} catch ( IllegalArgumentException ex ) {
string = "IllegalArgumentException";
} catch ( IllegalAccessException ex ) {
string = "IllegalAccessException";
}
stringList.add( string );
}
return stringList;
}
@Override
public String getTitleList ( Class clazz , String... fieldName ) {
if ( fieldMap == null ) {
fieldMap = ini( clazz , fieldName );
}
List<Map<String , String>> mapList = new ArrayList();
Collection<Field> fieldColl = fieldMap.values();
for ( Field field : fieldColl ) {
HashMap<String , String> hashMap = new HashMap<String , String>();
String key = Text.toStr( "sTitle" );
String value = Text.toStr( field.getAnnotation( Comment.class ).value() );
hashMap.put( key , value );
mapList.add( hashMap );
}
Collections.reverse( mapList );
return mapList.toString().replaceAll( "=" , ":" );
}
}
| zzblog | src/java/e/z/blog/back/com/impl/ComDataTable.java | Java | asf20 | 3,543 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com.impl;
import e.z.blog.back.com.ComGetLocaleApi;
import java.util.Collection;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import org.nutz.ioc.loader.annotation.IocBean;
/**
*
* @author EnzoZhong
*/
@IocBean
public class ComGetLocale implements ComGetLocaleApi {
@Override
public Collection<String> getLocale () {
Set<String> localeSet = new TreeSet();
for ( Locale locale : Locale.getAvailableLocales() ) {
localeSet.add( locale.toString() );
}
return localeSet;
}
}
| zzblog | src/java/e/z/blog/back/com/impl/ComGetLocale.java | Java | asf20 | 768 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com.impl;
import e.z.blog.back.com.ComGetIpApi;
import javax.servlet.http.HttpServletRequest;
import org.nutz.ioc.loader.annotation.IocBean;
/**
*
* @author EnzoZhong
*/
@IocBean
public class ComGetIp implements ComGetIpApi {
/**
*
*/
public ComGetIp() {
}
/**
*
* @param request
* @return
*/
@Override
public String getIP( HttpServletRequest request ) {
String ip = request.getHeader( "X-Forwarded-For" );
if ( ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase( ip ) ) {
ip = request.getHeader( "Proxy-Client-IP" );
}
if ( ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase( ip ) ) {
ip = request.getHeader( "WL-Proxy-Client-IP" );
}
if ( ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase( ip ) ) {
ip = request.getHeader( "HTTP_CLIENT_IP" );
}
if ( ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase( ip ) ) {
ip = request.getHeader( "HTTP_X_FORWARDED_FOR" );
}
if ( ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase( ip ) ) {
ip = request.getRemoteAddr();
}
return ip;
}
}
| zzblog | src/java/e/z/blog/back/com/impl/ComGetIp.java | Java | asf20 | 1,633 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com.impl;
import e.z.blog.back.com.ComFixNutzStringBugApi;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.nutz.ioc.loader.annotation.IocBean;
import z.h.w.jar.kit.Text;
/**
*
* @author EnzoZhong
*/
@IocBean( singleton = false )
public class ComFixNutzStringBug implements ComFixNutzStringBugApi {
@Override
public Map<String , String> fixString ( Map<String , String> map ) {
Map<String , String> translate = new HashMap();
Set<String> keySet = map.keySet();
for ( String str : keySet ) {
translate.put( Text.toStr( str ) , Text.toStr( map.get( str ) ) );
}
return translate;
}
}
| zzblog | src/java/e/z/blog/back/com/impl/ComFixNutzStringBug.java | Java | asf20 | 900 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com.impl;
import e.z.blog.back.com.ComVerfiyCodeApi;
import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.nutz.ioc.loader.annotation.IocBean;
import z.h.w.jar.data.time.Attr;
import z.h.w.jar.data.time.Time;
import z.h.w.jar.kit.Roll;
import z.h.w.jar.kit.To;
import z.h.w.jar.kit.code.String2Code;
/**
*
* @author EnzoZhong 验证码生成和验证
*/
@IocBean
public class ComVerfiyCode implements ComVerfiyCodeApi {
final String VERFIY_CODE_ANSWER = "_验证码的答案_";
private Map<String , String> test = createTest();
private Map<String , String> createTest () {
Map<String , String> map = new HashMap();
Time time = Time.born();
// map.put( "今年什么生肖?" , time.tell( Attr.ZODIAC ) );
// map.put( "现在是什么座?" , time.tell( Attr.HOROSCOPE ) );
// map.put( "现在几月份?" , time.tell( Attr.MONTH ) );
// map.put( "现在几年?" , time.tell( Attr.YEAR ) );
// map.put( "现在什么季节?" , time.tell( Attr.SEASON ) );
map.put( "How Old Are U??" , Time.howOldAmI().toString() );
map.put( "Quanti Anni Hai??" , Time.howOldAmI().toString() );
return map;
}
/**
* 数据库中获取所有的domanda,从中随机一个出来生成验证码
* <p/>
* @param session < p/>
* <p/>
* @return
*/
@Override
public BufferedImage create ( HttpSession session ) {
//Color[] colors, Integer rangRoutate, Integer[] fontSize, Font[] fonts, String string
String domanda = Roll.roll( test );
Integer size = 36;
Color[] colors = Roll.rollColor( 100 );
Integer[] sizes = To.objs2Array( size , Double.valueOf( size * 1.8 ).intValue() );
String[] fontNames = new String[] { "Arial" , "Arial Black" ,
"Impact" , "Microsoft Sans Serif" ,
"Tahoma" , "Times New Roman" };
List<Font> fontList = new LinkedList();
for ( String font : fontNames ) {
fontList.add( new Font( font , Font.PLAIN , size ) );
}
String2Code s2i = new String2Code( colors , 68 , true , sizes , To.list2Array( fontList ) , domanda );
s2i.drawNoise( size / 2 );
session.setAttribute( VERFIY_CODE_ANSWER , test.get( domanda ) );
return s2i.getImage();
}
/**
* 从session中取出所记录的domanda对象,并和传入的answer来进行对比
* <p/>
* @param session answer
* <p/>
* @param answer < p/>
* <p/>
* @return
*/
@Override
public Boolean verfiy ( HttpSession session , String answer ) {
String domanda = ( String ) session.getAttribute( VERFIY_CODE_ANSWER );
if ( domanda == null ) {
return false;
} else {
return domanda.equals( answer );
}
}
}
| zzblog | src/java/e/z/blog/back/com/impl/ComVerfiyCode.java | Java | asf20 | 3,756 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com.impl.dao;
import e.z.blog.back.bean.State;
import e.z.blog.back.bean.base.Lan;
import e.z.blog.back.com.DaoLanApi;
import java.util.List;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
/**
*
* @author EnzoZhong
*/
@IocBean
public class DaoLan implements DaoLanApi {
@Inject( "refer:$Ioc" )
private Ioc ioc;
@Inject
private Dao dao;
@Override
public Lan create ( Lan type ) {
type.setState( State.YELLOW );
return dao.insert( type );
}
@Override
public Lan read ( Lan type ) {
Integer lanId = type.getLanId();
String lanName = type.getLanName();
Cnd cnd = Cnd.where( "lanId" , "=" , lanId ).or( "lanName" , "=" , lanName );
return dao.fetch( Lan.class , cnd );
}
@Override
public List<Lan> readAll () {
return dao.query( Lan.class , null , null );
}
@Override
public Lan update ( Lan type ) {
type = read( type );
Lan defLan = ioc.get( Lan.class , "defLan" );
if ( defLan.getLanName().equalsIgnoreCase( type.getLanName() ) ) {
/*
* do nothing~
*/
} else {
dao.update( type );
}
return type;
}
@Override
public Lan delete ( Lan type ) {
type = read( type );
Lan defLan = ioc.get( Lan.class , "defLan" );
if ( defLan.getLanName().equalsIgnoreCase( type.getLanName() ) ) {
/*
* do nothing~
*/
} else {
switch ( type.getState() ) {
case State.BLACK: {
dao.delete( type );
break;
}
default: {
type.setState( type.getState() + 1 );
dao.update( type );
break;
}
}
}
return type;
}
}
| zzblog | src/java/e/z/blog/back/com/impl/dao/DaoLan.java | Java | asf20 | 2,722 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com.impl.dao;
import e.z.blog.back.com.DaoManagerApi;
import e.z.blog.back.bean.system.Manager;
import java.util.List;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
/**
*
* @author EnzoZhong
*/
@IocBean
public class DaoManager implements DaoManagerApi {
@Inject
private Dao dao;
@Override
public Boolean verfiy ( Manager admin ) {
String account = admin.getAccount();
String password = admin.getPassword();
if ( password.length() < 32 ) {
admin.encrypt();
password = admin.getPassword();
}
Cnd cnd = Cnd.where( "account" , "=" , account ).and( "password" , "=" , password );
return dao.fetch( Manager.class , cnd ) != null;
}
@Override
public Manager create ( Manager type ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
@Override
public Manager read ( Manager type ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
@Override
public List<Manager> readAll () {
throw new UnsupportedOperationException( "Not supported yet." );
}
@Override
public Manager update ( Manager type ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
@Override
public Manager delete ( Manager type ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
}
| zzblog | src/java/e/z/blog/back/com/impl/dao/DaoManager.java | Java | asf20 | 1,887 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com.impl.dao;
import e.z.blog.back.bean.State;
import e.z.blog.back.bean.base.Tag;
import e.z.blog.back.com.DaoTagApi;
import java.util.List;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
/**
*
* @author EnzoZhong
*/
@IocBean
public class DaoTag implements DaoTagApi {
@Inject
private Dao dao;
@Override
public Tag create ( Tag type ) {
type.setState( State.YELLOW );
return dao.insert( type );
}
@Override
public Tag read ( Tag type ) {
Integer tagId = type.getTagId();
String tagName = type.getTagName();
Cnd cnd = Cnd.where( "tagId" , "=" , tagId ).or( "tagName" , "=" , tagName );
return dao.fetch( Tag.class , cnd );
}
@Override
public List<Tag> readAll () {
return dao.query( Tag.class , null , null );
}
@Override
public Tag update ( Tag type ) {
dao.update( type );
return type;
}
@Override
public Tag delete ( Tag type ) {
type = read( type );
switch ( type.getState() ) {
case State.BLACK: {
dao.clearLinks( type , "tagList" );
dao.delete( type );
break;
}
default: {
type.setState( type.getState() + 1 );
dao.update( type );
break;
}
}
return type;
}
}
| zzblog | src/java/e/z/blog/back/com/impl/dao/DaoTag.java | Java | asf20 | 1,998 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com.impl.dao;
import e.z.blog.back.com.DaoTabApi;
import e.z.blog.back.bean.State;
import e.z.blog.back.bean.base.Tab;
import java.util.List;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
/**
*
* @author EnzoZhong
*/
@IocBean
public class DaoTab implements DaoTabApi {
@Inject( "refer:$Ioc" )
private Ioc ioc;
@Inject
private Dao dao;
@Override
public Tab create ( Tab tab ) {
tab.setState( State.YELLOW );
return dao.insert( tab );
}
@Override
public List<Tab> readAll () {
return dao.query( Tab.class , null , null );
}
@Override
public Tab read ( Tab tab ) {
Integer tabId = tab.getTabId();
String tabName = tab.getTabName();
Cnd cnd = Cnd.where( "tabId" , "=" , tabId ).or( "tabName" , "=" , tabName );
return dao.fetch( Tab.class , cnd );
}
@Override
public Tab update ( Tab tab ) {
Tab defCity = ioc.get( Tab.class , "defTab" );
//判断是否缺省城市,如果是不做任何修改。
if ( tab.getTabName().equalsIgnoreCase( defCity.getTabName() ) ) {
/**
* do nothing
*/
} else {
dao.update( tab );
}
return tab;
}
@Override
public Tab delete ( Tab type ) {
type = read( type );
Tab defTab = ioc.get( Tab.class , "defTab" );
if ( defTab.getTabName().equalsIgnoreCase( type.getTabName() ) ) {
/*
* do nothing~
*/
} else {
switch ( type.getState() ) {
case State.BLACK: {
dao.delete( type );
break;
}
default: {
type.setState( type.getState() + 1 );
dao.update( type );
break;
}
}
}
return type;
}
}
| zzblog | src/java/e/z/blog/back/com/impl/dao/DaoTab.java | Java | asf20 | 2,753 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
/**
*
* @author EnzoZhong
*/
public interface ComGetLocaleApi {
Collection<String> getLocale ();
}
| zzblog | src/java/e/z/blog/back/com/ComGetLocaleApi.java | Java | asf20 | 335 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
/**
*
* @author EnzoZhong
*/
public interface ComDataTableApi {
Map<String , Field> ini ( Class clazz , String... fieldName );
List<String> getValueList ( Object obj , String... fieldName );
String getTitleList ( Class clazz , String... fieldName );
}
| zzblog | src/java/e/z/blog/back/com/ComDataTableApi.java | Java | asf20 | 510 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com;
import java.util.Map;
import z.h.w.jar.data.tree.ReferTree;
/**
*
* @author EnzoZhong
*/
public interface ComNavTreeApi {
/**
*
* @return
*/
ReferTree<Map<String, String>> getNavTree();
}
| zzblog | src/java/e/z/blog/back/com/ComNavTreeApi.java | Java | asf20 | 386 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com;
import java.awt.image.BufferedImage;
import javax.servlet.http.HttpSession;
/**
*
* @author EnzoZhong 生成验证码和验证验证码接口
*/
public interface ComVerfiyCodeApi {
/**
*
* @param session
* @return
*/
BufferedImage create(HttpSession session);
/**
*
* @param session
* @param answer
* @return
*/
Boolean verfiy(HttpSession session, String answer);
}
| zzblog | src/java/e/z/blog/back/com/ComVerfiyCodeApi.java | Java | asf20 | 624 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com;
import e.z.blog.back.bean.system.Manager;
/**
*
* @author EnzoZhong
*/
public interface DaoManagerApi extends DaoBaseApi<Manager>{
Boolean verfiy ( Manager admin ) ;
}
| zzblog | src/java/e/z/blog/back/com/DaoManagerApi.java | Java | asf20 | 334 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com;
import e.z.blog.back.bean.base.Lan;
/**
*
* @author EnzoZhong
*/
public interface DaoLanApi extends DaoBaseApi<Lan>{
}
| zzblog | src/java/e/z/blog/back/com/DaoLanApi.java | Java | asf20 | 275 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.com;
import java.util.Map;
/**
*
* @author EnzoZhong
*/
public interface ComFixNutzStringBugApi {
Map<String , String> fixString ( Map<String , String> map );
}
| zzblog | src/java/e/z/blog/back/com/ComFixNutzStringBugApi.java | Java | asf20 | 313 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.setup;
import e.z.blog.back.bean.base.Essay;
import e.z.blog.back.bean.base.New;
import e.z.blog.back.bean.base.Lan;
import e.z.blog.back.bean.base.Tab;
import e.z.blog.back.bean.base.Tag;
import e.z.blog.back.com.DaoLanApi;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.Setup;
/**
*
* @author EnzoZhong
*/
public class LanTabEssayTagRemarkSetup implements Setup {
@Override
public void init ( NutConfig config ) {
Ioc ioc = config.getIoc();
Dao dao = ioc.get( Dao.class , "dao" );
/*
* 建表
*/
dao.create( Lan.class , false );
dao.create( Tab.class , false );
dao.create( Essay.class , false );
dao.create( Tag.class , false );
dao.create( New.class , false );
/*
* 创建默认对象
*/
Lan defLan = ioc.get( Lan.class , "defLan" );
Tab defTab = ioc.get( Tab.class , "defTab" );
/*
* 检查默认值是否存在
*/
if ( dao.fetch( Lan.class , defLan.getLanName() ) == null ) {
dao.insert( defLan );
}
if ( dao.fetch( Tab.class , defTab.getTabName() ) == null ) {
dao.insert( defTab );
}
}
@Override
public void destroy ( NutConfig config ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
}
| zzblog | src/java/e/z/blog/back/setup/LanTabEssayTagRemarkSetup.java | Java | asf20 | 1,948 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.setup;
import e.z.blog.back.bean.base.Lan;
import e.z.blog.back.bean.system.Manager;
import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.Setup;
import z.h.w.jar.data.time.Time;
/**
*
* @author EnzoZhong
*/
public class ManagerSetup implements Setup {
@Override
public void init ( NutConfig config ) {
Ioc ioc = config.getIoc();
Dao dao = ioc.get( Dao.class , "dao" );
/*
* 表创建
*/
dao.create( Manager.class , false );
/*
* 插入默认值
*/
Manager defManager = ioc.get( Manager.class , "defManager" );
if ( dao.fetch( Manager.class , defManager.getAccount() ) == null ) {
defManager.setBuildDate( Time.born() );
dao.insert( defManager );
}
}
@Override
public void destroy ( NutConfig config ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
}
| zzblog | src/java/e/z/blog/back/setup/ManagerSetup.java | Java | asf20 | 1,300 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.setup;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.Setup;
/**
*
* @author EnzoZhong
*/
public class IntallSetup implements Setup {
@Override
public void init ( NutConfig config ) {
new LanTabEssayTagRemarkSetup().init( config );
new ManagerSetup().init( config );
}
@Override
public void destroy ( NutConfig config ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
}
| zzblog | src/java/e/z/blog/back/setup/IntallSetup.java | Java | asf20 | 646 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.bean.system;
import e.z.blog.back.bean.AbstractUser;
import org.nutz.dao.entity.annotation.Table;
/**
*
* @author EnzoZhong
*/
@Table( "t_s_sys_bean_manager" )
public class Manager extends AbstractUser {
}
| zzblog | src/java/e/z/blog/back/bean/system/Manager.java | Java | asf20 | 349 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.bean;
import java.util.Date;
import org.nutz.dao.entity.annotation.ColDefine;
import org.nutz.dao.entity.annotation.ColType;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Comment;
import org.nutz.dao.entity.annotation.Id;
import org.nutz.dao.entity.annotation.Name;
import z.h.w.jar.kit.ED;
/**
*
* @author EnzoZhong 用户父类没有数据表
*/
public abstract class AbstractUser {
@Id
private Long userId;
@Name
@Comment( "电子邮件" )
private String account;
@Column
private String password;
@Column
@Comment( "创建时间" )
private Date buildDate;
@Column
@Comment( "状态" )
private Integer state;
@Column
@Comment( "备注" )
@ColDefine( type = ColType.TEXT )
private String remark;
public AbstractUser () {
}
/**
*
*/
public void encrypt () {
String md5Password = ED.toInreversiblePassword( this.getPassword() );
this.setPassword( md5Password );
}
/**
*
* @return
*/
public String getAccount () {
return account;
}
/**
*
* @param account
*/
public void setAccount ( String account ) {
this.account = account;
}
/**
*
* @return
*/
public Date getBuildDate () {
return buildDate;
}
/**
*
* @param buildDate
*/
public void setBuildDate ( Date buildDate ) {
this.buildDate = buildDate;
}
/**
*
* @return
*/
public String getPassword () {
return password;
}
/**
*
* @param password
*/
public void setPassword ( String password ) {
this.password = password;
}
/**
*
* @return
*/
public String getRemark () {
return remark;
}
/**
*
* @param remark
*/
public void setRemark ( String remark ) {
this.remark = remark;
}
/**
*
* @return
*/
public Integer getState () {
return state;
}
/**
*
* @param state
*/
public void setState ( Integer state ) {
this.state = state;
}
/**
*
* @return
*/
public Long getUserId () {
return userId;
}
/**
*
* @param userId
*/
public void setUserId ( Long userId ) {
this.userId = userId;
}
@Override
public boolean equals ( Object obj ) {
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
final AbstractUser other = ( AbstractUser ) obj;
if ( this.userId != other.userId && ( this.userId == null || !this.userId.equals( other.userId ) ) ) {
return false;
}
if ( ( this.account == null ) ? ( other.account != null ) : !this.account.equals( other.account ) ) {
return false;
}
return true;
}
@Override
public int hashCode () {
int hash = 5;
hash = 41 * hash + ( this.userId != null ? this.userId.hashCode() : 0 );
hash = 41 * hash + ( this.account != null ? this.account.hashCode() : 0 );
return hash;
}
@Override
public String toString () {
return "AbstractUser{" + "userId=" + userId + ", account=" + account + ", password=" + password + ", buildDate=" + buildDate + ", state=" + state + ", remark=" + remark + '}';
}
}
| zzblog | src/java/e/z/blog/back/bean/AbstractUser.java | Java | asf20 | 4,497 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.bean.base;
import java.util.List;
import java.util.Map;
import org.nutz.dao.entity.annotation.*;
/**
*
* @author EnzoZhong
*/
@Table( "t_s_blog_bean_tag" )
public class Tag {
@Id
@Column
@Comment( "序列号" )
private Integer tagId;
@Name
@Column
@Comment( "标签名" )
private String tagName;
@Column
@Comment( "翻译" )
@ColDefine( type = ColType.TEXT )
private Map<String , String> translate;
@Column
@Comment( "状态" )
private Integer state;
@ManyMany( target = Tag.class , relation = "t_s_blog_bean_essay_tag" , from = "tagId" , to = "essayId" )
private List<Tag> tagList;
public Tag () {
}
public Integer getState () {
return state;
}
public void setState ( Integer state ) {
this.state = state;
}
public Integer getTagId () {
return tagId;
}
public void setTagId ( Integer tagId ) {
this.tagId = tagId;
}
public List<Tag> getTagList () {
return tagList;
}
public void setTagList ( List<Tag> tagList ) {
this.tagList = tagList;
}
public String getTagName () {
return tagName;
}
public void setTagName ( String tagName ) {
this.tagName = tagName;
}
public Map<String , String> getTranslate () {
return translate;
}
public void setTranslate ( Map<String , String> translate ) {
this.translate = translate;
}
@Override
public boolean equals ( Object obj ) {
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
final Tag other = ( Tag ) obj;
if ( ( this.tagName == null ) ? ( other.tagName != null ) : !this.tagName.equals( other.tagName ) ) {
return false;
}
return true;
}
@Override
public int hashCode () {
int hash = 7;
hash = 89 * hash + ( this.tagName != null ? this.tagName.hashCode() : 0 );
return hash;
}
@Override
public String toString () {
return "Tag{" + "tagId=" + tagId + ", tagName=" + tagName + ", translate=" + translate + ", state=" + state + ", tagList=" + tagList + '}';
}
}
| zzblog | src/java/e/z/blog/back/bean/base/Tag.java | Java | asf20 | 2,897 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.bean.base;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Comment;
import org.nutz.dao.entity.annotation.Id;
import org.nutz.dao.entity.annotation.Name;
import org.nutz.dao.entity.annotation.Table;
/**
*
* @author EnzoZhong
*/
@Table( "t_s_blog_bean_lan" )
public class Lan {
@Id
@Comment( "序列号" )
private Integer lanId;
@Name
@Comment( "语言名" )
private String lanName;
@Column
@Comment( "语言代号" )
private String code;
@Column
@Comment( "状态" )
private Integer state;
public Lan () {
}
public String getCode () {
return code;
}
public void setCode ( String code ) {
this.code = code;
}
public Integer getLanId () {
return lanId;
}
public void setLanId ( Integer lanId ) {
this.lanId = lanId;
}
public String getLanName () {
return lanName;
}
public void setLanName ( String lanName ) {
this.lanName = lanName;
}
public Integer getState () {
return state;
}
public void setState ( Integer state ) {
this.state = state;
}
@Override
public boolean equals ( Object obj ) {
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
final Lan other = ( Lan ) obj;
if ( ( this.lanName == null ) ? ( other.lanName != null ) : !this.lanName.equals( other.lanName ) ) {
return false;
}
return true;
}
@Override
public int hashCode () {
int hash = 5;
hash = 89 * hash + ( this.lanName != null ? this.lanName.hashCode() : 0 );
return hash;
}
@Override
public String toString () {
return "Lan{" + "lanId=" + lanId + ", lanName=" + lanName + ", code=" + code + ", state=" + state + '}';
}
}
| zzblog | src/java/e/z/blog/back/bean/base/Lan.java | Java | asf20 | 2,506 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.bean.base;
import java.util.Date;
import java.util.List;
import org.nutz.dao.entity.annotation.*;
/**
*
* @author EnzoZhong
*/
@Table( "t_s_blog_bean_essay" )
public class Essay {
@Id
@Column
@Comment( "序列号" )
private Long essayId;
@Name
@Column
@Comment( "标题" )
private String essayTitle;
@Column
@Comment( "内容" )
@ColDefine( type = ColType.TEXT )
private String html;
@Column
@Comment( "创建时间" )
private Date build;
@Column
@Comment( "浏览数" )
private Integer see;
@Column
private Integer tabId;
@One( target = Tab.class , field = "tabId" )
private Tab tab;
@ManyMany( target = Tag.class , relation = "t_s_blog_bean_essay_tag" , from = "essayId" , to = "tagId" )
private List<Tag> tagList;
@Many( target = New.class , field = "essayId" )
private List<New> remarkList;
}
| zzblog | src/java/e/z/blog/back/bean/base/Essay.java | Java | asf20 | 1,177 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.bean.base;
import java.util.Date;
import org.nutz.dao.entity.annotation.ColDefine;
import org.nutz.dao.entity.annotation.ColType;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Comment;
import org.nutz.dao.entity.annotation.Id;
import org.nutz.dao.entity.annotation.One;
import org.nutz.dao.entity.annotation.Table;
/**
*
* @author EnzoZhong
*/
@Table( "t_s_blog_bean_new" )
public class New {
@Id
@Column
@Comment( "序列号" )
private Long newId;
@Column
@Comment( "内容" )
@ColDefine( type = ColType.TEXT )
private String context;
@Column
@Comment( "创建时间" )
private Date build;
@Column
@Comment( "留言地" )
private String name;
@Column
private Long essayId;
@One( target = Essay.class , field = "essayId" )
private Essay essay;
}
| zzblog | src/java/e/z/blog/back/bean/base/New.java | Java | asf20 | 1,097 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.bean.base;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.nutz.dao.entity.annotation.*;
/**
* 目录操作类,记录所有记录的目录,还有一个缺省目录,defTab他不能被修改和不能被删除,否
*
* 则肯定会引起数据逻辑错误!切记!
*
* @author EnzoZhong
*/
@Table( "t_s_blog_bean_tab" )
public class Tab {
@Id
@Comment( "序列号" )
private Integer tabId;
@Name
@Comment( "目录名" )
private String tabName;
@Column
@Comment( "翻译" )
@ColDefine( type = ColType.TEXT )
private Map<String , String> translate;
@Column
@Comment( "状态" )
private Integer state;
@Many( target = Essay.class , field = "tabId" )
private List<Essay> essayList;
public Tab () {
translate = new HashMap();
}
public List<Essay> getEssayList () {
return essayList;
}
public void setEssayList ( List<Essay> essayList ) {
this.essayList = essayList;
}
public Map<String , String> getTranslate () {
return translate;
}
public void setTranslate ( Map<String , String> translate ) {
this.translate = translate;
}
public Integer getState () {
return state;
}
public void setState ( Integer state ) {
this.state = state;
}
public Integer getTabId () {
return tabId;
}
public void setTabId ( Integer tabId ) {
this.tabId = tabId;
}
public String getTabName () {
return tabName;
}
public void setTabName ( String tabName ) {
this.tabName = tabName;
}
@Override
public boolean equals ( Object obj ) {
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
final Tab other = ( Tab ) obj;
if ( ( this.tabName == null ) ? ( other.tabName != null ) : !this.tabName.equals( other.tabName ) ) {
return false;
}
return true;
}
@Override
public int hashCode () {
int hash = 5;
hash = 79 * hash + ( this.tabName != null ? this.tabName.hashCode() : 0 );
return hash;
}
@Override
public String toString () {
return "Tab{" + "tabId=" + tabId + ", tabName=" + tabName + ", state=" + state + '}';
}
}
| zzblog | src/java/e/z/blog/back/bean/base/Tab.java | Java | asf20 | 3,028 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.bean;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author EnzoZhong
*/
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.FIELD )
@Documented
public @interface State {
/**
*
*/
int GREEN = 0;
/**
*
*/
int YELLOW = 1;
/**
*
*/
int RED = 2;
/**
*
*/
int BLACK = 3;
}
| zzblog | src/java/e/z/blog/back/bean/State.java | Java | asf20 | 744 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.action.crud;
import e.z.blog.back.action.AbstractAction;
import e.z.blog.back.action.CrudBaseApi;
import e.z.blog.back.com.ComDataTableApi;
import e.z.blog.back.com.ComFixNutzStringBugApi;
import e.z.blog.back.com.DaoLanApi;
import e.z.blog.back.com.DaoTabApi;
import e.z.blog.back.bean.base.Tab;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.adaptor.JsonAdaptor;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import z.h.w.jar.kit.To;
/**
*
* @author EnzoZhong
*/
@IocBean
@At( "/tab" )
public class CrudTab extends AbstractAction implements CrudBaseApi<Tab> {
final private String type = "tab";
final private String[] column = To.objs2Array( "tabId" , "tabName" , "state" );
@Inject
private ComFixNutzStringBugApi comFixNutzStringBug;
@Inject
private ComDataTableApi comDataTable;
@Inject
private DaoTabApi daoTab;
@Inject
private DaoLanApi daoLan;
@Override
@At( "" )
@Ok( "jsp:back.crudTab" )
public Map<String , Object> page ( HttpServletRequest request ) {
Map<String , Object> map = this.createMap( request , type );
map.put( "aoColumns" , comDataTable.getTitleList( Tab.class , column ) );
map.put( "lanList" , daoLan.readAll() );
map.put( "tabList" , daoTab.readAll() );
return map;
}
@Ok( "json" )
@At( CREATE )
@AdaptBy( type = JsonAdaptor.class )
public Tab create ( @Param( type ) Tab tab , @Param( "translate" ) Map<String , String> tmp ) {
Map<String , String> translate = comFixNutzStringBug.fixString( tmp );
tab.setTranslate( translate );
return daoTab.create( tab );
}
@Override
@Ok( "json" )
@At( READ_BY_ID )
@AdaptBy( type = JsonAdaptor.class )
public Tab read ( @Param( type ) Tab tab ) {
return daoTab.read( tab );
}
@Ok( "json" )
@At( READ_ALL )
@AdaptBy( type = JsonAdaptor.class )
public List<List<String>> readAll () {
List<List<String>> stringList = new LinkedList();
List<Tab> cityList = daoTab.readAll();
for ( Tab tab : cityList ) {
stringList.add( comDataTable.getValueList( tab , column ) );
}
return stringList;
}
@Ok( "json" )
@At( UPDATE )
@AdaptBy( type = JsonAdaptor.class )
public Tab update ( @Param( type ) Tab tab , @Param( "translate" ) Map<String , String> tmp ) {
Map<String , String> translate = comFixNutzStringBug.fixString( tmp );
tab.setTranslate( translate );
return daoTab.update( tab );
}
@Override
@Ok( "json" )
@At( DELETE )
@AdaptBy( type = JsonAdaptor.class )
public Tab delete ( @Param( type ) Tab tab ) {
return daoTab.delete( tab );
}
@Override
public Tab create ( Tab type ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
@Override
public Tab update ( Tab type ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
}
| zzblog | src/java/e/z/blog/back/action/crud/CrudTab.java | Java | asf20 | 3,882 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.action.crud;
import e.z.blog.back.action.AbstractAction;
import e.z.blog.back.action.CrudBaseApi;
import e.z.blog.back.bean.base.Tab;
import e.z.blog.back.bean.base.Tag;
import e.z.blog.back.com.ComDataTableApi;
import e.z.blog.back.com.ComFixNutzStringBugApi;
import e.z.blog.back.com.DaoLanApi;
import e.z.blog.back.com.DaoTagApi;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.adaptor.JsonAdaptor;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import z.h.w.jar.kit.To;
/**
*
* @author EnzoZhong
*/
@IocBean
@At( "/tag" )
public class CrudTag extends AbstractAction implements CrudBaseApi<Tag> {
final private String type = "tag";
final private String[] column = To.objs2Array( "tagId" , "tagName" , "state" );
@Inject
private ComFixNutzStringBugApi comFixNutzStringBug;
@Inject
private ComDataTableApi comDataTable;
@Inject
private DaoTagApi daoTag;
@Inject
private DaoLanApi daoLan;
@Override
@At( "" )
@Ok( "jsp:back.crudTag" )
public Map<String , Object> page ( HttpServletRequest request ) {
Map<String , Object> map = this.createMap( request , type );
map.put( "aoColumns" , comDataTable.getTitleList( Tag.class , column ) );
map.put( "lanList" , daoLan.readAll() );
map.put( "tagList" , daoTag.readAll() );
return map;
}
@Ok( "json" )
@At( CREATE )
@AdaptBy( type = JsonAdaptor.class )
public Tag create ( @Param( type ) Tag tab , @Param( "translate" ) Map<String , String> tmp ) {
Map<String , String> translate = comFixNutzStringBug.fixString( tmp );
tab.setTranslate( translate );
return daoTag.create( tab );
}
@Override
@Ok( "json" )
@At( READ_BY_ID )
@AdaptBy( type = JsonAdaptor.class )
public Tag read ( @Param( type ) Tag tab ) {
return daoTag.read( tab );
}
@Ok( "json" )
@At( READ_ALL )
@AdaptBy( type = JsonAdaptor.class )
public List<List<String>> readAll () {
List<List<String>> stringList = new LinkedList();
List<Tag> cityList = daoTag.readAll();
for ( Tag tab : cityList ) {
stringList.add( comDataTable.getValueList( tab , column ) );
}
return stringList;
}
@Ok( "json" )
@At( UPDATE )
@AdaptBy( type = JsonAdaptor.class )
public Tag update ( @Param( type ) Tag tab , @Param( "translate" ) Map<String , String> tmp ) {
Map<String , String> translate = comFixNutzStringBug.fixString( tmp );
tab.setTranslate( translate );
return daoTag.update( tab );
}
@Override
@Ok( "json" )
@At( DELETE )
@AdaptBy( type = JsonAdaptor.class )
public Tag delete ( @Param( type ) Tag tab ) {
return daoTag.delete( tab );
}
@Override
public Tag create ( Tag type ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
@Override
public Tag update ( Tag type ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
}
| zzblog | src/java/e/z/blog/back/action/crud/CrudTag.java | Java | asf20 | 3,919 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.action.crud;
import e.z.blog.back.action.AbstractAction;
import e.z.blog.back.action.CrudBaseApi;
import e.z.blog.back.com.ComDataTableApi;
import e.z.blog.back.com.ComGetLocaleApi;
import e.z.blog.back.com.DaoLanApi;
import e.z.blog.back.bean.base.Lan;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.adaptor.JsonAdaptor;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import z.h.w.jar.kit.To;
/**
*
* @author EnzoZhong
*/
@IocBean
@At( "/lan" )
public class CrudLan extends AbstractAction implements CrudBaseApi<Lan> {
final private String type = "lan";
final private String[] column = To.objs2Array( "lanId" , "lanName" , "code" , "state" );
@Inject
private ComDataTableApi comDataTable;
@Inject
private ComGetLocaleApi comGetLocale;
@Inject
private DaoLanApi daoLan;
@Override
@At( "" )
@Ok( "jsp:back.crudLan" )
public Map<String , Object> page ( HttpServletRequest req ) {
Map<String , Object> map = this.createMap( req , type );
map.put( "aoColumns" , comDataTable.getTitleList( Lan.class , column ) );
map.put( "locale" , comGetLocale.getLocale() );
return map;
}
@Override
@Ok( "json" )
@At( CREATE )
@AdaptBy( type = JsonAdaptor.class )
public Lan create ( @Param( type ) Lan lan ) {
return daoLan.create( lan );
}
@Override
@Ok( "json" )
@At( READ_BY_ID )
@AdaptBy( type = JsonAdaptor.class )
public Lan read ( @Param( type ) Lan lan ) {
return daoLan.read( lan );
}
@Ok( "json" )
@At( READ_ALL )
@AdaptBy( type = JsonAdaptor.class )
public List<List<String>> readAll () {
List<Lan> lanList = daoLan.readAll();
List<List<String>> stringList = new LinkedList();
for ( Lan lan : lanList ) {
stringList.add( comDataTable.getValueList( lan , column ) );
}
return stringList;
}
@Override
@Ok( "json" )
@At( UPDATE )
@AdaptBy( type = JsonAdaptor.class )
public Lan update ( @Param( type ) Lan lan ) {
return daoLan.update( lan );
}
@Override
@Ok( "json" )
@At( DELETE )
@AdaptBy( type = JsonAdaptor.class )
public Lan delete ( @Param( type ) Lan lan ) {
return daoLan.delete( lan );
}
}
| zzblog | src/java/e/z/blog/back/action/crud/CrudLan.java | Java | asf20 | 3,076 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.action;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import z.h.w.jar.kit.IO;
/**
*
* @author EnzoZhong
*/
public abstract class AbstractAction {
public abstract Map<String , Object> page ( HttpServletRequest req );
public Map<String , Object> createMap ( HttpServletRequest req , String path ) {
Map<String , Object> re = new HashMap();
re.put( "type" , path );
re.put( "id" , path + "Id" );
/*
* back2FirstFolder这个方法是为了计算要退格多少个例如../../这样就是退格
* 2个,这个做的好处是,可以使不管以后这个链接的url怎么换,前面所需要退格
* 的数量都是自动算出来的,这样的话,就达到所引用的js,css都能够正常加载
*/
re.put( "path" , IO.back2Floder( req.getServletPath() ) );
return re;
}
}
| zzblog | src/java/e/z/blog/back/action/AbstractAction.java | Java | asf20 | 1,175 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.action;
/**
*
* @author EnzoZhong
*/
public interface CrudBaseApi<Type> {
/**
*
*/
String CREATE = "/create";
/**
*
*/
String READ_ALL = "/readAll";
/**
*
*/
String READ_BY_ID = "/readById";
/**
*
*/
String READ_SON_BY_ID = "/readSonById";
/**
*
*/
String UPDATE = "/update";
/**
*
*/
String DELETE = "/delete";
//状态
/**
*
*/
String SUCCESS = "成功";
/**
*
*/
String FAIL = "失败";
Type create ( Type type );
Type read ( Type type );
Type update ( Type type );
Type delete ( Type type );
}
| zzblog | src/java/e/z/blog/back/action/CrudBaseApi.java | Java | asf20 | 995 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.action.base;
import e.z.blog.back.action.AbstractAction;
import e.z.blog.back.bean.system.Manager;
import e.z.blog.back.com.ComGetIpApi;
import e.z.blog.back.com.ComVerfiyCodeApi;
import e.z.blog.back.com.DaoManagerApi;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.adaptor.JsonAdaptor;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import z.h.w.jar.data.time.Time;
import z.h.w.jar.kit.Self;
/**
* 这个页面不进行权限管理,普通用户都能到达这个页面,除了这个页面以外所有的页面都要进行
*
* 权限管理。2012.02.21
*
* @author EnzoZhong
*/
@IocBean
@At( "" )
public class BackLogin extends AbstractAction {
@Inject
private ComVerfiyCodeApi comVerfiyCode;
@Inject
private ComGetIpApi comGetIp;
@Inject
private DaoManagerApi daoManager;
@At( "" )
@Ok( "jsp:back.login" )
public Map<String , Object> page ( HttpSession session , HttpServletRequest req ) {
// Mvcs.setLocaleName( session , "zh_CN" );
Map<String , Object> re = this.createMap( req , "" );
re.put( "time" , Time.born() );
re.put( "ip" , comGetIp.getIP( req ) );
re.put( "age" , Time.howOldAmI() );
return re;
}
/**
*
* @return
*/
@Ok( "json" )
@At( "/fonts" )
@AdaptBy( type = JsonAdaptor.class )
public String[] getFonts () {
return Self.getAllFontName();
}
/**
* 暂时还没有写权限系统,基本登陆,等CRUD和基本功能完善后,写权限系统,并把该
*
* 方法改写。2012.02.21
*/
@Ok( "json" )
@At( "/login" )
@AdaptBy( type = JsonAdaptor.class )
public Map<String , Object> login (
@Param( "manager" ) Manager admin , @Param( "code" ) String code , HttpSession session ) {
Boolean booleanAdmin = daoManager.verfiy( admin );
Boolean booleanCode = comVerfiyCode.verfiy( session , code );
Map<String , Object> re = new HashMap();
String successUrl = "/back/index";
String failUrl = "/back";
String msg = "";
Boolean res = booleanAdmin & booleanCode;
if ( !booleanAdmin ) {
msg = msg + "账户或密码错误!\r\n";
}
if ( !booleanCode ) {
msg = msg + "验证码错误!";
}
re.put( "res" , res );
if ( res ) {
re.put( "url" , successUrl );
} else {
re.put( "tip" , msg );
re.put( "url" , failUrl );
}
return re;
}
/**
*
* @param request < p/>
* <p/>
* @return
*/
@Ok( "json" )
@At( "/ip" )
@AdaptBy( type = JsonAdaptor.class )
public String getIp ( HttpServletRequest request ) {
return comGetIp.getIP( request );
}
/**
* 输出PNG验证码图片
* <p/>
* @param rep param session
* @param sess
*/
@Ok( "void" )
@At( "/code" )
public void outputCode ( HttpServletResponse rep , HttpSession sess ) {
try {
OutputStream os = rep.getOutputStream();
ImageIO.write( comVerfiyCode.create( sess ) , "PNG" , os );
} catch ( IOException ex ) {
}
}
@Override
public Map<String , Object> page ( HttpServletRequest req ) {
throw new UnsupportedOperationException( "Not supported yet." );
}
}
| zzblog | src/java/e/z/blog/back/action/base/BackLogin.java | Java | asf20 | 4,602 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package e.z.blog.back.action.base;
import e.z.blog.back.action.AbstractAction;
import e.z.blog.back.com.ComNavTreeApi;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.adaptor.JsonAdaptor;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import z.h.w.jar.data.tree.ReferTree;
/**
* 2012.02.21
*
* @author EnzoZhong
*/
@IocBean
@At( "" )
public class BackIndex extends AbstractAction {
@Inject
private ComNavTreeApi comNavTree;
@At( "/index" )
@Ok( "jsp:back.index" )
@Override
public Map<String , Object> page ( HttpServletRequest req ) {
Map<String , Object> map = this.createMap( req , "" );
return map;
}
/**
*
*/
@At( "/progress" )
@Ok( "raw:progress.html" )
public void age () {
}
/**
* 获取整个系统的所有url连接,权限系统完成后该方法取消,实现动态分发url资源和
*
* 目录资源。2012.02.21
* <p/>
* @return
*/
@Ok( "json" )
@At( "/getNavTree" )
@AdaptBy( type = JsonAdaptor.class )
public Collection<Map> navTree () {
ReferTree<Map<String , String>> tree = comNavTree.getNavTree();
return tree.getList();
}
}
| zzblog | src/java/e/z/blog/back/action/base/BackIndex.java | Java | asf20 | 1,822 |
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>
<a href="/back">Hello World!</a>
</h1>
</body>
</html>
| zzblog | web/index.jsp | Java Server Pages | asf20 | 483 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('quickformat', function(K) {
var self = this, name = 'quickformat',
blockMap = K.toMap('blockquote,center,div,h1,h2,h3,h4,h5,h6,p');
self.clickToolbar(name, function() {
self.focus();
var doc = self.edit.doc,
range = self.cmd.range,
child = K(doc.body).first(), next,
nodeList = [], subList = [],
bookmark = range.createBookmark(true);
while(child) {
next = child.next();
if (blockMap[child.name]) {
child.html(child.html().replace(/^(\s| | )+/ig, ''));
child.css('text-indent', '2em');
} else {
subList.push(child);
}
if (!next || (blockMap[next.name] || blockMap[child.name] && !blockMap[next.name])) {
if (subList.length > 0) {
nodeList.push(subList);
}
subList = [];
}
child = next;
}
K.each(nodeList, function(i, subList) {
var wrapper = K('<p style="text-indent:2em;"></p>', doc);
subList[0].before(wrapper);
K.each(subList, function(i, knode) {
wrapper.append(knode);
});
});
range.moveToBookmark(bookmark);
self.addBookmark();
});
});
/**
--------------------------
abcd<br />
1234<br />
to
<p style="text-indent:2em;">
abcd<br />
1234<br />
</p>
--------------------------
abcd<img>1233
<p>1234</p>
to
<p style="text-indent:2em;">abcd<img>1233</p>
<p style="text-indent:2em;">1234</p>
--------------------------
*/ | zzblog | web/js/kindeditor/plugins/quickformat/quickformat.js | JavaScript | asf20 | 1,805 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('insertfile', function(K) {
var self = this, name = 'insertfile',
allowFileManager = K.undef(self.allowFileManager, false),
uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
lang = self.lang(name + '.');
self.plugin.fileDialog = function(options) {
var fileUrl = K.undef(options.fileUrl, 'http://'),
fileTitle = K.undef(options.fileTitle, ''),
clickFn = options.clickFn;
var html = [
'<div style="padding:10px 20px;">',
'<div class="ke-dialog-row">',
'<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
'<input type="text" id="keUrl" name="url" class="ke-input-text" style="width:160px;" /> ',
'<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
'</span>',
'</div>',
//title
'<div class="ke-dialog-row">',
'<label for="keTitle" style="width:60px;">' + lang.title + '</label>',
'<input type="text" id="keTitle" class="ke-input-text" name="title" value="" style="width:160px;" /></div>',
'</div>',
//form end
'</form>',
'</div>'
].join('');
var dialog = self.createDialog({
name : name,
width : 450,
height : 180,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var url = K.trim(urlBox.val()),
title = titleBox.val();
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
if (K.trim(title) === '') {
title = url;
}
clickFn.call(self, url, title);
}
},
beforeRemove : function() {
viewServerBtn.remove();
uploadbutton.remove();
}
}),
div = dialog.div;
var urlBox = K('[name="url"]', div),
viewServerBtn = K('[name="viewServer"]', div),
titleBox = K('[name="title"]', div);
var uploadbutton = K.uploadbutton({
button : K('.ke-upload-button', div)[0],
fieldName : 'imgFile',
url : K.addParam(uploadJson, 'dir=file'),
afterUpload : function(data) {
dialog.hideLoading();
if (data.error === 0) {
var url = K.formatUrl(data.url, 'absolute');
urlBox.val(url);
if (self.afterUpload) {
self.afterUpload.call(self, url);
}
alert(self.lang('uploadSuccess'));
} else {
alert(data.message);
}
},
afterError : function(html) {
dialog.hideLoading();
self.errorDialog(html);
}
});
uploadbutton.fileBox.change(function(e) {
dialog.showLoading(self.lang('uploadLoading'));
uploadbutton.submit();
});
if (allowFileManager) {
viewServerBtn.click(function(e) {
self.loadPlugin('filemanager', function() {
self.plugin.filemanagerDialog({
viewType : 'LIST',
dirName : 'file',
clickFn : function(url, title) {
if (self.dialogs.length > 1) {
K('[name="url"]', div).val(url);
self.hideDialog();
}
}
});
});
});
} else {
viewServerBtn.hide();
}
urlBox.val(fileUrl);
titleBox.val(fileTitle);
urlBox[0].focus();
urlBox[0].select();
};
self.clickToolbar(name, function() {
self.plugin.fileDialog({
clickFn : function(url, title) {
var html = '<a href="' + url + '" data-ke-src="' + url + '" target="_blank">' + title + '</a>';
self.insertHtml(html).hideDialog().focus();
}
});
});
});
| zzblog | web/js/kindeditor/plugins/insertfile/insertfile.js | JavaScript | asf20 | 4,026 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
// Google Maps: http://code.google.com/apis/maps/index.html
KindEditor.plugin('map', function(K) {
var self = this, name = 'map', lang = self.lang(name + '.');
self.clickToolbar(name, function() {
var html = ['<div style="padding:10px 20px;">',
'<div class="ke-dialog-row">',
lang.address + ' <input id="kindeditor_plugin_map_address" name="address" class="ke-input-text" value="" style="width:200px;" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" name="searchBtn" class="ke-button-common ke-button" value="' + lang.search + '" />',
'</span>',
'</div>',
'<div class="ke-map" style="width:558px;height:360px;"></div>',
'</div>'].join('');
var dialog = self.createDialog({
name : name,
width : 600,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var geocoder = win.geocoder,
map = win.map,
center = map.getCenter().lat() + ',' + map.getCenter().lng(),
zoom = map.getZoom(),
maptype = map.getMapTypeId(),
url = 'http://maps.googleapis.com/maps/api/staticmap';
url += '?center=' + encodeURIComponent(center);
url += '&zoom=' + encodeURIComponent(zoom);
url += '&size=558x360';
url += '&maptype=' + encodeURIComponent(maptype);
url += '&markers=' + encodeURIComponent(center);
url += '&language=' + self.langType;
url += '&sensor=false';
self.exec('insertimage', url).hideDialog().focus();
}
},
beforeRemove : function() {
searchBtn.remove();
if (doc) {
doc.write('');
}
iframe.remove();
}
});
var div = dialog.div,
addressBox = K('[name="address"]', div),
searchBtn = K('[name="searchBtn"]', div),
win, doc;
var iframeHtml = ['<!doctype html><html><head>',
'<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />',
'<style>',
' html { height: 100% }',
' body { height: 100%; margin: 0; padding: 0; background-color: #FFF }',
' #map_canvas { height: 100% }',
'</style>',
'<script src="http://maps.googleapis.com/maps/api/js?sensor=false&language=' + self.langType + '"></script>',
'<script>',
'var map, geocoder;',
'function initialize() {',
' var latlng = new google.maps.LatLng(31.230393, 121.473704);',
' var options = {',
' zoom: 11,',
' center: latlng,',
' disableDefaultUI: true,',
' panControl: true,',
' zoomControl: true,',
' mapTypeControl: true,',
' scaleControl: true,',
' streetViewControl: false,',
' overviewMapControl: true,',
' mapTypeId: google.maps.MapTypeId.ROADMAP',
' };',
' map = new google.maps.Map(document.getElementById("map_canvas"), options);',
' geocoder = new google.maps.Geocoder();',
' geocoder.geocode({latLng: latlng}, function(results, status) {',
' if (status == google.maps.GeocoderStatus.OK) {',
' if (results[3]) {',
' parent.document.getElementById("kindeditor_plugin_map_address").value = results[3].formatted_address;',
' }',
' }',
' });',
'}',
'function search(address) {',
' if (!map) return;',
' geocoder.geocode({address : address}, function(results, status) {',
' if (status == google.maps.GeocoderStatus.OK) {',
' map.setZoom(11);',
' map.setCenter(results[0].geometry.location);',
' var marker = new google.maps.Marker({',
' map: map,',
' position: results[0].geometry.location',
' });',
' } else {',
' alert("Invalid address: " + address);',
' }',
' });',
'}',
'</script>',
'</head>',
'<body onload="initialize();">',
'<div id="map_canvas" style="width:100%; height:100%"></div>',
'</body></html>'].join('\n');
// TODO:用doc.write(iframeHtml)方式加载时,在IE6上第一次加载报错,暂时使用src方式
var iframe = K('<iframe class="ke-textarea" frameborder="0" src="' + self.pluginsPath + 'map/map.html" style="width:558px;height:360px;"></iframe>');
function ready() {
win = iframe[0].contentWindow;
doc = K.iframeDoc(iframe);
//doc.open();
//doc.write(iframeHtml);
//doc.close();
}
iframe.bind('load', function() {
iframe.unbind('load');
if (K.IE) {
ready();
} else {
setTimeout(ready, 0);
}
});
K('.ke-map', div).replaceWith(iframe);
// search map
searchBtn.click(function() {
win.search(addressBox.val());
});
});
});
| zzblog | web/js/kindeditor/plugins/map/map.js | JavaScript | asf20 | 4,932 |
<!doctype html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style>
html { height: 100% }
body { height: 100%; margin: 0; padding: 0; background-color: #FFF }
#map_canvas { height: 100% }
</style>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&language=zh_CN"></script>
<script>
var map, geocoder;
function initialize() {
var latlng = new google.maps.LatLng(31.230393, 121.473704);
var options = {
zoom: 11,
center: latlng,
disableDefaultUI: true,
panControl: true,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: false,
overviewMapControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), options);
geocoder = new google.maps.Geocoder();
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[3]) {
parent.document.getElementById("kindeditor_plugin_map_address").value = results[3].formatted_address;
}
}
});
}
function search(address) {
if (!map) return;
geocoder.geocode({address : address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setZoom(11);
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Invalid address: " + address);
}
});
}
</script>
</head>
<body onload="initialize();">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html> | zzblog | web/js/kindeditor/plugins/map/map.html | HTML | asf20 | 1,752 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('plainpaste', function(K) {
var self = this, name = 'plainpaste';
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
html = '<div style="padding:10px 20px;">' +
'<div style="margin-bottom:10px;">' + lang.comment + '</div>' +
'<textarea class="ke-textarea" style="width:408px;height:260px;"></textarea>' +
'</div>',
dialog = self.createDialog({
name : name,
width : 450,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var html = textarea.val();
html = K.escape(html);
html = html.replace(/ {2}/g, ' ');
if (self.newlineTag == 'p') {
html = html.replace(/^/, '<p>').replace(/$/, '</p>').replace(/\n/g, '</p><p>');
} else {
html = html.replace(/\n/g, '<br />$&');
}
self.insertHtml(html).hideDialog().focus();
}
}
}),
textarea = K('textarea', dialog.div);
textarea[0].focus();
});
});
| zzblog | web/js/kindeditor/plugins/plainpaste/plainpaste.js | JavaScript | asf20 | 1,413 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
// google code prettify: http://google-code-prettify.googlecode.com/
// http://google-code-prettify.googlecode.com/
KindEditor.plugin('code', function(K) {
var self = this, name = 'code';
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
html = ['<div style="padding:10px 20px;">',
'<div class="ke-dialog-row">',
'<select class="ke-code-type">',
'<option value="js">JavaScript</option>',
'<option value="html">HTML</option>',
'<option value="css">CSS</option>',
'<option value="php">PHP</option>',
'<option value="pl">Perl</option>',
'<option value="py">Python</option>',
'<option value="rb">Ruby</option>',
'<option value="java">Java</option>',
'<option value="vb">ASP/VB</option>',
'<option value="cpp">C/C++</option>',
'<option value="cs">C#</option>',
'<option value="xml">XML</option>',
'<option value="bsh">Shell</option>',
'<option value="">Other</option>',
'</select>',
'</div>',
'<textarea class="ke-textarea" style="width:408px;height:260px;"></textarea>',
'</div>'].join(''),
dialog = self.createDialog({
name : name,
width : 450,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var type = K('.ke-code-type', dialog.div).val(),
code = textarea.val(),
cls = type === '' ? '' : ' lang-' + type,
html = '<pre class="prettyprint' + cls + '">\n' + K.escape(code) + '</pre> ';
self.insertHtml(html).hideDialog().focus();
}
}
}),
textarea = K('textarea', dialog.div);
textarea[0].focus();
});
});
| zzblog | web/js/kindeditor/plugins/code/code.js | JavaScript | asf20 | 2,071 |
.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee}
pre.prettyprint {
border: 0;
border-left: 3px solid rgb(204, 204, 204);
margin-left: 2em;
padding: 0.5em;
font-size: 110%;
display: block;
font-family: "Consolas", "Monaco", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace;
margin: 1em 0px;
white-space: pre;
}
| zzblog | web/js/kindeditor/plugins/code/prettify.css | CSS | asf20 | 960 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('lineheight', function(K) {
var self = this, name = 'lineheight', lang = self.lang(name + '.');
self.clickToolbar(name, function() {
var curVal = '', commonNode = self.cmd.commonNode({'*' : '.line-height'});
if (commonNode) {
curVal = commonNode.css('line-height');
}
var menu = self.createMenu({
name : name,
width : 150
});
K.each(lang.lineHeight, function(i, row) {
K.each(row, function(key, val) {
menu.addItem({
title : val,
checked : curVal === key,
click : function() {
self.cmd.toggle('<span style="line-height:' + key + ';"></span>', {
span : '.line-height=' + key
});
self.updateState();
self.addBookmark();
self.hideMenu();
}
});
});
});
});
});
| zzblog | web/js/kindeditor/plugins/lineheight/lineheight.js | JavaScript | asf20 | 1,181 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('emoticons', function(K) {
var self = this, name = 'emoticons',
path = (self.emoticonsPath || self.basePath + 'plugins/emoticons/images/'),
allowPreview = self.allowPreviewEmoticons === undefined ? true : self.allowPreviewEmoticons,
currentPageNum = 1;
self.clickToolbar(name, function() {
var rows = 5, cols = 9, total = 135, startNum = 0,
cells = rows * cols, pages = Math.ceil(total / cells),
colsHalf = Math.floor(cols / 2),
wrapperDiv = K('<div class="ke-plugin-emoticons"></div>'),
elements = [],
menu = self.createMenu({
name : name,
beforeRemove : function() {
removeEvent();
}
});
menu.div.append(wrapperDiv);
var previewDiv, previewImg;
if (allowPreview) {
previewDiv = K('<div class="ke-preview"></div>').css('right', 0);
previewImg = K('<img class="ke-preview-img" src="' + path + startNum + '.gif" />');
wrapperDiv.append(previewDiv);
previewDiv.append(previewImg);
}
function bindCellEvent(cell, j, num) {
if (previewDiv) {
cell.mouseover(function() {
if (j > colsHalf) {
previewDiv.css('left', 0);
previewDiv.css('right', '');
} else {
previewDiv.css('left', '');
previewDiv.css('right', 0);
}
previewImg.attr('src', path + num + '.gif');
K(this).addClass('ke-on');
});
} else {
cell.mouseover(function() {
K(this).addClass('ke-on');
});
}
cell.mouseout(function() {
K(this).removeClass('ke-on');
});
cell.click(function(e) {
self.insertHtml('<img src="' + path + num + '.gif" border="0" alt="" />').hideMenu().focus();
e.stop();
});
}
function createEmoticonsTable(pageNum, parentDiv) {
var table = document.createElement('table');
parentDiv.append(table);
if (previewDiv) {
K(table).mouseover(function() {
previewDiv.show();
});
K(table).mouseout(function() {
previewDiv.hide();
});
elements.push(K(table));
}
table.className = 'ke-table';
table.cellPadding = 0;
table.cellSpacing = 0;
table.border = 0;
var num = (pageNum - 1) * cells + startNum;
for (var i = 0; i < rows; i++) {
var row = table.insertRow(i);
for (var j = 0; j < cols; j++) {
var cell = K(row.insertCell(j));
cell.addClass('ke-cell');
bindCellEvent(cell, j, num);
var span = K('<span class="ke-img"></span>')
.css('background-position', '-' + (24 * num) + 'px 0px')
.css('background-image', 'url(' + path + 'static.gif)');
cell.append(span);
elements.push(cell);
num++;
}
}
return table;
}
var table = createEmoticonsTable(currentPageNum, wrapperDiv);
function removeEvent() {
K.each(elements, function() {
this.unbind();
});
}
var pageDiv;
function bindPageEvent(el, pageNum) {
el.click(function(e) {
removeEvent();
table.parentNode.removeChild(table);
pageDiv.remove();
table = createEmoticonsTable(pageNum, wrapperDiv);
createPageTable(pageNum);
currentPageNum = pageNum;
e.stop();
});
}
function createPageTable(currentPageNum) {
pageDiv = K('<div class="ke-page"></div>');
wrapperDiv.append(pageDiv);
for (var pageNum = 1; pageNum <= pages; pageNum++) {
if (currentPageNum !== pageNum) {
var a = K('<a href="javascript:;">[' + pageNum + ']</a>');
bindPageEvent(a, pageNum);
pageDiv.append(a);
elements.push(a);
} else {
pageDiv.append(K('@[' + pageNum + ']'));
}
pageDiv.append(K('@ '));
}
}
createPageTable(currentPageNum);
});
});
| zzblog | web/js/kindeditor/plugins/emoticons/emoticons.js | JavaScript | asf20 | 4,063 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('media', function(K) {
var self = this, name = 'media', lang = self.lang(name + '.'),
allowMediaUpload = K.undef(self.allowMediaUpload, true),
allowFileManager = K.undef(self.allowFileManager, false),
uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php');
self.plugin.media = {
edit : function() {
var html = [
'<div style="padding:10px 20px;">',
//url
'<div class="ke-dialog-row">',
'<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
'<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:160px;" /> ',
'<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
'</span>',
'</div>',
//width
'<div class="ke-dialog-row">',
'<label for="keWidth" style="width:60px;">' + lang.width + '</label>',
'<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" />',
'</div>',
//height
'<div class="ke-dialog-row">',
'<label for="keHeight" style="width:60px;">' + lang.height + '</label>',
'<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" />',
'</div>',
//autostart
'<div class="ke-dialog-row">',
'<label for="keAutostart">' + lang.autostart + '</label>',
'<input type="checkbox" id="keAutostart" name="autostart" value="" /> ',
'</div>',
'</div>'
].join('');
var dialog = self.createDialog({
name : name,
width : 450,
height : 230,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var url = K.trim(urlBox.val()),
width = widthBox.val(),
height = heightBox.val();
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
if (!/^\d*$/.test(width)) {
alert(self.lang('invalidWidth'));
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
alert(self.lang('invalidHeight'));
heightBox[0].focus();
return;
}
var html = K.mediaImg(self.themesPath + 'common/blank.gif', {
src : url,
type : K.mediaType(url),
width : width,
height : height,
autostart : autostartBox[0].checked ? 'true' : 'false',
loop : 'true'
});
self.insertHtml(html).hideDialog().focus();
}
}
}),
div = dialog.div,
urlBox = K('[name="url"]', div),
viewServerBtn = K('[name="viewServer"]', div),
widthBox = K('[name="width"]', div),
heightBox = K('[name="height"]', div),
autostartBox = K('[name="autostart"]', div);
urlBox.val('http://');
if (allowMediaUpload) {
var uploadbutton = K.uploadbutton({
button : K('.ke-upload-button', div)[0],
fieldName : 'imgFile',
url : K.addParam(uploadJson, 'dir=media'),
afterUpload : function(data) {
dialog.hideLoading();
if (data.error === 0) {
var url = K.formatUrl(data.url, 'absolute');
urlBox.val(url);
if (self.afterUpload) {
self.afterUpload.call(self, url);
}
alert(self.lang('uploadSuccess'));
} else {
alert(data.message);
}
},
afterError : function(html) {
dialog.hideLoading();
self.errorDialog(html);
}
});
uploadbutton.fileBox.change(function(e) {
dialog.showLoading(self.lang('uploadLoading'));
uploadbutton.submit();
});
} else {
K('.ke-upload-button', div).hide();
urlBox.width(250);
}
if (allowFileManager) {
viewServerBtn.click(function(e) {
self.loadPlugin('filemanager', function() {
self.plugin.filemanagerDialog({
viewType : 'LIST',
dirName : 'media',
clickFn : function(url, title) {
if (self.dialogs.length > 1) {
K('[name="url"]', div).val(url);
self.hideDialog();
}
}
});
});
});
} else {
viewServerBtn.hide();
}
var img = self.plugin.getSelectedMedia();
if (img) {
var attrs = K.mediaAttrs(img.attr('data-ke-tag'));
urlBox.val(attrs.src);
widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0);
heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0);
autostartBox[0].checked = (attrs.autostart === 'true');
}
urlBox[0].focus();
urlBox[0].select();
},
'delete' : function() {
self.plugin.getSelectedMedia().remove();
}
};
self.clickToolbar(name, self.plugin.media.edit);
});
| zzblog | web/js/kindeditor/plugins/media/media.js | JavaScript | asf20 | 5,341 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('pagebreak', function(K) {
var self = this, name = 'pagebreak';
self.clickToolbar(name, function() {
var cmd = self.cmd, range = cmd.range;
self.focus();
range.enlarge(true);
cmd.split(true);
var tail = self.newlineTag == 'br' || K.WEBKIT ? '' : '<p id="__kindeditor_tail_tag__"></p>';
self.insertHtml('<hr style="page-break-after: always;" class="ke-pagebreak" />' + tail);
if (tail !== '') {
var p = K('#__kindeditor_tail_tag__', self.edit.doc);
range.selectNodeContents(p[0]);
p.removeAttr('id');
cmd.select();
}
});
});
| zzblog | web/js/kindeditor/plugins/pagebreak/pagebreak.js | JavaScript | asf20 | 970 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('link', function(K) {
var self = this, name = 'link';
self.plugin.link = {
edit : function() {
var lang = self.lang(name + '.'),
html = '<div style="padding:10px 20px;">' +
//url
'<div class="ke-dialog-row">' +
'<label for="keUrl">' + lang.url + '</label>' +
'<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:90%;" /></div>' +
//type
'<div class="ke-dialog-row"">' +
'<label for="keType">' + lang.linkType + '</label>' +
'<select id="keType" name="type"></select>' +
'</div>' +
'</div>',
dialog = self.createDialog({
name : name,
width : 400,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var url = K.trim(urlBox.val());
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
self.exec('createlink', url, typeBox.val()).hideDialog().focus();
}
}
}),
div = dialog.div,
urlBox = K('input[name="url"]', div),
typeBox = K('select[name="type"]', div);
urlBox.val('http://');
typeBox[0].options[0] = new Option(lang.newWindow, '_blank');
typeBox[0].options[1] = new Option(lang.selfWindow, '');
self.cmd.selection();
var a = self.plugin.getSelectedLink();
if (a) {
self.cmd.range.selectNode(a[0]);
self.cmd.select();
urlBox.val(a.attr('data-ke-src'));
typeBox.val(a.attr('target'));
}
urlBox[0].focus();
urlBox[0].select();
},
'delete' : function() {
self.exec('unlink', null);
}
};
self.clickToolbar(name, self.plugin.link.edit);
});
| zzblog | web/js/kindeditor/plugins/link/link.js | JavaScript | asf20 | 2,156 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('preview', function(K) {
var self = this, name = 'preview', undefined;
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
html = '<div style="padding:10px 20px;">' +
'<iframe class="ke-textarea" frameborder="0" style="width:708px;height:400px;"></iframe>' +
'</div>',
dialog = self.createDialog({
name : name,
width : 750,
title : self.lang(name),
body : html
}),
iframe = K('iframe', dialog.div),
doc = K.iframeDoc(iframe);
doc.open();
doc.write(self.fullHtml());
doc.close();
K(doc.body).css('background-color', '#FFF');
iframe[0].contentWindow.focus();
});
});
| zzblog | web/js/kindeditor/plugins/preview/preview.js | JavaScript | asf20 | 1,058 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('template', function(K) {
var self = this, name = 'template', lang = self.lang(name + '.'),
htmlPath = self.pluginsPath + name + '/html/';
function getFilePath(fileName) {
return htmlPath + fileName + '?ver=' + encodeURIComponent(K.DEBUG ? K.TIME : K.VERSION);
}
self.clickToolbar(name, function() {
var lang = self.lang(name + '.'),
arr = ['<div class="ke-plugin-template" style="padding:10px 20px;">',
'<div class="ke-header">',
// left start
'<div class="ke-left">',
lang. selectTemplate + ' <select>'];
K.each(lang.fileList, function(key, val) {
arr.push('<option value="' + key + '">' + val + '</option>');
});
html = [arr.join(''),
'</select></div>',
// right start
'<div class="ke-right">',
'<input type="checkbox" id="keReplaceFlag" name="replaceFlag" value="1" /> <label for="keReplaceFlag">' + lang.replaceContent + '</label>',
'</div>',
'<div class="ke-clearfix"></div>',
'</div>',
'<iframe class="ke-textarea" frameborder="0" style="width:458px;height:260px;background-color:#FFF;"></iframe>',
'</div>'].join('');
var dialog = self.createDialog({
name : name,
width : 500,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var doc = K.iframeDoc(iframe);
self[checkbox[0].checked ? 'html' : 'insertHtml'](doc.body.innerHTML).hideDialog().focus();
}
}
});
var selectBox = K('select', dialog.div),
checkbox = K('[name="replaceFlag"]', dialog.div),
iframe = K('iframe', dialog.div);
checkbox[0].checked = true;
iframe.attr('src', getFilePath(selectBox.val()));
selectBox.change(function() {
iframe.attr('src', getFilePath(this.value));
});
});
});
| zzblog | web/js/kindeditor/plugins/template/template.js | JavaScript | asf20 | 2,191 |
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h3>
<img align="left" height="100" style="margin-right: 10px" width="100" />在此处输入标题
</h3>
<p>
在此处输入内容
</p>
</body>
</html> | zzblog | web/js/kindeditor/plugins/template/html/1.html | HTML | asf20 | 230 |
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<p>
在此处输入内容
</p>
<ol>
<li>
描述1
</li>
<li>
描述2
</li>
<li>
描述3
</li>
</ol>
<p>
在此处输入内容
</p>
<ul>
<li>
描述1
</li>
<li>
描述2
</li>
<li>
描述3
</li>
</ul>
</body>
</html> | zzblog | web/js/kindeditor/plugins/template/html/3.html | HTML | asf20 | 338 |
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h3>
标题
</h3>
<table style="width:100%;" cellpadding="2" cellspacing="0" border="1">
<tbody>
<tr>
<td>
<h3>标题1</h3>
</td>
<td>
<h3>标题1</h3>
</td>
</tr>
<tr>
<td>
内容1
</td>
<td>
内容2
</td>
</tr>
<tr>
<td>
内容3
</td>
<td>
内容4
</td>
</tr>
</tbody>
</table>
<p>
表格说明
</p>
</body>
</html> | zzblog | web/js/kindeditor/plugins/template/html/2.html | HTML | asf20 | 498 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('filemanager', function(K) {
var self = this, name = 'filemanager',
fileManagerJson = K.undef(self.fileManagerJson, self.basePath + 'php/file_manager_json.php'),
imgPath = self.pluginsPath + name + '/images/',
lang = self.lang(name + '.');
function makeFileTitle(filename, filesize, datetime) {
return filename + ' (' + Math.ceil(filesize / 1024) + 'KB, ' + datetime + ')';
}
function bindTitle(el, data) {
if (data.is_dir) {
el.attr('title', data.filename);
} else {
el.attr('title', makeFileTitle(data.filename, data.filesize, data.datetime));
}
}
self.plugin.filemanagerDialog = function(options) {
var width = K.undef(options.width, 520),
height = K.undef(options.height, 510),
dirName = K.undef(options.dirName, ''),
viewType = K.undef(options.viewType, 'VIEW').toUpperCase(), // "LIST" or "VIEW"
clickFn = options.clickFn;
var html = [
'<div style="padding:10px 20px;">',
// header start
'<div class="ke-plugin-filemanager-header">',
// left start
'<div class="ke-left">',
'<img class="ke-inline-block" name="moveupImg" src="' + imgPath + 'go-up.gif" width="16" height="16" border="0" alt="" /> ',
'<a class="ke-inline-block" name="moveupLink" href="javascript:;">' + lang.moveup + '</a>',
'</div>',
// right start
'<div class="ke-right">',
lang.viewType + ' <select class="ke-inline-block" name="viewType">',
'<option value="VIEW">' + lang.viewImage + '</option>',
'<option value="LIST">' + lang.listImage + '</option>',
'</select> ',
lang.orderType + ' <select class="ke-inline-block" name="orderType">',
'<option value="NAME">' + lang.fileName + '</option>',
'<option value="SIZE">' + lang.fileSize + '</option>',
'<option value="TYPE">' + lang.fileType + '</option>',
'</select>',
'</div>',
'<div class="ke-clearfix"></div>',
'</div>',
// body start
'<div class="ke-plugin-filemanager-body"></div>',
'</div>'
].join('');
var dialog = self.createDialog({
name : name,
width : width,
height : height,
title : self.lang(name),
body : html
}),
div = dialog.div,
bodyDiv = K('.ke-plugin-filemanager-body', div),
moveupImg = K('[name="moveupImg"]', div),
moveupLink = K('[name="moveupLink"]', div),
viewServerBtn = K('[name="viewServer"]', div),
viewTypeBox = K('[name="viewType"]', div),
orderTypeBox = K('[name="orderType"]', div);
function reloadPage(path, order, func) {
var param = 'path=' + path + '&order=' + order + '&dir=' + dirName;
dialog.showLoading(self.lang('ajaxLoading'));
K.ajax(K.addParam(fileManagerJson, param + '&' + new Date().getTime()), function(data) {
dialog.hideLoading();
func(data);
});
}
var elList = [];
function bindEvent(el, result, data, createFunc) {
var fileUrl = K.formatUrl(result.current_url + data.filename, 'absolute'),
dirPath = encodeURIComponent(result.current_dir_path + data.filename + '/');
if (data.is_dir) {
el.click(function(e) {
reloadPage(dirPath, orderTypeBox.val(), createFunc);
});
} else if (data.is_photo) {
el.click(function(e) {
clickFn.call(this, fileUrl, data.filename);
});
} else {
el.click(function(e) {
clickFn.call(this, fileUrl, data.filename);
});
}
elList.push(el);
}
function createCommon(result, createFunc) {
// remove events
K.each(elList, function() {
this.unbind();
});
moveupLink.unbind();
viewTypeBox.unbind();
orderTypeBox.unbind();
// add events
if (result.current_dir_path) {
moveupLink.click(function(e) {
reloadPage(result.moveup_dir_path, orderTypeBox.val(), createFunc);
});
}
function changeFunc() {
if (viewTypeBox.val() == 'VIEW') {
reloadPage(result.current_dir_path, orderTypeBox.val(), createView);
} else {
reloadPage(result.current_dir_path, orderTypeBox.val(), createList);
}
}
viewTypeBox.change(changeFunc);
orderTypeBox.change(changeFunc);
bodyDiv.html('');
}
function createList(result) {
createCommon(result, createList);
var table = document.createElement('table');
table.className = 'ke-table';
table.cellPadding = 0;
table.cellSpacing = 0;
table.border = 0;
bodyDiv.append(table);
var fileList = result.file_list;
for (var i = 0, len = fileList.length; i < len; i++) {
var data = fileList[i], row = K(table.insertRow(i));
row.mouseover(function(e) {
K(this).addClass('ke-on');
})
.mouseout(function(e) {
K(this).removeClass('ke-on');
});
var iconUrl = imgPath + (data.is_dir ? 'folder-16.gif' : 'file-16.gif'),
img = K('<img src="' + iconUrl + '" width="16" height="16" alt="' + data.filename + '" align="absmiddle" />'),
cell0 = K(row[0].insertCell(0)).addClass('ke-cell ke-name').append(img).append(document.createTextNode(' ' + data.filename));
if (!data.is_dir || data.has_file) {
row.css('cursor', 'pointer');
cell0.attr('title', data.filename);
bindEvent(cell0, result, data, createList);
} else {
cell0.attr('title', lang.emptyFolder);
}
K(row[0].insertCell(1)).addClass('ke-cell ke-size').html(data.is_dir ? '-' : Math.ceil(data.filesize / 1024) + 'KB');
K(row[0].insertCell(2)).addClass('ke-cell ke-datetime').html(data.datetime);
}
}
function createView(result) {
createCommon(result, createView);
var fileList = result.file_list;
for (var i = 0, len = fileList.length; i < len; i++) {
var data = fileList[i],
div = K('<div class="ke-inline-block ke-item"></div>');
bodyDiv.append(div);
var photoDiv = K('<div class="ke-inline-block ke-photo"></div>')
.mouseover(function(e) {
K(this).addClass('ke-on');
})
.mouseout(function(e) {
K(this).removeClass('ke-on');
});
div.append(photoDiv);
var fileUrl = result.current_url + data.filename,
iconUrl = data.is_dir ? imgPath + 'folder-64.gif' : (data.is_photo ? fileUrl : imgPath + 'file-64.gif');
var img = K('<img src="' + iconUrl + '" width="80" height="80" alt="' + data.filename + '" />');
if (!data.is_dir || data.has_file) {
photoDiv.css('cursor', 'pointer');
bindTitle(photoDiv, data);
bindEvent(photoDiv, result, data, createView);
} else {
photoDiv.attr('title', lang.emptyFolder);
}
photoDiv.append(img);
div.append('<div class="ke-name" title="' + data.filename + '">' + data.filename + '</div>');
}
}
viewTypeBox.val(viewType);
reloadPage('', orderTypeBox.val(), viewType == 'VIEW' ? createView : createList);
return dialog;
}
});
| zzblog | web/js/kindeditor/plugins/filemanager/filemanager.js | JavaScript | asf20 | 7,157 |
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('anchor', function(K) {
var self = this, name = 'anchor', lang = self.lang(name + '.');
self.plugin.anchor = {
edit : function() {
var html = ['<div style="padding:10px 20px;">',
'<div class="ke-dialog-row">',
'<label for="keName">' + lang.name + '</label>',
'<input class="ke-input-text" type="text" id="keName" name="name" value="" style="width:100px;" />',
'</div>',
'</div>'].join('');
var dialog = self.createDialog({
name : name,
width : 300,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
self.insertHtml('<a name="' + nameBox.val() + '">').hideDialog().focus();
}
}
});
var div = dialog.div,
nameBox = K('input[name="name"]', div);
var img = self.plugin.getSelectedAnchor();
if (img) {
nameBox.val(unescape(img.attr('data-ke-name')));
}
nameBox[0].focus();
nameBox[0].select();
},
'delete' : function() {
self.plugin.getSelectedAnchor().remove();
}
};
self.clickToolbar(name, self.plugin.anchor.edit);
});
| zzblog | web/js/kindeditor/plugins/anchor/anchor.js | JavaScript | asf20 | 1,518 |