answer stringlengths 15 1.25M |
|---|
// Accord Unit Tests
// The Accord.NET Framework
// cesarsouza at gmail.com
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
namespace Accord.Tests.Statistics.Models.Fields
{
using System;
using Accord.Math.Differentiation;
using Accord.Statistics.Distributions.Multivariate;
using Accord.Statistics.Distributions.Univariate;
using Accord.Statistics.Models.Fields;
using Accord.Statistics.Models.Fields.Functions;
using Accord.Statistics.Models.Fields.Learning;
using Accord.Statistics.Models.Markov;
using Accord.Statistics.Models.Markov.Learning;
using Accord.Statistics.Models.Markov.Topology;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Accord.Statistics.Distributions.Fitting;
using Accord.Math;
using Accord.Statistics.Models.Fields.Functions.Specialized;
using System.Collections.Generic;
using Accord.Statistics.Models.Fields.Features;
using System.Linq;
[TestClass()]
public class <API key>
{
private TestContext testContextInstance;
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
public static <API key><Independent> CreateModel1()
{
// Create a Continuous density Hidden Markov Model Sequence Classifier
// to detect a multivariate sequence and the same sequence backwards.
double[][][] sequences = new double[][][]
{
new double[][]
{
// This is the first sequence with label = 0
new double[] { 0 },
new double[] { 1 },
new double[] { 2 },
new double[] { 3 },
new double[] { 4 },
},
new double[][]
{
// This is the second sequence with label = 1
new double[] { 4 },
new double[] { 3 },
new double[] { 2 },
new double[] { 1 },
new double[] { 0 },
}
};
// Labels for the sequences
int[] labels = { 0, 1 };
// Creates a sequence classifier containing 2 hidden Markov Models
// with 2 states and an underlying Normal distribution as density.
NormalDistribution component = new NormalDistribution();
Independent density = new Independent(component);
var classifier = new <API key><Independent>(2, new Ergodic(2), density);
// Configure the learning algorithms to train the sequence classifier
var teacher = new <API key><Independent>(classifier,
// Train each model until the log-likelihood changes less than 0.001
modelIndex => new BaumWelchLearning<Independent>(classifier.Models[modelIndex])
{
Tolerance = 0.0001,
Iterations = 0
}
);
// Train the sequence classifier using the algorithm
double logLikelihood = teacher.Run(sequences, labels);
return classifier;
}
public static <API key><Independent> CreateModel2(out double[][][] sequences, out int[] labels)
{
sequences = new double[][][]
{
new double[][]
{
// This is the first sequence with label = 0
new double[] { 0, 1.1 },
new double[] { 1, 2.5 },
new double[] { 1, 3.4 },
new double[] { 1, 4.7 },
new double[] { 2, 5.8 },
},
new double[][]
{
// This is the second sequence with label = 1
new double[] { 2, 3.2 },
new double[] { 2, 2.6 },
new double[] { 1, 1.2 },
new double[] { 1, 0.8 },
new double[] { 0, 1.1 },
}
};
labels = new[] { 0, 1 };
// Create a Continuous density Hidden Markov Model Sequence Classifier
// to detect a multivariate sequence and the same sequence backwards.
var comp1 = new <API key>(3);
var comp2 = new NormalDistribution(1);
var density = new Independent(comp1, comp2);
// Creates a sequence classifier containing 2 hidden Markov Models with 2 states
// and an underlying multivariate mixture of Normal distributions as density.
var classifier = new <API key><Independent>(
2, new Ergodic(2), density);
// Configure the learning algorithms to train the sequence classifier
var teacher = new <API key><Independent>(
classifier,
// Train each model until the log-likelihood changes less than 0.0001
modelIndex => new BaumWelchLearning<Independent>(
classifier.Models[modelIndex])
{
Tolerance = 0.0001,
Iterations = 0,
}
);
// Train the sequence classifier using the algorithm
double logLikelihood = teacher.Run(sequences, labels);
return classifier;
}
public static <API key><Independent> CreateModel3(out double[][][] sequences2, out int[] labels2)
{
sequences2 = new double[][][]
{
new double[][]
{
// This is the first sequence with label = 0
new double[] { 1, 1.12, 2.41, 1.17, 9.3 },
new double[] { 1, 2.54, 1.45, 0.16, 4.5 },
new double[] { 1, 3.46, 2.63, 1.15, 9.2 },
new double[] { 1, 4.73, 0.41, 1.54, 5.5 },
new double[] { 2, 5.81, 2.42, 1.13, 9.1 },
},
new double[][]
{
// This is the first sequence with label = 0
new double[] { 0, 1.49, 2.48, 1.18, 9.37 },
new double[] { 1, 2.18, 1.44, 2.19, 1.56 },
new double[] { 1, 3.77, 2.62, 1.10, 9.25 },
new double[] { 2, 4.76, 5.44, 3.58, 5.54 },
new double[] { 2, 5.85, 2.46, 1.16, 5.13 },
new double[] { 2, 4.84, 5.44, 3.54, 5.52 },
new double[] { 2, 5.83, 3.41, 1.22, 5.11 },
},
new double[][]
{
// This is the first sequence with label = 0
new double[] { 2, 1.11, 2.41, 1.12, 2.31 },
new double[] { 1, 2.52, 3.73, 0.12, 4.50 },
new double[] { 1, 3.43, 2.61, 1.24, 9.29 },
new double[] { 1, 4.74, 2.42, 2.55, 6.57 },
new double[] { 2, 5.85, 2.43, 1.16, 9.16 },
},
new double[][]
{
// This is the second sequence with label = 1
new double[] { 0, 1.26, 5.44, 1.56, 9.55 },
new double[] { 2, 2.67, 5.45, 4.27, 1.54 },
new double[] { 1, 1.28, 3.46, 2.18, 4.13 },
new double[] { 1, 5.89, 2.57, 1.79, 5.02 },
new double[] { 0, 1.40, 2.48, 2.10, 6.41 },
},
new double[][]
{
// This is the second sequence with label = 1
new double[] { 2, 3.21, 2.49, 1.54, 9.17 },
new double[] { 2, 2.62, 5.40, 4.25, 1.54 },
new double[] { 1, 1.53, 6.49, 2.17, 4.52 },
new double[] { 1, 2.84, 2.58, 1.73, 6.04 },
new double[] { 1, 1.45, 2.47, 2.28, 5.42 },
new double[] { 1, 1.46, 2.46, 2.35, 5.41 },
},
new double[][]
{
// This is the second sequence with label = 1
new double[] { 1, 5.27, 5.45, 1.4, 9.5 },
new double[] { 2, 2.68, 2.54, 3.2, 2.2 },
new double[] { 1, 2.89, 3.83, 2.6, 4.1 },
new double[] { 1, 1.80, 1.32, 1.2, 4.2 },
new double[] { 0, 1.41, 2.41, 2.1, 6.4 },
}
};
labels2 = new[] { 0, 0, 0, 1, 1, 1 };
// Create a Continuous density Hidden Markov Model Sequence Classifier
// to detect a multivariate sequence and the same sequence backwards.
var comp1 = new <API key>(3);
var comp2 = new NormalDistribution(1);
var comp3 = new NormalDistribution(2);
var comp4 = new NormalDistribution(3);
var comp5 = new NormalDistribution(4);
var density = new Independent(comp1, comp2, comp3, comp4, comp5);
// Creates a sequence classifier containing 2 hidden Markov Models with 2 states
// and an underlying multivariate mixture of Normal distributions as density.
var classifier = new <API key><Independent>(
2, new Forward(5), density);
// Configure the learning algorithms to train the sequence classifier
var teacher = new <API key><Independent>(
classifier,
// Train each model until the log-likelihood changes less than 0.0001
modelIndex => new BaumWelchLearning<Independent>(
classifier.Models[modelIndex])
{
Tolerance = 0.0001,
Iterations = 0,
}
);
// Train the sequence classifier using the algorithm
double logLikelihood = teacher.Run(sequences2, labels2);
return classifier;
}
public static <API key><Independent<NormalDistribution>> CreateModel4(out double[][][] words, out int[] labels, bool usePriors)
{
double[][] hello =
{
new double[] { 1.0, 0.1, 0.0, 0.0 }, // let's say the word
new double[] { 0.0, 1.0, 0.1, 0.1 }, // hello took 6 frames
new double[] { 0.0, 1.0, 0.1, 0.1 }, // to be recorded.
new double[] { 0.0, 0.0, 1.0, 0.0 },
new double[] { 0.0, 0.0, 1.0, 0.0 },
new double[] { 0.0, 0.0, 0.1, 1.1 },
};
double[][] car =
{
new double[] { 0.0, 0.0, 0.0, 1.0 }, // the car word
new double[] { 0.1, 0.0, 1.0, 0.1 }, // took only 4.
new double[] { 0.0, 0.0, 0.1, 0.0 },
new double[] { 1.0, 0.0, 0.0, 0.0 },
};
double[][] wardrobe =
{
new double[] { 0.0, 0.0, 1.0, 0.0 }, // same for the
new double[] { 0.1, 0.0, 1.0, 0.1 }, // wardrobe word.
new double[] { 0.0, 0.1, 1.0, 0.0 },
new double[] { 0.1, 0.0, 1.0, 0.1 },
};
double[][] wardrobe2 =
{
new double[] { 0.0, 0.0, 1.0, 0.0 }, // same for the
new double[] { 0.2, 0.0, 1.0, 0.1 }, // wardrobe word.
new double[] { 0.0, 0.1, 1.0, 0.0 },
new double[] { 0.1, 0.0, 1.0, 0.2 },
};
words = new double[][][] { hello, car, wardrobe, wardrobe2 };
labels = new [] { 0, 1, 2, 2 };
var initial = new Independent<NormalDistribution>
(
new NormalDistribution(0, 1),
new NormalDistribution(0, 1),
new NormalDistribution(0, 1),
new NormalDistribution(0, 1)
);
int numberOfWords = 3;
int numberOfStates = 5;
var classifier = new <API key><Independent<NormalDistribution>>
(
classes: numberOfWords,
topology: new Forward(numberOfStates),
initial: initial
);
var teacher = new <API key><Independent<NormalDistribution>>(classifier,
modelIndex => new BaumWelchLearning<Independent<NormalDistribution>>(classifier.Models[modelIndex])
{
Tolerance = 0.001,
Iterations = 100,
FittingOptions = new IndependentOptions()
{
InnerOption = new NormalOptions() { Regularization = 1e-5 }
}
}
);
if (usePriors)
teacher.Empirical = true;
double logLikelihood = teacher.Run(words, labels);
return classifier;
}
[TestMethod()]
public void ComputeTest()
{
var model = CreateModel1();
var target = new <API key>(model);
var hcrf = new <API key><double[]>(target);
double actual;
double expected;
double[][] x = { new double[] { 0 }, new double[] { 1 } };
for (int c = 0; c < model.Classes; c++)
{
for (int i = 0; i < model[c].States; i++)
{
// Check initial state transitions
expected = model.Priors[c] * Math.Exp(model[c].Probabilities[i]) * model[c].Emissions[i].<API key>(x[0]);
actual = Math.Exp(target.Factors[c].Compute(-1, i, x, 0, c));
Assert.AreEqual(expected, actual, 1e-6);
Assert.IsFalse(double.IsNaN(actual));
}
for (int t = 1; t < x.Length; t++)
{
// Check normal state transitions
for (int i = 0; i < model[c].States; i++)
{
for (int j = 0; j < model[c].States; j++)
{
double xb = Math.Exp(model[c].Transitions[i, j]);
double xc = model[c].Emissions[j].<API key>(x[t]);
expected = xb * xc;
actual = Math.Exp(target.Factors[c].Compute(i, j, x, t, c));
Assert.AreEqual(expected, actual, 1e-6);
Assert.IsFalse(double.IsNaN(actual));
}
}
}
actual = model.LogLikelihood(x, c);
expected = hcrf.LogLikelihood(x, c);
Assert.AreEqual(expected, actual, 1e-8);
Assert.IsFalse(double.IsNaN(actual));
}
}
[TestMethod()]
public void ComputeTest2()
{
double[][][] sequences;
int[] labels;
var model = CreateModel2(out sequences, out labels);
var target = new <API key>(model);
var hcrf = new <API key><double[]>(target);
double actual;
double expected;
double[][] x = { new double[] { 0, 1.7 }, new double[] { 2, 2.1 } };
for (int c = 0; c < model.Classes; c++)
{
for (int i = 0; i < model[c].States; i++)
{
// Check initial state transitions
expected = model.Priors[c] * Math.Exp(model[c].Probabilities[i]) * model[c].Emissions[i].<API key>(x[0]);
actual = Math.Exp(target.Factors[c].Compute(-1, i, x, 0, c));
Assert.AreEqual(expected, actual, 1e-6);
Assert.IsFalse(double.IsNaN(actual));
}
for (int t = 1; t < x.Length; t++)
{
// Check normal state transitions
for (int i = 0; i < model[c].States; i++)
{
for (int j = 0; j < model[c].States; j++)
{
double xb = Math.Exp(model[c].Transitions[i, j]);
double xc = model[c].Emissions[j].<API key>(x[t]);
expected = xb * xc;
actual = Math.Exp(target.Factors[c].Compute(i, j, x, t, c));
Assert.AreEqual(expected, actual, 1e-6);
Assert.IsFalse(double.IsNaN(actual));
}
}
}
actual = model.LogLikelihood(x, c);
expected = hcrf.LogLikelihood(x, c);
Assert.AreEqual(expected, actual);
Assert.IsFalse(double.IsNaN(actual));
}
}
[TestMethod()]
public void ComputeTest3()
{
double[][][] sequences2;
int[] labels2;
var model = CreateModel3(out sequences2, out labels2);
var target = new <API key>(model);
var hcrf = new <API key><double[]>(target);
double actual;
double expected;
for (int k = 0; k < 5; k++)
{
foreach (var x in sequences2)
{
for (int c = 0; c < model.Classes; c++)
{
for (int i = 0; i < model[c].States; i++)
{
// Check initial state transitions
double xa = model.Priors[c];
double xb = Math.Exp(model[c].Probabilities[i]);
double xc = model[c].Emissions[i].<API key>(x[0]);
expected = xa * xb * xc;
actual = Math.Exp(target.Factors[c].Compute(-1, i, x, 0, c));
Assert.AreEqual(expected, actual, 1e-6);
Assert.IsFalse(double.IsNaN(actual));
}
for (int t = 1; t < x.Length; t++)
{
// Check normal state transitions
for (int i = 0; i < model[c].States; i++)
{
for (int j = 0; j < model[c].States; j++)
{
double xb = Math.Exp(model[c].Transitions[i, j]);
double xc = model[c].Emissions[j].<API key>(x[t]);
expected = xb * xc;
actual = Math.Exp(target.Factors[c].Compute(i, j, x, t, c));
Assert.AreEqual(expected, actual, 1e-6);
Assert.IsFalse(double.IsNaN(actual));
}
}
}
actual = Math.Exp(model.LogLikelihood(x, c));
expected = Math.Exp(hcrf.LogLikelihood(x, c));
Assert.AreEqual(expected, actual, 1e-10);
Assert.IsFalse(double.IsNaN(actual));
actual = model.Compute(x);
expected = hcrf.Compute(x);
Assert.AreEqual(expected, actual);
Assert.IsFalse(double.IsNaN(actual));
}
}
}
}
[TestMethod()]
public void ComputeTest4()
{
int[] labels;
double[][][] words;
<API key><Independent<NormalDistribution>> model =
CreateModel4(out words, out labels, false);
var target = new <API key>(model);
var hcrf = new <API key><double[]>(target);
Assert.AreEqual(3, model.Priors.Length);
Assert.AreEqual(1 / 3.0, model.Priors[0]);
Assert.AreEqual(1 / 3.0, model.Priors[1]);
Assert.AreEqual(1 / 3.0, model.Priors[2]);
check4(words, model, target, hcrf);
}
[TestMethod()]
public void <API key>()
{
double[][][] sequences;
int[] labels;
var model = CreateModel3(out sequences, out labels);
var target = new <API key>(model);
#pragma warning disable 0618
target.Deoptimize();
#pragma warning restore 0618
var hcrf = new <API key><double[]>(target);
Assert.AreEqual(2, model.Priors.Length);
Assert.AreEqual(1 / 2.0, model.Priors[0]);
Assert.AreEqual(1 / 2.0, model.Priors[1]);
check4(sequences, model, target, hcrf);
}
[TestMethod()]
public void <API key>()
{
int[] labels;
double[][][] words;
var model = CreateModel4(out words, out labels, false);
var target = new <API key>(model);
#pragma warning disable 0618
target.Deoptimize();
#pragma warning restore 0618
var hcrf = new <API key><double[]>(target);
Assert.AreEqual(3, model.Priors.Length);
Assert.AreEqual(1 / 3.0, model.Priors[0]);
Assert.AreEqual(1 / 3.0, model.Priors[1]);
Assert.AreEqual(1 / 3.0, model.Priors[2]);
check4(words, model, target, hcrf);
}
private static void check4(double[][][] words, <API key><Independent<NormalDistribution>> model, <API key> target, <API key><double[]> hcrf)
{
double actual;
double expected;
foreach (var x in words)
{
for (int c = 0; c < model.Classes; c++)
{
for (int i = 0; i < model[c].States; i++)
{
// Check initial state transitions
double xa = model.Priors[c];
double xb = Math.Exp(model[c].Probabilities[i]);
double xc = model[c].Emissions[i].<API key>(x[0]);
expected = xa * xb * xc;
actual = Math.Exp(target.Factors[c].Compute(-1, i, x, 0, c));
Assert.IsTrue(expected.IsRelativelyEqual(actual, 1e-10));
Assert.IsFalse(double.IsNaN(actual));
}
for (int t = 0; t < x.Length; t++)
{
// Check normal state transitions
for (int i = 0; i < model[c].States; i++)
{
for (int j = 0; j < model[c].States; j++)
{
double xb = Math.Exp(model[c].Transitions[i, j]);
double xc = model[c].Emissions[j].<API key>(x[t]);
expected = xb * xc;
actual = Math.Exp(target.Factors[c].Compute(i, j, x, t, c));
Assert.IsTrue(expected.IsRelativelyEqual(actual, 1e-10));
Assert.IsFalse(double.IsNaN(actual));
}
}
}
actual = Math.Exp(model.LogLikelihood(x, c));
expected = Math.Exp(hcrf.LogLikelihood(x, c));
Assert.AreEqual(expected, actual, 1e-10);
Assert.IsFalse(double.IsNaN(actual));
actual = model.Compute(x);
expected = hcrf.Compute(x);
Assert.AreEqual(expected, actual);
Assert.IsFalse(double.IsNaN(actual));
}
}
}
private static void check4(double[][][] words, <API key><Independent> model, <API key> target, <API key><double[]> hcrf)
{
double actual;
double expected;
foreach (var x in words)
{
for (int c = 0; c < model.Classes; c++)
{
for (int i = 0; i < model[c].States; i++)
{
// Check initial state transitions
double xa = model.Priors[c];
double xb = Math.Exp(model[c].Probabilities[i]);
double xc = model[c].Emissions[i].<API key>(x[0]);
expected = xa * xb * xc;
actual = Math.Exp(target.Factors[c].Compute(-1, i, x, 0, c));
Assert.IsTrue(expected.IsRelativelyEqual(actual, 1e-10));
Assert.IsFalse(double.IsNaN(actual));
}
for (int t = 1; t < x.Length; t++)
{
// Check normal state transitions
for (int i = 0; i < model[c].States; i++)
{
for (int j = 0; j < model[c].States; j++)
{
double xb = Math.Exp(model[c].Transitions[i, j]);
double xc = model[c].Emissions[j].<API key>(x[t]);
expected = xb * xc;
actual = Math.Exp(target.Factors[c].Compute(i, j, x, t, c));
Assert.IsTrue(expected.IsRelativelyEqual(actual, 1e-10));
Assert.IsFalse(double.IsNaN(actual));
}
}
}
actual = Math.Exp(model.LogLikelihood(x, c));
expected = Math.Exp(hcrf.LogLikelihood(x, c));
Assert.AreEqual(expected, actual, 1e-10);
Assert.IsFalse(double.IsNaN(actual));
actual = model.Compute(x);
expected = hcrf.Compute(x);
Assert.AreEqual(expected, actual);
Assert.IsFalse(double.IsNaN(actual));
}
}
}
[TestMethod()]
public void ComputeTestPriors4()
{
int[] labels;
double[][][] words;
var model = CreateModel4(out words, out labels, true);
var target = new <API key>(model);
var hcrf = new <API key><double[]>(target);
double actual;
double expected;
foreach (var x in words)
{
for (int c = 0; c < model.Classes; c++)
{
for (int i = 0; i < model[c].States; i++)
{
// Check initial state transitions
double xa = model.Priors[c];
double xb = Math.Exp(model[c].Probabilities[i]);
double xc = model[c].Emissions[i].<API key>(x[0]);
expected = xa * xb * xc;
actual = Math.Exp(target.Factors[c].Compute(-1, i, x, 0, c));
Assert.IsTrue(expected.IsRelativelyEqual(actual, 1e-5));
Assert.IsFalse(double.IsNaN(actual));
}
for (int t = 1; t < x.Length; t++)
{
// Check normal state transitions
for (int i = 0; i < model[c].States; i++)
{
for (int j = 0; j < model[c].States; j++)
{
double xb = Math.Exp(model[c].Transitions[i, j]);
double xc = model[c].Emissions[j].<API key>(x[t]);
expected = xb * xc;
actual = Math.Exp(target.Factors[c].Compute(i, j, x, t, c));
Assert.IsTrue(expected.IsRelativelyEqual(actual, 1e-6));
Assert.IsFalse(double.IsNaN(actual));
}
}
}
actual = Math.Exp(model.LogLikelihood(x, c));
expected = Math.Exp(hcrf.LogLikelihood(x, c));
Assert.AreEqual(expected, actual, 1e-10);
Assert.IsFalse(double.IsNaN(actual));
actual = model.Compute(x);
expected = hcrf.Compute(x);
Assert.AreEqual(expected, actual);
Assert.IsFalse(double.IsNaN(actual));
}
}
}
[TestMethod()]
public void GradientTest2()
{
double[][][] sequences2;
int[] labels2;
var hmm = CreateModel3(out sequences2, out labels2);
var function = new <API key>(hmm);
var model = new <API key><double[]>(function);
var target = new <API key><double[]>(model);
var inputs = sequences2;
var outputs = labels2;
double[] actual = target.Gradient(function.Weights, inputs, outputs);
FiniteDifferences diff = new FiniteDifferences(function.Weights.Length);
diff.Function = parameters => func(model, parameters, inputs, outputs);
double[] expected = diff.Compute(function.Weights);
for (int i = 0; i < actual.Length; i++)
{
Assert.AreEqual(expected[i], actual[i], 1e-3);
Assert.IsFalse(double.IsNaN(actual[i]));
Assert.IsFalse(double.IsNaN(expected[i]));
}
}
[TestMethod()]
public void GradientTest3()
{
double[][][] sequences2;
int[] labels2;
var hmm = CreateModel3(out sequences2, out labels2);
var function = new <API key>(hmm);
var model = new <API key><double[]>(function);
var target = new <API key><double[]>(model);
target.Regularization = 2;
var inputs = sequences2;
var outputs = labels2;
FiniteDifferences diff = new FiniteDifferences(function.Weights.Length);
diff.Function = parameters => func(model, parameters, inputs, outputs, target.Regularization);
double[] expected = diff.Compute(function.Weights);
double[] actual = target.Gradient(function.Weights, inputs, outputs);
for (int i = 0; i < actual.Length; i++)
{
double e = expected[i];
double a = actual[i];
Assert.AreEqual(e, a, 1e-3);
Assert.IsFalse(double.IsNaN(actual[i]));
Assert.IsFalse(double.IsNaN(expected[i]));
}
}
private double func(<API key><double[]> model, double[] parameters, double[][][] inputs, int[] outputs)
{
model.Function.Weights = parameters;
return -model.LogLikelihood(inputs, outputs);
}
private double func(<API key><double[]> model, double[] parameters, double[][][] inputs, int[] outputs, double beta)
{
model.Function.Weights = parameters;
// Regularization
double sumSquaredWeights = 0;
if (beta != 0)
{
for (int i = 0; i < parameters.Length; i++)
if (!(Double.IsInfinity(parameters[i]) || Double.IsNaN(parameters[i])))
sumSquaredWeights += parameters[i] * parameters[i];
sumSquaredWeights = sumSquaredWeights * 0.5 / beta;
}
double logLikelihood = model.LogLikelihood(inputs, outputs);
// Maximize the log-likelihood and minimize the sum of squared weights
return -logLikelihood + sumSquaredWeights;
}
[TestMethod()]
public void <API key>()
{
double[][][] sequences2;
int[] labels2;
var hmm = CreateModel3(out sequences2, out labels2);
var function = new <API key>(hmm);
#pragma warning disable 0618
function.Deoptimize();
#pragma warning restore 0618
var model = new <API key><double[]>(function);
var target = new <API key><double[]>(model);
var inputs = sequences2;
var outputs = labels2;
double[] actual = target.Gradient(function.Weights, inputs, outputs);
FiniteDifferences diff = new FiniteDifferences(function.Weights.Length);
diff.Function = parameters => func(model, parameters, inputs, outputs);
double[] expected = diff.Compute(function.Weights);
for (int i = 0; i < actual.Length; i++)
{
Assert.AreEqual(expected[i], actual[i], 1e-3);
Assert.IsFalse(double.IsNaN(actual[i]));
Assert.IsFalse(double.IsNaN(expected[i]));
}
}
[TestMethod()]
public void <API key>()
{
double[][][] sequences2;
int[] labels2;
var hmm = CreateModel3(out sequences2, out labels2);
var function = new <API key>(hmm);
#pragma warning disable 0618
function.Deoptimize();
#pragma warning restore 0618
var model = new <API key><double[]>(function);
var target = new <API key><double[]>(model);
target.Regularization = 2;
var inputs = sequences2;
var outputs = labels2;
FiniteDifferences diff = new FiniteDifferences(function.Weights.Length);
diff.Function = parameters => func(model, parameters, inputs, outputs, target.Regularization);
double[] expected = diff.Compute(function.Weights);
double[] actual = target.Gradient(function.Weights, inputs, outputs);
for (int i = 0; i < actual.Length; i++)
{
double e = expected[i];
double a = actual[i];
Assert.AreEqual(e, a, 1e-3);
Assert.IsFalse(double.IsNaN(actual[i]));
Assert.IsFalse(double.IsNaN(expected[i]));
}
}
}
} |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Tue Jun 08 23:38:52 EDT 2010 -->
<TITLE>
Uses of Class org.pentaho.di.core.geospatial.GeotoolsWriter
</TITLE>
<META NAME="date" CONTENT="2010-06-08">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.pentaho.di.core.geospatial.GeotoolsWriter";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/pentaho/di/core/geospatial/GeotoolsWriter.html" title="class in org.pentaho.di.core.geospatial"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/pentaho/di/core/geospatial//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="GeotoolsWriter.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.pentaho.di.core.geospatial.GeotoolsWriter</B></H2>
</CENTER>
No usage of org.pentaho.di.core.geospatial.GeotoolsWriter
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/pentaho/di/core/geospatial/GeotoolsWriter.html" title="class in org.pentaho.di.core.geospatial"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/pentaho/di/core/geospatial//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="GeotoolsWriter.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML> |
// eca-audio-time.cpp: Generic class for representing time in audio
// environment.
// Attributes:
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <kvu_numtostr.h>
#include <kvu_dbc.h>
#include "eca-audio-time.h"
/**
* FIXME notes (last update 2008-03-09)
*
* - Add variant that allows specifying both sample position and
* sampling rate to set_time_string(). E.g. "1234@44100sa" or
* something similar.
*/
using SAMPLE_SPECS::sample_pos_t;
using SAMPLE_SPECS::sample_rate_t;
ECA_AUDIO_TIME::ECA_AUDIO_TIME(sample_pos_t samples,
sample_rate_t sample_rate)
{
<API key>(sample_rate);
set_samples(samples);
rate_set_rep = true;
}
ECA_AUDIO_TIME::ECA_AUDIO_TIME(double time_in_seconds)
: samples_rep(0),
sample_rate_rep(ECA_AUDIO_TIME::invalid_srate),
rate_set_rep(false)
{
set_seconds(time_in_seconds);
rate_set_rep = true;
}
ECA_AUDIO_TIME::ECA_AUDIO_TIME(format_type type,
const std::string& time)
: samples_rep(0),
sample_rate_rep(ECA_AUDIO_TIME::invalid_srate),
rate_set_rep(false)
{
set(type, time);
}
ECA_AUDIO_TIME::ECA_AUDIO_TIME(const std::string& time)
: samples_rep(0),
sample_rate_rep(ECA_AUDIO_TIME::invalid_srate),
rate_set_rep(false)
{
set_time_string(time);
}
ECA_AUDIO_TIME::ECA_AUDIO_TIME(void)
: samples_rep(0),
sample_rate_rep(ECA_AUDIO_TIME::invalid_srate),
rate_set_rep(false)
{
}
/**
* Sets time based on 'type', 'time' and 'srate'.
*
* @param sample_rate a value of zero will be ignored.
*/
void ECA_AUDIO_TIME::set(format_type type, const std::string& time)
{
switch(type)
{
/* FIXME: not implemented! */
case format_hour_min_sec: { DBC_CHECK(false); break; }
/* FIXME: not implemented! */
case format_min_sec: { DBC_CHECK(false); break; }
case format_seconds:
{
double seconds = atof(time.c_str());
set_seconds(seconds);
break;
}
case format_samples:
{
samples_rep = atol(time.c_str());
break;
}
default: { }
}
}
/**
* Sets time expressed in seconds. Additionally sample_rate is given
* to express the timing accuracy.
*
* @param sample_rate a value of zero will be ignored.
*/
void ECA_AUDIO_TIME::set_seconds(double seconds)
{
if (sample_rate_rep ==
ECA_AUDIO_TIME::invalid_srate) {
sample_rate_rep = ECA_AUDIO_TIME::default_srate;
rate_set_rep = true;
}
samples_rep = static_cast<SAMPLE_SPECS::sample_pos_t>(seconds * sample_rate_rep);
}
/**
* Sets time based on string 'time'. Additionally sample_rate is given
* to express the timing accuracy.
*
* The time string is by default interpreted as seconds (need not
* be an integer but can be given as a decimal number, e.g. "1.05").
* However, if the string contains an integer number and has a postfix
* of "sa" (e.g. "44100sa"), it is interpreted as time expressed as
* samples (in case of a multichannel stream, time in sample frames).
*
* @param sample_rate a value of zero will be ignored.
*/
void ECA_AUDIO_TIME::set_time_string(const std::string& time)
{
if (time.size() > 2 &&
time.find("sa") != std::string::npos)
ECA_AUDIO_TIME::set(format_samples, std::string(time, 0, time.size() - 2));
else
ECA_AUDIO_TIME::set(format_seconds, time);
}
/**
* Sets the sample count.
*
* Note, this can change the value of seconds().
*/
void ECA_AUDIO_TIME::set_samples(SAMPLE_SPECS::sample_pos_t samples)
{
samples_rep = samples;
}
/**
* Sets samples per second. Additionally sample_rate is given
* to express the timing accuracy.
*
* Note, this can change the value of seconds().
*/
void ECA_AUDIO_TIME::<API key>(SAMPLE_SPECS::sample_rate_t srate)
{
if (srate > 0) {
sample_rate_rep = srate;
rate_set_rep = true;
}
else {
rate_set_rep = false;
sample_rate_rep = ECA_AUDIO_TIME::invalid_srate;
}
}
/**
* Sets samples per second.
*
* Note, if sampling rate has been set earlier, this function
* does NOT change the value of seconds() like
* <API key>() potentially does.
*/
void ECA_AUDIO_TIME::<API key>(sample_rate_t srate)
{
if (srate > 0 &&
sample_rate_rep != srate) {
if (rate_set_rep == true) {
/* only needed if sampling rate has been set */
double time_secs = seconds();
<API key>(srate);
set_seconds(time_secs);
}
else {
<API key>(srate);
}
}
}
void ECA_AUDIO_TIME::mark_as_invalid(void)
{
<API key>(ECA_AUDIO_TIME::invalid_srate);
}
std::string ECA_AUDIO_TIME::to_string(format_type type) const
{
/* FIXME: not implemented */
switch(type)
{
case format_hour_min_sec:
{
return "";
}
case format_min_sec:
{
return "";
}
case format_seconds: { return kvu_numtostr(seconds(), 6); }
case format_samples: { return kvu_numtostr(samples_rep); }
default: { }
}
return "";
}
double ECA_AUDIO_TIME::seconds(void) const
{
if (rate_set_rep != true) {
sample_rate_rep = ECA_AUDIO_TIME::default_srate;
rate_set_rep = true;
}
return static_cast<double>(samples_rep) / sample_rate_rep;
}
SAMPLE_SPECS::sample_rate_t ECA_AUDIO_TIME::samples_per_second(void) const
{
return sample_rate_rep;
}
SAMPLE_SPECS::sample_pos_t ECA_AUDIO_TIME::samples(void) const
{
return samples_rep;
}
bool ECA_AUDIO_TIME::valid(void) const
{
return rate_set_rep;
} |
package org.pentaho.openformula.ui.model2;
public class <API key> extends FormulaElement {
public static final String ELEMENT = ";";
public <API key>( final FormulaDocument document,
final FormulaRootElement parentElement ) {
super( document, parentElement );
}
public String getText() {
return ELEMENT; // NON-NLS
}
/**
* Fetches the name of the element. If the element is used to represent some type of structure, this would be the
* type name.
*
* @return the element name
*/
public String getName() {
return "semicolon"; // NON-NLS
}
} |
using System;
using System.Reflection;
using System.ComponentModel;
namespace Zongsoft.Options.Configuration
{
public class <API key>
{
#region
private string _name;
private string _elementName;
private Type _type;
private object _defaultValue;
private TypeConverter _converter;
private <API key> _behavior;
#endregion
#region
public <API key>(string name, string elementName, Type type) : this(name, type, null, <API key>.None, null)
{
if(string.IsNullOrWhiteSpace(elementName))
throw new <API key>(nameof(elementName));
_elementName = elementName.Trim();
}
public <API key>(string name, Type type, object defaultValue = null, <API key> behavior = <API key>.None, TypeConverter converter = null)
{
_name = name == null ? string.Empty : name.Trim();
_type = type ?? throw new <API key>(nameof(type));
_behavior = behavior;
_converter = converter;
this.DefaultValue = defaultValue;
}
internal <API key>(PropertyInfo propertyInfo)
{
<API key> propertyAttribute = null;
<API key> converterAttribute = null;
<API key> defaultAttribute = null;
foreach(var attribute in Attribute.GetCustomAttributes(propertyInfo))
{
if(attribute is <API key>)
propertyAttribute = (<API key>)attribute;
else if(attribute is <API key>)
defaultAttribute = (<API key>)attribute;
else if(attribute is <API key>)
converterAttribute = (<API key>)attribute;
}
_name = propertyAttribute.Name;
_elementName = propertyAttribute.ElementName;
_type = propertyAttribute.Type ?? propertyInfo.PropertyType;
_behavior = propertyAttribute.Behavior;
if(converterAttribute != null && !string.IsNullOrEmpty(converterAttribute.ConverterTypeName))
{
Type type = Type.GetType(converterAttribute.ConverterTypeName, false);
if(type != null)
_converter = Activator.CreateInstance(type, true) as TypeConverter;
}
this.DefaultValue = defaultAttribute != null ? defaultAttribute.Value : propertyAttribute.DefaultValue;
}
#endregion
#region
public string Name
{
get
{
return _name;
}
}
public string ElementName
{
get
{
return _elementName;
}
}
public Type Type
{
get
{
return _type;
}
}
public object DefaultValue
{
get
{
return _defaultValue;
}
set
{
if(value == null)
{
if(_type.IsValueType)
_defaultValue = Activator.CreateInstance(_type);
else
_defaultValue = null;
}
else
{
if(_converter != null && _converter.CanConvertFrom(value.GetType()))
_defaultValue = _converter.ConvertFrom(value);
else
_defaultValue = Zongsoft.Common.Convert.ConvertValue(value, _type);
}
}
}
public TypeConverter Converter
{
get
{
return _converter;
}
}
public <API key> Behavior
{
get
{
return _behavior;
}
}
public bool IsKey
{
get
{
return (_behavior & <API key>.IsKey) == <API key>.IsKey;
}
}
public bool IsRequired
{
get
{
return (_behavior & <API key>.IsRequired) == <API key>.IsRequired;
}
}
public bool IsDefaultCollection
{
get
{
return string.IsNullOrEmpty(_name) && this.IsCollection;
}
}
public bool IsCollection
{
get
{
return Common.TypeExtension.IsCollection(_type) || Common.TypeExtension.IsDictionary(_type);
}
}
#endregion
}
} |
// Accord Audio Library
// The Accord.NET Framework
// cesarsouza at gmail.com
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
namespace Accord.Audio.Windows
{
using AForge.Math;
using System.Numerics;
<summary>
Base abstract class for signal windows.
</summary>
public abstract class WindowBase : IWindow
{
private int sampleRate;
private float[] window;
<summary>
Gets the window length.
</summary>
public int Length
{
get { return window.Length; }
}
<summary>
Gets the Window duration.
</summary>
public double Duration
{
get { return sampleRate * window.Length; }
}
<summary>
Constructs a new Window.
</summary>
protected WindowBase(double duration, int sampleRate)
: this((int)duration * sampleRate, sampleRate)
{
}
<summary>
Constructs a new Window.
</summary>
protected WindowBase(int length)
: this(length, 0)
{
}
<summary>
Constructs a new Window.
</summary>
protected WindowBase(int length, int sampleRate)
{
this.window = new float[length];
this.sampleRate = sampleRate;
}
<summary>
Gets or sets values for the Window function.
</summary>
public float this[int index]
{
get { return window[index]; }
protected set { window[index] = value; }
}
<summary>
Splits a signal using the window.
</summary>
public virtual Signal Apply(Signal signal, int sampleIndex)
{
int channels = signal.Channels;
int minLength = System.Math.Min(signal.Length - sampleIndex, Length);
Signal result = new Signal(channels, Length, signal.SampleRate, signal.SampleFormat);
if (signal.SampleFormat == SampleFormat.<API key>)
{
for (int c = 0; c < channels; c++)
{
unsafe
{
float* dst = (float*)result.Data.ToPointer() + c;
float* src = (float*)signal.Data.ToPointer() + c + channels * sampleIndex;
for (int i = 0; i < minLength; i++, dst += channels, src += channels)
{
*dst = window[i] * (*src);
}
}
}
}
else
{
throw new <API key>("Sample format is not supported by the filter.");
}
return result;
}
<summary>
Splits a signal using the window.
</summary>
public virtual unsafe ComplexSignal Apply(ComplexSignal complexSignal, int sampleIndex)
{
Complex[,] resultData = new Complex[Length, complexSignal.Channels];
ComplexSignal result = ComplexSignal.FromArray(resultData, complexSignal.SampleRate);
int channels = result.Channels;
int minLength = System.Math.Min(complexSignal.Length - sampleIndex, Length);
for (int c = 0; c < complexSignal.Channels; c++)
{
Complex* dst = (Complex*)result.Data.ToPointer() + c;
Complex* src = (Complex*)complexSignal.Data.ToPointer() + c + channels * sampleIndex;
for (int i = 0; i < minLength; i++, dst += channels, src += channels)
{
*dst = window[i] * (*src);
}
}
return result;
}
<summary>
Splits a signal using the window.
</summary>
public virtual double[] Apply(double[] signal, int sampleIndex)
{
int minLength = System.Math.Min(signal.Length - sampleIndex, Length);
double[] result = new double[Length];
unsafe
{
fixed (double* R = result)
fixed (double* S = signal)
{
double* dst = R;
double* src = S + sampleIndex;
for (int i = 0; i < minLength; i++, dst++, src++)
{
*dst = window[i] * (*src);
}
}
}
return result;
}
<summary>
Splits a signal using the window.
</summary>
public virtual double[][] Apply(double[][] signal, int sampleIndex)
{
int channels = signal[0].Length;
int minLength = System.Math.Min(signal.Length - sampleIndex, Length);
double[][] result = new double[signal.Length][];
for (int i = 0; i < result.Length; i++)
result[i] = new double[signal[i].Length];
for (int c = 0; c < channels; c++)
{
for (int i = 0; i < minLength; i++)
{
result[i][c] = window[i] * signal[i + sampleIndex][c];
}
}
return result;
}
}
} |
#include "mlt_playlist.h"
#include "mlt_tractor.h"
#include "mlt_multitrack.h"
#include "mlt_field.h"
#include "mlt_frame.h"
#include "mlt_transition.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/** \brief Virtual playlist entry used by mlt_playlist_s
*/
struct playlist_entry_s
{
mlt_producer producer;
mlt_position frame_in;
mlt_position frame_out;
mlt_position frame_count;
int repeat;
mlt_position producer_length;
mlt_event event;
int preservation_hack;
};
/* Forward declarations
*/
static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index );
static int mlt_playlist_unmix( mlt_playlist self, int clip );
static int <API key>( mlt_playlist self, int clip, int in, int out );
/** Construct a playlist.
*
* Sets the resource property to "<playlist>".
* Set the mlt_type to property to "mlt_producer".
* \public \memberof mlt_playlist_s
* \return a new playlist
*/
mlt_playlist mlt_playlist_init( )
{
mlt_playlist self = calloc( 1, sizeof( struct mlt_playlist_s ) );
if ( self != NULL )
{
mlt_producer producer = &self->parent;
// Construct the producer
if ( mlt_producer_init( producer, self ) != 0 ) goto error1;
// Override the producer get_frame
producer->get_frame = producer_get_frame;
// Define the destructor
producer->close = ( mlt_destructor )mlt_playlist_close;
producer->close_object = self;
// Initialise blank
if ( mlt_producer_init( &self->blank, NULL ) != 0 ) goto error1;
mlt_properties_set( <API key>( &self->blank ), "mlt_service", "blank" );
mlt_properties_set( <API key>( &self->blank ), "resource", "blank" );
// Indicate that this producer is a playlist
<API key>( <API key>( self ), "playlist", self, 0, NULL, NULL );
// Specify the eof condition
mlt_properties_set( <API key>( self ), "eof", "pause" );
mlt_properties_set( <API key>( self ), "resource", "<playlist>" );
mlt_properties_set( <API key>( self ), "mlt_type", "mlt_producer" );
<API key>( <API key>( self ), "in", 0 );
<API key>( <API key>( self ), "out", -1 );
<API key>( <API key>( self ), "length", 0 );
self->size = 10;
self->list = calloc( self->size, sizeof( playlist_entry * ) );
if ( self->list == NULL ) goto error2;
}
return self;
error2:
free( self->list );
error1:
free( self );
return NULL;
}
/** Construct a playlist with a profile.
*
* Sets the resource property to "<playlist>".
* Set the mlt_type to property to "mlt_producer".
* \public \memberof mlt_playlist_s
* \param profile the profile to use with the profile
* \return a new playlist
*/
mlt_playlist mlt_playlist_new( mlt_profile profile )
{
mlt_playlist self = mlt_playlist_init();
if ( self )
<API key>( <API key>( self ), "_profile", profile, 0, NULL, NULL );
return self;
}
/** Get the producer associated to this playlist.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \return the producer interface
* \see <API key>
*/
mlt_producer <API key>( mlt_playlist self )
{
return self != NULL ? &self->parent : NULL;
}
/** Get the service associated to this playlist.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \return the service interface
* \see <API key>
*/
mlt_service <API key>( mlt_playlist self )
{
return <API key>( &self->parent );
}
/** Get the properties associated to this playlist.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \return the playlist's properties list
* \see <API key>
*/
mlt_properties <API key>( mlt_playlist self )
{
return <API key>( &self->parent );
}
/** Refresh the playlist after a clip has been changed.
*
* \private \memberof mlt_playlist_s
* \param self a playlist
* \return false
*/
static int <API key>( mlt_playlist self )
{
// Obtain the properties
mlt_properties properties = <API key>( self );
int i = 0;
mlt_position frame_count = 0;
for ( i = 0; i < self->count; i ++ )
{
// Get the producer
mlt_producer producer = self->list[ i ]->producer;
if ( producer )
{
int current_length = <API key>( producer );
// Check if the length of the producer has changed
if ( self->list[ i ]->frame_in != mlt_producer_get_in( producer ) ||
self->list[ i ]->frame_out != <API key>( producer ) )
{
// This clip should be removed...
if ( current_length < 1 )
{
self->list[ i ]->frame_in = 0;
self->list[ i ]->frame_out = -1;
self->list[ i ]->frame_count = 0;
}
else
{
self->list[ i ]->frame_in = mlt_producer_get_in( producer );
self->list[ i ]->frame_out = <API key>( producer );
self->list[ i ]->frame_count = current_length;
}
// Update the producer_length
self->list[ i ]->producer_length = current_length;
}
}
// Calculate the frame_count
self->list[ i ]->frame_count = ( self->list[ i ]->frame_out - self->list[ i ]->frame_in + 1 ) * self->list[ i ]->repeat;
// Update the frame_count for self clip
frame_count += self->list[ i ]->frame_count;
}
// Refresh all properties
mlt_events_block( properties, properties );
<API key>( properties, "length", frame_count );
mlt_events_unblock( properties, properties );
<API key>( properties, "out", frame_count - 1 );
return 0;
}
/** Listener for producers on the playlist.
*
* Refreshes the playlist whenever an entry receives producer-changed.
* \private \memberof mlt_playlist_s
* \param producer a producer
* \param self a playlist
*/
static void <API key>( mlt_producer producer, mlt_playlist self )
{
<API key>( self );
}
/** Append to the virtual playlist.
*
* \private \memberof mlt_playlist_s
* \param self a playlist
* \param source a producer
* \param in the producer's starting time
* \param out the producer's ending time
* \return true if there was an error
*/
static int <API key>( mlt_playlist self, mlt_producer source, mlt_position in, mlt_position out )
{
mlt_producer producer = NULL;
mlt_properties properties = NULL;
mlt_properties parent = NULL;
// If we have a cut, then use the in/out points from the cut
if ( <API key>( source ) )
{
mlt_position length = out - in + 1;
// Make sure the blank is long enough to accomodate the length specified
if ( length > <API key>( &self->blank ) )
{
mlt_properties blank_props = <API key>( &self->blank );
mlt_events_block( blank_props, blank_props );
<API key>( &self->blank, in, out );
mlt_events_unblock( blank_props, blank_props );
}
// Now make sure the cut comes from this self->blank
if ( source == NULL )
{
producer = mlt_producer_cut( &self->blank, in, out );
}
else if ( !mlt_producer_is_cut( source ) || <API key>( source ) != &self->blank )
{
producer = mlt_producer_cut( &self->blank, in, out );
}
else
{
producer = source;
<API key>( <API key>( producer ) );
}
properties = <API key>( producer );
// Make sure this cut of blank is long enough
if ( length > <API key>( producer ) )
<API key>( properties, "length", length );
}
else if ( mlt_producer_is_cut( source ) )
{
producer = source;
if ( in < 0 )
in = mlt_producer_get_in( producer );
if ( out < 0 || out > <API key>( producer ) )
out = <API key>( producer );
properties = <API key>( producer );
<API key>( properties );
}
else
{
producer = mlt_producer_cut( source, in, out );
if ( in < 0 || in < mlt_producer_get_in( producer ) )
in = mlt_producer_get_in( producer );
if ( out < 0 || out > <API key>( producer ) )
out = <API key>( producer );
properties = <API key>( producer );
}
// Fetch the cuts parent properties
parent = <API key>( <API key>( producer ) );
// Remove loader normalisers for fx cuts
if ( <API key>( parent, "meta.fx_cut" ) )
{
mlt_service service = <API key>( <API key>( producer ) );
mlt_filter filter = mlt_service_filter( service, 0 );
while ( filter != NULL && <API key>( <API key>( filter ), "_loader" ) )
{
mlt_service_detach( service, filter );
filter = mlt_service_filter( service, 0 );
}
<API key>( <API key>( producer ), "meta.fx_cut", 1 );
}
// Check that we have room
if ( self->count >= self->size )
{
int i;
self->list = realloc( self->list, ( self->size + 10 ) * sizeof( playlist_entry * ) );
for ( i = self->size; i < self->size + 10; i ++ ) self->list[ i ] = NULL;
self->size += 10;
}
// Create the entry
self->list[ self->count ] = calloc( 1, sizeof( playlist_entry ) );
if ( self->list[ self->count ] != NULL )
{
self->list[ self->count ]->producer = producer;
self->list[ self->count ]->frame_in = in;
self->list[ self->count ]->frame_out = out;
self->list[ self->count ]->frame_count = out - in + 1;
self->list[ self->count ]->repeat = 1;
self->list[ self->count ]->producer_length = <API key>( producer );
self->list[ self->count ]->event = mlt_events_listen( parent, self, "producer-changed", ( mlt_listener )<API key> );
mlt_event_inc_ref( self->list[ self->count ]->event );
mlt_properties_set( properties, "eof", "pause" );
<API key>( producer, 0 );
self->count ++;
}
return <API key>( self );
}
/** Locate a producer by index.
*
* \private \memberof mlt_playlist_s
* \param self a playlist
* \param[in, out] position the time at which to locate the producer, returns the time relative to the producer's starting point
* \param[out] clip the index of the playlist entry
* \param[out] total the duration of the playlist up to and including this producer
* \return a producer or NULL if not found
*/
static mlt_producer mlt_playlist_locate( mlt_playlist self, mlt_position *position, int *clip, int *total )
{
// Default producer to NULL
mlt_producer producer = NULL;
// Loop for each producer until found
for ( *clip = 0; *clip < self->count; *clip += 1 )
{
// Increment the total
*total += self->list[ *clip ]->frame_count;
// Check if the position indicates that we have found the clip
// Note that 0 length clips get skipped automatically
if ( *position < self->list[ *clip ]->frame_count )
{
// Found it, now break
producer = self->list[ *clip ]->producer;
break;
}
else
{
// Decrement position by length of self entry
*position -= self->list[ *clip ]->frame_count;
}
}
return producer;
}
/** Seek in the virtual playlist.
*
* This gets the producer at the current position and seeks on the producer
* while doing repeat and end-of-file handling. This is also responsible for
* closing producers previous to the preceding playlist if the autoclose
* property is set.
* \private \memberof mlt_playlist_s
* \param self a playlist
* \param[out] progressive true if the producer should be displayed progressively
* \return the service interface of the producer at the play head
* \see producer_get_frame
*/
static mlt_service <API key>( mlt_playlist self, int *progressive )
{
// Map playlist position to real producer in virtual playlist
mlt_position position = mlt_producer_frame( &self->parent );
// Keep the original position since we change it while iterating through the list
mlt_position original = position;
// Clip index and total
int i = 0;
int total = 0;
// Locate the producer for the position
mlt_producer producer = mlt_playlist_locate( self, &position, &i, &total );
// Get the properties
mlt_properties properties = <API key>( self );
// Automatically close previous producers if requested
if ( i > 1 // keep immediate previous in case app wants to get info about what just finished
&& position < 2 // tolerate off-by-one error on going to next clip
&& <API key>( properties, "autoclose" ) )
{
int j;
// They might have jumped ahead!
for ( j = 0; j < i - 1; j++ )
{
mlt_service_lock( <API key>( self->list[ j ]->producer ) );
mlt_producer p = self->list[ j ]->producer;
if ( p )
{
self->list[ j ]->producer = NULL;
mlt_service_unlock( <API key>( p ) );
mlt_producer_close( p );
}
// If p is null, the lock will not have been "taken"
}
}
// Get the eof handling
char *eof = mlt_properties_get( properties, "eof" );
// Seek in real producer to relative position
if ( producer != NULL )
{
int count = self->list[ i ]->frame_count / self->list[ i ]->repeat;
*progressive = count == 1;
mlt_producer_seek( producer, (int)position % count );
}
else if ( !strcmp( eof, "pause" ) && total > 0 )
{
playlist_entry *entry = self->list[ self->count - 1 ];
int count = entry->frame_count / entry->repeat;
mlt_producer self_producer = <API key>( self );
mlt_producer_seek( self_producer, original - 1 );
producer = entry->producer;
mlt_producer_seek( producer, (int)entry->frame_out % count );
<API key>( self_producer, 0 );
<API key>( producer, 0 );
*progressive = count == 1;
}
else if ( !strcmp( eof, "loop" ) && total > 0 )
{
playlist_entry *entry = self->list[ 0 ];
mlt_producer self_producer = <API key>( self );
mlt_producer_seek( self_producer, 0 );
producer = entry->producer;
mlt_producer_seek( producer, 0 );
}
else
{
producer = &self->blank;
}
return <API key>( producer );
}
/** Invoked when a producer indicates that it has prematurely reached its end.
*
* \private \memberof mlt_playlist_s
* \param self a playlist
* \return a producer
* \see producer_get_frame
*/
static mlt_producer <API key>( mlt_playlist self )
{
// Default producer to blank
mlt_producer producer = &self->blank;
// Map playlist position to real producer in virtual playlist
mlt_position position = mlt_producer_frame( &self->parent );
// Loop through the virtual playlist
int i = 0;
for ( i = 0; i < self->count; i ++ )
{
if ( position < self->list[ i ]->frame_count )
{
// Found it, now break
producer = self->list[ i ]->producer;
break;
}
else
{
// Decrement position by length of this entry
position -= self->list[ i ]->frame_count;
}
}
// Seek in real producer to relative position
if ( i < self->count && self->list[ i ]->frame_out != position )
{
// Update the frame_count for the changed clip (hmmm)
self->list[ i ]->frame_out = position;
self->list[ i ]->frame_count = self->list[ i ]->frame_out - self->list[ i ]->frame_in + 1;
// Refresh the playlist
<API key>( self );
}
return producer;
}
/** Obtain the current clips index.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \return the index of the playlist entry at the current position
*/
int <API key>( mlt_playlist self )
{
// Map playlist position to real producer in virtual playlist
mlt_position position = mlt_producer_frame( &self->parent );
// Loop through the virtual playlist
int i = 0;
for ( i = 0; i < self->count; i ++ )
{
if ( position < self->list[ i ]->frame_count )
{
// Found it, now break
break;
}
else
{
// Decrement position by length of this entry
position -= self->list[ i ]->frame_count;
}
}
return i;
}
/** Obtain the current clips producer.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \return the producer at the current position
*/
mlt_producer <API key>( mlt_playlist self )
{
int i = <API key>( self );
if ( i < self->count )
return self->list[ i ]->producer;
else
return &self->blank;
}
/** Get the position which corresponds to the start of the next clip.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param whence the location from which to make the index relative:
* start of playlist, end of playlist, or current position
* \param index the playlist entry index relative to whence
* \return the time at which the referenced clip starts
*/
mlt_position mlt_playlist_clip( mlt_playlist self, mlt_whence whence, int index )
{
mlt_position position = 0;
int absolute_clip = index;
int i = 0;
// Determine the absolute clip
switch ( whence )
{
case <API key>:
absolute_clip = index;
break;
case <API key>:
absolute_clip = <API key>( self ) + index;
break;
case <API key>:
absolute_clip = self->count - index;
break;
}
// Check that we're in a valid range
if ( absolute_clip < 0 )
absolute_clip = 0;
else if ( absolute_clip > self->count )
absolute_clip = self->count;
// Now determine the position
for ( i = 0; i < absolute_clip; i ++ )
position += self->list[ i ]->frame_count;
return position;
}
/** Get all the info about the clip specified.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param info a clip info struct
* \param index a playlist entry index
* \return true if there was an error
*/
int <API key>( mlt_playlist self, <API key> *info, int index )
{
int error = index < 0 || index >= self->count || self->list[ index ]->producer == NULL;
memset( info, 0, sizeof( <API key> ) );
if ( !error )
{
mlt_producer producer = <API key>( self->list[ index ]->producer );
mlt_properties properties = <API key>( producer );
info->clip = index;
info->producer = producer;
info->cut = self->list[ index ]->producer;
info->start = mlt_playlist_clip( self, <API key>, index );
info->resource = mlt_properties_get( properties, "resource" );
info->frame_in = self->list[ index ]->frame_in;
info->frame_out = self->list[ index ]->frame_out;
info->frame_count = self->list[ index ]->frame_count;
info->repeat = self->list[ index ]->repeat;
info->length = <API key>( producer );
info->fps = <API key>( producer );
}
return error;
}
/** Get number of clips in the playlist.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \return the number of playlist entries
*/
int mlt_playlist_count( mlt_playlist self )
{
return self->count;
}
/** Clear the playlist.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \return true if there was an error
*/
int mlt_playlist_clear( mlt_playlist self )
{
int i;
for ( i = 0; i < self->count; i ++ )
{
mlt_event_close( self->list[ i ]->event );
mlt_producer_close( self->list[ i ]->producer );
}
self->count = 0;
return <API key>( self );
}
/** Append a producer to the playlist.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param producer the producer to append
* \return true if there was an error
*/
int mlt_playlist_append( mlt_playlist self, mlt_producer producer )
{
// Append to virtual list
return <API key>( self, producer, 0, <API key>( producer ) - 1 );
}
/** Append a producer to the playlist with in/out points.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param producer the producer to append
* \param in the starting point on the producer; a negative value is the same as 0
* \param out the ending point on the producer; a negative value is the same as producer length - 1
* \return true if there was an error
*/
int <API key>( mlt_playlist self, mlt_producer producer, mlt_position in, mlt_position out )
{
// Append to virtual list
if ( in < 0 && out < 0 )
return mlt_playlist_append( self, producer );
else
return <API key>( self, producer, in, out );
}
/** Append a blank to the playlist of a given length.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param out the ending time of the blank entry, not its duration
* \return true if there was an error
*/
int mlt_playlist_blank( mlt_playlist self, mlt_position out )
{
// Append to the virtual list
if ( out >= 0 )
return <API key>( self, &self->blank, 0, out );
else
return 1;
}
/** Append a blank item to the playlist with duration as a time string.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param length the duration of the blank entry as a time string
* \return true if there was an error
*/
int <API key>( mlt_playlist self, const char* length )
{
if ( self && length )
{
mlt_properties properties = <API key>( self );
mlt_properties_set( properties , "_blank_time", length );
mlt_position duration = <API key>( properties, "_blank_time" );
return mlt_playlist_blank( self, duration - 1 );
}
else
return 1;
}
/** Insert a producer into the playlist.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param producer the producer to insert
* \param where the producer's playlist entry index
* \param in the starting point on the producer
* \param out the ending point on the producer
* \return true if there was an error
*/
int mlt_playlist_insert( mlt_playlist self, mlt_producer producer, int where, mlt_position in, mlt_position out )
{
// Append to end
mlt_events_block( <API key>( self ), self );
<API key>( self, producer, in, out );
// Move to the position specified
mlt_playlist_move( self, self->count - 1, where );
mlt_events_unblock( <API key>( self ), self );
return <API key>( self );
}
/** Remove an entry in the playlist.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param where the playlist entry index
* \return true if there was an error
*/
int mlt_playlist_remove( mlt_playlist self, int where )
{
int error = where < 0 || where >= self->count;
if ( error == 0 && mlt_playlist_unmix( self, where ) != 0 )
{
// We need to know the current clip and the position within the playlist
int current = <API key>( self );
mlt_position position = <API key>( <API key>( self ) );
// We need all the details about the clip we're removing
<API key> where_info;
playlist_entry *entry = self->list[ where ];
mlt_properties properties = <API key>( entry->producer );
// Loop variable
int i = 0;
// Get the clip info
<API key>( self, &where_info, where );
// Reorganise the list
for ( i = where + 1; i < self->count; i ++ )
self->list[ i - 1 ] = self->list[ i ];
self->count
if ( entry->preservation_hack == 0 )
{
// Decouple from mix_in/out if necessary
if ( <API key>( properties, "mix_in", NULL ) != NULL )
{
mlt_properties mix = <API key>( properties, "mix_in", NULL );
<API key>( mix, "mix_out", NULL, 0, NULL, NULL );
}
if ( <API key>( properties, "mix_out", NULL ) != NULL )
{
mlt_properties mix = <API key>( properties, "mix_out", NULL );
<API key>( mix, "mix_in", NULL, 0, NULL, NULL );
}
if ( <API key>( <API key>( entry->producer ) ) == 1 )
mlt_producer_clear( entry->producer );
}
// Close the producer associated to the clip info
mlt_event_close( entry->event );
mlt_producer_close( entry->producer );
// Correct position
if ( where == current )
mlt_producer_seek( <API key>( self ), where_info.start );
else if ( where < current && self->count > 0 )
mlt_producer_seek( <API key>( self ), position - where_info.frame_count );
else if ( self->count == 0 )
mlt_producer_seek( <API key>( self ), 0 );
// Free the entry
free( entry );
// Refresh the playlist
<API key>( self );
}
return error;
}
/** Move an entry in the playlist.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param src an entry index
* \param dest an entry index
* \return false
*/
int mlt_playlist_move( mlt_playlist self, int src, int dest )
{
int i;
/* We need to ensure that the requested indexes are valid and correct it as necessary */
if ( src < 0 )
src = 0;
if ( src >= self->count )
src = self->count - 1;
if ( dest < 0 )
dest = 0;
if ( dest >= self->count )
dest = self->count - 1;
if ( src != dest && self->count > 1 )
{
int current = <API key>( self );
mlt_position position = <API key>( <API key>( self ) );
playlist_entry *src_entry = NULL;
// We need all the details about the current clip
<API key> current_info;
<API key>( self, ¤t_info, current );
position -= current_info.start;
if ( current == src )
current = dest;
else if ( current > src && current < dest )
current ++;
else if ( current == dest )
current = src;
src_entry = self->list[ src ];
if ( src > dest )
{
for ( i = src; i > dest; i
self->list[ i ] = self->list[ i - 1 ];
}
else
{
for ( i = src; i < dest; i ++ )
self->list[ i ] = self->list[ i + 1 ];
}
self->list[ dest ] = src_entry;
<API key>( self, ¤t_info, current );
mlt_producer_seek( <API key>( self ), current_info.start + position );
<API key>( self );
}
return 0;
}
/** Repeat the specified clip n times.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip a playlist entry index
* \param repeat the number of times to repeat the clip
* \return true if there was an error
*/
int <API key>( mlt_playlist self, int clip, int repeat )
{
int error = repeat < 1 || clip < 0 || clip >= self->count;
if ( error == 0 )
{
playlist_entry *entry = self->list[ clip ];
entry->repeat = repeat;
<API key>( self );
}
return error;
}
/** Resize the specified clip.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the playlist entry
* \param in the new starting time on the clip's producer; a negative value is the same as 0
* \param out the new ending time on the clip's producer; a negative value is the same as length - 1
* \return true if there was an error
*/
int <API key>( mlt_playlist self, int clip, mlt_position in, mlt_position out )
{
int error = clip < 0 || clip >= self->count;
if ( error == 0 && <API key>( self, clip, in, out ) != 0 )
{
playlist_entry *entry = self->list[ clip ];
mlt_producer producer = entry->producer;
mlt_properties properties = <API key>( self );
mlt_events_block( properties, properties );
if ( <API key>( producer ) )
{
mlt_position length = out - in + 1;
// Make sure the parent blank is long enough to accomodate the length specified
if ( length > <API key>( &self->blank ) )
{
mlt_properties blank_props = <API key>( &self->blank );
<API key>( blank_props, "length", length );
<API key>( &self->blank, 0, out - in );
}
// Make sure this cut of blank is long enough
if ( length > <API key>( producer ) )
<API key>( <API key>( producer ), "length", length );
}
if ( in < 0 )
in = 0;
if ( out < 0 || out >= <API key>( producer ) )
out = <API key>( producer ) - 1;
if ( out < in )
{
mlt_position t = in;
in = out;
out = t;
}
<API key>( producer, in, out );
mlt_events_unblock( properties, properties );
<API key>( self );
}
return error;
}
/** Split a clip on the playlist at the given position.
*
* This splits after the specified frame.
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the playlist entry
* \param position the time at which to split relative to the beginning of the clip or its end if negative
* \return true if there was an error
*/
int mlt_playlist_split( mlt_playlist self, int clip, mlt_position position )
{
int error = clip < 0 || clip >= self->count;
if ( error == 0 )
{
playlist_entry *entry = self->list[ clip ];
position = position < 0 ? entry->frame_count + position - 1 : position;
if ( position >= 0 && position < entry->frame_count - 1 )
{
int in = entry->frame_in;
int out = entry->frame_out;
mlt_events_block( <API key>( self ), self );
<API key>( self, clip, in, in + position );
if ( !<API key>( entry->producer ) )
{
int i = 0;
mlt_properties entry_properties = <API key>( entry->producer );
mlt_producer split = mlt_producer_cut( entry->producer, in + position + 1, out );
mlt_properties split_properties = <API key>( split );
mlt_playlist_insert( self, split, clip + 1, 0, -1 );
mlt_properties_lock( entry_properties );
for ( i = 0; i < <API key>( entry_properties ); i ++ )
{
char *name = <API key>( entry_properties, i );
if ( name != NULL && !strncmp( name, "meta.", 5 ) )
mlt_properties_set( split_properties, name, <API key>( entry_properties, i ) );
}
<API key>( entry_properties );
mlt_producer_close( split );
}
else
{
mlt_playlist_insert( self, &self->blank, clip + 1, 0, out - position - 1 );
}
mlt_events_unblock( <API key>( self ), self );
<API key>( self );
}
else
{
error = 1;
}
}
return error;
}
/** Split the playlist at the absolute position.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param position the time at which to split relative to the beginning of the clip
* \param left true to split before the frame starting at position
* \return true if there was an error
*/
int <API key>( mlt_playlist self, mlt_position position, int left )
{
int result = self == NULL ? -1 : 0;
if ( !result )
{
if ( position >= 0 && position < <API key>( <API key>( self ) ) )
{
int clip = <API key>( self, position );
<API key> info;
<API key>( self, &info, clip );
if ( left && position != info.start )
mlt_playlist_split( self, clip, position - info.start - 1 );
else if ( !left )
mlt_playlist_split( self, clip, position - info.start );
result = position;
}
else if ( position <= 0 )
{
result = 0;
}
else
{
result = <API key>( <API key>( self ) );
}
}
return result;
}
/** Join 1 or more consecutive clips.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the starting playlist entry index
* \param count the number of entries to merge
* \param merge ignored
* \return true if there was an error
*/
int mlt_playlist_join( mlt_playlist self, int clip, int count, int merge )
{
int error = clip < 0 || clip >= self->count;
if ( error == 0 )
{
int i = clip;
mlt_playlist new_clip = mlt_playlist_new( mlt_service_profile( <API key>(self) ) );
mlt_events_block( <API key>( self ), self );
if ( clip + count >= self->count )
count = self->count - clip - 1;
for ( i = 0; i <= count; i ++ )
{
playlist_entry *entry = self->list[ clip ];
mlt_playlist_append( new_clip, entry->producer );
<API key>( new_clip, i, entry->repeat );
entry->preservation_hack = 1;
mlt_playlist_remove( self, clip );
}
mlt_events_unblock( <API key>( self ), self );
mlt_playlist_insert( self, <API key>( new_clip ), clip, 0, -1 );
mlt_playlist_close( new_clip );
}
return error;
}
/** Mix consecutive clips for a specified length and apply transition if specified.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the playlist entry
* \param length the number of frames over which to create the mix
* \param transition the transition to use for the mix
* \return true if there was an error
*/
int mlt_playlist_mix( mlt_playlist self, int clip, int length, mlt_transition transition )
{
int error = ( clip < 0 || clip + 1 >= self->count );
if ( error == 0 )
{
playlist_entry *clip_a = self->list[ clip ];
playlist_entry *clip_b = self->list[ clip + 1 ];
mlt_producer track_a = NULL;
mlt_producer track_b = NULL;
mlt_tractor tractor = mlt_tractor_new( );
mlt_events_block( <API key>( self ), self );
// Check length is valid for both clips and resize if necessary.
int max_size = clip_a->frame_count > clip_b->frame_count ? clip_a->frame_count : clip_b->frame_count;
length = length > max_size ? max_size : length;
// Create the a and b tracks/cuts if necessary - note that no cuts are required if the length matches
if ( length != clip_a->frame_count )
track_a = mlt_producer_cut( clip_a->producer, clip_a->frame_out - length + 1, clip_a->frame_out );
else
track_a = clip_a->producer;
if ( length != clip_b->frame_count )
track_b = mlt_producer_cut( clip_b->producer, clip_b->frame_in, clip_b->frame_in + length - 1 );
else
track_b = clip_b->producer;
// Set the tracks on the tractor
<API key>( tractor, track_a, 0 );
<API key>( tractor, track_b, 1 );
// Insert the mix object into the playlist
mlt_playlist_insert( self, <API key>( tractor ), clip + 1, -1, -1 );
<API key>( <API key>( tractor ), "mlt_mix", tractor, 0, NULL, NULL );
// Attach the transition
if ( transition != NULL )
{
mlt_field field = mlt_tractor_field( tractor );
<API key>( field, transition, 0, 1 );
<API key>( transition, 0, length - 1 );
}
// Close our references to the tracks if we created new cuts above (the tracks can still be used here)
if ( track_a != clip_a->producer )
mlt_producer_close( track_a );
if ( track_b != clip_b->producer )
mlt_producer_close( track_b );
// Check if we have anything left on the right hand clip
if ( track_b == clip_b->producer )
{
clip_b->preservation_hack = 1;
mlt_playlist_remove( self, clip + 2 );
}
else if ( clip_b->frame_out - clip_b->frame_in > length )
{
<API key>( self, clip + 2, clip_b->frame_in + length, clip_b->frame_out );
<API key>( <API key>( clip_b->producer ), "mix_in", tractor, 0, NULL, NULL );
<API key>( <API key>( tractor ), "mix_out", clip_b->producer, 0, NULL, NULL );
}
else
{
mlt_producer_clear( clip_b->producer );
mlt_playlist_remove( self, clip + 2 );
}
// Check if we have anything left on the left hand clip
if ( track_a == clip_a->producer )
{
clip_a->preservation_hack = 1;
mlt_playlist_remove( self, clip );
}
else if ( clip_a->frame_out - clip_a->frame_in > length )
{
<API key>( self, clip, clip_a->frame_in, clip_a->frame_out - length );
<API key>( <API key>( clip_a->producer ), "mix_out", tractor, 0, NULL, NULL );
<API key>( <API key>( tractor ), "mix_in", clip_a->producer, 0, NULL, NULL );
}
else
{
mlt_producer_clear( clip_a->producer );
mlt_playlist_remove( self, clip );
}
// Unblock and force a fire off of change events to listeners
mlt_events_unblock( <API key>( self ), self );
<API key>( self );
mlt_tractor_close( tractor );
}
return error;
}
/** Add a transition to an existing mix.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the playlist entry
* \param transition a transition
* \return true if there was an error
*/
int <API key>( mlt_playlist self, int clip, mlt_transition transition )
{
mlt_producer producer = <API key>( <API key>( self, clip ) );
mlt_properties properties = producer != NULL ? <API key>( producer ) : NULL;
mlt_tractor tractor = properties != NULL ? <API key>( properties, "mlt_mix", NULL ) : NULL;
int error = transition == NULL || tractor == NULL;
if ( error == 0 )
{
mlt_field field = mlt_tractor_field( tractor );
<API key>( field, transition, 0, 1 );
<API key>( transition, 0, self->list[ clip ]->frame_count - 1 );
}
return error;
}
/** Return the clip at the clip index.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of a playlist entry
* \return a producer or NULL if there was an error
*/
mlt_producer <API key>( mlt_playlist self, int clip )
{
if ( clip >= 0 && clip < self->count )
return self->list[ clip ]->producer;
return NULL;
}
/** Return the clip at the specified position.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param position a time relative to the beginning of the playlist
* \return a producer or NULL if not found
*/
mlt_producer <API key>( mlt_playlist self, mlt_position position )
{
int index = 0, total = 0;
return mlt_playlist_locate( self, &position, &index, &total );
}
/** Return the clip index of the specified position.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param position a time relative to the beginning of the playlist
* \return the index of the playlist entry
*/
int <API key>( mlt_playlist self, mlt_position position )
{
int index = 0, total = 0;
mlt_playlist_locate( self, &position, &index, &total );
return index;
}
/** Determine if the clip is a mix.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the playlist entry
* \return true if the producer is a mix
*/
int <API key>( mlt_playlist self, int clip )
{
mlt_producer producer = <API key>( <API key>( self, clip ) );
mlt_properties properties = producer != NULL ? <API key>( producer ) : NULL;
mlt_tractor tractor = properties != NULL ? <API key>( properties, "mlt_mix", NULL ) : NULL;
return tractor != NULL;
}
/** Remove a mixed clip - ensure that the cuts included in the mix find their way
* back correctly on to the playlist.
*
* \private \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the playlist entry
* \return true if there was an error
*/
static int mlt_playlist_unmix( mlt_playlist self, int clip )
{
int error = ( clip < 0 || clip >= self->count );
// Ensure that the clip request is actually a mix
if ( error == 0 )
{
mlt_producer producer = <API key>( self->list[ clip ]->producer );
mlt_properties properties = <API key>( producer );
error = <API key>( properties, "mlt_mix", NULL ) == NULL ||
self->list[ clip ]->preservation_hack;
}
if ( error == 0 )
{
playlist_entry *mix = self->list[ clip ];
mlt_tractor tractor = ( mlt_tractor )<API key>( mix->producer );
mlt_properties properties = <API key>( tractor );
mlt_producer clip_a = <API key>( properties, "mix_in", NULL );
mlt_producer clip_b = <API key>( properties, "mix_out", NULL );
int length = <API key>( <API key>( tractor ) );
mlt_events_block( <API key>( self ), self );
if ( clip_a != NULL )
{
<API key>( clip_a, mlt_producer_get_in( clip_a ), <API key>( clip_a ) + length );
}
else
{
mlt_producer cut = <API key>( tractor, 0 );
mlt_playlist_insert( self, cut, clip, -1, -1 );
clip ++;
}
if ( clip_b != NULL )
{
<API key>( clip_b, mlt_producer_get_in( clip_b ) - length, <API key>( clip_b ) );
}
else
{
mlt_producer cut = <API key>( tractor, 1 );
mlt_playlist_insert( self, cut, clip + 1, -1, -1 );
}
<API key>( properties, "mlt_mix", NULL, 0, NULL, NULL );
mlt_playlist_remove( self, clip );
mlt_events_unblock( <API key>( self ), self );
<API key>( self );
}
return error;
}
/** Resize a mix clip.
*
* \private \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the playlist entry
* \param in the new starting point
* \param out the new ending point
* \return true if there was an error
*/
static int <API key>( mlt_playlist self, int clip, int in, int out )
{
int error = ( clip < 0 || clip >= self->count );
// Ensure that the clip request is actually a mix
if ( error == 0 )
{
mlt_producer producer = <API key>( self->list[ clip ]->producer );
mlt_properties properties = <API key>( producer );
error = <API key>( properties, "mlt_mix", NULL ) == NULL;
}
if ( error == 0 )
{
playlist_entry *mix = self->list[ clip ];
mlt_tractor tractor = ( mlt_tractor )<API key>( mix->producer );
mlt_properties properties = <API key>( tractor );
mlt_producer clip_a = <API key>( properties, "mix_in", NULL );
mlt_producer clip_b = <API key>( properties, "mix_out", NULL );
mlt_producer track_a = <API key>( tractor, 0 );
mlt_producer track_b = <API key>( tractor, 1 );
int length = out - in + 1;
int length_diff = length - <API key>( <API key>( tractor ) );
mlt_events_block( <API key>( self ), self );
if ( clip_a != NULL )
<API key>( clip_a, mlt_producer_get_in( clip_a ), <API key>( clip_a ) - length_diff );
if ( clip_b != NULL )
<API key>( clip_b, mlt_producer_get_in( clip_b ) + length_diff, <API key>( clip_b ) );
<API key>( track_a, mlt_producer_get_in( track_a ) - length_diff, <API key>( track_a ) );
<API key>( track_b, mlt_producer_get_in( track_b ), <API key>( track_b ) + length_diff );
<API key>( <API key>( <API key>( tractor ) ), in, out );
<API key>( <API key>( tractor ), in, out );
<API key>( <API key>( mix->producer ), "length", out - in + 1 );
<API key>( mix->producer, in, out );
mlt_events_unblock( <API key>( self ), self );
<API key>( self );
}
return error;
}
/** Consolidate adjacent blank producers.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param keep_length set false to remove the last entry if it is blank
*/
void <API key>( mlt_playlist self, int keep_length )
{
if ( self != NULL )
{
int i = 0;
mlt_properties properties = <API key>( self );
mlt_events_block( properties, properties );
for ( i = 1; i < self->count; i ++ )
{
playlist_entry *left = self->list[ i - 1 ];
playlist_entry *right = self->list[ i ];
if ( <API key>( left->producer ) && <API key>( right->producer ) )
{
<API key>( self, i - 1, 0, left->frame_count + right->frame_count - 1 );
mlt_playlist_remove( self, i
}
}
if ( !keep_length && self->count > 0 )
{
playlist_entry *last = self->list[ self->count - 1 ];
if ( <API key>( last->producer ) )
mlt_playlist_remove( self, self->count - 1 );
}
mlt_events_unblock( properties, properties );
<API key>( self );
}
}
/** Determine if the specified clip index is a blank.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the playlist entry
* \return true if there was an error
*/
int <API key>( mlt_playlist self, int clip )
{
return self == NULL || <API key>( <API key>( self, clip ) );
}
/** Determine if the specified position is a blank.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param position a time relative to the start or end (negative) of the playlist
* \return true if there was an error
*/
int <API key>( mlt_playlist self, mlt_position position )
{
return self == NULL || <API key>( <API key>( self, position ) );
}
/** Replace the specified clip with a blank and return the clip.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the playlist entry
* \return a producer or NULL if there was an error
*/
mlt_producer <API key>( mlt_playlist self, int clip )
{
mlt_producer producer = NULL;
if ( !<API key>( self, clip ) )
{
playlist_entry *entry = self->list[ clip ];
int in = entry->frame_in;
int out = entry->frame_out;
mlt_properties properties = <API key>( self );
producer = entry->producer;
<API key>( <API key>( producer ) );
mlt_events_block( properties, properties );
mlt_playlist_remove( self, clip );
mlt_playlist_blank( self, out - in );
mlt_playlist_move( self, self->count - 1, clip );
mlt_events_unblock( properties, properties );
<API key>( self );
<API key>( producer, in, out );
}
return producer;
}
/** Insert blank space.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the new blank section
* \param length the ending time of the new blank section (duration - 1)
*/
void <API key>( mlt_playlist self, int clip, int length )
{
if ( self != NULL && length >= 0 )
{
mlt_properties properties = <API key>( self );
mlt_events_block( properties, properties );
mlt_playlist_blank( self, length );
mlt_playlist_move( self, self->count - 1, clip );
mlt_events_unblock( properties, properties );
<API key>( self );
}
}
/** Resize a blank entry.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param position the time at which the blank entry exists relative to the start or end (negative) of the playlist.
* \param length the additional amount of blank frames to add
* \param find true to fist locate the blank after the clip at position
*/
void <API key>( mlt_playlist self, mlt_position position, int length, int find )
{
if ( self != NULL && length != 0 )
{
int clip = <API key>( self, position );
mlt_properties properties = <API key>( self );
mlt_events_block( properties, properties );
if ( find && clip < self->count && !<API key>( self, clip ) )
clip ++;
if ( clip < self->count && <API key>( self, clip ) )
{
<API key> info;
<API key>( self, &info, clip );
if ( info.frame_out + length > info.frame_in )
<API key>( self, clip, info.frame_in, info.frame_out + length );
else
mlt_playlist_remove( self, clip );
}
else if ( find && clip < self->count && length > 0 )
{
<API key>( self, clip, length );
}
mlt_events_unblock( properties, properties );
<API key>( self );
}
}
/** Insert a clip at a specific time.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param position the time at which to insert
* \param producer the producer to insert
* \param mode true if you want to overwrite any blank section
* \return true if there was an error
*/
int <API key>( mlt_playlist self, mlt_position position, mlt_producer producer, int mode )
{
int ret = self == NULL || position < 0 || producer == NULL;
if ( ret == 0 )
{
mlt_properties properties = <API key>( self );
int length = <API key>( producer );
int clip = <API key>( self, position );
<API key> info;
<API key>( self, &info, clip );
mlt_events_block( properties, self );
if ( clip < self->count && <API key>( self, clip ) )
{
// Split and move to new clip if need be
if ( position != info.start && mlt_playlist_split( self, clip, position - info.start - 1 ) == 0 )
<API key>( self, &info, ++ clip );
// Split again if need be
if ( length < info.frame_count )
mlt_playlist_split( self, clip, length - 1 );
// Remove
mlt_playlist_remove( self, clip );
// Insert
mlt_playlist_insert( self, producer, clip, -1, -1 );
ret = clip;
}
else if ( clip < self->count )
{
if ( position > info.start + info.frame_count / 2 )
clip ++;
if ( mode == 1 && clip < self->count && <API key>( self, clip ) )
{
<API key>( self, &info, clip );
if ( length < info.frame_count )
mlt_playlist_split( self, clip, length );
mlt_playlist_remove( self, clip );
}
mlt_playlist_insert( self, producer, clip, -1, -1 );
ret = clip;
}
else
{
if ( mode == 1 ) {
if ( position == info.start )
mlt_playlist_remove( self, clip );
else
mlt_playlist_blank( self, position - <API key>( properties, "length" ) - 1 );
}
mlt_playlist_append( self, producer );
ret = self->count - 1;
}
mlt_events_unblock( properties, self );
<API key>( self );
}
else
{
ret = -1;
}
return ret;
}
/** Get the time at which the clip starts relative to the playlist.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the playlist entry
* \return the starting time
*/
int <API key>( mlt_playlist self, int clip )
{
<API key> info;
if ( <API key>( self, &info, clip ) == 0 )
return info.start;
return clip < 0 ? 0 : <API key>( <API key>( self ) );
}
/** Get the playable duration of the clip.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the playlist entry
* \return the duration of the playlist entry
*/
int <API key>( mlt_playlist self, int clip )
{
<API key> info;
if ( <API key>( self, &info, clip ) == 0 )
return info.frame_count;
return 0;
}
/** Get the duration of a blank space.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param clip the index of the playlist entry
* \param bounded the maximum number of blank entries or 0 for all
* \return the duration of a blank section
*/
int <API key>( mlt_playlist self, int clip, int bounded )
{
int count = 0;
<API key> info;
if ( self != NULL && clip < self->count )
{
<API key>( self, &info, clip );
if ( <API key>( self, clip ) )
count += info.frame_count;
if ( bounded == 0 )
bounded = self->count;
for ( clip ++; clip < self->count && bounded >= 0; clip ++ )
{
<API key>( self, &info, clip );
if ( <API key>( self, clip ) )
count += info.frame_count;
else
bounded
}
}
return count;
}
/** Remove a portion of the playlist by time.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
* \param position the starting time
* \param length the duration of time to remove
* \return the new entry index at the position
*/
int <API key>( mlt_playlist self, mlt_position position, int length )
{
int index = <API key>( self, position );
if ( index >= 0 && index < self->count )
{
mlt_properties properties = <API key>( self );
int clip_start = <API key>( self, index );
int list_length = <API key>( <API key>( self ) );
mlt_events_block( properties, self );
if ( position + length > list_length )
length -= ( position + length - list_length );
if ( clip_start < position )
{
mlt_playlist_split( self, index ++, position - clip_start - 1 );
}
while( length > 0 )
{
if ( <API key>( self, index ) > length )
mlt_playlist_split( self, index, length - 1 );
length -= <API key>( self, index );
mlt_playlist_remove( self, index );
}
<API key>( self, 0 );
mlt_events_unblock( properties, self );
<API key>( self );
// Just to be sure, we'll get the clip index again...
index = <API key>( self, position );
}
return index;
}
/** Not implemented
*
* \deprecated not implemented
* \public \memberof mlt_playlist_s
* \param self
* \param position
* \param length
* \param new_position
* \return
*/
int <API key>( mlt_playlist self, mlt_position position, int length, int new_position )
{
if ( self != NULL )
{
}
return 0;
}
/** Get the current frame.
*
* The implementation of the get_frame virtual function.
* \private \memberof mlt_playlist_s
* \param producer a producer
* \param frame a frame by reference
* \param index the time at which to get the frame
* \return false
*/
static int producer_get_frame( mlt_producer producer, mlt_frame_ptr frame, int index )
{
// Check that we have a producer
if ( producer == NULL )
{
*frame = NULL;
return -1;
}
// Get this mlt_playlist
mlt_playlist self = producer->child;
// Need to ensure the frame is deinterlaced when repeating 1 frame
int progressive = 0;
// Get the real producer
mlt_service real = <API key>( self, &progressive );
// Check that we have a producer
if ( real == NULL )
{
*frame = mlt_frame_init( <API key>( producer ) );
return 0;
}
// Get the frame
if ( !<API key>( <API key>( real ), "meta.fx_cut" ) )
{
<API key>( real, frame, index );
}
else
{
mlt_producer parent = <API key>( ( mlt_producer )real );
*frame = mlt_frame_init( <API key>( parent ) );
<API key>( <API key>( *frame ), "fx_cut", 1 );
<API key>( *frame, NULL );
<API key>( *frame, NULL );
<API key>( <API key>( parent ), *frame, 0 );
<API key>( real, *frame, 0 );
mlt_deque_pop_front( <API key>( *frame ) );
mlt_deque_pop_front( <API key>( *frame ) );
}
// Check if we're at the end of the clip
mlt_properties properties = <API key>( *frame );
if ( <API key>( properties, "end_of_clip" ) )
<API key>( self );
// Set the consumer progressive property
if ( progressive )
{
<API key>( properties, "<API key>", progressive );
<API key>( properties, "test_audio", 1 );
}
// Check for notifier and call with appropriate argument
mlt_properties playlist_properties = <API key>( producer );
void ( *notifier )( void * ) = <API key>( playlist_properties, "notifier", NULL );
if ( notifier != NULL )
{
void *argument = <API key>( playlist_properties, "notifier_arg", NULL );
notifier( argument );
}
// Update position on the frame we're creating
<API key>( *frame, mlt_producer_frame( producer ) );
// Position ourselves on the next frame
<API key>( producer );
return 0;
}
/** Close the playlist.
*
* \public \memberof mlt_playlist_s
* \param self a playlist
*/
void mlt_playlist_close( mlt_playlist self )
{
if ( self != NULL && <API key>( <API key>( self ) ) <= 0 )
{
int i = 0;
self->parent.close = NULL;
for ( i = 0; i < self->count; i ++ )
{
mlt_event_close( self->list[ i ]->event );
mlt_producer_close( self->list[ i ]->producer );
free( self->list[ i ] );
}
mlt_producer_close( &self->blank );
mlt_producer_close( &self->parent );
free( self->list );
free( self );
}
} |
#!/bin/sh
CURDIR=`pwd`
PACKAGE_NAME=`grep AppFullName AndroidAppSettings.cfg | sed 's/.*=
../setEnvironment-$1.sh sh -c '\
$CC $CFLAGS -c main.c -o main-'"$1.o" || exit 1
../setEnvironment-$1.sh sh -c '\
$CC $CFLAGS -c gfx.c -o gfx-'"$1.o" || exit 1
[ -e xserver/android ] || {
CURDIR=`pwd`
cd ../../../..
git submodule update --init project/jni/application/xserver/xserver || exit 1
cd $CURDIR
} || exit 1
cd xserver
[ -e configure ] || autoreconf --force -v --install || exit 1
[ -e android/android-shmem/LICENSE ] || git submodule update --init android/android-shmem || exit 1
cd android
[ -e android-shmem/libancillary/ancillary.h ] || {
cd android-shmem
git submodule update --init libancillary || exit 1
cd ..
} || exit 1
cd $1
[ -e libfontenc-*/Makefile ] && {
grep "/data/data/$PACKAGE_NAME" libfontenc-*/Makefile || \
git clean -f -d -x .
}
env TARGET_DIR=/data/data/$PACKAGE_NAME/files \
./build.sh || exit 1
env CURDIR=$CURDIR \
../../../../setEnvironment-$1.sh sh -c '\
$CC $CFLAGS $LDFLAGS -o $CURDIR/libapplication-'"$1.so"' -L. \
$CURDIR/main-'"$1.o"' \
$CURDIR/gfx-'"$1.o"' \
hw/kdrive/sdl/sdl.o \
dix/.libs/libmain.a \
dix/.libs/libdix.a \
hw/kdrive/src/.libs/libkdrive.a \
hw/kdrive/src/.libs/libkdrivestubs.a \
fb/.libs/libfb.a \
mi/.libs/libmi.a \
xfixes/.libs/libxfixes.a \
Xext/.libs/libXext.a \
dbe/.libs/libdbe.a \
record/.libs/librecord.a \
randr/.libs/librandr.a \
render/.libs/librender.a \
damageext/.libs/libdamageext.a \
miext/sync/.libs/libsync.a \
miext/damage/.libs/libdamage.a \
miext/shadow/.libs/libshadow.a \
Xi/.libs/libXi.a \
xkb/.libs/libxkb.a \
xkb/.libs/libxkbstubs.a \
composite/.libs/libcomposite.a \
os/.libs/libos.a \
hw/kdrive/linux/.libs/liblinux.a \
-lpixman-1 -lXfont -lXau -lXdmcp -lfontenc -lts -lfreetype -landroid-shmem' \
|| exit 1
rm -rf $CURDIR/tmp-$1
mkdir -p $CURDIR/tmp-$1
cd $CURDIR/tmp-$1
cp $CURDIR/xserver/data/busybox-$1 ./busybox
cp $CURDIR/ssh ./
cp $CURDIR/sshpass ./
mkdir -p usr/bin
for f in xhost xkbcomp xli ; do cp $CURDIR/xserver/android/$1/$f ./usr/bin/ ; done
rm -f ../AndroidData/binaries-$1.zip
zip -r ../AndroidData/binaries-$1.zip .
exit 0 |
package org.lucee.extension.pdf.util;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXSource;
import org.ccil.cowan.tagsoup.Parser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import lucee.loader.engine.CFMLEngineFactory;
import lucee.runtime.exp.PageException;
public class XMLUtil {
public static final short UNDEFINED_NODE = -1;
private static TransformerFactory transformerFactory;
public static Element getRootElement(Node node) {
Document doc = null;
if (node instanceof Document) doc = (Document) node;
else doc = node.getOwnerDocument();
return doc.getDocumentElement();
}
public static synchronized Element getChildWithName(String name, Element el) {
Element[] children = <API key>(el);
for (int i = 0; i < children.length; i++) {
if (name.equalsIgnoreCase(children[i].getNodeName())) return children[i];
}
return null;
}
public static Element[] <API key>(Node node) {
ArrayList<Node> nodeList = getChildNodes(node, Node.ELEMENT_NODE, null);
return nodeList.toArray(new Element[nodeList.size()]);
}
public static synchronized ArrayList<Node> getChildNodes(Node node, short type, String filter) {
ArrayList<Node> rtn = new ArrayList<Node>();
NodeList nodes = node.getChildNodes();
int len = nodes.getLength();
Node n;
for (int i = 0; i < len; i++) {
try {
n = nodes.item(i);
if (n != null && (type == UNDEFINED_NODE || n.getNodeType() == type)) {
if (filter == null || filter.equals(n.getLocalName())) rtn.add(n);
}
}
catch (Exception t) {
}
}
return rtn;
}
public static Document getDocument(Node node) {
if (node instanceof Document) return (Document) node;
return node.getOwnerDocument();
}
public static final Document parseHTML(InputSource xml) throws SAXException, IOException {
XMLReader reader = new Parser();
reader.setFeature(Parser.namespacesFeature, true);
reader.setFeature(Parser.<API key>, true);
try {
Transformer transformer = <API key>().newTransformer();
DOMResult result = new DOMResult();
transformer.transform(new SAXSource(reader, xml), result);
return getDocument(result.getNode());
}
catch (Exception e) {
throw new SAXException(e);
}
}
public static TransformerFactory <API key>() {
if (transformerFactory == null) {
try {
Class<?> clazz = CFMLEngineFactory.getInstance().getClassUtil().loadClass("lucee.runtime.text.xml.XMLUtil");
transformerFactory = (TransformerFactory) clazz.getMethod("<API key>", new Class[0]).invoke(null, new Object[0]);
}
catch (Exception e) {
e.printStackTrace();
transformerFactory = TransformerFactory.newInstance();
}
}
return transformerFactory;
}
// toString(node, omitXMLDecl, indent, publicId, systemId, encoding);
public static String toString(Node node, boolean omitXMLDecl, boolean indent, String publicId, String systemId, String encoding) throws PageException {
// FUTURE use interface from loader
try {
Class<?> clazz = CFMLEngineFactory.getInstance().getClassUtil().loadClass("lucee.runtime.text.xml.XMLCaster");
Method method = clazz.getMethod("toString", new Class[] { Node.class, boolean.class, boolean.class, String.class, String.class, String.class });
return (String) method.invoke(null, new Object[] { node, omitXMLDecl, indent, publicId, systemId, encoding });
}
catch (Exception e) {
throw CFMLEngineFactory.getInstance().getCastUtil().toPageException(e);
}
}
public static InputSource toInputSource(String str) {
return new InputSource(new StringReader(str));
}
} |
#ifndef <API key>
#define <API key>
#include <gst/gst.h>
#include "kmsbasesdpendpoint.h"
#include "kmsmediatype.h"
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define <API key> \
(<API key>())
#define <API key>(obj) \
(<API key>((obj),<API key>,KmsBaseRtpEndpoint))
#define <API key>(klass) \
(<API key>((klass),<API key>,<API key>))
#define <API key>(obj) \
(<API key>((obj),<API key>))
#define <API key>(klass) \
(<API key>((klass),<API key>))
#define <API key>(obj) ((KmsBaseRtpEndpoint*)(obj))
typedef struct _KmsBaseRtpEndpoint KmsBaseRtpEndpoint;
typedef struct <API key> <API key>;
typedef struct <API key> <API key>;
#define <API key>(elem) \
(g_rec_mutex_lock (&<API key> ((elem))->media_mutex))
#define <API key>(elem) \
(g_rec_mutex_unlock (&<API key> ((elem))->media_mutex))
/* rtpbin pad names */
#define <API key> "recv_rtp_sink_0"
#define <API key> "recv_rtcp_sink_0"
#define <API key> "send_rtp_src_0"
#define <API key> "send_rtcp_src_0"
#define <API key> "send_rtp_sink_0"
#define <API key> "recv_rtp_sink_1"
#define <API key> "recv_rtcp_sink_1"
#define <API key> "send_rtp_src_1"
#define <API key> "send_rtcp_src_1"
#define <API key> "send_rtp_sink_1"
/* RTP enconding names */
#define OPUS_ENCONDING_NAME "OPUS"
#define VP8_ENCONDING_NAME "VP8"
struct _KmsBaseRtpEndpoint
{
KmsBaseSdpEndpoint parent;
<API key> *priv;
};
struct <API key>
{
<API key> parent_class;
void (*media_start) (KmsBaseRtpEndpoint * self, KmsMediaType type,
gboolean local);
void (*media_stop) (KmsBaseRtpEndpoint * self, KmsMediaType type,
gboolean local);
};
GType <API key> (void);
/* rtpbin must be used helding the KmsBaseRtpEndpoint's lock */
GstElement *<API key> (KmsBaseRtpEndpoint * self);
G_END_DECLS
#endif /* <API key> */ |
using System;
namespace WinrtCifs.Util.Sharpen
{
public class UrlConnection
{
protected Uri Url;
}
} |
package org.jfree.chart.axis;
import java.util.ArrayList;
import java.util.List;
import org.jfree.chart.api.RectangleEdge;
import org.jfree.chart.internal.Args;
/**
* Instances of this class are used to carry state information for an axis
* during the drawing process. By retaining this information in a separate
* object, it is possible for multiple threads to draw the same axis to
* different output targets (each drawing will maintain separate state
* information).
*/
public class AxisState {
/** The cursor position. */
private double cursor;
/** The axis ticks. */
private List<ValueTick> ticks;
/** The maximum width/height. */
private double max;
/**
* Creates a new axis state.
*/
public AxisState() {
this(0.0);
}
/**
* Creates a new axis state.
*
* @param cursor the cursor.
*/
public AxisState(double cursor) {
this.cursor = cursor;
this.ticks = new ArrayList<>();
}
/**
* Returns the cursor position.
*
* @return The cursor position.
*/
public double getCursor() {
return this.cursor;
}
/**
* Sets the cursor position.
*
* @param cursor the cursor position.
*/
public void setCursor(double cursor) {
this.cursor = cursor;
}
/**
* Moves the cursor outwards by the specified number of units.
*
* @param units the units.
* @param edge the edge ({@code null} not permitted).
*/
public void moveCursor(double units, RectangleEdge edge) {
Args.nullNotPermitted(edge, "edge");
switch (edge) {
case TOP:
cursorUp(units);
break;
case BOTTOM:
cursorDown(units);
break;
case LEFT:
cursorLeft(units);
break;
case RIGHT:
cursorRight(units);
break;
default:
throw new <API key>("Unexpected enum value " + edge);
}
}
/**
* Moves the cursor up by the specified number of Java 2D units.
*
* @param units the units.
*/
public void cursorUp(double units) {
this.cursor = this.cursor - units;
}
/**
* Moves the cursor down by the specified number of Java 2D units.
*
* @param units the units.
*/
public void cursorDown(double units) {
this.cursor = this.cursor + units;
}
/**
* Moves the cursor left by the specified number of Java 2D units.
*
* @param units the units.
*/
public void cursorLeft(double units) {
this.cursor = this.cursor - units;
}
/**
* Moves the cursor right by the specified number of Java 2D units.
*
* @param units the units.
*/
public void cursorRight(double units) {
this.cursor = this.cursor + units;
}
/**
* Returns the list of ticks.
*
* @return The list of ticks.
*/
public List<ValueTick> getTicks() {
return this.ticks;
}
/**
* Sets the list of ticks.
*
* @param ticks the ticks.
*/
public void setTicks(List<ValueTick> ticks) {
this.ticks = ticks;
}
/**
* Returns the maximum width/height.
*
* @return The maximum width/height.
*/
public double getMax() {
return this.max;
}
/**
* Sets the maximum width/height.
*
* @param max the maximum width/height.
*/
public void setMax(double max) {
this.max = max;
}
} |
package org.biojava.nbio.structure;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.biojava.nbio.structure.align.util.AtomCache;
import org.biojava.nbio.structure.contact.Grid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is the canonical way to identify a part of a structure.
*
* <p>The current syntax allows the specification of a set of residues from
* the first model of a structure. Future versions may be extended to represent
* additional properties.
*
* <p>Identifiers should adhere to the following specification, although some
* additional forms may be tolerated where unambiguous for backwards compatibility.
* <pre>
* name := pdbID
* | pdbID '.' chainID
* | pdbID '.' range
* range := range (',' range)?
* | chainID
* | chainID '_' resNum '-' resNum
* pdbID := [1-9][a-zA-Z0-9]{3}
* | PDB_[a-zA-Z0-9]{8}
* chainID := [a-zA-Z0-9]+
* resNum := [-+]?[0-9]+[A-Za-z]?
* </pre>
* For example:
* <pre>
* 1TIM #whole structure (short format)
* 1tim #same as above
* 4HHB.C #single chain
* 3AA0.A,B #two chains
* 4GCR.A_1-40 #substructure
* 3iek.A_17-28,A_56-294,A_320-377 #substructure of 3 disjoint parts
* PDB_00001TIM #whole structure (extended format)
* pdb_00001tim #same as above
* PDB_00004HHB.C #single chain
* PDB_00003AA0.A,B #two chains
* PDB_00004GCR.A_1-40 #substructure
* pdb_00003iek.A_17-28,A_56-294,A_320-377 #substructure of 3 disjoint parts
* </pre>
* More options may be added to the specification at a future time.
* @author dmyersturnbull
* @author Spencer Bliven
*/
public class <API key> implements StructureIdentifier {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(<API key>.class);
private final PdbId pdbId;
private final List<ResidueRange> ranges;
/**
* Create a new identifier from a string.
* @param id
*/
public <API key>(String id) {
String[] idRange = id.split("\\.");
if(1 > idRange.length || idRange.length > 2 ) {
throw new <API key>(String.format("Malformed %s: %s",getClass().getSimpleName(),id));
}
//used tempId to avoid writing 2 assignment statements to a final field,
// although one is in the try block and the other in the catch block.
PdbId tempId = null;
try {
tempId = new PdbId(idRange[0]);
} catch (<API key> e) {
// Changed from Exception to a warning to support files and stuff -sbliven 2015/01/22
logger.warn(String.format("Unrecognized PDB code %s", idRange[0]));
}
this.pdbId = tempId;
if( idRange.length == 2) {
String rangeStr = idRange[1].trim();
this.ranges = ResidueRange.parseMultiple(rangeStr);
} else {
this.ranges = new LinkedList<ResidueRange>();
}
}
/**
* Create a new identifier based on a set of ranges.
*
* If ranges is empty, includes all residues.
* @param pdbId
* @param ranges
*/
public <API key>(String pdbId, List<ResidueRange> ranges) {
this(new PdbId(pdbId), ranges);
}
/**
* Create a new identifier based on a set of ranges.
*
* If ranges is empty, includes all residues.
* @param pdbId
* @param ranges
*/
public <API key>(PdbId pdbId, List<ResidueRange> ranges) {
if(ranges == null) {
throw new <API key>("Null ranges list");
}
this.pdbId = pdbId;
this.ranges = ranges;
}
@Override
public String toString() {
return getIdentifier();
}
/**
* Get the String form of this identifier.
*
* This provides the canonical form for a StructureIdentifier and has
* all the information needed to recreate a particular substructure.
*
* Example: 3iek.A_17-28,A_56-294
* @return The String form of this identifier
*/
@Override
public String getIdentifier() {
String pdbId = this.pdbId == null? "": this.pdbId.getId();
if (ranges.isEmpty()) return pdbId;
return pdbId + "." + ResidueRange.toString(ranges);
}
/**
* Get the PDB identifier part of the <API key>
* @return the PDB ID
*/
public PdbId getPdbId() {
return pdbId;
}
public List<ResidueRange> getResidueRanges() {
return ranges;
}
/**
* Return itself. <API key> are canonical!
*/
@Override
public <API key> toCanonical() {
return this;
}
/**
* Takes a complete structure as input and reduces it to residues present in
* the specified ranges
*
* <p>The returned structure will be a shallow copy of the input, with shared
* Chains, Residues, etc.
*
* <p>Ligands are handled in a special way. If a full chain is selected
* (e.g. '1ABC.A') then any waters and ligands with matching chain name are
* included. If a residue range is present ('1ABC.A:1-100') then any
* ligands (technically non-water non-polymer atoms) within
* {@link StructureTools#<API key>} of the selected
* range are included, regardless of chain.
* @param input A full structure, e.g. as loaded from the PDB. The structure
* ID should match that returned by getPdbId().
* @return
* @throws StructureException
* @see StructureTools#getReducedStructure(Structure, String)
*/
@Override
public Structure reduce(Structure s) throws StructureException {
// Follows StructureImpl.clone()
if(s == null)
throw new StructureException("<API key> Possibly due to malformed PIBId format.");
// Create new structure & copy basic properties
Structure newS = new StructureImpl();
newS.setPdbId(s.getPdbId());
newS.setPDBHeader(s.getPDBHeader());
newS.setName(this.toString());
newS.setDBRefs(s.getDBRefs());
newS.<API key>(s.<API key>());
newS.getPDBHeader().setDescription(
"sub-range " + ranges + " of " + newS.getPdbId() + " "
+ s.getPDBHeader().getDescription());
newS.setEntityInfos(new ArrayList<>());
// TODO The following should be only copied for atoms which are present in the range.
newS.setSSBonds(s.getSSBonds());
newS.setSites(s.getSites());
newS.<API key>(this);
for( int modelNr=0;modelNr<s.nrModels();modelNr++) {
// Construct new model
newS.addModel(new ArrayList<Chain>());
if(getResidueRanges().isEmpty()) {
// Include all residues
newS.setEntityInfos(s.getEntityInfos());
newS.setSSBonds(s.getSSBonds());
newS.setSites(s.getSites());
newS.setModel(modelNr, s.getModel(modelNr));
} else {
// Restrict residues
for( ResidueRange range: getResidueRanges()) {
String chainName = range.getChainName();
ResidueNumber pdbresnum1 = range.getStart();
ResidueNumber pdbresnum2 = range.getEnd();
// StructureTools.<API key>(newS, groups, modelNr, false);
Chain polyChain; //polymer
if(chainName.equals("_") ) {
// Handle special case of "_" chain for single-chain proteins
polyChain = s.getPolyChains(modelNr).get(0);
chainName = polyChain.getName();
if(pdbresnum1 != null)
pdbresnum1.setChainName(chainName);
if(pdbresnum2 != null)
pdbresnum2.setChainName(chainName);
if(s.getPolyChains().size() != 1) {
// SCOP 1.71 uses this for some proteins with multiple chains
// Print a warning in this ambiguous case
logger.warn("Multiple possible chains match '_'. Using chain {}",chainName);
}
} else {
// Explicit chain
polyChain = s.getPolyChainByPDB(chainName,modelNr);
if( polyChain == null ) {
// Chain not found
// Maybe it was a chain index, masquerading as a chainName?
try {
int chainNum = Integer.parseInt(chainName);
polyChain = s.getChainByIndex(modelNr, chainNum);
chainName = polyChain.getName();
if(pdbresnum1 != null)
pdbresnum1.setChainName(chainName);
if(pdbresnum2 != null)
pdbresnum2.setChainName(chainName);
logger.warn("No chain found for {}. Interpretting it as an index, using chain {} instead",chainName,polyChain.getId());
} catch(<API key> e3) {
// Not an index. Throw the original exception
throw new StructureException(String.format("Unrecognized chain %s in %s",chainName,getIdentifier()));
}
}
}
if(pdbresnum1 == null && pdbresnum2 == null) {
// Include all atoms with matching chainName
StructureTools.<API key>(newS, polyChain.getAtomGroups(), modelNr, false);
for(Chain chain : s.<API key>(chainName, modelNr) ) {
StructureTools.<API key>(newS, chain.getAtomGroups(), modelNr, false);
}
Chain waters = s.getWaterChainByPDB(chainName, modelNr);
if( waters != null) {
StructureTools.<API key>(newS, waters.getAtomGroups(), modelNr, false);
}
// TODO do we need to prune SeqRes down to the atoms present? -SB 2016-10-7
} else {
// Include polymer range and any proximal ligands
List<Group> polygroups = Arrays.asList(polyChain.getGroupsByPDB(pdbresnum1, pdbresnum2));
StructureTools.<API key>(newS, polygroups, modelNr, false);
<API key>(s,newS, StructureTools.<API key>, modelNr, modelNr);
}
} // end range
}
} // end modelNr
return newS;
}
/**
* Loads the complete structure based on {@link #getPdbId()}.
*
* @param AtomCache A source of structures
* @return A Structure containing at least the atoms identified by this,
* or null if no PDB ID is set
* @throws StructureException For errors loading and parsing the structure
* @throws IOException Errors reading the structure from disk
*/
@Override
public Structure loadStructure(AtomCache cache) throws IOException, StructureException {
PdbId pdb = getPdbId();
if(pdb == null)
return null;
return cache.<API key>(pdb);
}
/**
* Supplements the reduced structure with ligands from the full structure based on
* a distance cutoff. Ligand groups are moved (destructively) from full to reduced
* if they fall within the cutoff of any atom in the reduced structure.
* The {@link StructureTools#<API key> default cutoff}
* is used.
* @param full Structure containing all ligands
* @param reduced Structure with a subset of the polymer groups from full
* @see StructureTools#<API key>(java.util.Collection, Atom[], double)
*/
protected static void <API key>(Structure full, Structure reduced) {
// Normal case where all models should be copied from full to reduced
assert full.nrModels() >= reduced.nrModels();
for(int model = 0; model< reduced.nrModels(); model++) {
<API key>(full, reduced, StructureTools.<API key>, model, model);
}
}
protected static void <API key>(Structure full, Structure reduced, double cutoff, int fromModel, int toModel) {
// Geometric hashing of the reduced structure
Grid grid = new Grid(cutoff);
Atom[] nonwaters = StructureTools.getAllNonHAtomArray(reduced,true,toModel);
if( nonwaters.length < 1 )
return;
grid.addAtoms(nonwaters);
full.getNonPolyChains(fromModel).stream() //potential ligand chains
.flatMap((chain) -> chain.getAtomGroups().stream() ) // potential ligand groups
.filter( (g) -> !g.isWater() ) // ignore waters
.filter( (g) -> !g.isPolymeric() ) // already shouldn't be polymeric, but filter anyways
.filter( (g) -> grid.hasAnyContact(Calc.atomsToPoints(g.getAtoms())) ) // must contact reduced
.sequential() // Keeps ligands from the same chain together if possible
.reduce((Chain)null, // reduction updates the chain guess
(guess, g ) -> {
boolean wasAdded;
try {
// Check that it's not in reduced already
wasAdded = reduced.findGroup(g.getChainId(),
g.getResidueNumber().toString(), toModel) != null;
} catch (StructureException e) {
// not found
wasAdded = false;
}
if( !wasAdded ) {
// Add the ligand to reduced
// note this is not idempotent, but it is synchronized on reduced
logger.info("Adding ligand group {} {} by proximity",g.getPDBName(), g.getResidueNumber().toPDB());
return StructureTools.addGroupToStructure(reduced, g, toModel, guess, false);
}
return guess;
},
// update to the new guess
(oldGuess, newGuess) -> newGuess );
}
} |
/* $Id: spinlock.c,v 1.2 2001/09/09 15:30:52 sandervl Exp $ */ |
#!/usr/bin/env python
import fluidity.diagnostics.annulus_mesh as mesh
import fluidity.diagnostics.triangletools as tt
div = mesh.SliceCoordsConstant(0.0, 1.0, 3)
m = mesh.<API key>(div, div)
tt.WriteTriangle(m, "<API key>") |
/* A wrapper round the decoder that recognises single-entry single-exit blocks
* of contiguous instructions containing an exclusive load/store pair and bundles
* them into a macro-instruction, OP_ldstex. This is a temporary solution for
* i#1698 and is likely to be fragile. Known problems:
*
* - We only handle single-entry single-exit contiguous code blocks. (Usually
* they are written as inline assembler so they do fit this pattern.)
* - If the block uses all of X0-X5 and the stolen register then we cannot
* mangle it (so it is better not to recognise it at all).
* - The contents of an OP_ldstex cannot be instrumented.
* - If execution remains in an OP_ldstex then signal delivery may be delayed.
* - Bad things might happen if there is a SIGSEGV or SIGBUS in an OP_ldstex.
* - Code flushing.
*
* This is currently modularised as a layer between the normal decoder and the
* block builder. It might be better to merge it with the block builder.
*
* If this solution can be made robust then it might be worth porting it to
* ARM/AArch32.
*/
#include "../globals.h"
#include "arch.h"
#include "decode.h"
#include "disassemble.h"
#include "instr.h"
#include "instr_create.h"
#include "build_ldstex.h"
static bool
<API key>(instr_t *instr)
{
int i, n;
n = instr_num_dsts(instr);
for (i = 0; i < n; i++)
ASSERT(!OPND_IS_REL_ADDR(instr_get_dst(instr, i)));
n = instr_num_srcs(instr);
for (i = 0; i < n; i++) {
if (OPND_IS_REL_ADDR(instr_get_src(instr, i)))
return true;
}
return false;
}
static void
instr_create_ldstex(dcontext_t *dcontext, int len, uint *pc, instr_t *instr,
OUT instr_t *instr_ldstex)
{
int num_dsts = 0;
int num_srcs = 0;
int i, d, s, j;
for (i = 0; i < len; i++) {
ASSERT(instr[i].length == AARCH64_INSTR_SIZE &&
instr[i].bytes == instr[0].bytes + AARCH64_INSTR_SIZE * i);
num_dsts += instr_num_dsts(&instr[i]);
num_srcs += instr_num_srcs(&instr[i]);
}
instr_set_opcode(instr_ldstex, OP_ldstex);
instr_set_num_opnds(dcontext, instr_ldstex, num_dsts, num_srcs);
d = 0;
s = 0;
for (i = 0; i < len; i++) {
int dsts = instr_num_dsts(&instr[i]);
int srcs = instr_num_srcs(&instr[i]);
for (j = 0; j < dsts; j++)
instr_set_dst(instr_ldstex, d++, instr_get_dst(&instr[i], j));
for (j = 0; j < srcs; j++)
instr_set_src(instr_ldstex, s++, instr_get_src(&instr[i], j));
}
ASSERT(d == num_dsts && s == num_srcs);
/* Set raw bits to original encoding. */
instr_set_raw_bits(instr_ldstex, instr[0].bytes, len * AARCH64_INSTR_SIZE);
/* Conservatively assume all flags are read and written. */
instr_ldstex->eflags = EFLAGS_READ_ALL | EFLAGS_WRITE_ALL;
<API key>(instr_ldstex, true);
}
/* Here we attempt to combine a loop involving ldex (load exclusive) and
* stex (store exclusive) into an OP_ldstex macro-instruction. The algorithm
* is roughly this:
*
* Decode up to (2 * N) instructions while:
* - none of them are indirect branches or system calls
* - none of them is a direct branch out of these (2 * N) instructions
* - none of them is OP_xx (to be safe)
* - there is, or might yet be, both ldex and stex in the first N
* - none of them is a non-branch PC-relative instruction: ADR, ADRP,
* PC-relative PRFM, literal load (this last condition could be removed
* if we mangled such instructions as we encountered them)
*
* To save time, give up if the first instruction is neither ldex nor stex
* and there is no branch to it.
* Take a sub-block containing both ldex and stex from the first N instructions.
* Expand this sub-block to a minimal single-entry single-exit block.
* Give up if the sub-block grows beyond N instructions.
* Finally, give up if the sub-block does not contain the first instruction.
* Also give up if the sub-block uses all of X0-X5 and the stolen register
* because we would be unable to mangle such a block.
*
* XXX: This function uses a lot of CPU time. It could be made faster in
* several ways, for example by caching decoded instructions or using a
* custom decoder to recognise the particular instructions that we care
* about here.
*/
byte *
decode_ldstex(dcontext_t *dcontext, byte *pc_, byte *orig_pc_, instr_t *instr_ldstex)
{
#define N (MAX_INSTR_LENGTH / AARCH64_INSTR_SIZE)
instr_t ibuf[2 * N];
uint *pc = (uint *)pc_;
uint *orig_pc = (uint *)orig_pc_;
bool seen_ldex = false;
bool seen_stex = false;
bool <API key> = false;
bool failed = false;
int ldstex_beg = -1;
int ldstex_end = -1;
int i, len;
/* Decode up to 2 * N instructions. */
for (i = 0; i < N; i++) {
instr_t *instr = &ibuf[i];
instr_init(dcontext, instr);
decode_from_copy(dcontext, (byte *)(pc + i), (byte *)(orig_pc + i), instr);
if (instr_is_mbr_arch(instr) || instr_is_syscall(instr) ||
instr_get_opcode(instr) == OP_xx || <API key>(instr))
break;
if (instr_is_ubr_arch(instr) || instr_is_cbr_arch(instr)) {
ptr_uint_t target = (ptr_uint_t)<API key>(instr);
if (target < (ptr_uint_t)pc || target > (ptr_uint_t)(pc + 2 * N))
break;
if (target == (ptr_uint_t)pc)
<API key> = true;
}
if (<API key>(instr))
seen_ldex = true;
if (<API key>(instr))
seen_stex = true;
if (i + 1 >= N && !(seen_ldex && seen_stex))
break;
if (ldstex_beg == -1 && (seen_ldex || seen_stex))
ldstex_beg = i;
if (ldstex_end == -1 && (seen_ldex && seen_stex))
ldstex_end = i + 1;
}
if (i < N) {
instr_reset(dcontext, &ibuf[i]);
len = i;
} else
len = N;
/* Quick check for hopeless situations. */
if (len == 0 || !(seen_ldex && seen_stex) ||
!(<API key> ||
(<API key>(&ibuf[0]) || <API key>(&ibuf[0])))) {
for (i = 0; i < len; i++)
instr_reset(dcontext, &ibuf[i]);
return NULL;
}
/* There are several ways we could choose a sub-block containing both ldex
* and stex from the first N instructions. Investigate further, perhaps.
* We have already set ldstex_beg and ldstex_end.
*/
ASSERT(ldstex_beg != -1 && ldstex_end != -1 && ldstex_beg < ldstex_end);
/* Expand ldstex sub-block until it is a single-entry single-exit block. */
for (;;) {
int new_beg = ldstex_beg;
int new_end = ldstex_end;
for (i = ldstex_beg; i < ldstex_end; i++) {
instr_t *instr = &ibuf[i];
if (instr_is_ubr_arch(instr) || instr_is_cbr_arch(instr)) {
int target = (uint *)<API key>(instr) - pc;
if (target > len) {
failed = true;
break;
}
if (target < new_beg)
new_beg = target;
if (target > new_end)
new_end = target;
}
}
if (new_beg == ldstex_beg && new_end == ldstex_end)
break;
ldstex_beg = new_beg;
ldstex_end = new_end;
}
if (ldstex_beg != 0)
failed = true;
if (!failed) {
/* Check whether the sub-block uses the stolen register and all of X0-X5.
* If it does, it would be impossible to mangle it so it is better not to
* create an OP_ldstex.
*/
reg_id_t regs[] = { dr_reg_stolen, DR_REG_X0, DR_REG_X1, DR_REG_X2,
DR_REG_X3, DR_REG_X4, DR_REG_X5 };
int r;
for (r = 0; r < sizeof(regs) / sizeof(*regs); r++) {
for (i = ldstex_beg; i < ldstex_end; i++) {
if (instr_uses_reg(&ibuf[i], regs[r]))
break;
}
if (i >= ldstex_end)
break;
}
if (r >= sizeof(regs) / sizeof(*regs))
failed = true;
}
if (!failed) {
instr_create_ldstex(dcontext, ldstex_end - ldstex_beg, pc + ldstex_beg,
&ibuf[ldstex_beg], instr_ldstex);
}
for (i = 0; i < len; i++)
instr_reset(dcontext, &ibuf[i]);
return failed ? NULL : (byte *)(pc + ldstex_end);
}
static byte *
<API key>(dcontext_t *dcontext, byte *pc, byte *orig_pc, instr_t *instr)
{
if (INTERNAL_OPTION(unsafe_build_ldstex)) {
byte *pc_next = decode_ldstex(dcontext, pc, orig_pc, instr);
if (pc_next != NULL)
return pc_next;
}
return decode_from_copy(dcontext, pc, orig_pc, instr);
}
byte *
decode_with_ldstex(dcontext_t *dcontext, byte *pc, instr_t *instr)
{
return <API key>(dcontext, pc, pc, instr);
}
byte *
<API key>(dcontext_t *dcontext, byte *pc, instr_t *instr)
{
return decode_with_ldstex(dcontext, pc, instr);
} |
# include "vvp_darray.h"
# include <iostream>
# include <typeinfo>
using namespace std;
vvp_darray::~vvp_darray()
{
}
void vvp_darray::set_word(unsigned, const vvp_vector4_t&)
{
cerr << "XXXX set_word(vvp_vector4_t) not implemented for " << typeid(*this).name() << endl;
}
void vvp_darray::set_word(unsigned, double)
{
cerr << "XXXX set_word(double) not implemented for " << typeid(*this).name() << endl;
}
void vvp_darray::set_word(unsigned, const string&)
{
cerr << "XXXX set_word(string) not implemented for " << typeid(*this).name() << endl;
}
void vvp_darray::set_word(unsigned, const vvp_object_t&)
{
cerr << "XXXX set_word(vvp_object_t) not implemented for " << typeid(*this).name() << endl;
}
void vvp_darray::get_word(unsigned, vvp_vector4_t&)
{
cerr << "XXXX get_word(vvp_vector4_t) not implemented for " << typeid(*this).name() << endl;
}
void vvp_darray::get_word(unsigned, double&)
{
cerr << "XXXX get_word(double) not implemented for " << typeid(*this).name() << endl;
}
void vvp_darray::get_word(unsigned, string&)
{
cerr << "XXXX get_word(string) not implemented for " << typeid(*this).name() << endl;
}
void vvp_darray::get_word(unsigned, vvp_object_t&)
{
cerr << "XXXX get_word(vvp_object_t) not implemented for " << typeid(*this).name() << endl;
}
void vvp_darray::shallow_copy(const vvp_object*)
{
cerr << "XXXX shallow_copy(vvp_object_t) not implemented for " << typeid(*this).name() << endl;
}
template <class TYPE> vvp_darray_atom<TYPE>::~vvp_darray_atom()
{
}
template <class TYPE> size_t vvp_darray_atom<TYPE>::get_size() const
{
return array_.size();
}
template <class TYPE> void vvp_darray_atom<TYPE>::set_word(unsigned adr, const vvp_vector4_t&value)
{
if (adr >= array_.size())
return;
TYPE tmp;
vector4_to_value(value, tmp, true, false);
array_[adr] = tmp;
}
template <class TYPE> void vvp_darray_atom<TYPE>::get_word(unsigned adr, vvp_vector4_t&value)
{
if (adr >= array_.size()) {
value = vvp_vector4_t(8*sizeof(TYPE), BIT4_X);
return;
}
TYPE word = array_[adr];
vvp_vector4_t tmp (8*sizeof(TYPE), BIT4_0);
for (unsigned idx = 0 ; idx < tmp.size() ; idx += 1) {
if (word&1) tmp.set_bit(idx, BIT4_1);
word >>= 1;
}
value = tmp;
}
template <class TYPE> void vvp_darray_atom<TYPE>::shallow_copy(const vvp_object*obj)
{
const vvp_darray_atom<TYPE>*that = dynamic_cast<const vvp_darray_atom<TYPE>*>(obj);
assert(that);
unsigned num_items = min(array_.size(), that->array_.size());
for (unsigned idx = 0 ; idx < num_items ; idx += 1)
array_[idx] = that->array_[idx];
}
template class vvp_darray_atom<uint8_t>;
template class vvp_darray_atom<uint16_t>;
template class vvp_darray_atom<uint32_t>;
template class vvp_darray_atom<uint64_t>;
template class vvp_darray_atom<int8_t>;
template class vvp_darray_atom<int16_t>;
template class vvp_darray_atom<int32_t>;
template class vvp_darray_atom<int64_t>;
vvp_darray_vec4::~vvp_darray_vec4()
{
}
size_t vvp_darray_vec4::get_size(void) const
{
return array_.size();
}
void vvp_darray_vec4::set_word(unsigned adr, const vvp_vector4_t&value)
{
if (adr >= array_.size()) return;
assert(value.size() == word_wid_);
array_[adr] = value;
}
void vvp_darray_vec4::get_word(unsigned adr, vvp_vector4_t&value)
{
/*
* Return an undefined value for an out of range address or if the
* value has not been written yet (has a size of zero).
*/
if ((adr >= array_.size()) || (array_[adr].size() == 0)) {
value = vvp_vector4_t(word_wid_, BIT4_X);
return;
}
value = array_[adr];
assert(value.size() == word_wid_);
}
void vvp_darray_vec4::shallow_copy(const vvp_object*obj)
{
const vvp_darray_vec4*that = dynamic_cast<const vvp_darray_vec4*>(obj);
assert(that);
unsigned num_items = min(array_.size(), that->array_.size());
for (unsigned idx = 0 ; idx < num_items ; idx += 1)
array_[idx] = that->array_[idx];
}
vvp_darray_vec2::~vvp_darray_vec2()
{
}
size_t vvp_darray_vec2::get_size(void) const
{
return array_.size();
}
void vvp_darray_vec2::set_word(unsigned adr, const vvp_vector4_t&value)
{
if (adr >= array_.size()) return;
assert(value.size() == word_wid_);
array_[adr] = value;
}
void vvp_darray_vec2::get_word(unsigned adr, vvp_vector4_t&value)
{
/*
* Return a zero value for an out of range address or if the
* value has not been written yet (has a size of zero).
*/
if ((adr >= array_.size()) || (array_[adr].size() == 0)) {
value = vvp_vector4_t(word_wid_, BIT4_0);
return;
}
assert(array_[adr].size() == word_wid_);
value.resize(word_wid_);
for (unsigned idx = 0; idx < word_wid_; idx += 1) {
value.set_bit(idx, array_[adr].value4(idx));
}
}
void vvp_darray_vec2::shallow_copy(const vvp_object*obj)
{
const vvp_darray_vec2*that = dynamic_cast<const vvp_darray_vec2*>(obj);
assert(that);
unsigned num_items = min(array_.size(), that->array_.size());
for (unsigned idx = 0 ; idx < num_items ; idx += 1)
array_[idx] = that->array_[idx];
}
vvp_darray_object::~vvp_darray_object()
{
}
size_t vvp_darray_object::get_size() const
{
return array_.size();
}
void vvp_darray_object::set_word(unsigned adr, const vvp_object_t&value)
{
if (adr >= array_.size())
return;
array_[adr] = value;
}
void vvp_darray_object::get_word(unsigned adr, vvp_object_t&value)
{
if (adr >= array_.size()) {
value = vvp_object_t();
return;
}
value = array_[adr];
}
void vvp_darray_object::shallow_copy(const vvp_object*obj)
{
const vvp_darray_object*that = dynamic_cast<const vvp_darray_object*>(obj);
assert(that);
unsigned num_items = min(array_.size(), that->array_.size());
for (unsigned idx = 0 ; idx < num_items ; idx += 1)
array_[idx] = that->array_[idx];
}
vvp_darray_real::~vvp_darray_real()
{
}
size_t vvp_darray_real::get_size() const
{
return array_.size();
}
void vvp_darray_real::set_word(unsigned adr, double value)
{
if (adr >= array_.size())
return;
array_[adr] = value;
}
void vvp_darray_real::get_word(unsigned adr, double&value)
{
if (adr >= array_.size()) {
value = 0.0;
return;
}
value = array_[adr];
}
void vvp_darray_real::shallow_copy(const vvp_object*obj)
{
const vvp_darray_real*that = dynamic_cast<const vvp_darray_real*>(obj);
assert(that);
unsigned num_items = min(array_.size(), that->array_.size());
for (unsigned idx = 0 ; idx < num_items ; idx += 1)
array_[idx] = that->array_[idx];
}
vvp_darray_string::~vvp_darray_string()
{
}
size_t vvp_darray_string::get_size() const
{
return array_.size();
}
void vvp_darray_string::set_word(unsigned adr, const string&value)
{
if (adr >= array_.size())
return;
array_[adr] = value;
}
void vvp_darray_string::get_word(unsigned adr, string&value)
{
if (adr >= array_.size()) {
value = "";
return;
}
value = array_[adr];
}
void vvp_darray_string::shallow_copy(const vvp_object*obj)
{
const vvp_darray_string*that = dynamic_cast<const vvp_darray_string*>(obj);
assert(that);
unsigned num_items = min(array_.size(), that->array_.size());
for (unsigned idx = 0 ; idx < num_items ; idx += 1)
array_[idx] = that->array_[idx];
}
vvp_queue::~vvp_queue()
{
}
void vvp_queue::push_back(const vvp_vector4_t&)
{
cerr << "XXXX push_back(vvp_vector4_t) not implemented for " << typeid(*this).name() << endl;
}
void vvp_queue::push_front(const vvp_vector4_t&)
{
cerr << "XXXX push_front(vvp_vector4_t) not implemented for " << typeid(*this).name() << endl;
}
void vvp_queue::push_back(double)
{
cerr << "XXXX push_back(double) not implemented for " << typeid(*this).name() << endl;
}
void vvp_queue::push_front(double)
{
cerr << "XXXX push_front(double) not implemented for " << typeid(*this).name() << endl;
}
void vvp_queue::push_back(const string&)
{
cerr << "XXXX push_back(string) not implemented for " << typeid(*this).name() << endl;
}
void vvp_queue::push_front(const string&)
{
cerr << "XXXX push_front(string) not implemented for " << typeid(*this).name() << endl;
}
vvp_queue_string::~vvp_queue_string()
{
}
size_t vvp_queue_string::get_size() const
{
return array_.size();
}
void vvp_queue_string::push_back(const string&val)
{
array_.push_back(val);
}
void vvp_queue_string::set_word(unsigned adr, const string&value)
{
if (adr >= array_.size())
return;
list<string>::iterator cur = array_.begin();
while (adr > 0) {
++ cur;
adr -= 1;
}
*cur = value;
}
void vvp_queue_string::get_word(unsigned adr, string&value)
{
if (adr >= array_.size()) {
value = "";
return;
}
list<string>::const_iterator cur = array_.begin();
while (adr > 0) {
++ cur;
adr -= 1;
}
value = *cur;
}
void vvp_queue_string::pop_back(void)
{
array_.pop_back();
}
void vvp_queue_string::pop_front(void)
{
array_.pop_front();
}
vvp_queue_vec4::~vvp_queue_vec4()
{
}
size_t vvp_queue_vec4::get_size() const
{
return array_.size();
}
void vvp_queue_vec4::set_word(unsigned adr, const vvp_vector4_t&value)
{
if (adr >= array_.size())
return;
list<vvp_vector4_t>::iterator cur = array_.begin();
while (adr > 0) {
++ cur;
adr -= 1;
}
*cur = value;
}
void vvp_queue_vec4::get_word(unsigned adr, vvp_vector4_t&value)
{
if (adr >= array_.size()) {
value = vvp_vector4_t();
return;
}
list<vvp_vector4_t>::const_iterator cur = array_.begin();
while (adr > 0) {
++ cur;
adr -= 1;
}
value = *cur;
}
void vvp_queue_vec4::push_back(const vvp_vector4_t&val)
{
array_.push_back(val);
}
void vvp_queue_vec4::push_front(const vvp_vector4_t&val)
{
array_.push_front(val);
}
void vvp_queue_vec4::pop_back(void)
{
array_.pop_back();
}
void vvp_queue_vec4::pop_front(void)
{
array_.pop_front();
} |
<?php
// vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker:
// | Smarty {arag_categorylist} categorylist plugin |
// | Type: arag_categorylist |
// | Name: arag_categorylist |
// | Purpose: Show categories |
function <API key>($params, &$smarty)
{
$ext = Kohana::config('smarty.templates_ext');
$name = 'category';
$template = 'categorylist';
$category_id = null;
$extra = array();
$uri_schema = '';
foreach ($params as $_key => $_val) {
switch ($_key) {
case 'template':
$template = $_val;
$template = rtrim($template, '.'.$ext);
break;
case 'extra':
$extra = $_val ? $_val : $extra;
break;
case 'category_id':
case 'uri_schema':
case 'name':
$$_key = $_val;
break;
default:
$smarty->trigger_error("arag_categorylist: Unknown attribute '$_key'");
}
}
$category_manager = Model::load('Category_Manager', 'category_manager');
$category = $category_manager->getCategory($category_id);
if ($category) {
$childs = $category_manager->getCategories($category_id);
$smarty->assign('category_manager', $category_manager);
$smarty->assign('name', $name);
$smarty->assign('current_category', $category);
$smarty->assign('childs', $childs);
$smarty->assign('uri_schema', $uri_schema);
foreach($extra as $key => $value) {
is_int($key) OR $smarty->assign($key, $value);
}
return $smarty->fetch(Arag::find_file('category_manager', 'views', $template, False, $ext));
}
return Null;
}
?> |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>length</title>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic|Source+Code+Pro:300,400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="../assets/css/bootstrap.css">
<link rel="stylesheet" href="../assets/css/jquery.bonsai.css">
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/css/icons.css">
<script type="text/javascript" src="../assets/js/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.js"></script>
<script type="text/javascript" src="../assets/js/jquery.bonsai.js"></script>
<!-- <script type="text/javascript" src="../assets/js/main.js"></script> -->
</head>
<body>
<div>
<!-- Name Title -->
<h1>length</h1>
<!-- Type and Stereotype -->
<section style="margin-top: .5em;">
<span class="alert alert-info">
<span class="node-icon _icon-UMLParameter"></span>
UMLParameter
</span>
</section>
<!-- Path -->
<section style="margin-top: 10px">
<span class="label label-info"><a href='<API key>.html'><span class='node-icon _icon-Project'></span>Untitled</a></span>
<span>::</span>
<span class="label label-info"><a href='<API key>.html'><span class='node-icon _icon-UMLModel'></span>JavaReverse</a></span>
<span>::</span>
<span class="label label-info"><a href='<API key>.html'><span class='node-icon _icon-UMLPackage'></span>net</a></span>
<span>::</span>
<span class="label label-info"><a href='<API key>.html'><span class='node-icon _icon-UMLPackage'></span>gleamynode</a></span>
<span>::</span>
<span class="label label-info"><a href='<API key>.html'><span class='node-icon _icon-UMLPackage'></span>netty</a></span>
<span>::</span>
<span class="label label-info"><a href='<API key>.html'><span class='node-icon _icon-UMLPackage'></span>handler</a></span>
<span>::</span>
<span class="label label-info"><a href='<API key>.html'><span class='node-icon _icon-UMLPackage'></span>codec</a></span>
<span>::</span>
<span class="label label-info"><a href='<API key>.html'><span class='node-icon _icon-UMLPackage'></span>replay</a></span>
<span>::</span>
<span class="label label-info"><a href='<API key>.html'><span class='node-icon _icon-UMLClass'></span><API key></a></span>
<span>::</span>
<span class="label label-info"><a href='<API key>.html'><span class='node-icon _icon-UMLOperation'></span>getBytes</a></span>
<span>::</span>
<span class="label label-info"><a href='<API key>.html'><span class='node-icon _icon-UMLParameter'></span>length</a></span>
</section>
<!-- Diagram -->
<!-- Description -->
<section>
<h3>Description</h3>
<div>
<span class="label label-info">none</span>
</div>
</section>
<!-- Specification -->
<!-- Directed Relationship -->
<!-- Undirected Relationship -->
<!-- Classifier -->
<!-- Interface -->
<!-- Component -->
<!-- Node -->
<!-- Actor -->
<!-- Use Case -->
<!-- Template Parameters -->
<!-- Literals -->
<!-- Attributes -->
<!-- Operations -->
<!-- Receptions -->
<!-- Extension Points -->
<!-- Parameters -->
<!-- Diagrams -->
<!-- Behavior -->
<!-- Action -->
<!-- Interaction -->
<!-- CombinedFragment -->
<!-- Activity -->
<!-- State Machine -->
<!-- State Machine -->
<!-- State -->
<!-- Vertex -->
<!-- Transition -->
<!-- Properties -->
<section>
<h3>Properties</h3>
<table class="table table-striped table-bordered">
<tr>
<th width="50%">Name</th>
<th width="50%">Value</th>
</tr>
<tr>
<td>name</td>
<td>length</td>
</tr>
<tr>
<td>stereotype</td>
<td><span class='label label-info'>null</span></td>
</tr>
<tr>
<td>visibility</td>
<td>public</td>
</tr>
<tr>
<td>isStatic</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>isLeaf</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>type</td>
<td>int</td>
</tr>
<tr>
<td>multiplicity</td>
<td></td>
</tr>
<tr>
<td>isReadOnly</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>isOrdered</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>isUnique</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>defaultValue</td>
<td></td>
</tr>
<tr>
<td>direction</td>
<td>in</td>
</tr>
</table>
</section>
<!-- Tags -->
<!-- Constraints, Dependencies, Dependants -->
<!-- Relationships -->
<!-- Owned Elements -->
</div>
</body>
</html> |
/* Support for thread pools ... like threadgroups, but lighter.
*
* 18/3/10
* - from threadgroup.c
* - distributed work allocation idea from Christian Blenia, thank you
* very much
* 21/3/10
* - progress feedback
* - only expose VipsThreadState
* 11/5/10
* - argh, stopping many threads could sometimes leave allocated work
* undone
* 17/7/10
* - set pool->error whenever we set thr->error, lets us catch allocate
* errors (thanks Tim)
* 25/7/14
* - limit nthr on tiny images
*/
/*
#define VIPS_DEBUG_RED
#define VIPS_DEBUG
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /*HAVE_CONFIG_H*/
#include <vips/intl.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif /*HAVE_UNISTD_H*/
#include <errno.h>
#include <vips/vips.h>
#include <vips/internal.h>
#include <vips/thread.h>
#include <vips/debug.h>
#ifdef OS_WIN32
#include <windows.h>
#endif /*OS_WIN32*/
/**
* SECTION: threadpool
* @short_description: pools of worker threads
* @stability: Stable
* @see_also: <link linkend="libvips-generate">generate</link>
* @include: vips/vips.h
*
* vips_threadpool_run() loops a set of threads over an image. Threads take it
* in turns to allocate units of work (a unit might be a tile in an image),
* then run in parallel to process those units. An optional progress function
* can be used to give feedback.
*/
/* Maximum number of concurrent threads we allow. No reason for the limit,
* it's just there to stop mad values for VIPS_CONCURRENCY killing the system.
*/
#define MAX_THREADS (1024)
/* Default tile geometry ... can be set by vips_init().
*/
int vips__tile_width = VIPS__TILE_WIDTH;
int vips__tile_height = VIPS__TILE_HEIGHT;
int <API key> = <API key>;
int <API key> = <API key>;
/* Default n threads ... 0 means get from environment.
*/
int vips__concurrency = 0;
/* Glib 2.32 revised the thread API. We need some compat functions.
*/
GMutex *
vips_g_mutex_new( void )
{
GMutex *mutex;
#ifdef HAVE_MUTEX_INIT
mutex = g_new( GMutex, 1 );
g_mutex_init( mutex );
#else
mutex = g_mutex_new();
#endif
return( mutex );
}
void
vips_g_mutex_free( GMutex *mutex )
{
#ifdef HAVE_MUTEX_INIT
g_mutex_clear( mutex );
g_free( mutex );
#else
g_mutex_free( mutex );
#endif
}
GCond *
vips_g_cond_new( void )
{
GCond *cond;
#ifdef HAVE_COND_INIT
cond = g_new( GCond, 1 );
g_cond_init( cond );
#else
cond = g_cond_new();
#endif
return( cond );
}
void
vips_g_cond_free( GCond *cond )
{
#ifdef HAVE_COND_INIT
g_cond_clear( cond );
g_free( cond );
#else
g_cond_free( cond );
#endif
}
typedef struct {
const char *domain;
GThreadFunc func;
gpointer data;
} VipsThreadInfo;
static void *
vips_thread_run( gpointer data )
{
VipsThreadInfo *info = (VipsThreadInfo *) data;
void *result;
if( <API key> )
<API key>( info->domain );
result = info->func( info->data );
g_free( info );
<API key>();
return( result );
}
GThread *
vips_g_thread_new( const char *domain, GThreadFunc func, gpointer data )
{
GThread *thread;
VipsThreadInfo *info;
GError *error = NULL;
info = g_new( VipsThreadInfo, 1 );
info->domain = domain;
info->func = func;
info->data = data;
#ifdef HAVE_THREAD_NEW
thread = g_thread_try_new( domain, vips_thread_run, info, &error );
#else
thread = g_thread_create( vips_thread_run, info, TRUE, &error );
#endif
if( !thread ) {
if( error )
vips_g_error( &error );
else
vips_error( domain,
"%s", _( "unable to create thread" ) );
}
return( thread );
}
/**
* <API key>:
* @concurrency: number of threads to run
*
* Sets the number of worker threads that vips should use when running a
* #VipsThreadPool.
*
* The special value 0 means "default". In this case, the number of threads is
* set by the environmnt variable VIPS_CONCURRENCY, or if that is not set, the
* number of threads availble on the hist machine.
*
* See also: <API key>().
*/
void
<API key>( int concurrency )
{
vips__concurrency = concurrency;
}
static int
get_num_processors( void )
{
int nproc;
nproc = 1;
#ifdef G_OS_UNIX
#if defined(HAVE_UNISTD_H) && defined(<API key>)
{
/* POSIX style.
*/
int x;
x = sysconf( <API key> );
if( x > 0 )
nproc = x;
}
#elif defined HW_NCPU
{
/* BSD style.
*/
int x;
size_t len = sizeof(x);
sysctl( (int[2]) {CTL_HW, HW_NCPU}, 2, &x, &len, NULL, 0 );
if( x > 0 )
nproc = x;
}
#endif
/* libgomp has some very complex code on Linux to count the number of
* processors available to the current process taking pthread affinity
* into account, but we don't attempt that here. Perhaps we should?
*/
#endif /*G_OS_UNIX*/
#ifdef OS_WIN32
{
/* Count the CPUs currently available to this process.
*/
DWORD_PTR process_cpus;
DWORD_PTR system_cpus;
if( <API key>( GetCurrentProcess(),
&process_cpus, &system_cpus ) ) {
unsigned int count;
for( count = 0; process_cpus != 0; process_cpus >>= 1 )
if( process_cpus & 1 )
count++;
if( count > 0 )
nproc = count;
}
}
#endif /*OS_WIN32*/
return( nproc );
}
/**
* <API key>:
*
* Returns the number of worker threads that vips should use when running a
* #VipsThreadPool.
*
* vips gets this values from these sources in turn:
*
* If <API key>() has been called, this value is used. The special
* value 0 means "default". You can also use the command-line argument
* "--vips-concurrency" to set this value.
*
* If <API key>() has not been called and no command-line argument
* was used, vips uses the value of the environment variable VIPS_CONCURRENCY,
*
* If VIPS_CONCURRENCY has not been set, vips find the number of hardware
* threads that the host machine can run in parallel and uses that value.
*
* The final value is clipped to the range 1 - 1024.
*
* See also: <API key>().
*
* Returns: number of worker threads to use.
*/
int
<API key>( void )
{
const char *str;
int nthr;
int x;
/* Tell the threads system how much concurrency we expect.
*/
if( vips__concurrency > 0 )
nthr = vips__concurrency;
else if( ((str = g_getenv( "VIPS_CONCURRENCY" )) ||
(str = g_getenv( "IM_CONCURRENCY" ))) &&
(x = atoi( str )) > 0 )
nthr = x;
else
nthr = get_num_processors();
if( nthr < 1 || nthr > MAX_THREADS ) {
nthr = VIPS_CLIP( 1, nthr, MAX_THREADS );
vips_warn( "<API key>",
_( "threads clipped to %d" ), nthr );
}
/* Save for next time around.
*/
<API key>( nthr );
return( nthr );
}
G_DEFINE_TYPE( VipsThreadState, vips_thread_state, VIPS_TYPE_OBJECT );
static void
<API key>( GObject *gobject )
{
VipsThreadState *state = (VipsThreadState *) gobject;
VIPS_DEBUG_MSG( "<API key>:\n" );
VIPS_UNREF( state->reg );
G_OBJECT_CLASS( <API key> )->dispose( gobject );
}
static int
<API key>( VipsObject *object )
{
VipsThreadState *state = (VipsThreadState *) object;
if( !(state->reg = vips_region_new( state->im )) )
return( -1 );
return( VIPS_OBJECT_CLASS(
<API key> )->build( object ) );
}
static void
<API key>( <API key> *class )
{
GObjectClass *gobject_class = G_OBJECT_CLASS( class );
VipsObjectClass *object_class = VIPS_OBJECT_CLASS( class );
gobject_class->dispose = <API key>;
object_class->build = <API key>;
object_class->nickname = "threadstate";
object_class->description = _( "per-thread state for vipsthreadpool" );
}
static void
<API key>( VipsThreadState *state )
{
VIPS_DEBUG_MSG( "<API key>:\n" );
state->reg = NULL;
state->stop = FALSE;
}
void *
<API key>( VipsObject *object, void *a, void *b )
{
VipsThreadState *state = (VipsThreadState *) object;
VipsImage *im = (VipsImage *) a;
VIPS_DEBUG_MSG( "<API key>:\n" );
state->im = im;
state->a = b;
return( NULL );
}
VipsThreadState *
<API key>( VipsImage *im, void *a )
{
VIPS_DEBUG_MSG( "<API key>:\n" );
return( VIPS_THREAD_STATE( vips_object_new(
<API key>, <API key>, im, a ) ) );
}
/* What we track for each thread in the pool.
*/
typedef struct {
/* All private.
*/
/*< private >*/
struct _VipsThreadpool *pool; /* Pool we are part of */
VipsThreadState *state;
/* Thread we are running.
*/
GThread *thread;
/* Set this to ask the thread to exit.
*/
gboolean exit;
/* Set by the thread if work or allocate return an error.
*/
gboolean error;
} VipsThread;
/* What we track for a group of threads working together.
*/
typedef struct _VipsThreadpool {
/* All private.
*/
/*< private >*/
VipsImage *im; /* Image we are calculating */
/* Start a thread, do a unit of work (runs in parallel) and allocate
* a unit of work (serial). Plus the mutex we use to serialize work
* allocation.
*/
VipsThreadStartFn start;
<API key> allocate;
<API key> work;
GMutex *allocate_lock;
void *a; /* User argument to start / allocate / etc. */
int nthr; /* Number of threads in pool */
VipsThread **thr; /* Threads */
/* The caller blocks here until all threads finish.
*/
VipsSemaphore finish;
/* Workers up this for every loop to make the main thread tick.
*/
VipsSemaphore tick;
/* Set this to abort evaluation early with an error.
*/
gboolean error;
/* Set by Allocate (via an arg) to indicate normal end of computation.
*/
gboolean stop;
/* Set by the first thread to hit allocate. The first work unit runs
* single-threaded to give loaders a change to get to the right spot
* in the input.
*/
gboolean done_first;
} VipsThreadpool;
/* Junk a thread.
*/
static void
vips_thread_free( VipsThread *thr )
{
/* Is there a thread running this region? Kill it!
*/
if( thr->thread ) {
thr->exit = 1;
/* Return value is always NULL (see thread_main_loop).
*/
(void) g_thread_join( thr->thread );
VIPS_DEBUG_MSG_RED( "thread_free: g_thread_join()\n" );
thr->thread = NULL;
}
VIPS_FREEF( g_object_unref, thr->state );
thr->pool = NULL;
}
static int
<API key>( VipsThread *thr )
{
VipsThreadpool *pool = thr->pool;
g_assert( !pool->stop );
if( !thr->state ) {
if( !(thr->state = pool->start( pool->im, pool->a )) )
return( -1 );
}
if( pool->allocate( thr->state, pool->a, &pool->stop ) )
return( -1 );
return( 0 );
}
/* Run this once per main loop. Get some work (single-threaded), then do it
* (many-threaded).
*
* The very first workunit is also executed single-threaded. This gives
* loaders a change to seek to the correct spot, see vips_sequential().
*/
static void
<API key>( VipsThread *thr )
{
VipsThreadpool *pool = thr->pool;
if( thr->error )
return;
VIPS_GATE_START( "<API key>: wait" );
g_mutex_lock( pool->allocate_lock );
VIPS_GATE_STOP( "<API key>: wait" );
/* Has another worker signaled stop while we've been working?
*/
if( pool->stop ) {
g_mutex_unlock( pool->allocate_lock );
return;
}
if( <API key>( thr ) ) {
thr->error = TRUE;
pool->error = TRUE;
g_mutex_unlock( pool->allocate_lock );
return;
}
/* Have we just signalled stop?
*/
if( pool->stop ) {
g_mutex_unlock( pool->allocate_lock );
return;
}
if( pool->done_first )
g_mutex_unlock( pool->allocate_lock );
/* Process a work unit.
*/
if( pool->work( thr->state, pool->a ) ) {
thr->error = TRUE;
pool->error = TRUE;
}
if( !pool->done_first ) {
pool->done_first = TRUE;
g_mutex_unlock( pool->allocate_lock );
}
}
/* What runs as a thread ... loop, waiting to be told to do stuff.
*/
static void *
<API key>( void *a )
{
VipsThread *thr = (VipsThread *) a;
VipsThreadpool *pool = thr->pool;
g_assert( pool == thr->pool );
VIPS_GATE_START( "<API key>: thread" );
/* Process work units! Always tick, even if we are stopping, so the
* main thread will wake up for exit.
*/
for(;;) {
VIPS_GATE_START( "<API key>: u" );
<API key>( thr );
VIPS_GATE_STOP( "<API key>: u" );
vips_semaphore_up( &pool->tick );
if( pool->stop ||
pool->error )
break;
}
/* We are exiting: tell the main thread.
*/
vips_semaphore_up( &pool->finish );
VIPS_GATE_STOP( "<API key>: thread" );
return( NULL );
}
/* Attach another thread to a threadpool.
*/
static VipsThread *
vips_thread_new( VipsThreadpool *pool )
{
VipsThread *thr;
if( !(thr = VIPS_NEW( pool->im, VipsThread )) )
return( NULL );
thr->pool = pool;
thr->state = NULL;
thr->thread = NULL;
thr->exit = 0;
thr->error = 0;
/* We can't build the state here, it has to be done by the worker
* itself the first time that allocate runs so that any regions are
* owned by the correct thread.
*/
if( !(thr->thread = vips_g_thread_new( "worker",
<API key>, thr )) ) {
vips_thread_free( thr );
return( NULL );
}
VIPS_DEBUG_MSG_RED( "vips_thread_new: vips_g_thread_new()\n" );
return( thr );
}
/* Kill all threads in a threadpool, if there are any.
*/
static void
<API key>( VipsThreadpool *pool )
{
if( pool->thr ) {
int i;
for( i = 0; i < pool->nthr; i++ )
vips_thread_free( pool->thr[i] );
pool->thr = NULL;
VIPS_DEBUG_MSG( "<API key>: "
"killed %d threads\n", pool->nthr );
}
}
/* This can be called multiple times, careful.
*/
static int
<API key>( VipsThreadpool *pool )
{
VIPS_DEBUG_MSG( "<API key>: \"%s\" (%p)\n",
pool->im->filename, pool );
<API key>( pool );
VIPS_FREEF( vips_g_mutex_free, pool->allocate_lock );
<API key>( &pool->finish );
<API key>( &pool->tick );
return( 0 );
}
static void
<API key>( VipsImage *im, VipsThreadpool *pool )
{
<API key>( pool );
}
static VipsThreadpool *
vips_threadpool_new( VipsImage *im )
{
VipsThreadpool *pool;
int tile_width;
int tile_height;
int n_tiles;
int n_lines;
/* Allocate and init new thread block.
*/
if( !(pool = VIPS_NEW( im, VipsThreadpool )) )
return( NULL );
pool->im = im;
pool->allocate = NULL;
pool->work = NULL;
pool->allocate_lock = vips_g_mutex_new();
pool->nthr = <API key>();
pool->thr = NULL;
vips_semaphore_init( &pool->finish, 0, "finish" );
vips_semaphore_init( &pool->tick, 0, "tick" );
pool->error = FALSE;
pool->stop = FALSE;
pool->done_first = FALSE;
/* If this is a tiny image, we won't need all nthr threads. Guess how
* many tiles we might need to cover the image and use that to limit
* the number of threads we create.
*/
vips_get_tile_size( im, &tile_width, &tile_height, &n_lines );
n_tiles = (1 + im->Xsize / tile_width) * (1 + im->Ysize / tile_height);
pool->nthr = VIPS_MIN( pool->nthr, n_tiles );
/* Attach tidy-up callback.
*/
g_signal_connect( im, "close",
G_CALLBACK( <API key> ), pool );
VIPS_DEBUG_MSG( "vips_threadpool_new: \"%s\" (%p), with %d threads\n",
im->filename, pool, pool->nthr );
return( pool );
}
/* Attach a set of threads.
*/
static int
<API key>( VipsThreadpool *pool )
{
int i;
g_assert( !pool->thr );
/* Make thread array.
*/
if( !(pool->thr = VIPS_ARRAY( pool->im, pool->nthr, VipsThread * )) )
return( -1 );
for( i = 0; i < pool->nthr; i++ )
pool->thr[i] = NULL;
/* Attach threads and start them working.
*/
for( i = 0; i < pool->nthr; i++ )
if( !(pool->thr[i] = vips_thread_new( pool )) ) {
<API key>( pool );
return( -1 );
}
return( 0 );
}
/**
* <API key>:
* @a: client data
* @b: client data
* @c: client data
*
* This function is called once by each worker just before the first time work
* is allocated to it to build the per-thread state. Per-thread state is used
* by #<API key> and #VipsThreadpoolWork to communicate.
*
* #VipsThreadState is a subclass of #VipsObject. Start functions are called
* from allocate, that is, they are single-threaded.
*
* See also: vips_threadpool_run().
*
* Returns: a new #VipsThreadState object, or NULL on error
*/
/**
* <API key>:
* @state: per-thread state
* @a: client data
* @b: client data
* @c: client data
* @stop: set this to signal end of computation
*
* This function is called to allocate a new work unit for the thread. It is
* always single-threaded, so it can modify per-pool state (such as a
* counter).
*
* @a, @b, @c are the values supplied to the call to
* vips_threadpool_run().
*
* It should set @stop to %TRUE to indicate that no work could be allocated
* because the job is done.
*
* See also: vips_threadpool_run().
*
* Returns: 0 on success, or -1 on error
*/
/**
* <API key>:
* @state: per-thread state
* @a: client data
* @b: client data
* @c: client data
*
* This function is called to process a work unit. Many copies of this can run
* at once, so it should not write to the per-pool state. It can write to
* per-thread state.
*
* @a, @b, @c are the values supplied to the call to
* vips_threadpool_run().
*
* See also: vips_threadpool_run().
*
* Returns: 0 on success, or -1 on error
*/
/**
* <API key>:
* @a: client data
* @b: client data
* @c: client data
*
* This function is called by the main thread once for every work unit
* processed. It can be used to give the user progress feedback.
*
* See also: vips_threadpool_run().
*
* Returns: 0 on success, or -1 on error
*/
/**
* vips_threadpool_run:
* @im: image to loop over
* @start: allocate per-thread state
* @allocate: allocate a work unit
* @work: process a work unit
* @progress: give progress feedback about a work unit, or %NULL
* @a: client data
*
* This function runs a set of threads over an image. Each thread first calls
* @start to create new per-thread state, then runs
* @allocate to set up a new work unit (perhaps the next tile in an image, for
* example), then @work to process that work unit. After each unit is
* processed, @progress is called, so that the operation can give
* progress feedback. @progress may be %NULL.
*
* The object returned by @start must be an instance of a subclass of
* #VipsThreadState. Use this to communicate between @allocate and @work.
*
* @allocate and @start are always single-threaded (so they can write to the
* per-pool state), whereas @work can be executed concurrently. @progress is
* always called by
* the main thread (ie. the thread which called vips_threadpool_run()).
*
* See also: <API key>().
*
* Returns: 0 on success, or -1 on error.
*/
int
vips_threadpool_run( VipsImage *im,
VipsThreadStartFn start,
<API key> allocate,
<API key> work,
<API key> progress,
void *a )
{
VipsThreadpool *pool;
int result;
if( !(pool = vips_threadpool_new( im )) )
return( -1 );
pool->start = start;
pool->allocate = allocate;
pool->work = work;
pool->a = a;
/* Attach workers and set them going.
*/
if( <API key>( pool ) ) {
<API key>( pool );
return( -1 );
}
for(;;) {
/* Wait for a tick from a worker.
*/
vips_semaphore_down( &pool->tick );
VIPS_DEBUG_MSG( "vips_threadpool_run: tick\n" );
if( pool->stop ||
pool->error )
break;
if( progress &&
progress( pool->a ) )
pool->error = TRUE;
if( pool->stop ||
pool->error )
break;
}
/* Wait for them all to hit finish.
*/
<API key>( &pool->finish, pool->nthr );
/* Return 0 for success.
*/
result = pool->error ? -1 : 0;
<API key>( pool );
<API key>( im );
return( result );
}
/* Round N down to P boundary.
*/
#define ROUND_DOWN(N,P) ((N) - ((N) % P))
/* Round N up to P boundary.
*/
#define ROUND_UP(N,P) (ROUND_DOWN( (N) + (P) - 1, (P) ))
/**
* vips_get_tile_size:
* @im: image to guess for
* @tile_width: return selected tile width
* @tile_height: return selected tile height
* @n_lines: return buffer height in scanlines
*
* Pick a tile size and a buffer height for this image and the current
* value of <API key>(). The buffer height
* will always be a multiple of tile_height.
*/
void
vips_get_tile_size( VipsImage *im,
int *tile_width, int *tile_height, int *n_lines )
{
const int nthr = <API key>();
/* Pick a render geometry.
*/
switch( im->dhint ) {
case <API key>:
*tile_width = vips__tile_width;
*tile_height = vips__tile_height;
break;
case <API key>:
case <API key>:
*tile_width = im->Xsize;
*tile_height = <API key>;
break;
case <API key>:
*tile_width = im->Xsize;
*tile_height = <API key>;
break;
default:
g_assert( 0 );
}
/* We can't set n_lines for the current demand style: a later bit of
* the pipeline might see a different hint and we need to synchronise
* buffer sizes everywhere.
*
* Pick the maximum buffer size we might possibly need, then round up
* to a multiple of tileheight.
*/
*n_lines = vips__tile_height *
(1 + nthr / VIPS_MAX( 1, im->Xsize / vips__tile_width )) * 2;
*n_lines = VIPS_MAX( *n_lines, <API key> * nthr * 2 );
*n_lines = VIPS_MAX( *n_lines, <API key> * nthr * 2 );
*n_lines = ROUND_UP( *n_lines, *tile_height );
/* We make this assumption in several places.
*/
g_assert( *n_lines % *tile_height == 0 );
VIPS_DEBUG_MSG( "vips_get_tile_size: %d by %d patches, "
"groups of %d scanlines\n",
*tile_width, *tile_height, *n_lines );
} |
#ifndef __FANIMATION_HPP__
#define __FANIMATION_HPP__
// Headers
#include <initializer_list>
#include <vector>
#include <string>
\brief Clase para represenar la animación de un sprite.
Ésta clase está pensada para uso interno y es
empleada por <API key> en conjunto
con un objeto de tipo fSpritesheet.
\see <API key> fSpritesheet
class fAnimation
{
public:
\brief Construye una animación
\param name Nombre de la animación
\param frames Indices de los cuadros del fSpritesheet que conforman la animación
\param fps Velocidad de la animación en cantidad de cuadros por segundo
\param loop Indica si la animación debe reiniciar automáticamente al finalizar
fAnimation(const std::string &name, const std::initializer_list<int> &frames, float fps = 10, bool loop = true);
\brief Devuelve la duración de un cuadro de la animación.
Todos los cuadros tienen la misma duración
\return Duración (en segundos) de un cuadro de la animación
float getFrameDuration() const;
\brief Devuelve la cantidad de cuadros que componen la animación
\return Cantidad de cuadros que componen la animación
int getFrameCount() const;
\brief Devuelve el número de cuadro dentro del fSpritesheet
para un determinado cuadro de la animación
\param i Ordinal del cuadro la animación cuyo cuadro dentro del fSpritesheet se desea conocer
\return Número de cuadro, dentro del fSpritesheet, del i-ésimo cuadro de la animación
int getFrame(int i) const;
\brief Devuelve el nombre de la animación
\return Nombre de la animación
const std::string &getName() const;
\brief Devuelve si la animación se ejecuta en un bucle, es decir, vuelve a comenzar al terminar
\return Si la animación debe o no volver a comenzar cuando haya terminado
bool loops() const;
private:
// Member data
float _frameDuration;
std::vector<int> _frames;
std::string _name;
bool _loop;
};
// Inline functions implementation
inline float fAnimation::getFrameDuration() const { return _frameDuration; }
inline int fAnimation::getFrameCount() const { return _frames.size(); }
inline int fAnimation::getFrame(int i) const{ return _frames[i]; }
inline bool fAnimation::loops() const{ return _loop; }
inline const std::string &fAnimation::getName() const{ return _name; }
#endif // __FANIMATION_HPP__ |
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
public delegate void NotifyHandler (object o, NotifyArgs args);
public class NotifyArgs : GLib.SignalArgs {
[DllImport("libgobject-2.0-0.dll", CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr <API key> (IntPtr pspec);
public string Property {
get {
IntPtr raw_ret = <API key> ((IntPtr) Args[0]);
return Marshaller.Utf8PtrToString (raw_ret);
}
}
}
} |
#include "tstringlist.h"
#include "tdebug.h"
#include "xmfile.h"
#include "modfileprivate.h"
#include "tpropertymap.h"
#include <string.h>
#include <algorithm>
using namespace TagLib;
using namespace XM;
using TagLib::uint;
using TagLib::ushort;
/*!
* The Reader classes are helpers to make handling of the stripped XM
* format more easy. In the stripped XM format certain header sizes might
* be smaller than one would expect. The fields that are not included
* are then just some predefined valued (e.g. 0).
*
* Using these classes this code:
*
* if(headerSize >= 4) {
* if(!readU16L(value1)) ERROR();
* if(headerSize >= 8) {
* if(!readU16L(value2)) ERROR();
* if(headerSize >= 12) {
* if(!readString(value3, 22)) ERROR();
* ...
* }
* }
* }
*
* Becomes:
*
* StructReader header;
* header.u16L(value1).u16L(value2).string(value3, 22). ...;
* if(header.read(*this, headerSize) < std::min(header.size(), headerSize))
* ERROR();
*
* Maybe if this is useful to other formats these classes can be moved to
* their own public files.
*/
namespace
{
class Reader
{
public:
virtual ~Reader()
{
}
/*!
* Reads associated values from \a file, but never reads more
* then \a limit bytes.
*/
virtual uint read(TagLib::File &file, uint limit) = 0;
/*!
* Returns the number of bytes this reader would like to read.
*/
virtual uint size() const = 0;
};
class SkipReader : public Reader
{
public:
SkipReader(uint size) : m_size(size)
{
}
uint read(TagLib::File &file, uint limit)
{
uint count = std::min(m_size, limit);
file.seek(count, TagLib::File::Current);
return count;
}
uint size() const
{
return m_size;
}
private:
uint m_size;
};
template<typename T>
class ValueReader : public Reader
{
public:
ValueReader(T &value) : value(value)
{
}
protected:
T &value;
};
class StringReader : public ValueReader<String>
{
public:
StringReader(String &string, uint size) :
ValueReader<String>(string), m_size(size)
{
}
uint read(TagLib::File &file, uint limit)
{
ByteVector data = file.readBlock(std::min(m_size, limit));
size_t count = data.size();
const size_t index = data.find((char) 0);
if(index != ByteVector::npos) {
data.resize(index);
}
data.replace((char) 0xff, ' ');
value = data;
return static_cast<uint>(count);
}
uint size() const
{
return m_size;
}
private:
uint m_size;
};
class ByteReader : public ValueReader<uchar>
{
public:
ByteReader(uchar &byte) : ValueReader<uchar>(byte) {}
uint read(TagLib::File &file, uint limit)
{
ByteVector data = file.readBlock(std::min(1U,limit));
if(data.size() > 0) {
value = data[0];
}
return static_cast<uint>(data.size());
}
uint size() const
{
return 1;
}
};
template<typename T>
class NumberReader : public ValueReader<T>
{
public:
NumberReader(T &value, bool bigEndian) :
ValueReader<T>(value), bigEndian(bigEndian)
{
}
protected:
bool bigEndian;
};
class U16Reader : public NumberReader<ushort>
{
public:
U16Reader(ushort &value, bool bigEndian)
: NumberReader<ushort>(value, bigEndian) {}
uint read(TagLib::File &file, uint limit)
{
ByteVector data = file.readBlock(std::min(2U,limit));
if(bigEndian)
value = data.toUInt16BE(0);
else
value = data.toUInt16LE(0);
return static_cast<uint>(data.size());
}
uint size() const
{
return 2;
}
};
class U32Reader : public NumberReader<uint>
{
public:
U32Reader(uint &value, bool bigEndian = true) :
NumberReader<uint>(value, bigEndian)
{
}
uint read(TagLib::File &file, uint limit)
{
ByteVector data = file.readBlock(std::min(4U,limit));
if(bigEndian)
value = data.toUInt32BE(0);
else
value = data.toUInt32LE(0);
return static_cast<uint>(data.size());
}
uint size() const
{
return 4;
}
};
class StructReader : public Reader
{
public:
StructReader()
{
m_readers.setAutoDelete(true);
}
/*!
* Add a nested reader. This reader takes ownership.
*/
StructReader &reader(Reader *reader)
{
m_readers.append(reader);
return *this;
}
/*!
* Don't read anything but skip \a size bytes.
*/
StructReader &skip(uint size)
{
m_readers.append(new SkipReader(size));
return *this;
}
/*!
* Read a string of \a size characters (bytes) into \a string.
*/
StructReader &string(String &string, uint size)
{
m_readers.append(new StringReader(string, size));
return *this;
}
/*!
* Read a byte into \a byte.
*/
StructReader &byte(uchar &byte)
{
m_readers.append(new ByteReader(byte));
return *this;
}
/*!
* Read a unsigned 16 Bit integer into \a number. The byte order
* is controlled by \a bigEndian.
*/
StructReader &u16(ushort &number, bool bigEndian)
{
m_readers.append(new U16Reader(number, bigEndian));
return *this;
}
/*!
* Read a unsigned 16 Bit little endian integer into \a number.
*/
StructReader &u16L(ushort &number)
{
return u16(number, false);
}
/*!
* Read a unsigned 16 Bit big endian integer into \a number.
*/
StructReader &u16B(ushort &number)
{
return u16(number, true);
}
/*!
* Read a unsigned 32 Bit integer into \a number. The byte order
* is controlled by \a bigEndian.
*/
StructReader &u32(uint &number, bool bigEndian)
{
m_readers.append(new U32Reader(number, bigEndian));
return *this;
}
/*!
* Read a unsigned 32 Bit little endian integer into \a number.
*/
StructReader &u32L(uint &number)
{
return u32(number, false);
}
/*!
* Read a unsigned 32 Bit big endian integer into \a number.
*/
StructReader &u32B(uint &number)
{
return u32(number, true);
}
uint size() const
{
uint size = 0;
for(List<Reader*>::ConstIterator i = m_readers.begin();
i != m_readers.end(); ++ i) {
size += (*i)->size();
}
return size;
}
uint read(TagLib::File &file, uint limit)
{
uint sumcount = 0;
for(List<Reader*>::ConstIterator i = m_readers.begin();
limit > 0 && i != m_readers.end(); ++ i) {
uint count = (*i)->read(file, limit);
limit -= count;
sumcount += count;
}
return sumcount;
}
private:
List<Reader*> m_readers;
};
}
class XM::File::FilePrivate
{
public:
FilePrivate(AudioProperties::ReadStyle propertiesStyle)
: tag(), properties(propertiesStyle)
{
}
Mod::Tag tag;
XM::AudioProperties properties;
};
XM::File::File(FileName file, bool readProperties,
AudioProperties::ReadStyle propertiesStyle) :
Mod::FileBase(file),
d(new FilePrivate(propertiesStyle))
{
if(isOpen())
read(readProperties);
}
XM::File::File(IOStream *stream, bool readProperties,
AudioProperties::ReadStyle propertiesStyle) :
Mod::FileBase(stream),
d(new FilePrivate(propertiesStyle))
{
if(isOpen())
read(readProperties);
}
XM::File::~File()
{
delete d;
}
Mod::Tag *XM::File::tag() const
{
return &d->tag;
}
XM::AudioProperties *XM::File::audioProperties() const
{
return &d->properties;
}
bool XM::File::save()
{
if(readOnly()) {
debug("XM::File::save() - Cannot save to a read only file.");
return false;
}
seek(17);
writeString(d->tag.title(), 20);
seek(38);
writeString(d->tag.trackerName(), 20);
seek(60);
uint headerSize = 0;
if(!readU32L(headerSize))
return false;
seek(70);
ushort patternCount = 0;
ushort instrumentCount = 0;
if(!readU16L(patternCount) || !readU16L(instrumentCount))
return false;
long pos = 60 + headerSize; // should be offset_t in taglib2.
// need to read patterns again in order to seek to the instruments:
for(ushort i = 0; i < patternCount; ++ i) {
seek(pos);
uint patternHeaderLength = 0;
if(!readU32L(patternHeaderLength) || patternHeaderLength < 4)
return false;
seek(pos + 7);
ushort dataSize = 0;
if (!readU16L(dataSize))
return false;
pos += patternHeaderLength + dataSize;
}
const StringList lines = d->tag.comment().split("\n");
uint sampleNameIndex = instrumentCount;
for(ushort i = 0; i < instrumentCount; ++ i) {
seek(pos);
uint <API key> = 0;
if(!readU32L(<API key>) || <API key> < 4)
return false;
seek(pos + 4);
const uint len = std::min(22U, <API key> - 4U);
if(i >= lines.size())
writeString(String::null, len);
else
writeString(lines[i], len);
ushort sampleCount = 0;
if(<API key> >= 29U) {
seek(pos + 27);
if(!readU16L(sampleCount))
return false;
}
uint sampleHeaderSize = 0;
if(sampleCount > 0) {
seek(pos + 29);
if(<API key> < 33U || !readU32L(sampleHeaderSize))
return false;
}
pos += <API key>;
for(ushort j = 0; j < sampleCount; ++ j) {
if(sampleHeaderSize > 4U) {
seek(pos);
uint sampleLength = 0;
if(!readU32L(sampleLength))
return false;
if(sampleHeaderSize > 18U) {
seek(pos + 18);
const uint len = std::min(sampleHeaderSize - 18U, 22U);
if(sampleNameIndex >= lines.size())
writeString(String::null, len);
else
writeString(lines[sampleNameIndex ++], len);
}
}
pos += sampleHeaderSize;
}
}
return true;
}
void XM::File::read(bool)
{
if(!isOpen())
return;
seek(0);
ByteVector magic = readBlock(17);
// it's all 0x00 for stripped XM files:
READ_ASSERT(magic == "Extended Module: " || magic == ByteVector(17, 0));
READ_STRING(d->tag.setTitle, 20);
READ_BYTE_AS(escape);
// in stripped XM files this is 0x00:
READ_ASSERT(escape == 0x1A || escape == 0x00);
READ_STRING(d->tag.setTrackerName, 20);
READ_U16L(d->properties.setVersion);
READ_U32L_AS(headerSize);
READ_ASSERT(headerSize >= 4);
ushort length = 0;
ushort restartPosition = 0;
ushort channels = 0;
ushort patternCount = 0;
ushort instrumentCount = 0;
ushort flags = 0;
ushort tempo = 0;
ushort bpmSpeed = 0;
StructReader header;
header.u16L(length)
.u16L(restartPosition)
.u16L(channels)
.u16L(patternCount)
.u16L(instrumentCount)
.u16L(flags)
.u16L(tempo)
.u16L(bpmSpeed);
uint count = header.read(*this, headerSize - 4U);
uint size = std::min(headerSize - 4U, header.size());
READ_ASSERT(count == size);
d->properties.setLengthInPatterns(length);
d->properties.setRestartPosition(restartPosition);
d->properties.setChannels(channels);
d->properties.setPatternCount(patternCount);
d->properties.setInstrumentCount(instrumentCount);
d->properties.setFlags(flags);
d->properties.setTempo(tempo);
d->properties.setBpmSpeed(bpmSpeed);
seek(60 + headerSize);
// read patterns:
for(ushort i = 0; i < patternCount; ++ i) {
READ_U32L_AS(patternHeaderLength);
READ_ASSERT(patternHeaderLength >= 4);
uchar packingType = 0;
ushort rowCount = 0;
ushort dataSize = 0;
StructReader pattern;
pattern.byte(packingType).u16L(rowCount).u16L(dataSize);
uint count = pattern.read(*this, patternHeaderLength - 4U);
READ_ASSERT(count == std::min(patternHeaderLength - 4U, pattern.size()));
seek(patternHeaderLength - (4 + count) + dataSize, Current);
}
StringList intrumentNames;
StringList sampleNames;
uint sumSampleCount = 0;
// read instruments:
for(ushort i = 0; i < instrumentCount; ++ i) {
READ_U32L_AS(<API key>);
READ_ASSERT(<API key> >= 4);
String instrumentName;
uchar instrumentType = 0;
ushort sampleCount = 0;
StructReader instrument;
instrument.string(instrumentName, 22).byte(instrumentType).u16L(sampleCount);
// 4 for <API key>
uint count = 4 + instrument.read(*this, <API key> - 4U);
READ_ASSERT(count == std::min(<API key>, instrument.size() + 4));
uint sampleHeaderSize = 0;
long offset = 0;
if(sampleCount > 0) {
sumSampleCount += sampleCount;
// wouldn't know which header size to assume otherwise:
READ_ASSERT(<API key> >= count + 4 && readU32L(sampleHeaderSize));
// skip unhandeled header proportion:
seek(<API key> - count - 4, Current);
for(ushort j = 0; j < sampleCount; ++ j) {
uint sampleLength = 0;
uint loopStart = 0;
uint loopLength = 0;
uchar volume = 0;
uchar finetune = 0;
uchar sampleType = 0;
uchar panning = 0;
uchar noteNumber = 0;
uchar compression = 0;
String sampleName;
StructReader sample;
sample.u32L(sampleLength)
.u32L(loopStart)
.u32L(loopLength)
.byte(volume)
.byte(finetune)
.byte(sampleType)
.byte(panning)
.byte(noteNumber)
.byte(compression)
.string(sampleName, 22);
uint count = sample.read(*this, sampleHeaderSize);
READ_ASSERT(count == std::min(sampleHeaderSize, sample.size()));
// skip unhandeled header proportion:
seek(sampleHeaderSize - count, Current);
offset += sampleLength;
sampleNames.append(sampleName);
}
}
else {
offset = <API key> - count;
}
intrumentNames.append(instrumentName);
seek(offset, Current);
}
d->properties.setSampleCount(sumSampleCount);
String comment(intrumentNames.toString("\n"));
if(sampleNames.size() > 0) {
comment += "\n";
comment += sampleNames.toString("\n");
}
d->tag.setComment(comment);
} |
/*
* Don't know how to identify if we are using SEH so it's only C++ for now
*/
#if defined(__cplusplus)
#include "test.h"
/*
* Create NUMTHREADS threads in addition to the Main thread.
*/
enum {
NUMTHREADS = 4
};
typedef struct bag_t_ bag_t;
struct bag_t_ {
int threadnum;
int started;
/* Add more per-thread state variables here */
};
static bag_t threadbag[NUMTHREADS + 1];
static pthread_barrier_t go = NULL;
void *
mythread(void * arg)
{
int result = 0;
bag_t * bag = (bag_t *) arg;
assert(bag == &threadbag[bag->threadnum]);
assert(bag->started == 0);
bag->started = 1;
/* Set to known state and type */
assert(<API key>(<API key>, NULL) == 0);
assert(<API key>(<API key>, NULL) == 0);
result = 1;
#if !defined(__cplusplus)
__try
#else
try
#endif
{
/* Wait for go from main */
<API key>(&go);
<API key>(&go);
pthread_testcancel();
}
#if !defined(__cplusplus)
__except(<API key>)
#else
#if defined(PtW32CatchAll)
PtW32CatchAll
#else
catch(...)
#endif
#endif
{
/*
* Should not get into here.
*/
result += 100;
}
/*
* Should not get to here either.
*/
result += 1000;
return (void *)(size_t)result;
}
int
main()
{
int failed = 0;
int i;
pthread_t t[NUMTHREADS + 1];
assert((t[0] = pthread_self()).p != NULL);
assert(<API key>(&go, NULL, NUMTHREADS + 1) == 0);
for (i = 1; i <= NUMTHREADS; i++)
{
threadbag[i].started = 0;
threadbag[i].threadnum = i;
assert(pthread_create(&t[i], NULL, mythread, (void *) &threadbag[i]) == 0);
}
/*
* Code to control or manipulate child threads should probably go here.
*/
<API key>(&go);
for (i = 1; i <= NUMTHREADS; i++)
{
assert(pthread_cancel(t[i]) == 0);
}
<API key>(&go);
/*
* Standard check that all threads started.
*/
for (i = 1; i <= NUMTHREADS; i++)
{
if (!threadbag[i].started)
{
failed |= !threadbag[i].started;
fprintf(stderr, "Thread %d: started %d\n", i, threadbag[i].started);
}
}
assert(!failed);
/*
* Check any results here. Set "failed" and only print output on failure.
*/
failed = 0;
for (i = 1; i <= NUMTHREADS; i++)
{
int fail = 0;
void* result = (void*)0;
assert(pthread_join(t[i], &result) == 0);
fail = (result != PTHREAD_CANCELED);
if (fail)
{
fprintf(stderr, "Thread %d: started %d: location %d\n",
i,
threadbag[i].started,
(int)(size_t)result);
}
failed |= fail;
}
assert(!failed);
assert(<API key>(&go) == 0);
/*
* Success.
*/
return 0;
}
#else /* defined(__cplusplus) */
#include <stdio.h>
int
main()
{
fprintf(stderr, "Test N/A for this compiler environment.\n");
return 0;
}
#endif /* defined(__cplusplus) */ |
<?php
abstract class CMS_Model_Tree extends CMS_Model_MultiLang {
protected $name_tree_field = null;
protected $id_tree = null;
protected $cond_sql_multi_tree = null;
public function __construct($name_tree_field = null, $id_tree = null){
parent::__construct();
// Construction de la chaine de condition pour le multi arbre
if ($name_tree_field && $id_tree){
$this->name_tree_field = $name_tree_field;
$this->id_tree = $id_tree;
$this->cond_sql_multi_tree = " AND ".$this->name_tree_field." = ".$this->id_tree." ";
}
}
public function getParentId($id)
{
if (!$id)
throw new Exception('No id');
$sql = "SELECT parent." . $this->_primaryKey . "
FROM pagespro_activites parent,
pagespro_activites node
WHERE parent.lft < node.lft AND parent.rgt > node.rgt
AND node." . $this->_primaryKey . " = ".$id." ";
$sql .= $this->cond_sql_multi_tree;
$sql .="ORDER BY parent.rgt-node.rgt ASC
LIMIT 1";
$return = $this->getAdapter()->fetchOne($sql);
if(!empty($return))
return $return;
else
return null;
}
public function getTree($id_lang = null){
$this->_values = array_merge($this->_values, array('parent_id', 'level'));
$return = $this-><API key>($this->_getDatas($id_lang));
foreach ($this->_values as $key => $value) {
if ($value == 'parent_id' || $value == 'level')
unset($this->_values[$key]);
}
return $return ? $return : null;
}
protected function _getDatas($id_lang = null)
{
$sql = "SELECT A.*, B.* , (COUNT(parent." . $this->_primaryKey . ")-1) AS level, (SELECT " . $this->_primaryKey . "
FROM ".$this->_name." t2
WHERE t2.lft < A.lft AND t2.rgt > A.rgt
ORDER BY t2.rgt-A.rgt ASC
LIMIT 1) AS parent_id
FROM ".$this->_name." AS A,
".$this->_name." AS parent,
".$this->_name."_lang AS B
WHERE A.lft BETWEEN parent.lft AND parent.rgt
";
$sql .= $this->cond_sql_multi_tree;
$sql .= " AND B." . $this->_primaryKey . " = A." . $this->_primaryKey . "
GROUP BY A." . $this->_primaryKey . ", id_lang
ORDER BY A.lft;";
//parent::generateSQL($sql, $where, $order, $limit);
$return = $this->getAdapter()->fetchAll($sql, null, zend_db::FETCH_OBJ);
return $return ? $return : null;
}
/*
* Fonction d'ajout d'un item
* */
public function addItem($obj)
{
$db = $this->getAdapter();
try
{
$db->beginTransaction();
$db->query("SELECT @myRight := rgt FROM " . $this->_name . " WHERE ".$this->_primaryKey." = ?", array($obj->parent_id));
if ($this->id_tree && $this->name_tree_field) {
$cond_lft = array("lft >= @myRight", $this->name_field_tree." = ".$this->id_tree);
$cond_rgt = array("rgt >= @myRight", $this->name_field_tree." = ".$this->id_tree);
} else {
$cond_lft = array("lft >= @myRight");
$cond_rgt = array("rgt >= @myRight");
}
$db->update(
$this->_name,
array( "rgt" => new Zend_Db_Expr("rgt + 2") ),
$cond_rgt
);
$db->update(
$this->_name,
array( "lft" => new Zend_Db_Expr("lft + 2") ),
$cond_lft
);
$obj->lft = new Zend_Db_Expr('@myRight');
$obj->rgt = new Zend_Db_Expr('@myRight+1');
$obj->save();
$db->commit();
}
catch (Exception $e)
{
$db->rollBack();
throw new Zend_Db_Exception($e->getMessage(), $e->getCode());
}
return $obj->id;
}
public function deleteEntity($param)
{
if(is_int($param))
{
if(!$param)
throw new Zend_Exception(_t('Missing parameter'));
$db = $this->getAdapter();
try
{
$db->beginTransaction();
// /!\ Delete children if folder
$db->query("SELECT @myLeft := lft, @myRight := rgt, @myWidth := rgt - lft + 1 FROM " . $this->_name . " WHERE ".$this->_primaryKey." = ?", array($param));
$objs = $db->query("SELECT ".$this->_primaryKey." FROM " . $this->_name . " WHERE lft BETWEEN @myLeft AND @myRight ".$this->cond_sql_multi_tree)->fetchAll(PDO::FETCH_OBJ);
foreach ($objs as $obj){
parent::delete((int)$obj->id);
}
// Condition pour le multi tree
if ($this->id_tree && $this->name_tree_field) {
$cond_lft = array("lft > @myRight", $this->name_field_tree." = ".$this->id_tree);
$cond_rgt = array("rgt > @myRight", $this->name_field_tree." = ".$this->id_tree);
} else {
$cond_lft = array("lft > @myRight");
$cond_rgt = array("rgt > @myRight");
}
$db->update(
$this->_name,
array( "rgt" => new Zend_Db_Expr("rgt - @myWidth") ),
$cond_rgt
);
$db->update(
$this->_name,
array( "lft" => new Zend_Db_Expr("lft - @myWidth") ),
$cond_lft
);
$db->commit();
}
catch (Exception $e)
{
$db->rollBack();
throw new Zend_Db_Exception($e->getMessage(), $e->getCode());
}
return true;
}
return false;
}
/** NESTED TREE **/
public function updateParent($itemId, $parentId)
{
$row = $this->find ($itemId)->current();
if ($row)
{
$destItem = $this->find ( $parentId )->current ();
if($destItem)
{
if (($destItem->lft>$row->lft) && ($destItem->rgt<$row->rgt))
return false;
$pos = $this->_moveToLastChild($row,$destItem);
return true;
}
}
return false;
}
public function <API key>($srcId, $destId)
{
$scrItem = $this->find($srcId)->current();
$destItem = $this->find($destId)->current();
if ($scrItem && $destItem)
{
$newpos = $this-><API key>($scrItem,$destItem);
return true;
}
else
{
throw new Zend_Exception("Error moving menu items");
return false;
}
return false;
}
private function _moveToNextSibling($srcNode, $destNode)
{
return $this->_moveSubtree($srcNode, $destNode->rgt+1);
}
private function <API key>($srcNode, $destNode)
{
return $this->_moveSubtree($srcNode, $destNode->lft);
}
private function _moveToFirstChild($srcNode, $destNode)
{
return $this->_moveSubtree($srcNode, $destNode->lft+1);
}
private function _moveToLastChild($srcNode, $destNode)
{
return $this->_moveSubtree($srcNode, $destNode->rgt);
}
private function _moveSubtree($srcNode, $dst)
{
$treesize = $srcNode->rgt-$srcNode->lft+1;
$this->_shiftRLValues($dst, $treesize);
if($srcNode->lft >= $dst) // src was shifted too?
{
$srcNode->lft += $treesize;
$srcNode->rgt += $treesize;
}
/* Now there is enough room next to target to move the subtree */
$newpos = $this->_shiftRLRange($srcNode->lft, $srcNode->rgt, $dst-$srcNode->lft);
/* Correct values after source */
$this->_shiftRLValues($srcNode->rgt+1, -$treesize);
if($srcNode->lft <= $dst) // dst was shifted too?
{
$newpos['l'] -= $treesize;
$newpos['r'] -= $treesize;
}
return $newpos;
}
private function _shiftRLValues($first, $delta)
{
$db = Zend_Registry::get('db');
$db->query("UPDATE ". $this->_name
." SET lft = lft+".$delta
." WHERE lft >= ".$first
." ".$this->cond_sql_multi_tree);
$db->query("UPDATE ". $this->_name
." SET rgt = rgt+".$delta
." WHERE rgt >= ".$first
." ".$this->cond_sql_multi_tree);
}
private function _shiftRLRange($first, $last, $delta)
{
$db = Zend_Registry::get('db');
$db->query("UPDATE ". $this->_name
." SET lft = lft+".$delta
." WHERE lft >= ".$first." AND lft <= ".$last
." ".$this->cond_sql_multi_tree);
$db->query("UPDATE ". $this->_name
." SET rgt = rgt+".$delta
." WHERE rgt >= ".$first." AND rgt <= ".$last
." ".$this->cond_sql_multi_tree);
return array('l' => $first+$delta, 'r' => $last+$delta);
}
} |
/**
* SECTION:gstbaseparse
* @short_description: Base class for stream parsers
* @see_also: #GstBaseTransform
*
* This base class is for parser elements that process data and splits it
* into separate audio/video/whatever frames.
*
* It provides for:
* <itemizedlist>
* <listitem><para>provides one sink pad and one source pad</para></listitem>
* <listitem><para>handles state changes</para></listitem>
* <listitem><para>can operate in pull mode or push mode</para></listitem>
* <listitem><para>handles seeking in both modes</para></listitem>
* <listitem><para>handles events (NEWSEGMENT/EOS/FLUSH)</para></listitem>
* <listitem><para>
* handles queries (POSITION/DURATION/SEEKING/FORMAT/CONVERT)
* </para></listitem>
* <listitem><para>handles flushing</para></listitem>
* </itemizedlist>
*
* The purpose of this base class is to provide the basic functionality of
* a parser and share a lot of rather complex code.
*
* Description of the parsing mechanism:
* <orderedlist>
* <listitem>
* <itemizedlist><title>Set-up phase</title>
* <listitem><para>
* GstBaseParse class calls @set_sink_caps to inform the subclass about
* incoming sinkpad caps. Subclass should set the srcpad caps accordingly.
* </para></listitem>
* <listitem><para>
* GstBaseParse calls @start to inform subclass that data processing is
* about to start now.
* </para></listitem>
* <listitem><para>
* At least at this point subclass needs to tell the GstBaseParse class
* how big data chunks it wants to receive (min_frame_size). It can do
* this with <API key>().
* </para></listitem>
* <listitem><para>
* GstBaseParse class sets up appropriate data passing mode (pull/push)
* and starts to process the data.
* </para></listitem>
* </itemizedlist>
* </listitem>
* <listitem>
* <itemizedlist>
* <title>Parsing phase</title>
* <listitem><para>
* GstBaseParse gathers at least min_frame_size bytes of data either
* by pulling it from upstream or collecting buffers in an internal
* #GstAdapter.
* </para></listitem>
* <listitem><para>
* A buffer of (at least) min_frame_size bytes is passed to subclass with
* @check_valid_frame. Subclass checks the contents and returns TRUE
* if the buffer contains a valid frame. It also needs to set the
* @framesize according to the detected frame size. If buffer didn't
* contain a valid frame, this call must return FALSE and optionally
* set the @skipsize value to inform base class that how many bytes
* it needs to skip in order to find a valid frame. @framesize can always
* indicate a new minimum for current frame parsing. Indicating G_MAXUINT
* for requested amount means subclass simply needs best available
* subsequent data. In push mode this amounts to an additional input buffer
* (thus minimal additional latency), in pull mode this amounts to some
* arbitrary reasonable buffer size increase. The passed buffer
* is read-only. Note that @check_valid_frame might receive any small
* amount of input data when leftover data is being drained (e.g. at EOS).
* </para></listitem>
* <listitem><para>
* After valid frame is found, it will be passed again to subclass with
* @parse_frame call. Now subclass is responsible for parsing the
* frame contents and setting the caps, and buffer metadata (e.g.
* buffer timestamp and duration, or keyframe if applicable).
* (although the latter can also be done by GstBaseParse if it is
* appropriately configured, see below). Frame is provided with
* timestamp derived from upstream (as much as generally possible),
* duration obtained from configuration (see below), and offset
* if meaningful (in pull mode).
* </para></listitem>
* <listitem><para>
* Finally the buffer can be pushed downstream and the parsing loop starts
* over again. Just prior to actually pushing the buffer in question,
* it is passed to @pre_push_frame which gives subclass yet one
* last chance to examine buffer metadata, or to send some custom (tag)
* events, or to perform custom (segment) filtering.
* </para></listitem>
* <listitem><para>
* During the parsing process GstBaseParseClass will handle both srcpad
* and sinkpad events. They will be passed to subclass if @event or
* @src_event callbacks have been provided.
* </para></listitem>
* </itemizedlist>
* </listitem>
* <listitem>
* <itemizedlist><title>Shutdown phase</title>
* <listitem><para>
* GstBaseParse class calls @stop to inform the subclass that data
* parsing will be stopped.
* </para></listitem>
* </itemizedlist>
* </listitem>
* </orderedlist>
*
* Subclass is responsible for providing pad template caps for
* source and sink pads. The pads need to be named "sink" and "src". It also
* needs to set the fixed caps on srcpad, when the format is ensured (e.g.
* when base class calls subclass' @set_sink_caps function).
*
* This base class uses #GST_FORMAT_DEFAULT as a meaning of frames. So,
* subclass conversion routine needs to know that conversion from
* #GST_FORMAT_TIME to #GST_FORMAT_DEFAULT must return the
* frame number that can be found from the given byte position.
*
* GstBaseParse uses subclasses conversion methods also for seeking (or
* otherwise uses its own default one, see also below).
*
* Subclass @start and @stop functions will be called to inform the beginning
* and end of data processing.
*
* Things that subclass need to take care of:
* <itemizedlist>
* <listitem><para>Provide pad templates</para></listitem>
* <listitem><para>
* Fixate the source pad caps when appropriate
* </para></listitem>
* <listitem><para>
* Inform base class how big data chunks should be retrieved. This is
* done with <API key>() function.
* </para></listitem>
* <listitem><para>
* Examine data chunks passed to subclass with @check_valid_frame
* and tell if they contain a valid frame
* </para></listitem>
* <listitem><para>
* Set the caps and timestamp to frame that is passed to subclass with
* @parse_frame function.
* </para></listitem>
* <listitem><para>Provide conversion functions</para></listitem>
* <listitem><para>
* Update the duration information with <API key>()
* </para></listitem>
* <listitem><para>
* Optionally passthrough using <API key>()
* </para></listitem>
* <listitem><para>
* Configure various baseparse parameters using
* <API key>(), <API key>()
* and <API key>().
* </para></listitem>
* <listitem><para>
* In particular, if subclass is unable to determine a duration, but
* parsing (or specs) yields a frames per seconds rate, then this can be
* provided to GstBaseParse to enable it to cater for
* buffer time metadata (which will be taken from upstream as much as
* possible). Internally keeping track of frame durations and respective
* sizes that have been pushed provides GstBaseParse with an estimated
* bitrate. A default @convert (used if not overriden) will then use these
* rates to perform obvious conversions. These rates are also used to
* update (estimated) duration at regular frame intervals.
* </para></listitem>
* </itemizedlist>
*
*/
/* TODO:
* - In push mode provide a queue of adapter-"queued" buffers for upstream
* buffer metadata
* - Queue buffers/events until caps are set
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
/* FIXME 0.11: suppress warnings for deprecated API such as GStaticRecMutex
* with newer GLib versions (>= 2.31.0) */
#define <API key>
#include <gst/base/gstadapter.h>
#include "gstbaseparse.h"
#define <API key> (1 << 0)
#define <API key> 10
#define TARGET_DIFFERENCE (20 * GST_SECOND)
<API key> (<API key>);
#define GST_CAT_DEFAULT <API key>
/* Supported formats */
static const GstFormat fmtlist[] = {
GST_FORMAT_DEFAULT,
GST_FORMAT_BYTES,
GST_FORMAT_TIME,
<API key>
};
#define <API key>(obj) \
(<API key> ((obj), GST_TYPE_BASE_PARSE, GstBaseParsePrivate))
struct <API key>
{
GstActivateMode pad_mode;
GstAdapter *adapter;
gint64 duration;
GstFormat duration_fmt;
gint64 estimated_duration;
gint64 estimated_drift;
guint min_frame_size;
gboolean passthrough;
gboolean syncable;
gboolean has_timing_info;
guint fps_num, fps_den;
gint update_interval;
guint bitrate;
guint lead_in, lead_out;
GstClockTime lead_in_ts, lead_out_ts;
GstClockTime min_latency, max_latency;
gboolean discont;
gboolean flushing;
gboolean drain;
gint64 offset;
gint64 sync_offset;
GstClockTime next_ts;
GstClockTime prev_ts;
GstClockTime frame_duration;
gboolean seen_keyframe;
gboolean is_video;
guint64 framecount;
guint64 bytecount;
guint64 data_bytecount;
guint64 acc_duration;
GstClockTime first_frame_ts;
gint64 first_frame_offset;
gboolean post_min_bitrate;
gboolean post_avg_bitrate;
gboolean post_max_bitrate;
guint min_bitrate;
guint avg_bitrate;
guint max_bitrate;
guint posted_avg_bitrate;
/* frames/buffers that are queued and ready to go on OK */
GQueue queued_frames;
GstBuffer *cache;
/* index entry storage, either ours or provided */
GstIndex *index;
gint index_id;
gboolean own_index;
#if !GLIB_CHECK_VERSION (2, 31, 0)
GStaticMutex index_lock;
#else
GMutex index_lock;
#endif
/* seek table entries only maintained if upstream is BYTE seekable */
gboolean upstream_seekable;
gboolean <API key>;
gint64 upstream_size;
/* minimum distance between two index entries */
GstClockTimeDiff idx_interval;
/* ts and offset of last entry added */
GstClockTime index_last_ts;
gint64 index_last_offset;
gboolean index_last_valid;
/* timestamps currently produced are accurate, e.g. started from 0 onwards */
gboolean exact_position;
/* seek events are temporarily kept to match them with newsegments */
GSList *pending_seeks;
/* reverse playback */
GSList *buffers_pending;
GSList *buffers_queued;
GSList *buffers_send;
GstClockTime last_ts;
gint64 last_offset;
/* Pending serialized events */
GList *pending_events;
/* Newsegment event to be sent after SEEK */
gboolean pending_segment;
/* Segment event that closes the running segment prior to SEEK */
GstEvent *close_segment;
/* push mode helper frame */
GstBaseParseFrame frame;
/* TRUE if we're still detecting the format, i.e.
* if ::detect() is still called for future buffers */
gboolean detecting;
GList *detect_buffers;
guint detect_buffers_size;
};
typedef struct _GstBaseParseSeek
{
GstSegment segment;
gboolean accurate;
gint64 offset;
GstClockTime start_ts;
} GstBaseParseSeek;
#if !GLIB_CHECK_VERSION (2, 31, 0)
#define <API key>(parse) \
g_static_mutex_lock (&parse->priv->index_lock);
#define <API key>(parse) \
<API key> (&parse->priv->index_lock);
#else
#define <API key>(parse) \
g_mutex_lock (&parse->priv->index_lock);
#define <API key>(parse) \
g_mutex_unlock (&parse->priv->index_lock);
#endif
static GstElementClass *parent_class = NULL;
static void <API key> (GstBaseParseClass * klass);
static void gst_base_parse_init (GstBaseParse * parse,
GstBaseParseClass * klass);
GType
<API key> (void)
{
static volatile gsize base_parse_type = 0;
if (g_once_init_enter (&base_parse_type)) {
static const GTypeInfo base_parse_info = {
sizeof (GstBaseParseClass),
(GBaseInitFunc) NULL,
(GBaseFinalizeFunc) NULL,
(GClassInitFunc) <API key>,
NULL,
NULL,
sizeof (GstBaseParse),
0,
(GInstanceInitFunc) gst_base_parse_init,
};
GType _type;
_type = <API key> (GST_TYPE_ELEMENT,
"GstBaseParse", &base_parse_info, <API key>);
g_once_init_leave (&base_parse_type, _type);
}
return (GType) base_parse_type;
}
static void <API key> (GObject * object);
static <API key> <API key> (GstElement * element,
GstStateChange transition);
static void <API key> (GstBaseParse * parse);
static void <API key> (GstElement * element, GstIndex * index);
static GstIndex *<API key> (GstElement * element);
static gboolean <API key> (GstPad * sinkpad);
static gboolean <API key> (GstPad * pad,
gboolean active);
static gboolean <API key> (GstPad * pad,
gboolean active);
static gboolean <API key> (GstBaseParse * parse,
GstEvent * event);
static void <API key> (GstBaseParse * parse, GstEvent * event);
static gboolean <API key> (GstPad * pad, GstEvent * event);
static gboolean <API key> (GstPad * pad, GstEvent * event);
static gboolean <API key> (GstPad * pad, GstQuery * query);
static gboolean <API key> (GstPad * pad, GstCaps * caps);
static GstCaps *<API key> (GstPad * pad);
static const GstQueryType *<API key> (GstPad * pad);
static GstFlowReturn <API key> (GstPad * pad, GstBuffer * buffer);
static void gst_base_parse_loop (GstPad * pad);
static gboolean <API key> (GstBaseParse * parse,
GstBaseParseFrame * frame, guint * framesize, gint * skipsize);
static GstFlowReturn <API key> (GstBaseParse * parse,
GstBaseParseFrame * frame);
static gboolean <API key> (GstBaseParse * parse,
GstEvent * event);
static gboolean <API key> (GstBaseParse * parse,
GstEvent * event);
static void <API key> (GstBaseParse * parse);
static void <API key> (GstBaseParse * parse,
gboolean post_min, gboolean post_avg, gboolean post_max);
static gint64 <API key> (GstBaseParse * parse,
GstClockTime time, gboolean before, GstClockTime * _ts);
static GstFlowReturn <API key> (GstBaseParse * parse,
GstClockTime * _time, gint64 * _offset);
static GstFlowReturn <API key> (GstBaseParse * parse,
gboolean push_only);
static gboolean <API key> (GstBaseParse * parse);
static void
<API key> (GstBaseParse * parse)
{
g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
g_slist_free (parse->priv->buffers_queued);
parse->priv->buffers_queued = NULL;
g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
NULL);
g_slist_free (parse->priv->buffers_pending);
parse->priv->buffers_pending = NULL;
g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
g_slist_free (parse->priv->buffers_send);
parse->priv->buffers_send = NULL;
g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
g_list_free (parse->priv->detect_buffers);
parse->priv->detect_buffers = NULL;
parse->priv->detect_buffers_size = 0;
g_queue_foreach (&parse->priv->queued_frames,
(GFunc) <API key>, NULL);
g_queue_clear (&parse->priv->queued_frames);
gst_buffer_replace (&parse->priv->cache, NULL);
g_list_foreach (parse->priv->pending_events, (GFunc) gst_event_unref, NULL);
g_list_free (parse->priv->pending_events);
parse->priv->pending_events = NULL;
parse->priv->pending_segment = FALSE;
gst_event_replace (&parse->priv->close_segment, NULL);
}
static void
<API key> (GObject * object)
{
GstBaseParse *parse = GST_BASE_PARSE (object);
GstEvent **p_ev;
g_object_unref (parse->priv->adapter);
if (parse->priv->close_segment) {
p_ev = &parse->priv->close_segment;
gst_event_replace (p_ev, NULL);
}
if (parse->priv->cache) {
gst_buffer_unref (parse->priv->cache);
parse->priv->cache = NULL;
}
g_list_foreach (parse->priv->pending_events, (GFunc) <API key>,
NULL);
g_list_free (parse->priv->pending_events);
parse->priv->pending_events = NULL;
parse->priv->pending_segment = FALSE;
if (parse->priv->index) {
gst_object_unref (parse->priv->index);
parse->priv->index = NULL;
}
#if !GLIB_CHECK_VERSION (2, 31, 0)
g_static_mutex_free (&parse->priv->index_lock);
#else
g_mutex_clear (&parse->priv->index_lock);
#endif
<API key> (parse);
G_OBJECT_CLASS (parent_class)->finalize (object);
}
static void
<API key> (GstBaseParseClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = G_OBJECT_CLASS (klass);
<API key> (klass, sizeof (GstBaseParsePrivate));
parent_class = <API key> (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (<API key>);
gstelement_class = (GstElementClass *) klass;
gstelement_class->change_state =
GST_DEBUG_FUNCPTR (<API key>);
gstelement_class->set_index = GST_DEBUG_FUNCPTR (<API key>);
gstelement_class->get_index = GST_DEBUG_FUNCPTR (<API key>);
/* Default handlers */
klass->check_valid_frame = <API key>;
klass->parse_frame = <API key>;
klass->src_event = <API key>;
klass->convert = <API key>;
<API key> (<API key>, "baseparse", 0,
"baseparse element");
}
static void
gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
{
GstPadTemplate *pad_template;
GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
parse->priv = <API key> (parse);
pad_template =
<API key> (GST_ELEMENT_CLASS (bclass), "sink");
g_return_if_fail (pad_template != NULL);
parse->sinkpad = <API key> (pad_template, "sink");
<API key> (parse->sinkpad,
GST_DEBUG_FUNCPTR (<API key>));
<API key> (parse->sinkpad,
GST_DEBUG_FUNCPTR (<API key>));
<API key> (parse->sinkpad,
GST_DEBUG_FUNCPTR (<API key>));
<API key> (parse->sinkpad,
GST_DEBUG_FUNCPTR (<API key>));
<API key> (parse->sinkpad,
GST_DEBUG_FUNCPTR (<API key>));
<API key> (parse->sinkpad,
GST_DEBUG_FUNCPTR (<API key>));
<API key> (parse->sinkpad,
GST_DEBUG_FUNCPTR (<API key>));
gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
GST_DEBUG_OBJECT (parse, "sinkpad created");
pad_template =
<API key> (GST_ELEMENT_CLASS (bclass), "src");
g_return_if_fail (pad_template != NULL);
parse->srcpad = <API key> (pad_template, "src");
<API key> (parse->srcpad,
GST_DEBUG_FUNCPTR (<API key>));
<API key> (parse->srcpad,
GST_DEBUG_FUNCPTR (<API key>));
<API key> (parse->srcpad,
GST_DEBUG_FUNCPTR (<API key>));
<API key> (parse->srcpad);
gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
GST_DEBUG_OBJECT (parse, "src created");
g_queue_init (&parse->priv->queued_frames);
parse->priv->adapter = gst_adapter_new ();
parse->priv->pad_mode = GST_ACTIVATE_NONE;
#if !GLIB_CHECK_VERSION (2, 31, 0)
g_static_mutex_init (&parse->priv->index_lock);
#else
g_mutex_init (&parse->priv->index_lock);
#endif
/* init state */
<API key> (parse);
GST_DEBUG_OBJECT (parse, "init ok");
}
static GstBaseParseFrame *
<API key> (GstBaseParseFrame * frame)
{
GstBaseParseFrame *copy;
copy = g_slice_dup (GstBaseParseFrame, frame);
copy->buffer = gst_buffer_ref (frame->buffer);
copy->_private_flags &= ~<API key>;
GST_TRACE ("copied frame %p -> %p", frame, copy);
return copy;
}
void
<API key> (GstBaseParseFrame * frame)
{
GST_TRACE ("freeing frame %p", frame);
if (frame->buffer) {
gst_buffer_unref (frame->buffer);
frame->buffer = NULL;
}
if (!(frame->_private_flags & <API key>)) {
g_slice_free (GstBaseParseFrame, frame);
} else {
memset (frame, 0, sizeof (*frame));
}
}
GType
<API key> (void)
{
static volatile gsize frame_type = 0;
if (g_once_init_enter (&frame_type)) {
GType _type;
_type = <API key> ("GstBaseParseFrame",
(GBoxedCopyFunc) <API key>,
(GBoxedFreeFunc) <API key>);
g_once_init_leave (&frame_type, _type);
}
return (GType) frame_type;
}
/**
* <API key>:
* @frame: #GstBaseParseFrame.
*
* Sets a #GstBaseParseFrame to initial state. Currently this means
* all public fields are zero-ed and a private flag is set to make
* sure <API key>() only frees the contents but not
* the actual frame. Use this function to initialise a #GstBaseParseFrame
* allocated on the stack.
*
* Since: 0.10.33
*/
void
<API key> (GstBaseParseFrame * frame)
{
memset (frame, 0, sizeof (GstBaseParseFrame));
frame->_private_flags = <API key>;
GST_TRACE ("inited frame %p", frame);
}
/**
* <API key>:
* @buffer: (transfer none): a #GstBuffer
* @flags: the flags
* @overhead: number of bytes in this frame which should be counted as
* metadata overhead, ie. not used to calculate the average bitrate.
* Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
*
* Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
* elements written in C should usually allocate the frame on the stack and
* then use <API key>() to initialise it.
*
* Returns: a newly-allocated #GstBaseParseFrame. Free with
* <API key>() when no longer needed, unless you gave
* away ownership to <API key>().
*
* Since: 0.10.33
*/
GstBaseParseFrame *
<API key> (GstBuffer * buffer, <API key> flags,
gint overhead)
{
GstBaseParseFrame *frame;
frame = g_slice_new0 (GstBaseParseFrame);
frame->buffer = gst_buffer_ref (buffer);
GST_TRACE ("created frame %p", frame);
return frame;
}
static inline void
<API key> (GstBaseParse * parse, GstBaseParseFrame * frame,
GstBuffer * buf)
{
gst_buffer_replace (&frame->buffer, buf);
parse->flags = 0;
/* set flags one by one for clarity */
if (G_UNLIKELY (parse->priv->drain))
parse->flags |= <API key>;
/* losing sync is pretty much a discont (and vice versa), no ? */
if (G_UNLIKELY (parse->priv->discont))
parse->flags |= <API key>;
}
static void
<API key> (GstBaseParse * parse)
{
GST_OBJECT_LOCK (parse);
gst_segment_init (&parse->segment, GST_FORMAT_TIME);
parse->priv->duration = -1;
parse->priv->min_frame_size = 1;
parse->priv->discont = TRUE;
parse->priv->flushing = FALSE;
parse->priv->offset = 0;
parse->priv->sync_offset = 0;
parse->priv->update_interval = -1;
parse->priv->fps_num = parse->priv->fps_den = 0;
parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
parse->priv->lead_in = parse->priv->lead_out = 0;
parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
parse->priv->bitrate = 0;
parse->priv->framecount = 0;
parse->priv->bytecount = 0;
parse->priv->acc_duration = 0;
parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
parse->priv->first_frame_offset = -1;
parse->priv->estimated_duration = -1;
parse->priv->estimated_drift = 0;
parse->priv->next_ts = 0;
parse->priv->syncable = TRUE;
parse->priv->passthrough = FALSE;
parse->priv->has_timing_info = FALSE;
parse->priv->post_min_bitrate = TRUE;
parse->priv->post_avg_bitrate = TRUE;
parse->priv->post_max_bitrate = TRUE;
parse->priv->min_bitrate = G_MAXUINT;
parse->priv->max_bitrate = 0;
parse->priv->avg_bitrate = 0;
parse->priv->posted_avg_bitrate = 0;
parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
parse->priv->index_last_offset = -1;
parse->priv->index_last_valid = TRUE;
parse->priv->upstream_seekable = FALSE;
parse->priv->upstream_size = 0;
parse->priv-><API key> = FALSE;
parse->priv->idx_interval = 0;
parse->priv->exact_position = TRUE;
parse->priv->seen_keyframe = FALSE;
parse->priv->last_ts = GST_CLOCK_TIME_NONE;
parse->priv->last_offset = 0;
g_list_foreach (parse->priv->pending_events, (GFunc) <API key>,
NULL);
g_list_free (parse->priv->pending_events);
parse->priv->pending_events = NULL;
parse->priv->pending_segment = FALSE;
gst_event_replace (&parse->priv->close_segment, NULL);
if (parse->priv->cache) {
gst_buffer_unref (parse->priv->cache);
parse->priv->cache = NULL;
}
g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
g_slist_free (parse->priv->pending_seeks);
parse->priv->pending_seeks = NULL;
if (parse->priv->adapter)
gst_adapter_clear (parse->priv->adapter);
/* we know it is not alloc'ed, but maybe other stuff to free, some day ... */
parse->priv->frame._private_flags |=
<API key>;
<API key> (&parse->priv->frame);
g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
g_list_free (parse->priv->detect_buffers);
parse->priv->detect_buffers = NULL;
parse->priv->detect_buffers_size = 0;
GST_OBJECT_UNLOCK (parse);
}
/* <API key>:
* @parse: #GstBaseParse.
* @buffer: GstBuffer.
* @framesize: This will be set to tell the found frame size in bytes.
* @skipsize: Output parameter that tells how much data needs to be skipped
* in order to find the following frame header.
*
* Default callback for check_valid_frame.
*
* Returns: Always TRUE.
*/
static gboolean
<API key> (GstBaseParse * parse,
GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
{
*framesize = GST_BUFFER_SIZE (frame->buffer);
*skipsize = 0;
return TRUE;
}
/* <API key>:
* @parse: #GstBaseParse.
* @buffer: #GstBuffer.
*
* Default callback for parse_frame.
*/
static GstFlowReturn
<API key> (GstBaseParse * parse, GstBaseParseFrame * frame)
{
GstBuffer *buffer = frame->buffer;
if (!<API key> (buffer) &&
<API key> (parse->priv->next_ts)) {
<API key> (buffer) = parse->priv->next_ts;
}
if (!<API key> (buffer) &&
<API key> (parse->priv->frame_duration)) {
GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
}
return GST_FLOW_OK;
}
/* <API key>:
* @parse: #GstBaseParse.
* @src_format: #GstFormat describing the source format.
* @src_value: Source value to be converted.
* @dest_format: #GstFormat defining the converted format.
* @dest_value: Pointer where the conversion result will be put.
*
* Converts using configured "convert" vmethod in #GstBaseParse class.
*
* Returns: TRUE if conversion was successful.
*/
static gboolean
<API key> (GstBaseParse * parse,
GstFormat src_format,
gint64 src_value, GstFormat dest_format, gint64 * dest_value)
{
GstBaseParseClass *klass = <API key> (parse);
gboolean ret;
<API key> (dest_value != NULL, FALSE);
if (!klass->convert)
return FALSE;
ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
#ifndef <API key>
{
if (ret) {
if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
GST_LOG_OBJECT (parse,
"TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
GST_TIME_ARGS (src_value), *dest_value);
} else if (dest_format == GST_FORMAT_TIME &&
src_format == GST_FORMAT_BYTES) {
GST_LOG_OBJECT (parse,
"BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
src_value, GST_TIME_ARGS (*dest_value));
} else {
GST_LOG_OBJECT (parse,
"%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
GST_STR_NULL (gst_format_get_name (src_format)),
GST_STR_NULL (gst_format_get_name (dest_format)),
src_value, *dest_value);
}
} else {
GST_DEBUG_OBJECT (parse, "conversion failed");
}
}
#endif
return ret;
}
/* <API key>:
* @pad: #GstPad that received the event.
* @event: #GstEvent to be handled.
*
* Handler for sink pad events.
*
* Returns: TRUE if the event was handled.
*/
static gboolean
<API key> (GstPad * pad, GstEvent * event)
{
GstBaseParse *parse;
GstBaseParseClass *bclass;
gboolean handled = FALSE;
gboolean ret = TRUE;
parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
bclass = <API key> (parse);
GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
GST_EVENT_TYPE_NAME (event));
/* Cache all serialized events except EOS, NEWSEGMENT and FLUSH_STOP if we have a
* pending segment */
if (parse->priv->pending_segment && <API key> (event)
&& GST_EVENT_TYPE (event) != GST_EVENT_EOS
&& GST_EVENT_TYPE (event) != <API key>
&& GST_EVENT_TYPE (event) != <API key>
&& GST_EVENT_TYPE (event) != <API key>) {
if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
/* See if any bitrate tags were posted */
<API key> (parse, event);
parse->priv->pending_events =
g_list_append (parse->priv->pending_events, event);
ret = TRUE;
} else {
if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
parse->priv->framecount < <API key>)
/* We've not posted bitrate tags yet - do so now */
<API key> (parse, TRUE, TRUE, TRUE);
if (bclass->event)
handled = bclass->event (parse, event);
if (!handled)
handled = <API key> (parse, event);
if (!handled)
ret = <API key> (pad, event);
}
gst_object_unref (parse);
GST_DEBUG_OBJECT (parse, "event handled");
return ret;
}
/* <API key>:
* @parse: #GstBaseParse.
* @event: #GstEvent to be handled.
*
* Element-level event handler function.
*
* The event will be unreffed only if it has been handled and this
* function returns %TRUE
*
* Returns: %TRUE if the event was handled and not need forwarding.
*/
static gboolean
<API key> (GstBaseParse * parse, GstEvent * event)
{
gboolean handled = FALSE;
switch (GST_EVENT_TYPE (event)) {
case <API key>:
{
gdouble rate, applied_rate;
GstFormat format;
gint64 start, stop, pos, next_ts, offset = 0;
gboolean update;
<API key> (event, &update, &rate, &applied_rate,
&format, &start, &stop, &pos);
GST_DEBUG_OBJECT (parse, "newseg rate %g, applied rate %g, "
"format %d, start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
", pos = %" GST_TIME_FORMAT, rate, applied_rate, format,
GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (pos));
if (format == GST_FORMAT_BYTES) {
GstClockTime seg_start, seg_stop;
GstBaseParseSeek *seek = NULL;
GSList *node;
/* stop time is allowed to be open-ended, but not start & pos */
seg_stop = GST_CLOCK_TIME_NONE;
seg_start = 0;
offset = pos;
GST_OBJECT_LOCK (parse);
for (node = parse->priv->pending_seeks; node; node = node->next) {
GstBaseParseSeek *tmp = node->data;
if (tmp->offset == pos) {
seek = tmp;
break;
}
}
parse->priv->pending_seeks =
g_slist_remove (parse->priv->pending_seeks, seek);
GST_OBJECT_UNLOCK (parse);
if (seek) {
GST_DEBUG_OBJECT (parse,
"Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
seek->accurate ? " accurate" : "", &seek->segment);
seg_start = seek->segment.start;
seg_stop = seek->segment.stop;
next_ts = seek->start_ts;
parse->priv->exact_position = seek->accurate;
g_free (seek);
} else {
/* best attempt convert */
/* as these are only estimates, stop is kept open-ended to avoid
* premature cutting */
<API key> (parse, GST_FORMAT_BYTES, start,
GST_FORMAT_TIME, (gint64 *) & seg_start);
parse->priv->exact_position = (start == 0);
next_ts = seg_start;
}
gst_event_unref (event);
event = <API key> (update, rate, applied_rate,
GST_FORMAT_TIME, seg_start, seg_stop, seg_start);
format = GST_FORMAT_TIME;
start = seg_start;
stop = seg_stop;
GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
"start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT,
GST_TIME_ARGS (seg_start), GST_TIME_ARGS (seg_stop));
} else if (format != GST_FORMAT_TIME) {
/* Unknown incoming segment format. Output a default open-ended
* TIME segment */
gst_event_unref (event);
event = <API key> (update, rate, applied_rate,
GST_FORMAT_TIME, 0, GST_CLOCK_TIME_NONE, 0);
format = GST_FORMAT_TIME;
next_ts = start = 0;
stop = GST_CLOCK_TIME_NONE;
} else {
/* not considered BYTE seekable if it is talking to us in TIME,
* whatever else it might claim */
parse->priv->upstream_seekable = FALSE;
next_ts = start;
}
<API key> (&parse->segment, update, rate,
applied_rate, format, start, stop, start);
/* save the segment for later, right before we push a new buffer so that
* the caps are fixed and the next linked element can receive
* the segment. */
parse->priv->pending_events =
g_list_append (parse->priv->pending_events, event);
parse->priv->pending_segment = TRUE;
handled = TRUE;
/* but finish the current segment */
GST_DEBUG_OBJECT (parse, "draining current segment");
if (parse->segment.rate > 0.0)
<API key> (parse);
else
<API key> (parse, FALSE);
gst_adapter_clear (parse->priv->adapter);
parse->priv->offset = offset;
parse->priv->sync_offset = offset;
parse->priv->next_ts = next_ts;
parse->priv->last_ts = GST_CLOCK_TIME_NONE;
parse->priv->discont = TRUE;
parse->priv->seen_keyframe = FALSE;
break;
}
case <API key>:
parse->priv->flushing = TRUE;
handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
if (handled)
gst_event_unref (event);
/* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
GST_PAD_STREAM_LOCK (parse->srcpad);
<API key> (parse->srcpad);
break;
case <API key>:
gst_adapter_clear (parse->priv->adapter);
<API key> (parse);
parse->priv->flushing = FALSE;
parse->priv->discont = TRUE;
parse->priv->last_ts = GST_CLOCK_TIME_NONE;
parse->priv->frame._private_flags |=
<API key>;
<API key> (&parse->priv->frame);
break;
case GST_EVENT_EOS:
if (parse->segment.rate > 0.0)
<API key> (parse);
else
<API key> (parse, FALSE);
/* If we STILL have zero frames processed, fire an error */
if (parse->priv->framecount == 0) {
GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
("No valid frames found before end of stream"), (NULL));
}
/* newsegment and other serialized events before eos */
if (G_UNLIKELY (parse->priv->pending_events)) {
GList *l;
for (l = parse->priv->pending_events; l != NULL; l = l->next) {
gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
}
g_list_free (parse->priv->pending_events);
parse->priv->pending_events = NULL;
parse->priv->pending_segment = FALSE;
}
break;
default:
break;
}
return handled;
}
/* <API key>:
* @pad: #GstPad that received the event.
* @event: #GstEvent that was received.
*
* Handler for source pad events.
*
* Returns: TRUE if the event was handled.
*/
static gboolean
<API key> (GstPad * pad, GstEvent * event)
{
GstBaseParse *parse;
GstBaseParseClass *bclass;
gboolean handled = FALSE;
gboolean ret = TRUE;
parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
bclass = <API key> (parse);
GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
GST_EVENT_TYPE_NAME (event));
if (bclass->src_event)
handled = bclass->src_event (parse, event);
if (!handled)
ret = <API key> (pad, event);
gst_object_unref (parse);
return ret;
}
static gboolean
<API key> (GstBaseParse * parse)
{
/* FIXME: could do more here, e.g. check index or just send data from 0
* in pull mode and let decoder/sink clip */
return parse->priv->syncable;
}
/* <API key>:
* @parse: #GstBaseParse.
* @event: #GstEvent that was received.
*
* Default srcpad event handler.
*
* Returns: TRUE if the event was handled and can be dropped.
*/
static gboolean
<API key> (GstBaseParse * parse, GstEvent * event)
{
gboolean handled = FALSE;
switch (GST_EVENT_TYPE (event)) {
case GST_EVENT_SEEK:
{
if (<API key> (parse)) {
handled = <API key> (parse, event);
}
break;
}
default:
break;
}
return handled;
}
/**
* <API key>:
* @parse: #GstBaseParse.
* @src_format: #GstFormat describing the source format.
* @src_value: Source value to be converted.
* @dest_format: #GstFormat defining the converted format.
* @dest_value: Pointer where the conversion result will be put.
*
* Default implementation of "convert" vmethod in #GstBaseParse class.
*
* Returns: TRUE if conversion was successful.
*
* Since: 0.10.33
*/
gboolean
<API key> (GstBaseParse * parse,
GstFormat src_format,
gint64 src_value, GstFormat dest_format, gint64 * dest_value)
{
gboolean ret = FALSE;
guint64 bytes, duration;
if (G_UNLIKELY (src_format == dest_format)) {
*dest_value = src_value;
return TRUE;
}
if (G_UNLIKELY (src_value == -1)) {
*dest_value = -1;
return TRUE;
}
if (G_UNLIKELY (src_value == 0)) {
*dest_value = 0;
return TRUE;
}
/* need at least some frames */
if (!parse->priv->framecount)
return FALSE;
duration = parse->priv->acc_duration / GST_MSECOND;
bytes = parse->priv->bytecount;
if (G_UNLIKELY (!duration || !bytes))
return FALSE;
if (src_format == GST_FORMAT_BYTES) {
if (dest_format == GST_FORMAT_TIME) {
/* BYTES -> TIME conversion */
GST_DEBUG_OBJECT (parse, "converting bytes -> time");
*dest_value = <API key> (src_value, duration, bytes);
*dest_value *= GST_MSECOND;
GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
*dest_value / GST_MSECOND);
ret = TRUE;
}
} else if (src_format == GST_FORMAT_TIME) {
if (dest_format == GST_FORMAT_BYTES) {
GST_DEBUG_OBJECT (parse, "converting time -> bytes");
*dest_value = <API key> (src_value / GST_MSECOND, bytes,
duration);
GST_DEBUG_OBJECT (parse,
"time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
src_value / GST_MSECOND, *dest_value);
ret = TRUE;
}
} else if (src_format == GST_FORMAT_DEFAULT) {
/* DEFAULT == frame-based */
if (dest_format == GST_FORMAT_TIME) {
if (parse->priv->fps_den) {
*dest_value = <API key> (src_value,
GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
ret = TRUE;
}
} else if (dest_format == GST_FORMAT_BYTES) {
}
}
return ret;
}
static void
<API key> (GstBaseParse * baseparse)
{
GstPad *peer;
GstBaseParse *parse;
parse = GST_BASE_PARSE (baseparse);
peer = gst_pad_get_peer (parse->sinkpad);
if (peer) {
GstFormat pformat = GST_FORMAT_BYTES;
gboolean qres = FALSE;
gint64 ptot, dest_value;
qres = <API key> (peer, &pformat, &ptot);
gst_object_unref (GST_OBJECT (peer));
if (qres) {
if (<API key> (parse, pformat, ptot,
GST_FORMAT_TIME, &dest_value)) {
/* inform if duration changed, but try to avoid spamming */
parse->priv->estimated_drift +=
dest_value - parse->priv->estimated_duration;
if (parse->priv->estimated_drift > GST_SECOND ||
parse->priv->estimated_drift < -GST_SECOND) {
<API key> (GST_ELEMENT (parse),
<API key> (GST_OBJECT (parse),
GST_FORMAT_TIME, dest_value));
parse->priv->estimated_drift = 0;
}
parse->priv->estimated_duration = dest_value;
GST_LOG_OBJECT (parse,
"updated estimated duration to %" GST_TIME_FORMAT,
GST_TIME_ARGS (dest_value));
}
}
}
}
static void
<API key> (GstBaseParse * parse, gboolean post_min,
gboolean post_avg, gboolean post_max)
{
GstTagList *taglist = NULL;
if (post_min && parse->priv->post_min_bitrate) {
taglist = gst_tag_list_new ();
gst_tag_list_add (taglist, <API key>,
<API key>, parse->priv->min_bitrate, NULL);
}
if (post_avg && parse->priv->post_avg_bitrate) {
if (taglist == NULL)
taglist = gst_tag_list_new ();
parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
gst_tag_list_add (taglist, <API key>, GST_TAG_BITRATE,
parse->priv->avg_bitrate, NULL);
}
if (post_max && parse->priv->post_max_bitrate) {
if (taglist == NULL)
taglist = gst_tag_list_new ();
gst_tag_list_add (taglist, <API key>,
<API key>, parse->priv->max_bitrate, NULL);
}
GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
parse->priv->min_bitrate, parse->priv->avg_bitrate,
parse->priv->max_bitrate);
if (taglist != NULL) {
<API key> (GST_ELEMENT_CAST (parse), parse->srcpad,
taglist);
}
}
/* <API key>:
* @parse: #GstBaseParse.
* @buffer: Current frame as a #GstBuffer
*
* Keeps track of the minimum and maximum bitrates, and also maintains a
* running average bitrate of the stream so far.
*/
static void
<API key> (GstBaseParse * parse, GstBaseParseFrame * frame)
{
/* Only update the tag on a 10 kbps delta */
static const gint update_threshold = 10000;
guint64 data_len, frame_dur;
gint overhead, frame_bitrate, old_avg_bitrate;
gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
GstBuffer *buffer = frame->buffer;
overhead = frame->overhead;
if (overhead == -1)
return;
data_len = GST_BUFFER_SIZE (buffer) - overhead;
parse->priv->data_bytecount += data_len;
/* duration should be valid by now,
* either set by subclass or maybe based on fps settings */
if (<API key> (buffer) && parse->priv->acc_duration != 0) {
/* Calculate duration of a frame from buffer properties */
frame_dur = GST_BUFFER_DURATION (buffer);
parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
parse->priv->acc_duration;
} else {
/* No way to figure out frame duration (is this even possible?) */
return;
}
/* override if subclass provided bitrate, e.g. metadata based */
if (parse->priv->bitrate) {
parse->priv->avg_bitrate = parse->priv->bitrate;
/* spread this (confirmed) info ASAP */
if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
<API key> (parse, FALSE, TRUE, FALSE);
}
if (frame_dur)
frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
else
return;
GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
parse->priv->avg_bitrate);
if (parse->priv->framecount < <API key>) {
goto exit;
} else if (parse->priv->framecount == <API key>) {
/* always post all at threshold time */
update_min = update_max = update_avg = TRUE;
}
if (G_LIKELY (parse->priv->framecount >= <API key>)) {
if (frame_bitrate < parse->priv->min_bitrate) {
parse->priv->min_bitrate = frame_bitrate;
update_min = TRUE;
}
if (frame_bitrate > parse->priv->max_bitrate) {
parse->priv->max_bitrate = frame_bitrate;
update_max = TRUE;
}
old_avg_bitrate = parse->priv->posted_avg_bitrate;
if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
|| (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
update_threshold)
update_avg = TRUE;
}
if ((update_min || update_avg || update_max))
<API key> (parse, update_min, update_avg, update_max);
exit:
return;
}
/**
* <API key>:
* @parse: #GstBaseParse.
* @offset: offset of entry
* @ts: timestamp associated with offset
* @key: whether entry refers to keyframe
* @force: add entry disregarding sanity checks
*
* Adds an entry to the index associating @offset to @ts. It is recommended
* to only add keyframe entries. @force allows to bypass checks, such as
* whether the stream is (upstream) seekable, another entry is already "close"
* to the new entry, etc.
*
* Returns: #gboolean indicating whether entry was added
*
* Since: 0.10.33
*/
gboolean
<API key> (GstBaseParse * parse, guint64 offset,
GstClockTime ts, gboolean key, gboolean force)
{
gboolean ret = FALSE;
GstIndexAssociation associations[2];
GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
" @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
if (G_LIKELY (!force)) {
if (!parse->priv->upstream_seekable) {
GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
goto exit;
}
/* FIXME need better helper data structure that handles these issues
* related to ongoing collecting of index entries */
if (parse->priv->index_last_offset >= (gint64) offset) {
GST_DEBUG_OBJECT (parse, "already have entries up to offset "
"0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
goto exit;
}
if (<API key> (parse->priv->index_last_ts) &&
GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
parse->priv->idx_interval) {
GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
GST_TIME_ARGS (parse->priv->index_last_ts));
goto exit;
}
/* if last is not really the last one */
if (!parse->priv->index_last_valid) {
GstClockTime prev_ts;
<API key> (parse, ts, TRUE, &prev_ts);
if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
GST_DEBUG_OBJECT (parse,
"entry too close to existing entry %" GST_TIME_FORMAT,
GST_TIME_ARGS (prev_ts));
parse->priv->index_last_offset = offset;
parse->priv->index_last_ts = ts;
goto exit;
}
}
}
associations[0].format = GST_FORMAT_TIME;
associations[0].value = ts;
associations[1].format = GST_FORMAT_BYTES;
associations[1].value = offset;
/* index might change on-the-fly, although that would be nutty app ... */
<API key> (parse);
<API key> (parse->priv->index, parse->priv->index_id,
(key) ? <API key> : <API key>,
2, (const GstIndexAssociation *) &associations);
<API key> (parse);
if (key) {
parse->priv->index_last_offset = offset;
parse->priv->index_last_ts = ts;
}
ret = TRUE;
exit:
return ret;
}
/* check for seekable upstream, above and beyond a mere query */
static void
<API key> (GstBaseParse * parse)
{
GstQuery *query;
gboolean seekable = FALSE;
gint64 start = -1, stop = -1;
guint idx_interval = 0;
query = <API key> (GST_FORMAT_BYTES);
if (!gst_pad_peer_query (parse->sinkpad, query)) {
GST_DEBUG_OBJECT (parse, "seeking query failed");
goto done;
}
<API key> (query, NULL, &seekable, &start, &stop);
/* try harder to query upstream size if we didn't get it the first time */
if (seekable && stop == -1) {
GstFormat fmt = GST_FORMAT_BYTES;
GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
<API key> (parse->sinkpad, &fmt, &stop);
}
/* if upstream doesn't know the size, it's likely that it's not seekable in
* practice even if it technically may be seekable */
if (seekable && (start != 0 || stop <= start)) {
GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
seekable = FALSE;
}
/* let's not put every single frame into our index */
if (seekable) {
if (stop < 10 * 1024 * 1024)
idx_interval = 100;
else if (stop < 100 * 1024 * 1024)
idx_interval = 500;
else
idx_interval = 1000;
}
done:
gst_query_unref (query);
GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
G_GUINT64_FORMAT ")", seekable, start, stop);
parse->priv->upstream_seekable = seekable;
parse->priv->upstream_size = seekable ? stop : 0;
GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
parse->priv->idx_interval = idx_interval * GST_MSECOND;
}
/* some misc checks on upstream */
static void
<API key> (GstBaseParse * parse)
{
GstFormat fmt = GST_FORMAT_TIME;
gint64 stop;
if (<API key> (parse->sinkpad, &fmt, &stop))
if (<API key> (stop) && stop) {
/* upstream has one, accept it also, and no further updates */
<API key> (parse, GST_FORMAT_TIME, stop, 0);
parse->priv-><API key> = TRUE;
}
GST_DEBUG_OBJECT (parse, "<API key>: %d",
parse->priv-><API key>);
}
/* checks src caps to determine if dealing with audio or video */
/* TODO maybe forego automagic stuff and let subclass configure it ? */
static void
<API key> (GstBaseParse * parse)
{
GstCaps *caps;
GstStructure *s;
caps = GST_PAD_CAPS (parse->srcpad);
if (G_LIKELY (caps) && (s = <API key> (caps, 0))) {
parse->priv->is_video =
g_str_has_prefix (<API key> (s), "video");
} else {
/* historical default */
parse->priv->is_video = FALSE;
}
GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
}
/* takes ownership of frame */
static void
<API key> (GstBaseParse * parse, GstBaseParseFrame * frame)
{
if (!(frame->_private_flags & <API key>)) {
/* frame allocated on the heap, we can just take ownership */
g_queue_push_tail (&parse->priv->queued_frames, frame);
GST_TRACE ("queued frame %p", frame);
} else {
GstBaseParseFrame *copy;
/* probably allocated on the stack, must make a proper copy */
copy = <API key> (frame);
g_queue_push_tail (&parse->priv->queued_frames, copy);
GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
<API key> (frame);
}
}
/* <API key>:
* @parse: #GstBaseParse.
* @klass: #GstBaseParseClass.
* @frame: (transfer full): a #GstBaseParseFrame
*
* Parses the frame from given buffer and pushes it forward. Also performs
* timestamp handling and checks the segment limits.
*
* This is called with srcpad STREAM_LOCK held.
*
* Returns: #GstFlowReturn
*/
static GstFlowReturn
<API key> (GstBaseParse * parse,
GstBaseParseClass * klass, GstBaseParseFrame * frame)
{
GstFlowReturn ret;
gint64 offset;
GstBuffer *buffer;
<API key> (frame != NULL, GST_FLOW_ERROR);
buffer = frame->buffer;
if (parse->priv->discont) {
GST_DEBUG_OBJECT (parse, "marking DISCONT");
GST_BUFFER_FLAG_SET (buffer, <API key>);
parse->priv->discont = FALSE;
}
/* some one-time start-up */
if (G_UNLIKELY (!parse->priv->framecount)) {
<API key> (parse);
<API key> (parse);
}
GST_LOG_OBJECT (parse,
"parsing frame at offset %" G_GUINT64_FORMAT
" (%#" G_GINT64_MODIFIER "x) of size %d",
GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
GST_BUFFER_SIZE (buffer));
/* use default handler to provide initial (upstream) metadata */
<API key> (parse, frame);
/* store offset as it might get overwritten */
offset = GST_BUFFER_OFFSET (buffer);
ret = klass->parse_frame (parse, frame);
/* sync */
buffer = frame->buffer;
/* subclass must play nice */
<API key> (buffer != NULL, GST_FLOW_ERROR);
/* check if subclass/format can provide ts.
* If so, that allows and enables extra seek and duration determining options */
if (G_UNLIKELY (parse->priv->first_frame_offset < 0 && ret == GST_FLOW_OK)) {
if (<API key> (buffer) && parse->priv->has_timing_info
&& parse->priv->pad_mode == GST_ACTIVATE_PULL) {
parse->priv->first_frame_offset = offset;
parse->priv->first_frame_ts = <API key> (buffer);
GST_DEBUG_OBJECT (parse, "subclass provided ts %" GST_TIME_FORMAT
" for first frame at offset %" G_GINT64_FORMAT,
GST_TIME_ARGS (parse->priv->first_frame_ts),
parse->priv->first_frame_offset);
if (!<API key> (parse->priv->duration)) {
gint64 off;
GstClockTime last_ts = G_MAXINT64;
GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
<API key> (parse, &last_ts, &off);
if (<API key> (last_ts))
<API key> (parse, GST_FORMAT_TIME, last_ts, 0);
}
} else {
/* disable further checks */
parse->priv->first_frame_offset = 0;
}
}
/* again use default handler to add missing metadata;
* we may have new information on frame properties */
<API key> (parse, frame);
if (<API key> (buffer) &&
<API key> (buffer)) {
parse->priv->next_ts =
<API key> (buffer) + GST_BUFFER_DURATION (buffer);
} else {
/* we lost track, do not produce bogus time next time around
* (probably means parser subclass has given up on parsing as well) */
GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
parse->priv->next_ts = GST_CLOCK_TIME_NONE;
}
if (parse->priv->upstream_seekable && parse->priv->exact_position &&
<API key> (buffer))
<API key> (parse, offset,
<API key> (buffer),
!<API key> (buffer, <API key>), FALSE);
/* First buffers are dropped, this means that the subclass needs more
* frames to decide on the format and queues them internally */
/* convert internal flow to OK and mark discont for the next buffer. */
if (ret == <API key>) {
<API key> (frame);
return GST_FLOW_OK;
} else if (ret == <API key>) {
<API key> (parse, frame);
return GST_FLOW_OK;
} else if (ret != GST_FLOW_OK) {
return ret;
}
/* All OK, push queued frames if there are any */
if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
GstBaseParseFrame *queued_frame;
while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
queued_frame->buffer =
<API key> (queued_frame->buffer);
gst_buffer_set_caps (queued_frame->buffer,
GST_PAD_CAPS (<API key> (parse)));
<API key> (parse, queued_frame);
}
}
return <API key> (parse, frame);
}
/**
* <API key>:
* @parse: #GstBaseParse.
* @frame: (transfer full): a #GstBaseParseFrame
*
* Pushes the frame downstream, sends any pending events and
* does some timestamp and segment handling. Takes ownership
* of @frame and will clear it (if it was initialised with
* <API key>()) or free it.
*
* This must be called with sinkpad STREAM_LOCK held.
*
* Returns: #GstFlowReturn
*
* Since: 0.10.33
*/
GstFlowReturn
<API key> (GstBaseParse * parse, GstBaseParseFrame * frame)
{
GstFlowReturn ret = GST_FLOW_OK;
GstClockTime last_start = GST_CLOCK_TIME_NONE;
GstClockTime last_stop = GST_CLOCK_TIME_NONE;
GstBaseParseClass *klass = <API key> (parse);
GstBuffer *buffer;
<API key> (frame != NULL, GST_FLOW_ERROR);
<API key> (frame->buffer != NULL, GST_FLOW_ERROR);
GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
buffer = frame->buffer;
GST_LOG_OBJECT (parse,
"processing buffer of size %d with ts %" GST_TIME_FORMAT
", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
GST_TIME_ARGS (<API key> (buffer)),
GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
/* update stats */
parse->priv->bytecount += GST_BUFFER_SIZE (buffer);
if (G_LIKELY (!(frame->flags & <API key>))) {
parse->priv->framecount++;
if (<API key> (buffer)) {
parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
}
}
/* 0 means disabled */
if (parse->priv->update_interval < 0)
parse->priv->update_interval = 50;
else if (parse->priv->update_interval > 0 &&
(parse->priv->framecount % parse->priv->update_interval) == 0)
<API key> (parse);
if (<API key> (buffer))
last_start = last_stop = <API key> (buffer);
if (last_start != GST_CLOCK_TIME_NONE
&& <API key> (buffer))
last_stop = last_start + GST_BUFFER_DURATION (buffer);
/* should have caps by now */
<API key> (GST_PAD_CAPS (parse->srcpad), GST_FLOW_ERROR);
if (G_UNLIKELY (parse->priv->pending_segment)) {
/* have caps; check identity */
<API key> (parse);
}
/* and should then also be linked downstream, so safe to send some events */
if (G_UNLIKELY (parse->priv->close_segment)) {
/* only set up by loop */
GST_DEBUG_OBJECT (parse, "loop sending close segment");
gst_pad_push_event (parse->srcpad, parse->priv->close_segment);
parse->priv->close_segment = NULL;
}
/* Push pending events, including NEWSEGMENT events */
if (G_UNLIKELY (parse->priv->pending_events)) {
GList *l;
for (l = parse->priv->pending_events; l != NULL; l = l->next) {
gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
}
g_list_free (parse->priv->pending_events);
parse->priv->pending_events = NULL;
parse->priv->pending_segment = FALSE;
}
/* segment adjustment magic; only if we are running the whole show */
if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
(parse->priv->pad_mode == GST_ACTIVATE_PULL ||
parse->priv->upstream_seekable)) {
/* handle gaps */
if (<API key> (parse->segment.last_stop) &&
<API key> (last_start)) {
GstClockTimeDiff diff;
/* only send newsegments with increasing start times,
* otherwise if these go back and forth downstream (sinks) increase
* accumulated time and running_time */
diff = GST_CLOCK_DIFF (parse->segment.last_stop, last_start);
if (G_UNLIKELY (diff > 2 * GST_SECOND
&& last_start > parse->segment.start
&& (!<API key> (parse->segment.stop)
|| last_start < parse->segment.stop))) {
GST_DEBUG_OBJECT (parse,
"Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
"Sending updated NEWSEGMENT events", diff,
GST_TIME_ARGS (parse->segment.last_stop),
GST_TIME_ARGS (last_start));
/* send newsegment events such that the gap is not accounted in
* accum time, hence running_time */
/* close ahead of gap */
gst_pad_push_event (parse->srcpad,
<API key> (TRUE, parse->segment.rate,
parse->segment.format, parse->segment.last_stop,
parse->segment.last_stop, parse->segment.last_stop));
/* skip gap */
gst_pad_push_event (parse->srcpad,
<API key> (FALSE, parse->segment.rate,
parse->segment.format, last_start,
parse->segment.stop, last_start));
/* align segment view with downstream,
* prevents double-counting accum when closing segment */
<API key> (&parse->segment, FALSE,
parse->segment.rate, parse->segment.format, last_start,
parse->segment.stop, last_start);
parse->segment.last_stop = last_start;
}
}
}
/* update bitrates and optionally post corresponding tags
* (following newsegment) */
<API key> (parse, frame);
if (klass->pre_push_frame) {
ret = klass->pre_push_frame (parse, frame);
} else {
frame->flags |= <API key>;
}
/* take final ownership of frame buffer */
buffer = frame->buffer;
frame->buffer = NULL;
/* subclass must play nice */
<API key> (buffer != NULL, GST_FLOW_ERROR);
/* decorate */
buffer = <API key> (buffer);
gst_buffer_set_caps (buffer, GST_PAD_CAPS (parse->srcpad));
parse->priv->seen_keyframe |= parse->priv->is_video &&
!<API key> (buffer, <API key>);
if (frame->flags & <API key>) {
if (<API key> (buffer) &&
<API key> (parse->segment.stop) &&
<API key> (buffer) >
parse->segment.stop + parse->priv->lead_out_ts) {
GST_LOG_OBJECT (parse, "Dropped frame, after segment");
ret = GST_FLOW_UNEXPECTED;
} else if (<API key> (buffer) &&
<API key> (buffer) &&
<API key> (parse->segment.start) &&
<API key> (buffer) + GST_BUFFER_DURATION (buffer) +
parse->priv->lead_in_ts < parse->segment.start) {
if (parse->priv->seen_keyframe) {
GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
ret = GST_FLOW_OK;
} else {
GST_LOG_OBJECT (parse, "Dropped frame, before segment");
ret = <API key>;
}
} else {
ret = GST_FLOW_OK;
}
}
if (ret == <API key>) {
GST_LOG_OBJECT (parse, "frame (%d bytes) dropped",
GST_BUFFER_SIZE (buffer));
gst_buffer_unref (buffer);
ret = GST_FLOW_OK;
} else if (ret == GST_FLOW_OK) {
if (parse->segment.rate > 0.0) {
GST_LOG_OBJECT (parse, "pushing frame (%d bytes) now..",
GST_BUFFER_SIZE (buffer));
ret = gst_pad_push (parse->srcpad, buffer);
GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
} else {
GST_LOG_OBJECT (parse, "frame (%d bytes) queued for now",
GST_BUFFER_SIZE (buffer));
parse->priv->buffers_queued =
g_slist_prepend (parse->priv->buffers_queued, buffer);
ret = GST_FLOW_OK;
}
} else {
GST_LOG_OBJECT (parse, "frame (%d bytes) not pushed: %s",
GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
gst_buffer_unref (buffer);
/* if we are not sufficiently in control, let upstream decide on EOS */
if (ret == GST_FLOW_UNEXPECTED &&
(parse->priv->passthrough ||
(parse->priv->pad_mode == GST_ACTIVATE_PUSH &&
!parse->priv->upstream_seekable)))
ret = GST_FLOW_OK;
}
/* Update current running segment position */
if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
parse->segment.last_stop < last_stop)
<API key> (&parse->segment, GST_FORMAT_TIME, last_stop);
<API key> (frame);
return ret;
}
/* <API key>:
*
* Drains the adapter until it is empty. It decreases the min_frame_size to
* match the current adapter size and calls chain method until the adapter
* is emptied or chain returns with error.
*/
static void
<API key> (GstBaseParse * parse)
{
guint avail;
GST_DEBUG_OBJECT (parse, "draining");
parse->priv->drain = TRUE;
for (;;) {
avail = <API key> (parse->priv->adapter);
if (!avail)
break;
if (<API key> (parse->sinkpad, NULL) != GST_FLOW_OK) {
break;
}
/* nothing changed, maybe due to truncated frame; break infinite loop */
if (avail == <API key> (parse->priv->adapter)) {
GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
gst_adapter_clear (parse->priv->adapter);
}
}
parse->priv->drain = FALSE;
}
/* <API key>
*
* Sends buffers collected in send_buffers downstream, and ensures that list
* is empty at the end (errors or not).
*/
static GstFlowReturn
<API key> (GstBaseParse * parse)
{
GSList *send = NULL;
GstBuffer *buf;
GstFlowReturn ret = GST_FLOW_OK;
send = parse->priv->buffers_send;
/* send buffers */
while (send) {
buf = GST_BUFFER_CAST (send->data);
GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
", offset %" G_GINT64_FORMAT, buf,
GST_TIME_ARGS (<API key> (buf)),
GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
/* iterate output queue an push downstream */
ret = gst_pad_push (parse->srcpad, buf);
send = g_slist_delete_link (send, send);
/* clear any leftover if error */
if (G_UNLIKELY (ret != GST_FLOW_OK)) {
while (send) {
buf = GST_BUFFER_CAST (send->data);
gst_buffer_unref (buf);
send = g_slist_delete_link (send, send);
}
}
}
parse->priv->buffers_send = send;
return ret;
}
/* <API key>:
*
* Processes a reverse playback (forward) fragment:
* - append head of last fragment that was skipped to current fragment data
* - drain the resulting current fragment data (i.e. repeated chain)
* - add time/duration (if needed) to frames queued by chain
* - push queued data
*/
static GstFlowReturn
<API key> (GstBaseParse * parse, gboolean push_only)
{
GstBuffer *buf;
GstFlowReturn ret = GST_FLOW_OK;
gboolean seen_key = FALSE, seen_delta = FALSE;
if (push_only)
goto push;
/* restore order */
parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
while (parse->priv->buffers_pending) {
buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
GST_LOG_OBJECT (parse, "adding pending buffer (size %d)",
GST_BUFFER_SIZE (buf));
gst_adapter_push (parse->priv->adapter, buf);
parse->priv->buffers_pending =
g_slist_delete_link (parse->priv->buffers_pending,
parse->priv->buffers_pending);
}
/* invalidate so no fall-back timestamping is performed;
* ok if taken from subclass or upstream */
parse->priv->next_ts = GST_CLOCK_TIME_NONE;
/* prevent it hanging around stop all the time */
parse->segment.last_stop = GST_CLOCK_TIME_NONE;
/* mark next run */
parse->priv->discont = TRUE;
/* chain looks for frames and queues resulting ones (in stead of pushing) */
/* initial skipped data is added to buffers_pending */
<API key> (parse);
push:
if (parse->priv->buffers_send) {
buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
seen_key |= !<API key> (buf, <API key>);
}
/* add metadata (if needed to queued buffers */
GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
GST_TIME_ARGS (parse->priv->last_ts));
while (parse->priv->buffers_queued) {
buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
/* no touching if upstream or parsing provided time */
if (<API key> (buf)) {
GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
GST_TIME_ARGS (<API key> (buf)));
} else if (<API key> (parse->priv->last_ts) &&
<API key> (buf)) {
if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
else
parse->priv->last_ts = 0;
<API key> (buf) = parse->priv->last_ts;
GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
GST_TIME_ARGS (<API key> (buf)));
} else {
/* no idea, very bad */
GST_WARNING_OBJECT (parse, "could not determine time for buffer");
}
parse->priv->last_ts = <API key> (buf);
/* reverse order for ascending sending */
/* send downstream at keyframe not preceded by a keyframe
* (e.g. that should identify start of collection of IDR nals) */
if (<API key> (buf, <API key>)) {
if (seen_key) {
ret = <API key> (parse);
/* if a problem, throw all to sending */
if (ret != GST_FLOW_OK) {
parse->priv->buffers_send =
g_slist_reverse (parse->priv->buffers_queued);
parse->priv->buffers_queued = NULL;
break;
}
seen_key = FALSE;
}
seen_delta = TRUE;
} else {
seen_key = TRUE;
}
parse->priv->buffers_send =
g_slist_prepend (parse->priv->buffers_send, buf);
parse->priv->buffers_queued =
g_slist_delete_link (parse->priv->buffers_queued,
parse->priv->buffers_queued);
}
/* audio may have all marked as keyframe, so arrange to send here */
if (!seen_delta)
ret = <API key> (parse);
/* any trailing unused no longer usable (ideally none) */
if (G_UNLIKELY (<API key> (parse->priv->adapter))) {
GST_DEBUG_OBJECT (parse, "discarding %d trailing bytes",
<API key> (parse->priv->adapter));
gst_adapter_clear (parse->priv->adapter);
}
return ret;
}
/* small helper that checks whether we have been trying to resync too long */
static inline GstFlowReturn
<API key> (GstBaseParse * parse)
{
if (G_UNLIKELY (parse->priv->discont &&
parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
GST_ELEMENT_ERROR (parse, STREAM, DECODE,
("Failed to parse stream"), (NULL));
return GST_FLOW_ERROR;
}
return GST_FLOW_OK;
}
static GstFlowReturn
<API key> (GstPad * pad, GstBuffer * buffer)
{
GstBaseParseClass *bclass;
GstBaseParse *parse;
GstFlowReturn ret = GST_FLOW_OK;
GstBuffer *outbuf = NULL;
GstBuffer *tmpbuf = NULL;
guint fsize = 1;
gint skip = -1;
const guint8 *data;
guint old_min_size = 0, min_size, av;
GstClockTime timestamp;
GstBaseParseFrame *frame;
parse = GST_BASE_PARSE (GST_OBJECT_PARENT (pad));
bclass = <API key> (parse);
if (parse->priv->detecting) {
GstBuffer *detect_buf;
if (parse->priv->detect_buffers_size == 0) {
detect_buf = gst_buffer_ref (buffer);
} else {
GList *l;
guint offset = 0;
detect_buf =
<API key> (parse->priv->detect_buffers_size +
(buffer ? GST_BUFFER_SIZE (buffer) : 0));
for (l = parse->priv->detect_buffers; l; l = l->next) {
memcpy (GST_BUFFER_DATA (detect_buf) + offset,
GST_BUFFER_DATA (l->data), GST_BUFFER_SIZE (l->data));
offset += GST_BUFFER_SIZE (l->data);
}
if (buffer)
memcpy (GST_BUFFER_DATA (detect_buf) + offset, GST_BUFFER_DATA (buffer),
GST_BUFFER_SIZE (buffer));
}
ret = bclass->detect (parse, detect_buf);
gst_buffer_unref (detect_buf);
if (ret == GST_FLOW_OK) {
GList *l;
/* Detected something */
parse->priv->detecting = FALSE;
for (l = parse->priv->detect_buffers; l; l = l->next) {
if (ret == GST_FLOW_OK && !parse->priv->flushing)
ret =
<API key> (<API key> (parse),
GST_BUFFER_CAST (l->data));
else
gst_buffer_unref (GST_BUFFER_CAST (l->data));
}
g_list_free (parse->priv->detect_buffers);
parse->priv->detect_buffers = NULL;
parse->priv->detect_buffers_size = 0;
if (ret != GST_FLOW_OK) {
return ret;
}
/* Handle the current buffer */
} else if (ret == <API key>) {
/* Still detecting, append buffer or error out if draining */
if (parse->priv->drain) {
GST_DEBUG_OBJECT (parse, "Draining but did not detect format yet");
return GST_FLOW_ERROR;
} else if (parse->priv->flushing) {
g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref,
NULL);
g_list_free (parse->priv->detect_buffers);
parse->priv->detect_buffers = NULL;
parse->priv->detect_buffers_size = 0;
} else {
parse->priv->detect_buffers =
g_list_append (parse->priv->detect_buffers, buffer);
parse->priv->detect_buffers_size += GST_BUFFER_SIZE (buffer);
return GST_FLOW_OK;
}
} else {
/* Something went wrong, subclass responsible for error reporting */
return ret;
}
/* And now handle the current buffer if detection worked */
}
frame = &parse->priv->frame;
if (G_LIKELY (buffer)) {
GST_LOG_OBJECT (parse, "buffer size: %d, offset = %" G_GINT64_FORMAT,
GST_BUFFER_SIZE (buffer), GST_BUFFER_OFFSET (buffer));
if (G_UNLIKELY (parse->priv->passthrough)) {
<API key> (frame);
frame->buffer = <API key> (buffer);
return <API key> (parse, frame);
}
/* upstream feeding us in reverse playback;
* gather each fragment, then process it in single run */
if (parse->segment.rate < 0.0) {
if (G_UNLIKELY (<API key> (buffer, <API key>))) {
GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
ret = <API key> (parse, FALSE);
}
gst_adapter_push (parse->priv->adapter, buffer);
return ret;
}
gst_adapter_push (parse->priv->adapter, buffer);
}
if (G_UNLIKELY (buffer &&
<API key> (buffer, <API key>))) {
frame->_private_flags |= <API key>;
<API key> (frame);
}
/* Parse and push as many frames as possible */
/* Stop either when adapter is empty or we are flushing */
while (!parse->priv->flushing) {
gboolean res;
/* maintain frame state for a single frame parsing round across _chain calls,
* so only init when needed */
if (!frame->_private_flags)
<API key> (frame);
tmpbuf = gst_buffer_new ();
old_min_size = 0;
/* Synchronization loop */
for (;;) {
/* note: if subclass indicates MAX fsize,
* this will not likely be available anyway ... */
min_size = MAX (parse->priv->min_frame_size, fsize);
av = <API key> (parse->priv->adapter);
/* loop safety check */
if (G_UNLIKELY (old_min_size >= min_size))
goto invalid_min;
old_min_size = min_size;
if (G_UNLIKELY (parse->priv->drain)) {
min_size = av;
GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
if (G_UNLIKELY (!min_size)) {
gst_buffer_unref (tmpbuf);
goto done;
}
}
/* Collect at least min_frame_size bytes */
if (av < min_size) {
GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
av);
gst_buffer_unref (tmpbuf);
goto done;
}
/* always pass all available data */
data = gst_adapter_peek (parse->priv->adapter, av);
GST_BUFFER_DATA (tmpbuf) = (guint8 *) data;
GST_BUFFER_SIZE (tmpbuf) = av;
GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
GST_BUFFER_FLAG_SET (tmpbuf, <API key>);
if (parse->priv->discont) {
GST_DEBUG_OBJECT (parse, "marking DISCONT");
GST_BUFFER_FLAG_SET (tmpbuf, <API key>);
}
skip = -1;
<API key> (parse, frame, tmpbuf);
res = bclass->check_valid_frame (parse, frame, &fsize, &skip);
gst_buffer_replace (&frame->buffer, NULL);
if (res) {
if (<API key> (parse->priv->adapter) < fsize) {
GST_DEBUG_OBJECT (parse,
"found valid frame but not enough data available (only %d bytes)",
<API key> (parse->priv->adapter));
gst_buffer_unref (tmpbuf);
goto done;
}
GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
break;
}
if (skip == -1) {
/* subclass didn't touch this value. By default we skip 1 byte */
skip = 1;
}
if (skip > 0) {
GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
/* reverse playback, and no frames found yet, so we are skipping
* the leading part of a fragment, which may form the tail of
* fragment coming later, hopefully subclass skips efficiently ... */
timestamp = <API key> (parse->priv->adapter, NULL);
outbuf = <API key> (parse->priv->adapter, skip);
outbuf = <API key> (outbuf);
<API key> (outbuf) = timestamp;
parse->priv->buffers_pending =
g_slist_prepend (parse->priv->buffers_pending, outbuf);
outbuf = NULL;
} else {
gst_adapter_flush (parse->priv->adapter, skip);
}
parse->priv->offset += skip;
if (!parse->priv->discont)
parse->priv->sync_offset = parse->priv->offset;
parse->priv->discont = TRUE;
/* something changed least; nullify loop check */
old_min_size = 0;
}
/* skip == 0 should imply subclass set min_size to need more data;
* we check this shortly */
if ((ret = <API key> (parse)) != GST_FLOW_OK) {
gst_buffer_unref (tmpbuf);
goto done;
}
}
gst_buffer_unref (tmpbuf);
tmpbuf = NULL;
if (skip > 0) {
/* Subclass found the sync, but still wants to skip some data */
GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
gst_adapter_flush (parse->priv->adapter, skip);
parse->priv->offset += skip;
}
/* Grab lock to prevent a race with FLUSH_START handler */
GST_PAD_STREAM_LOCK (parse->srcpad);
/* FLUSH_START event causes the "flushing" flag to be set. In this
* case we can leave the frame pushing loop */
if (parse->priv->flushing) {
<API key> (parse->srcpad);
break;
}
/* move along with upstream timestamp (if any),
* but interpolate in between */
timestamp = <API key> (parse->priv->adapter, NULL);
if (<API key> (timestamp) &&
(parse->priv->prev_ts != timestamp)) {
parse->priv->prev_ts = parse->priv->next_ts = timestamp;
}
/* FIXME: Would it be more efficient to make a subbuffer instead? */
outbuf = <API key> (parse->priv->adapter, fsize);
outbuf = <API key> (outbuf);
/* Subclass may want to know the data offset */
GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
parse->priv->offset += fsize;
<API key> (outbuf) = GST_CLOCK_TIME_NONE;
GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
frame->buffer = outbuf;
ret = <API key> (parse, bclass, frame);
<API key> (parse->srcpad);
if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED) {
GST_LOG_OBJECT (parse, "push returned %d", ret);
break;
}
}
done:
GST_LOG_OBJECT (parse, "chain leaving");
return ret;
/* ERRORS */
invalid_min:
{
GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
("min_size evolution %d -> %d; breaking to avoid looping",
old_min_size, min_size));
return GST_FLOW_ERROR;
}
}
/* pull @size bytes at current offset,
* i.e. at least try to and possibly return a shorter buffer if near the end */
static GstFlowReturn
<API key> (GstBaseParse * parse, guint size,
GstBuffer ** buffer)
{
GstFlowReturn ret = GST_FLOW_OK;
<API key> (buffer != NULL, GST_FLOW_ERROR);
/* Caching here actually makes much less difference than one would expect.
* We do it mainly to avoid pulling buffers of 1 byte all the time */
if (parse->priv->cache) {
gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
gint cache_size = GST_BUFFER_SIZE (parse->priv->cache);
if (cache_offset <= parse->priv->offset &&
(parse->priv->offset + size) <= (cache_offset + cache_size)) {
*buffer = <API key> (parse->priv->cache,
parse->priv->offset - cache_offset, size);
GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
return GST_FLOW_OK;
}
/* not enough data in the cache, free cache and get a new one */
gst_buffer_unref (parse->priv->cache);
parse->priv->cache = NULL;
}
/* refill the cache */
ret =
gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
64 * 1024), &parse->priv->cache);
if (ret != GST_FLOW_OK) {
parse->priv->cache = NULL;
return ret;
}
if (GST_BUFFER_SIZE (parse->priv->cache) >= size) {
*buffer = <API key> (parse->priv->cache, 0, size);
GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
return GST_FLOW_OK;
}
/* Not possible to get enough data, try a last time with
* requesting exactly the size we need */
gst_buffer_unref (parse->priv->cache);
parse->priv->cache = NULL;
ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
&parse->priv->cache);
if (ret != GST_FLOW_OK) {
GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
*buffer = NULL;
return ret;
}
if (GST_BUFFER_SIZE (parse->priv->cache) < size) {
GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
G_GUINT64_FORMAT ": wanted %u bytes, got %u bytes", parse->priv->offset,
size, GST_BUFFER_SIZE (parse->priv->cache));
*buffer = parse->priv->cache;
parse->priv->cache = NULL;
return GST_FLOW_OK;
}
*buffer = <API key> (parse->priv->cache, 0, size);
GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
return GST_FLOW_OK;
}
static GstFlowReturn
<API key> (GstBaseParse * parse)
{
gint64 offset = 0;
GstClockTime ts = 0;
GstBuffer *buffer;
GstFlowReturn ret;
GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
parse->priv->last_offset);
if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
GST_TIME_ARGS (parse->segment.start));
ret = GST_FLOW_UNEXPECTED;
goto exit;
}
/* last fragment started at last_offset / last_ts;
* seek back 10s capped at 1MB */
if (parse->priv->last_ts >= 10 * GST_SECOND)
ts = parse->priv->last_ts - 10 * GST_SECOND;
/* if we are exact now, we will be more so going backwards */
if (parse->priv->exact_position) {
offset = <API key> (parse, ts, TRUE, NULL);
} else {
GstFormat dstformat = GST_FORMAT_BYTES;
if (!<API key> (parse->srcpad, GST_FORMAT_TIME, ts,
&dstformat, &offset)) {
GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
}
}
offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
parse->priv->last_offset - 1024);
offset = MAX (0, offset);
GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
offset);
parse->priv->offset = offset;
ret = <API key> (parse, parse->priv->last_offset - offset,
&buffer);
if (ret != GST_FLOW_OK)
goto exit;
/* offset will increase again as fragment is processed/parsed */
parse->priv->last_offset = offset;
gst_adapter_push (parse->priv->adapter, buffer);
ret = <API key> (parse, FALSE);
if (ret != GST_FLOW_OK)
goto exit;
/* force previous fragment */
parse->priv->offset = -1;
exit:
return ret;
}
/* PULL mode:
* pull and scan for next frame starting from current offset
* ajusts sync, drain and offset going along */
static GstFlowReturn
<API key> (GstBaseParse * parse, GstBaseParseClass * klass,
GstBaseParseFrame * frame, gboolean full)
{
GstBuffer *buffer, *outbuf;
GstFlowReturn ret = GST_FLOW_OK;
guint fsize = 1, min_size, old_min_size = 0;
gint skip = 0;
<API key> (frame != NULL, GST_FLOW_ERROR);
GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
" (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
/* let's make this efficient for all subclass once and for all;
* maybe it does not need this much, but in the latter case, we know we are
* in pull mode here and might as well try to read and supply more anyway
* (so does the buffer caching mechanism) */
fsize = 64 * 1024;
while (TRUE) {
gboolean res;
min_size = MAX (parse->priv->min_frame_size, fsize);
/* loop safety check */
if (G_UNLIKELY (old_min_size >= min_size))
goto invalid_min;
old_min_size = min_size;
ret = <API key> (parse, min_size, &buffer);
if (ret != GST_FLOW_OK)
goto done;
if (parse->priv->discont) {
GST_DEBUG_OBJECT (parse, "marking DISCONT");
GST_BUFFER_FLAG_SET (buffer, <API key>);
}
/* if we got a short read, inform subclass we are draining leftover
* and no more is to be expected */
if (GST_BUFFER_SIZE (buffer) < min_size)
parse->priv->drain = TRUE;
if (parse->priv->detecting) {
ret = klass->detect (parse, buffer);
if (ret == <API key>) {
/* If draining we error out, otherwise request a buffer
* with 64kb more */
if (parse->priv->drain) {
gst_buffer_unref (buffer);
GST_ERROR_OBJECT (parse, "Failed to detect format but draining");
return GST_FLOW_ERROR;
} else {
fsize += 64 * 1024;
gst_buffer_unref (buffer);
continue;
}
} else if (ret != GST_FLOW_OK) {
gst_buffer_unref (buffer);
GST_ERROR_OBJECT (parse, "detect() returned %s",
gst_flow_get_name (ret));
return ret;
}
/* Else handle this buffer normally */
}
skip = -1;
<API key> (parse, frame, buffer);
res = klass->check_valid_frame (parse, frame, &fsize, &skip);
gst_buffer_replace (&frame->buffer, NULL);
if (res) {
parse->priv->drain = FALSE;
GST_LOG_OBJECT (parse, "valid frame of size %d at pos %d", fsize, skip);
break;
}
parse->priv->drain = FALSE;
if (skip == -1)
skip = 1;
if (skip > 0) {
GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
if (full && parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
/* reverse playback, and no frames found yet, so we are skipping
* the leading part of a fragment, which may form the tail of
* fragment coming later, hopefully subclass skips efficiently ... */
outbuf = <API key> (buffer, 0, skip);
parse->priv->buffers_pending =
g_slist_prepend (parse->priv->buffers_pending, outbuf);
outbuf = NULL;
}
parse->priv->offset += skip;
if (!parse->priv->discont)
parse->priv->sync_offset = parse->priv->offset;
parse->priv->discont = TRUE;
/* something changed at least; nullify loop check */
if (fsize == G_MAXUINT)
fsize = old_min_size + 64 * 1024;
old_min_size = 0;
}
/* skip == 0 should imply subclass set min_size to need more data;
* we check this shortly */
GST_DEBUG_OBJECT (parse, "finding sync...");
gst_buffer_unref (buffer);
if ((ret = <API key> (parse)) != GST_FLOW_OK) {
goto done;
}
}
/* Does the subclass want to skip too? */
if (skip > 0)
parse->priv->offset += skip;
else if (skip < 0)
skip = 0;
if (fsize + skip <= GST_BUFFER_SIZE (buffer)) {
outbuf = <API key> (buffer, skip, fsize);
GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer) + skip;
<API key> (outbuf) = GST_CLOCK_TIME_NONE;
gst_buffer_unref (buffer);
} else {
gst_buffer_unref (buffer);
ret = <API key> (parse, fsize, &outbuf);
if (ret != GST_FLOW_OK)
goto done;
if (GST_BUFFER_SIZE (outbuf) < fsize) {
gst_buffer_unref (outbuf);
ret = GST_FLOW_UNEXPECTED;
}
}
parse->priv->offset += fsize;
frame->buffer = outbuf;
done:
return ret;
/* ERRORS */
invalid_min:
{
GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
("min_size evolution %d -> %d; breaking to avoid looping",
old_min_size, min_size));
return GST_FLOW_ERROR;
}
}
/* Loop that is used in pull mode to retrieve data from upstream */
static void
gst_base_parse_loop (GstPad * pad)
{
GstBaseParse *parse;
GstBaseParseClass *klass;
GstFlowReturn ret = GST_FLOW_OK;
GstBaseParseFrame frame;
parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
klass = <API key> (parse);
/* reverse playback:
* first fragment (closest to stop time) is handled normally below,
* then we pull in fragments going backwards */
if (parse->segment.rate < 0.0) {
/* check if we jumped back to a previous fragment,
* which is a post-first fragment */
if (parse->priv->offset < 0) {
ret = <API key> (parse);
goto done;
}
}
<API key> (&frame);
ret = <API key> (parse, klass, &frame, TRUE);
if (ret != GST_FLOW_OK)
goto done;
/* This always cleans up frame, even if error occurs */
ret = <API key> (parse, klass, &frame);
/* eat expected eos signalling past segment in reverse playback */
if (parse->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
parse->segment.last_stop >= parse->segment.stop) {
GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
/* push what was accumulated during loop run */
<API key> (parse, TRUE);
/* force previous fragment */
parse->priv->offset = -1;
ret = GST_FLOW_OK;
}
done:
if (ret == GST_FLOW_UNEXPECTED)
goto eos;
else if (ret != GST_FLOW_OK)
goto pause;
gst_object_unref (parse);
return;
/* ERRORS */
eos:
{
ret = GST_FLOW_UNEXPECTED;
GST_DEBUG_OBJECT (parse, "eos");
/* fall-through */
}
pause:
{
gboolean push_eos = FALSE;
GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
gst_flow_get_name (ret));
gst_pad_pause_task (parse->sinkpad);
if (ret == GST_FLOW_UNEXPECTED) {
/* handle end-of-stream/segment */
if (parse->segment.flags & <API key>) {
gint64 stop;
if ((stop = parse->segment.stop) == -1)
stop = parse->segment.duration;
GST_DEBUG_OBJECT (parse, "sending segment_done");
<API key>
(GST_ELEMENT_CAST (parse),
<API key> (GST_OBJECT_CAST (parse),
GST_FORMAT_TIME, stop));
} else {
/* If we STILL have zero frames processed, fire an error */
if (parse->priv->framecount == 0) {
GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
("No valid frames found before end of stream"), (NULL));
}
push_eos = TRUE;
}
} else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
/* for fatal errors we post an error message, wrong-state is
* not fatal because it happens due to flushes and only means
* that we should stop now. */
GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
("streaming stopped, reason %s", gst_flow_get_name (ret)));
push_eos = TRUE;
}
if (push_eos) {
/* Push pending events, including NEWSEGMENT events */
if (G_UNLIKELY (parse->priv->pending_events)) {
GList *l;
for (l = parse->priv->pending_events; l != NULL; l = l->next) {
gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
}
g_list_free (parse->priv->pending_events);
parse->priv->pending_events = NULL;
parse->priv->pending_segment = FALSE;
}
gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
}
gst_object_unref (parse);
}
}
static gboolean
<API key> (GstPad * sinkpad)
{
GstBaseParse *parse;
gboolean result = TRUE;
parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
GST_DEBUG_OBJECT (parse, "sink activate");
if (<API key> (sinkpad)) {
GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
result = <API key> (sinkpad, TRUE);
} else {
GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
result = <API key> (sinkpad, TRUE);
}
GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
gst_object_unref (parse);
return result;
}
static gboolean
<API key> (GstBaseParse * parse, gboolean active)
{
GstBaseParseClass *klass;
gboolean result = TRUE;
GST_DEBUG_OBJECT (parse, "activate %d", active);
klass = <API key> (parse);
if (active) {
if (parse->priv->pad_mode == GST_ACTIVATE_NONE && klass->start)
result = klass->start (parse);
/* If the subclass implements ::detect we want to
* call it for the first buffers now */
parse->priv->detecting = (klass->detect != NULL);
} else {
/* We must make sure streaming has finished before resetting things
* and calling the ::stop vfunc */
GST_PAD_STREAM_LOCK (parse->sinkpad);
<API key> (parse->sinkpad);
if (parse->priv->pad_mode != GST_ACTIVATE_NONE && klass->stop)
result = klass->stop (parse);
parse->priv->pad_mode = GST_ACTIVATE_NONE;
}
GST_DEBUG_OBJECT (parse, "activate return: %d", result);
return result;
}
static gboolean
<API key> (GstPad * pad, gboolean active)
{
gboolean result = TRUE;
GstBaseParse *parse;
parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
GST_DEBUG_OBJECT (parse, "sink activate push %d", active);
result = <API key> (parse, active);
if (result)
parse->priv->pad_mode = active ? GST_ACTIVATE_PUSH : GST_ACTIVATE_NONE;
GST_DEBUG_OBJECT (parse, "sink activate push return: %d", result);
gst_object_unref (parse);
return result;
}
static gboolean
<API key> (GstPad * sinkpad, gboolean active)
{
gboolean result = FALSE;
GstBaseParse *parse;
parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
GST_DEBUG_OBJECT (parse, "activate pull %d", active);
result = <API key> (parse, active);
if (result) {
if (active) {
GstEvent *event;
event = <API key> (FALSE,
parse->segment.rate, parse->segment.format,
parse->segment.start, parse->segment.stop, parse->segment.last_stop);
parse->priv->pending_events =
g_list_append (parse->priv->pending_events, event);
parse->priv->pending_segment = TRUE;
result &=
gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
sinkpad);
} else {
result &= gst_pad_stop_task (sinkpad);
}
}
if (result)
parse->priv->pad_mode = active ? GST_ACTIVATE_PULL : GST_ACTIVATE_NONE;
GST_DEBUG_OBJECT (parse, "sink activate pull return: %d", result);
gst_object_unref (parse);
return result;
}
/**
* <API key>:
* @parse: #GstBaseParse.
* @fmt: #GstFormat.
* @duration: duration value.
* @interval: how often to update the duration estimate based on bitrate, or 0.
*
* Sets the duration of the currently playing media. Subclass can use this
* when it is able to determine duration and/or notices a change in the media
* duration. Alternatively, if @interval is non-zero (default), then stream
* duration is determined based on estimated bitrate, and updated every @interval
* frames.
*
* Since: 0.10.33
*/
void
<API key> (GstBaseParse * parse,
GstFormat fmt, gint64 duration, gint interval)
{
g_return_if_fail (parse != NULL);
if (parse->priv-><API key>) {
GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
goto exit;
}
if (duration != parse->priv->duration) {
GstMessage *m;
m = <API key> (GST_OBJECT (parse), fmt, duration);
<API key> (GST_ELEMENT (parse), m);
/* TODO: what about duration tag? */
}
parse->priv->duration = duration;
parse->priv->duration_fmt = fmt;
GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
if (fmt == GST_FORMAT_TIME && <API key> (duration)) {
if (interval != 0) {
GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
interval = 0;
}
}
GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
parse->priv->update_interval = interval;
exit:
return;
}
/**
* <API key>:
* @parse: #GstBaseParse.
* @bitrate: average bitrate in bits/second
*
* Optionally sets the average bitrate detected in media (if non-zero),
* e.g. based on metadata, as it will be posted to the application.
*
* By default, announced average bitrate is estimated. The average bitrate
* is used to estimate the total duration of the stream and to estimate
* a seek position, if there's no index and the format is syncable
* (see <API key>()).
*
* Since: 0.10.33
*/
void
<API key> (GstBaseParse * parse, guint bitrate)
{
parse->priv->bitrate = bitrate;
GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
}
/**
* <API key>:
* @parse: #GstBaseParse.
* @min_size: Minimum size of the data that this base class should give to
* subclass.
*
* Subclass can use this function to tell the base class that it needs to
* give at least #min_size buffers.
*
* Since: 0.10.33
*/
void
<API key> (GstBaseParse * parse, guint min_size)
{
g_return_if_fail (parse != NULL);
parse->priv->min_frame_size = min_size;
GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
}
/**
* <API key>:
* @parse: the #GstBaseParse to set
* @fps_num: frames per second (numerator).
* @fps_den: frames per second (denominator).
* @lead_in: frames needed before a segment for subsequent decode
* @lead_out: frames needed after a segment
*
* If frames per second is configured, parser can take care of buffer duration
* and timestamping. When performing segment clipping, or seeking to a specific
* location, a corresponding decoder might need an initial @lead_in and a
* following @lead_out number of frames to ensure the desired segment is
* entirely filled upon decoding.
*
* Since: 0.10.33
*/
void
<API key> (GstBaseParse * parse, guint fps_num,
guint fps_den, guint lead_in, guint lead_out)
{
g_return_if_fail (parse != NULL);
parse->priv->fps_num = fps_num;
parse->priv->fps_den = fps_den;
if (!fps_num || !fps_den) {
GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
fps_num, fps_den);
fps_num = fps_den = 0;
parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
parse->priv->lead_in = parse->priv->lead_out = 0;
parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
} else {
parse->priv->frame_duration =
<API key> (GST_SECOND, fps_den, fps_num);
parse->priv->lead_in = lead_in;
parse->priv->lead_out = lead_out;
parse->priv->lead_in_ts =
<API key> (GST_SECOND, fps_den * lead_in, fps_num);
parse->priv->lead_out_ts =
<API key> (GST_SECOND, fps_den * lead_out, fps_num);
/* aim for about 1.5s to estimate duration */
if (parse->priv->update_interval < 0) {
parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
parse->priv->update_interval);
}
}
GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
"lead out: %d frames = %" G_GUINT64_FORMAT " ms",
lead_in, parse->priv->lead_in_ts / GST_MSECOND,
lead_out, parse->priv->lead_out_ts / GST_MSECOND);
}
/**
* <API key>:
* @parse: a #GstBaseParse
* @has_timing: whether frames carry timing information
*
* Set if frames carry timing information which the subclass can (generally)
* parse and provide. In particular, intrinsic (rather than estimated) time
* can be obtained following a seek.
*
* Since: 0.10.33
*/
void
<API key> (GstBaseParse * parse, gboolean has_timing)
{
parse->priv->has_timing_info = has_timing;
GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
}
/**
* <API key>:
* @parse: a #GstBaseParse
* @syncable: set if frame starts can be identified
*
* Set if frame starts can be identified. This is set by default and
* determines whether seeking based on bitrate averages
* is possible for a format/stream.
*
* Since: 0.10.33
*/
void
<API key> (GstBaseParse * parse, gboolean syncable)
{
parse->priv->syncable = syncable;
GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
}
/**
* <API key>:
* @parse: a #GstBaseParse
* @passthrough: %TRUE if parser should run in passthrough mode
*
* Set if the nature of the format or configuration does not allow (much)
* parsing, and the parser should operate in passthrough mode (which only
* applies when operating in push mode). That is, incoming buffers are
* pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
* callbacks will be invoked, but @pre_push_frame will still be invoked,
* so subclass can perform as much or as little is appropriate for
* passthrough semantics in @pre_push_frame.
*
* Since: 0.10.33
*/
void
<API key> (GstBaseParse * parse, gboolean passthrough)
{
parse->priv->passthrough = passthrough;
GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
}
/**
* <API key>:
* @parse: a #GstBaseParse
* @min_latency: minimum parse latency
* @max_latency: maximum parse latency
*
* Sets the minimum and maximum (which may likely be equal) latency introduced
* by the parsing process. If there is such a latency, which depends on the
* particular parsing of the format, it typically corresponds to 1 frame duration.
*
* Since: 0.10.36
*/
void
<API key> (GstBaseParse * parse, GstClockTime min_latency,
GstClockTime max_latency)
{
GST_OBJECT_LOCK (parse);
parse->priv->min_latency = min_latency;
parse->priv->max_latency = max_latency;
GST_OBJECT_UNLOCK (parse);
GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
GST_TIME_ARGS (max_latency));
}
static gboolean
<API key> (GstBaseParse * parse, GstFormat format,
GstClockTime * duration)
{
gboolean res = FALSE;
<API key> (duration != NULL, FALSE);
*duration = GST_CLOCK_TIME_NONE;
if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
GST_LOG_OBJECT (parse, "using provided duration");
*duration = parse->priv->duration;
res = TRUE;
} else if (parse->priv->duration != -1) {
GST_LOG_OBJECT (parse, "converting provided duration");
res = <API key> (parse, parse->priv->duration_fmt,
parse->priv->duration, format, (gint64 *) duration);
} else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
GST_LOG_OBJECT (parse, "using estimated duration");
*duration = parse->priv->estimated_duration;
res = TRUE;
}
GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
GST_TIME_ARGS (*duration));
return res;
}
static const GstQueryType *
<API key> (GstPad * pad)
{
static const GstQueryType list[] = {
GST_QUERY_POSITION,
GST_QUERY_DURATION,
GST_QUERY_FORMATS,
GST_QUERY_SEEKING,
GST_QUERY_CONVERT,
GST_QUERY_NONE
};
return list;
}
static gboolean
<API key> (GstPad * pad, GstQuery * query)
{
GstBaseParse *parse;
gboolean res = FALSE;
parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
switch (GST_QUERY_TYPE (query)) {
case GST_QUERY_POSITION:
{
gint64 dest_value;
GstFormat format;
GST_DEBUG_OBJECT (parse, "position query");
<API key> (query, &format, NULL);
/* try upstream first */
res = <API key> (pad, query);
if (!res) {
/* Fall back on interpreting segment */
GST_OBJECT_LOCK (parse);
if (format == GST_FORMAT_BYTES) {
dest_value = parse->priv->offset;
res = TRUE;
} else if (format == parse->segment.format &&
<API key> (parse->segment.last_stop)) {
dest_value = <API key> (&parse->segment,
parse->segment.format, parse->segment.last_stop);
res = TRUE;
}
GST_OBJECT_UNLOCK (parse);
if (!res) {
/* no precise result, upstream no idea either, then best estimate */
/* priv->offset is updated in both PUSH/PULL modes */
res = <API key> (parse,
GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
}
if (res)
<API key> (query, format, dest_value);
}
break;
}
case GST_QUERY_DURATION:
{
GstFormat format;
GstClockTime duration;
GST_DEBUG_OBJECT (parse, "duration query");
<API key> (query, &format, NULL);
/* consult upstream */
res = <API key> (pad, query);
/* otherwise best estimate from us */
if (!res) {
res = <API key> (parse, format, &duration);
if (res)
<API key> (query, format, duration);
}
break;
}
case GST_QUERY_SEEKING:
{
GstFormat fmt;
GstClockTime duration = GST_CLOCK_TIME_NONE;
gboolean seekable = FALSE;
GST_DEBUG_OBJECT (parse, "seeking query");
<API key> (query, &fmt, NULL, NULL, NULL);
/* consult upstream */
res = <API key> (pad, query);
/* we may be able to help if in TIME */
if (fmt == GST_FORMAT_TIME && <API key> (parse)) {
<API key> (query, &fmt, &seekable, NULL, NULL);
/* already OK if upstream takes care */
GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
res, seekable);
if (!(res && seekable)) {
if (!<API key> (parse, GST_FORMAT_TIME, &duration)
|| duration == -1) {
/* seekable if we still have a chance to get duration later on */
seekable =
parse->priv->upstream_seekable && parse->priv->update_interval;
} else {
seekable = parse->priv->upstream_seekable;
GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
seekable);
}
<API key> (query, GST_FORMAT_TIME, seekable, 0, duration);
res = TRUE;
}
}
break;
}
case GST_QUERY_FORMATS:
<API key> (query, 3, fmtlist);
res = TRUE;
break;
case GST_QUERY_CONVERT:
{
GstFormat src_format, dest_format;
gint64 src_value, dest_value;
<API key> (query, &src_format, &src_value,
&dest_format, &dest_value);
res = <API key> (parse, src_format, src_value,
dest_format, &dest_value);
if (res) {
<API key> (query, src_format, src_value,
dest_format, dest_value);
}
break;
}
case GST_QUERY_LATENCY:
{
if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
gboolean live;
GstClockTime min_latency, max_latency;
<API key> (query, &live, &min_latency, &max_latency);
GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
GST_OBJECT_LOCK (parse);
/* add our latency */
if (min_latency != -1)
min_latency += parse->priv->min_latency;
if (max_latency != -1)
max_latency += parse->priv->max_latency;
GST_OBJECT_UNLOCK (parse);
<API key> (query, live, min_latency, max_latency);
}
break;
}
default:
res = <API key> (pad, query);
break;
}
return res;
}
/* scans for a cluster start from @pos,
* return GST_FLOW_OK and frame position/time in @pos/@time if found */
static GstFlowReturn
<API key> (GstBaseParse * parse, gint64 * pos,
GstClockTime * time, GstClockTime * duration)
{
GstBaseParseClass *klass;
gint64 orig_offset;
gboolean orig_drain, orig_discont;
GstFlowReturn ret = GST_FLOW_OK;
GstBuffer *buf = NULL;
GstBaseParseFrame frame;
<API key> (pos != NULL, GST_FLOW_ERROR);
<API key> (time != NULL, GST_FLOW_ERROR);
<API key> (duration != NULL, GST_FLOW_ERROR);
klass = <API key> (parse);
*time = GST_CLOCK_TIME_NONE;
*duration = GST_CLOCK_TIME_NONE;
/* save state */
orig_offset = parse->priv->offset;
orig_discont = parse->priv->discont;
orig_drain = parse->priv->drain;
GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
" (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
<API key> (&frame);
/* jump elsewhere and locate next frame */
parse->priv->offset = *pos;
ret = <API key> (parse, klass, &frame, FALSE);
if (ret != GST_FLOW_OK)
goto done;
buf = frame.buffer;
GST_LOG_OBJECT (parse,
"peek parsing frame at offset %" G_GUINT64_FORMAT
" (%#" G_GINT64_MODIFIER "x) of size %d",
GST_BUFFER_OFFSET (buf), GST_BUFFER_OFFSET (buf), GST_BUFFER_SIZE (buf));
/* get offset first, subclass parsing might dump other stuff in there */
*pos = GST_BUFFER_OFFSET (buf);
ret = klass->parse_frame (parse, &frame);
buf = frame.buffer;
/* but it should provide proper time */
*time = <API key> (buf);
*duration = GST_BUFFER_DURATION (buf);
<API key> (&frame);
GST_LOG_OBJECT (parse,
"frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
GST_TIME_ARGS (*time), *pos);
done:
/* restore state */
parse->priv->offset = orig_offset;
parse->priv->discont = orig_discont;
parse->priv->drain = orig_drain;
return ret;
}
/* bisect and scan through file for frame starting before @time,
* returns OK and @time/@offset if found, NONE and/or error otherwise
* If @time == G_MAXINT64, scan for duration ( == last frame) */
static GstFlowReturn
<API key> (GstBaseParse * parse, GstClockTime * _time,
gint64 * _offset)
{
GstFlowReturn ret = GST_FLOW_OK;
gint64 lpos, hpos, newpos;
GstClockTime time, ltime, htime, newtime, dur;
gboolean cont = TRUE;
const GstClockTime tolerance = TARGET_DIFFERENCE;
const guint chunk = 4 * 1024;
<API key> (_time != NULL, GST_FLOW_ERROR);
<API key> (_offset != NULL, GST_FLOW_ERROR);
GST_DEBUG_OBJECT (parse, "Bisecting for time %" GST_TIME_FORMAT,
GST_TIME_ARGS (*_time));
/* TODO also make keyframe aware if useful some day */
time = *_time;
/* basic cases */
if (time == 0) {
*_offset = 0;
return GST_FLOW_OK;
}
if (time == -1) {
*_offset = -1;
return GST_FLOW_OK;
}
/* do not know at first */
*_offset = -1;
*_time = GST_CLOCK_TIME_NONE;
/* need initial positions; start and end */
lpos = parse->priv->first_frame_offset;
ltime = parse->priv->first_frame_ts;
if (!<API key> (parse, GST_FORMAT_TIME, &htime)) {
GST_DEBUG_OBJECT (parse, "Unknown time duration, cannot bisect");
return GST_FLOW_ERROR;
}
hpos = parse->priv->upstream_size;
GST_DEBUG_OBJECT (parse,
"Bisection initial bounds: bytes %" G_GINT64_FORMAT " %" G_GINT64_FORMAT
", times %" GST_TIME_FORMAT " %" GST_TIME_FORMAT, lpos, htime,
GST_TIME_ARGS (ltime), GST_TIME_ARGS (htime));
/* check preconditions are satisfied;
* start and end are needed, except for special case where we scan for
* last frame to determine duration */
if (parse->priv->pad_mode != GST_ACTIVATE_PULL || !hpos ||
!<API key> (ltime) ||
(!<API key> (htime) && time != G_MAXINT64)) {
return GST_FLOW_OK;
}
/* shortcut cases */
if (time < ltime) {
goto exit;
} else if (time < ltime + tolerance) {
*_offset = lpos;
*_time = ltime;
goto exit;
} else if (time >= htime) {
*_offset = hpos;
*_time = htime;
goto exit;
}
while (htime > ltime && cont) {
GST_LOG_OBJECT (parse,
"lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
GST_TIME_ARGS (ltime));
GST_LOG_OBJECT (parse,
"hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
GST_TIME_ARGS (htime));
if (G_UNLIKELY (time == G_MAXINT64)) {
newpos = hpos;
} else if (G_LIKELY (hpos > lpos)) {
newpos =
<API key> (hpos - lpos, time - ltime, htime - ltime) +
lpos - chunk;
} else {
/* should mean lpos == hpos, since lpos <= hpos is invariant */
newpos = lpos;
/* we check this case once, but not forever, so break loop */
cont = FALSE;
}
/* ensure */
newpos = CLAMP (newpos, lpos, hpos);
GST_LOG_OBJECT (parse,
"estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
GST_TIME_ARGS (time), newpos);
ret = <API key> (parse, &newpos, &newtime, &dur);
if (ret == GST_FLOW_UNEXPECTED) {
/* heuristic HACK */
hpos = MAX (lpos, hpos - chunk);
continue;
} else if (ret != GST_FLOW_OK) {
goto exit;
}
if (newtime == -1 || newpos == -1) {
GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
break;
}
if (G_UNLIKELY (time == G_MAXINT64)) {
*_offset = newpos;
*_time = newtime;
if (<API key> (dur))
*_time += dur;
break;
} else if (newtime > time) {
/* overshoot */
hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
htime = newtime;
} else if (newtime + tolerance > time) {
/* close enough undershoot */
*_offset = newpos;
*_time = newtime;
break;
} else if (newtime < ltime) {
/* so a position beyond lpos resulted in earlier time than ltime ... */
GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
break;
} else {
/* undershoot too far */
newpos += newpos == lpos ? chunk : 0;
lpos = CLAMP (newpos, lpos, hpos);
ltime = newtime;
}
}
exit:
GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
return ret;
}
static gint64
<API key> (GstBaseParse * parse, GstClockTime time,
gboolean before, GstClockTime * _ts)
{
gint64 bytes = 0, ts = 0;
GstIndexEntry *entry = NULL;
if (time == GST_CLOCK_TIME_NONE) {
ts = time;
bytes = -1;
goto exit;
}
<API key> (parse);
if (parse->priv->index) {
/* Let's check if we have an index entry for that time */
entry = <API key> (parse->priv->index,
parse->priv->index_id,
before ? <API key> : <API key>,
<API key>, GST_FORMAT_TIME, time);
}
if (entry) {
<API key> (entry, GST_FORMAT_BYTES, &bytes);
<API key> (entry, GST_FORMAT_TIME, &ts);
GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
" at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
} else {
GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
GST_TIME_ARGS (time));
if (!before) {
bytes = -1;
ts = GST_CLOCK_TIME_NONE;
}
}
<API key> (parse);
exit:
if (_ts)
*_ts = ts;
return bytes;
}
/* returns TRUE if seek succeeded */
static gboolean
<API key> (GstBaseParse * parse, GstEvent * event)
{
gdouble rate;
GstFormat format;
GstSeekFlags flags;
GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
gboolean flush, update, res = TRUE, accurate;
gint64 cur, stop, seekpos, seekstop;
GstSegment seeksegment = { 0, };
GstFormat dstformat;
GstClockTime start_ts;
<API key> (event, &rate, &format, &flags,
&cur_type, &cur, &stop_type, &stop);
GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
"start type %d at %" GST_TIME_FORMAT ", end type %d at %"
GST_TIME_FORMAT, gst_format_get_name (format), rate,
cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
/* no negative rates in push mode */
if (rate < 0.0 && parse->priv->pad_mode == GST_ACTIVATE_PUSH)
goto negative_rate;
if (cur_type != GST_SEEK_TYPE_SET ||
(stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
goto wrong_type;
/* For any format other than TIME, see if upstream handles
* it directly or fail. For TIME, try upstream, but do it ourselves if
* it fails upstream */
if (format != GST_FORMAT_TIME) {
/* default action delegates to upstream */
res = FALSE;
goto done;
} else {
gst_event_ref (event);
if ((res = gst_pad_push_event (parse->sinkpad, event))) {
goto done;
}
}
/* get flush flag */
flush = flags & GST_SEEK_FLAG_FLUSH;
/* copy segment, we need this because we still need the old
* segment when we close the current segment. */
memcpy (&seeksegment, &parse->segment, sizeof (GstSegment));
GST_DEBUG_OBJECT (parse, "configuring seek");
<API key> (&seeksegment, rate, format, flags,
cur_type, cur, stop_type, stop, &update);
/* accurate seeking implies seek tables are used to obtain position,
* and the requested segment is maintained exactly, not adjusted any way */
accurate = flags & <API key>;
/* maybe we can be accurate for (almost) free */
<API key> (parse, seeksegment.last_stop, TRUE, &start_ts);
if (seeksegment.last_stop <= start_ts + TARGET_DIFFERENCE) {
GST_DEBUG_OBJECT (parse, "accurate seek possible");
accurate = TRUE;
}
if (accurate) {
GstClockTime startpos = seeksegment.last_stop;
/* accurate requested, so ... seek a bit before target */
if (startpos < parse->priv->lead_in_ts)
startpos = 0;
else
startpos -= parse->priv->lead_in_ts;
seekpos = <API key> (parse, startpos, TRUE, &start_ts);
seekstop = <API key> (parse, seeksegment.stop, FALSE,
NULL);
} else {
start_ts = seeksegment.last_stop;
dstformat = GST_FORMAT_BYTES;
if (!<API key> (parse->srcpad, format, seeksegment.last_stop,
&dstformat, &seekpos))
goto convert_failed;
if (!<API key> (parse->srcpad, format, seeksegment.stop,
&dstformat, &seekstop))
goto convert_failed;
}
GST_DEBUG_OBJECT (parse,
"seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
start_ts, seekpos);
GST_DEBUG_OBJECT (parse,
"seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
seeksegment.stop, seekstop);
if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
gint64 last_stop;
GST_DEBUG_OBJECT (parse, "seek in PULL mode");
if (flush) {
if (parse->srcpad) {
GST_DEBUG_OBJECT (parse, "sending flush start");
gst_pad_push_event (parse->srcpad, <API key> ());
/* unlock upstream pull_range */
gst_pad_push_event (parse->sinkpad, <API key> ());
}
} else {
gst_pad_pause_task (parse->sinkpad);
}
/* we should now be able to grab the streaming thread because we stopped it
* with the above flush/pause code */
GST_PAD_STREAM_LOCK (parse->sinkpad);
/* save current position */
last_stop = parse->segment.last_stop;
GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
last_stop);
/* now commit to new position */
/* prepare for streaming again */
if (flush) {
GST_DEBUG_OBJECT (parse, "sending flush stop");
gst_pad_push_event (parse->srcpad, <API key> ());
gst_pad_push_event (parse->sinkpad, <API key> ());
<API key> (parse);
} else {
if (parse->priv->close_segment)
gst_event_unref (parse->priv->close_segment);
parse->priv->close_segment = <API key> (TRUE,
parse->segment.rate, parse->segment.format,
parse->segment.accum, parse->segment.last_stop, parse->segment.accum);
/* keep track of our last_stop */
seeksegment.accum = parse->segment.last_stop;
GST_DEBUG_OBJECT (parse, "Created close seg format %d, "
"start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
", pos = %" GST_TIME_FORMAT, format,
GST_TIME_ARGS (parse->segment.accum),
GST_TIME_ARGS (parse->segment.last_stop),
GST_TIME_ARGS (parse->segment.accum));
}
memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
/* store the newsegment event so it can be sent from the streaming thread. */
parse->priv->pending_segment = TRUE;
parse->priv->pending_events = g_list_append (parse->priv->pending_events,
<API key> (FALSE, parse->segment.rate,
parse->segment.format, parse->segment.start,
parse->segment.stop, parse->segment.start));
GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
"start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
", pos = %" GST_TIME_FORMAT, format,
GST_TIME_ARGS (parse->segment.start),
GST_TIME_ARGS (parse->segment.stop),
GST_TIME_ARGS (parse->segment.start));
/* one last chance in pull mode to stay accurate;
* maybe scan and subclass can find where to go */
if (!accurate) {
gint64 scanpos;
GstClockTime ts = seeksegment.last_stop;
<API key> (parse, &ts, &scanpos);
if (scanpos >= 0) {
accurate = TRUE;
seekpos = scanpos;
/* running collected index now consists of several intervals,
* so optimized check no longer possible */
parse->priv->index_last_valid = FALSE;
parse->priv->index_last_offset = 0;
parse->priv->index_last_ts = 0;
}
}
/* mark discont if we are going to stream from another position. */
if (seekpos != parse->priv->offset) {
GST_DEBUG_OBJECT (parse,
"mark DISCONT, we did a seek to another position");
parse->priv->offset = seekpos;
parse->priv->last_offset = seekpos;
parse->priv->seen_keyframe = FALSE;
parse->priv->discont = TRUE;
parse->priv->next_ts = start_ts;
parse->priv->last_ts = GST_CLOCK_TIME_NONE;
parse->priv->sync_offset = seekpos;
parse->priv->exact_position = accurate;
}
/* Start streaming thread if paused */
gst_pad_start_task (parse->sinkpad,
(GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
<API key> (parse->sinkpad);
/* handled seek */
res = TRUE;
} else {
GstEvent *new_event;
GstBaseParseSeek *seek;
GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
/* The only thing we need to do in PUSH-mode is to send the
seek event (in bytes) to upstream. Segment / flush handling happens
in corresponding src event handlers */
GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
if (seekstop >= 0 && seekstop <= seekpos)
seekstop = seekpos;
new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
/* store segment info so its precise details can be reconstructed when
* receiving newsegment;
* this matters for all details when accurate seeking,
* is most useful to preserve NONE stop time otherwise */
seek = g_new0 (GstBaseParseSeek, 1);
seek->segment = seeksegment;
seek->accurate = accurate;
seek->offset = seekpos;
seek->start_ts = start_ts;
GST_OBJECT_LOCK (parse);
/* less optimal, but preserves order */
parse->priv->pending_seeks =
g_slist_append (parse->priv->pending_seeks, seek);
GST_OBJECT_UNLOCK (parse);
res = gst_pad_push_event (parse->sinkpad, new_event);
if (!res) {
GST_OBJECT_LOCK (parse);
parse->priv->pending_seeks =
g_slist_remove (parse->priv->pending_seeks, seek);
GST_OBJECT_UNLOCK (parse);
g_free (seek);
}
}
done:
/* handled event is ours to free */
if (res)
gst_event_unref (event);
return res;
/* ERRORS */
negative_rate:
{
GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
res = FALSE;
goto done;
}
wrong_type:
{
GST_DEBUG_OBJECT (parse, "unsupported seek type.");
res = FALSE;
goto done;
}
convert_failed:
{
GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
res = FALSE;
goto done;
}
}
/* Checks if bitrates are available from upstream tags so that we don't
* override them later
*/
static void
<API key> (GstBaseParse * parse, GstEvent * event)
{
GstTagList *taglist = NULL;
guint tmp;
gst_event_parse_tag (event, &taglist);
if (<API key> (taglist, <API key>, &tmp)) {
GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
parse->priv->post_min_bitrate = FALSE;
}
if (<API key> (taglist, GST_TAG_BITRATE, &tmp)) {
GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
parse->priv->post_avg_bitrate = FALSE;
}
if (<API key> (taglist, <API key>, &tmp)) {
GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
parse->priv->post_max_bitrate = FALSE;
}
}
static gboolean
<API key> (GstPad * pad, GstCaps * caps)
{
GstBaseParse *parse;
GstBaseParseClass *klass;
gboolean res = TRUE;
parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
klass = <API key> (parse);
GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
if (klass->set_sink_caps)
res = klass->set_sink_caps (parse, caps);
return res;
}
static GstCaps *
<API key> (GstPad * pad)
{
GstBaseParse *parse;
GstBaseParseClass *klass;
GstCaps *caps;
parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
klass = <API key> (parse);
g_assert (pad == <API key> (parse));
if (klass->get_sink_caps)
caps = klass->get_sink_caps (parse);
else
caps = gst_caps_copy (<API key> (pad));
gst_object_unref (parse);
GST_LOG_OBJECT (parse, "sink getcaps returning caps %" GST_PTR_FORMAT, caps);
return caps;
}
static void
<API key> (GstElement * element, GstIndex * index)
{
GstBaseParse *parse = GST_BASE_PARSE (element);
<API key> (parse);
if (parse->priv->index)
gst_object_unref (parse->priv->index);
if (index) {
parse->priv->index = gst_object_ref (index);
<API key> (index, GST_OBJECT_CAST (element),
&parse->priv->index_id);
parse->priv->own_index = FALSE;
} else {
parse->priv->index = NULL;
}
<API key> (parse);
}
static GstIndex *
<API key> (GstElement * element)
{
GstBaseParse *parse = GST_BASE_PARSE (element);
GstIndex *result = NULL;
<API key> (parse);
if (parse->priv->index)
result = gst_object_ref (parse->priv->index);
<API key> (parse);
return result;
}
static <API key>
<API key> (GstElement * element, GstStateChange transition)
{
GstBaseParse *parse;
<API key> result;
parse = GST_BASE_PARSE (element);
switch (transition) {
case <API key>:
/* If this is our own index destroy it as the
* old entries might be wrong for the new stream */
<API key> (parse);
if (parse->priv->own_index) {
gst_object_unref (parse->priv->index);
parse->priv->index = NULL;
parse->priv->own_index = FALSE;
}
/* If no index was created, generate one */
if (G_UNLIKELY (!parse->priv->index)) {
GST_DEBUG_OBJECT (parse, "no index provided creating our own");
parse->priv->index = <API key> ("memindex");
<API key> (parse->priv->index, GST_OBJECT (parse),
&parse->priv->index_id);
parse->priv->own_index = TRUE;
}
<API key> (parse);
break;
default:
break;
}
result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
switch (transition) {
case <API key>:
<API key> (parse);
break;
default:
break;
}
return result;
} |
package org.exist.util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.backup.SystemExport;
import org.exist.collections.CollectionCache;
import org.exist.repo.Deployment;
import org.exist.start.Main;
import org.exist.storage.lock.LockManager;
import org.exist.storage.lock.LockTable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.exist.Indexer;
import org.exist.indexing.IndexManager;
import org.exist.dom.memtree.SAXAdapter;
import org.exist.scheduler.JobConfig;
import org.exist.scheduler.JobException;
import org.exist.security.internal.RealmImpl;
import org.exist.storage.BrokerFactory;
import org.exist.storage.BrokerPool;
import org.exist.storage.DBBroker;
import org.exist.storage.DefaultCacheManager;
import org.exist.storage.IndexSpec;
import org.exist.storage.NativeBroker;
import org.exist.storage.NativeValueIndex;
import org.exist.storage.XQueryPool;
import org.exist.storage.journal.Journal;
import org.exist.storage.serializers.<API key>;
import org.exist.storage.serializers.Serializer;
import org.exist.validation.GrammarPool;
import org.exist.validation.resolver.<API key>;
import org.exist.xmldb.DatabaseImpl;
import org.exist.xquery.FunctionFactory;
import org.exist.xquery.PerformanceStats;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.XQueryWatchDog;
import org.exist.xslt.<API key>;
import java.io.IOException;
import java.io.InputStream;
import java.net.<API key>;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.Map.Entry;
import javax.annotation.Nullable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.<API key>;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.exist.Namespaces;
import org.exist.scheduler.JobType;
import org.exist.xquery.Module;
import static javax.xml.XMLConstants.<API key>;
public class Configuration implements ErrorHandler
{
private final static Logger LOG = LogManager.getLogger(Configuration.class); //Logger
protected Optional<Path> configFilePath = Optional.empty();
protected Optional<Path> existHome = Optional.empty();
protected DocumentBuilder builder = null;
protected HashMap<String, Object> config = new HashMap<>(); //Configuration
private static final String <API key> = "xquery";
private static final String <API key> = "builtin-modules";
private static final String <API key> = "module";
public final static String <API key> = "binary.cache.class";
public Configuration() throws <API key> {
this(DatabaseImpl.CONF_XML, Optional.empty());
}
public Configuration(final String configFilename) throws <API key> {
this(configFilename, Optional.empty());
}
public Configuration(String configFilename, Optional<Path> existHomeDirname) throws <API key> {
InputStream is = null;
try {
if(configFilename == null) {
// Default file name
configFilename = DatabaseImpl.CONF_XML;
}
// firstly, try to read the configuration from a file within the
// classpath
try {
is = Configuration.class.getClassLoader().getResourceAsStream(configFilename);
if(is != null) {
LOG.info("Reading configuration from classloader");
configFilePath = Optional.of(Paths.get(Configuration.class.getClassLoader().getResource(configFilename).toURI()));
}
} catch(final Exception e) {
// EB: ignore and go forward, e.g. in case there is an absolute
// file name for configFileName
LOG.debug( e );
}
// otherwise, secondly try to read configuration from file. Guess the
// location if necessary
if(is == null) {
existHome = existHomeDirname.map(Optional::of).orElse(ConfigurationHelper.getExistHome(configFilename));
if(!existHome.isPresent()) {
// EB: try to create existHome based on location of config file
// when config file points to absolute file location
final Path absoluteConfigFile = Paths.get(configFilename);
if(absoluteConfigFile.isAbsolute() && Files.exists(absoluteConfigFile) && Files.isReadable(absoluteConfigFile)) {
existHome = Optional.of(absoluteConfigFile.getParent());
configFilename = FileUtils.fileName(absoluteConfigFile);
}
}
Path configFile = Paths.get(configFilename);
if(!configFile.isAbsolute() && existHome.isPresent()) {
// try the passed or constructed existHome first
configFile = existHome.get().resolve(configFilename);
if (!Files.exists(configFile)) {
configFile = existHome.get().resolve(Main.CONFIG_DIR_NAME).resolve(configFilename);
}
}
//if( configFile == null ) {
// configFile = ConfigurationHelper.lookup( configFilename );
if(!Files.exists(configFile) || !Files.isReadable(configFile)) {
throw new <API key>("Unable to read configuration file at " + configFile);
}
configFilePath = Optional.of(configFile.toAbsolutePath());
is = Files.newInputStream(configFile);
}
LOG.info("Reading configuration from file " + configFilePath.map(Path::toString).orElse("Unknown"));
// set dbHome to parent of the conf file found, to resolve relative
// path from conf file
existHomeDirname = configFilePath.map(Path::getParent);
// initialize xml parser
// we use eXist's in-memory DOM implementation to work
// around a bug in Xerces
final SAXParserFactory factory = <API key>.getSAXParserFactory();
factory.setNamespaceAware(true);
final InputSource src = new InputSource(is);
final SAXParser parser = factory.newSAXParser();
final XMLReader reader = parser.getXMLReader();
reader.setFeature("http://xml.org/sax/features/<API key>", false);
reader.setFeature("http://xml.org/sax/features/<API key>", false);
reader.setFeature(<API key>, true);
final SAXAdapter adapter = new SAXAdapter();
reader.setContentHandler(adapter);
reader.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
reader.parse(src);
final Document doc = adapter.getDocument();
//indexer settings
final NodeList indexers = doc.<API key>(Indexer.<API key>);
if(indexers.getLength() > 0) {
configureIndexer( existHomeDirname, doc, (Element)indexers.item( 0 ) );
}
//scheduler settings
final NodeList schedulers = doc.<API key>(JobConfig.<API key>);
if(schedulers.getLength() > 0) {
configureScheduler((Element)schedulers.item(0));
}
//db connection settings
final NodeList dbcon = doc.<API key>(BrokerPool.<API key>);
if(dbcon.getLength() > 0) {
configureBackend(existHomeDirname, (Element)dbcon.item(0));
}
// lock-table settings
final NodeList lockManager = doc.<API key>("lock-manager");
if(lockManager.getLength() > 0) {
<API key>((Element) lockManager.item(0));
}
// repository settings
final NodeList repository = doc.<API key>("repository");
if(repository.getLength() > 0) {
configureRepository((Element) repository.item(0));
}
// binary manager settings
final NodeList binaryManager = doc.<API key>("binary-manager");
if(binaryManager.getLength() > 0) {
<API key>((Element)binaryManager.item(0));
}
//transformer settings
final NodeList transformers = doc.<API key>(<API key>.<API key>);
if( transformers.getLength() > 0 ) {
<API key>((Element)transformers.item(0));
}
//parser settings
final NodeList parsers = doc.<API key>(HtmlToXmlParser.PARSER_ELEMENT_NAME);
if(parsers.getLength() > 0) {
configureParser((Element)parsers.item(0));
}
//serializer settings
final NodeList serializers = doc.<API key>(Serializer.<API key>);
if(serializers.getLength() > 0) {
configureSerializer((Element)serializers.item(0));
}
//XUpdate settings
final NodeList xupdates = doc.<API key>(DBBroker.<API key>);
if(xupdates.getLength() > 0) {
configureXUpdate((Element)xupdates.item(0));
}
//XQuery settings
final NodeList xquery = doc.<API key>(<API key>);
if(xquery.getLength() > 0) {
configureXQuery((Element)xquery.item(0));
}
//Validation
final NodeList validations = doc.<API key>(<API key>.<API key>);
if(validations.getLength() > 0) {
configureValidation(existHomeDirname, doc, (Element)validations.item(0));
}
}
catch(final SAXException | IOException | <API key> e) {
LOG.error("error while reading config file: " + configFilename, e);
throw new <API key>(e.getMessage(), e);
} finally {
if(is != null) {
try {
is.close();
} catch(final IOException ioe) {
LOG.error(ioe);
}
}
}
}
private void <API key>(final Element lockManager) throws <API key> {
final boolean upgradeCheck = parseBoolean(<API key>(lockManager, "upgrade-check"), false);
final boolean <API key> = parseBoolean(<API key>(lockManager, "<API key>"), false);
final boolean pathsMultiWriter = parseBoolean(<API key>(lockManager, "paths-multi-writer"), false);
config.put(LockManager.<API key>, upgradeCheck);
config.put(LockManager.<API key>, <API key>);
config.put(LockManager.<API key>, pathsMultiWriter);
final NodeList nlLockTable = lockManager.<API key>("lock-table");
if(nlLockTable.getLength() > 0) {
final Element lockTable = (Element)nlLockTable.item(0);
final boolean lockTableDisabled = parseBoolean(<API key>(lockTable, "disabled"), false);
final int <API key> = parseInt(<API key>(lockTable, "trace-stack-depth"), 0);
config.put(LockTable.<API key>, lockTableDisabled);
config.put(LockTable.<API key>, <API key>);
}
final NodeList nlDocument = lockManager.<API key>("document");
if(nlDocument.getLength() > 0) {
final Element document = (Element)nlDocument.item(0);
final boolean <API key> = parseBoolean(<API key>(document, "use-path-locks"), false);
config.put(LockManager.<API key>, <API key>);
}
}
private void configureRepository(Element element) {
String root = <API key>(element, "root");
if (root != null && root.length() > 0) {
if (!root.endsWith("/"))
{root += "/";}
config.put(Deployment.PROPERTY_APP_ROOT, root);
}
}
private void <API key>(Element binaryManager) throws <API key> {
final NodeList nlCache = binaryManager.<API key>("cache");
if(nlCache.getLength() > 0) {
final Element cache = (Element)nlCache.item(0);
final String binaryCacheClass = <API key>(cache, "class");
config.put(<API key>, binaryCacheClass);
LOG.debug(<API key> + ": " + config.get(<API key>));
}
}
private void configureXQuery( Element xquery ) throws <API key>
{
//java binding
final String javabinding = <API key>( xquery, FunctionFactory.<API key> );
if( javabinding != null ) {
config.put( FunctionFactory.<API key>, javabinding );
LOG.debug( FunctionFactory.<API key> + ": " + config.get( FunctionFactory.<API key> ) );
}
final String disableDeprecated = <API key>( xquery, FunctionFactory.<API key> );
config.put( FunctionFactory.<API key>, Configuration.parseBoolean( disableDeprecated, FunctionFactory.<API key> ) );
LOG.debug( FunctionFactory.<API key> + ": " + config.get( FunctionFactory.<API key> ) );
final String optimize = <API key>( xquery, XQueryContext.<API key> );
if( ( optimize != null ) && ( optimize.length() > 0 ) ) {
config.put( XQueryContext.<API key>, optimize );
LOG.debug( XQueryContext.<API key> + ": " + config.get( XQueryContext.<API key> ) );
}
final String enforceIndexUse = <API key>( xquery, XQueryContext.<API key> );
if (enforceIndexUse != null) {
config.put( XQueryContext.<API key>, enforceIndexUse );
}
final String backwardCompatible = <API key>( xquery, XQueryContext.<API key> );
if( ( backwardCompatible != null ) && ( backwardCompatible.length() > 0 ) ) {
config.put( XQueryContext.<API key>, backwardCompatible );
LOG.debug( XQueryContext.<API key> + ": " + config.get( XQueryContext.<API key> ) );
}
final String <API key> = <API key>( xquery, XQueryContext.<API key> );
config.put( XQueryContext.<API key>, Configuration.parseBoolean( <API key>, XQueryContext.<API key> ) );
LOG.debug( XQueryContext.<API key> + ": " + config.get( XQueryContext.<API key> ) );
final String trace = <API key>( xquery, PerformanceStats.CONFIG_ATTR_TRACE );
config.put( PerformanceStats.<API key>, trace );
// built-in-modules
final Map<String, Class<?>> classMap = new HashMap<>();
final Map<String, String> knownMappings = new HashMap<>();
final Map<String, Map<String, List<? extends Object>>> moduleParameters = new HashMap<>();
loadModuleClasses(xquery, classMap, knownMappings, moduleParameters);
config.put( XQueryContext.<API key>, classMap);
config.put( XQueryContext.<API key>, knownMappings);
config.put( XQueryContext.<API key>, moduleParameters);
}
/**
* Read list of built-in modules from the configuration. This method will only make sure
* that the specified module class exists and is a subclass of {@link org.exist.xquery.Module}.
*
* @param xquery configuration root
* @param modulesClassMap map containing all classes of modules
* @param modulesSourceMap map containing all source uris to external resources
*
* @throws <API key>
*/
private void loadModuleClasses( Element xquery, Map<String, Class<?>> modulesClassMap, Map<String, String> modulesSourceMap, Map<String, Map<String, List<? extends Object>>> moduleParameters) throws <API key> {
// add the standard function module
modulesClassMap.put(Namespaces.XPATH_FUNCTIONS_NS, org.exist.xquery.functions.fn.FnModule.class);
// add other modules specified in configuration
final NodeList builtins = xquery.<API key>(<API key>);
// search under <builtin-modules>
if(builtins.getLength() > 0) {
Element elem = (Element)builtins.item(0);
final NodeList modules = elem.<API key>(<API key>);
if(modules.getLength() > 0) {
// iterate over all <module src= uri= class=> entries
for(int i = 0; i < modules.getLength(); i++) {
// Get element.
elem = (Element)modules.item(i);
// Get attributes uri class and src
final String uri = elem.getAttribute(XQueryContext.<API key>);
final String clazz = elem.getAttribute(XQueryContext.<API key>);
final String source = elem.getAttribute(XQueryContext.<API key>);
// uri attribute is the identifier and is always required
if(uri == null) {
throw(new <API key>("element 'module' requires an attribute 'uri'" ));
}
// either class or source attribute must be present
if((clazz == null) && (source == null)) {
throw(new <API key>("element 'module' requires either an attribute " + "'class' or 'src'" ));
}
if(source != null) {
// Store src attribute info
modulesSourceMap.put(uri, source);
if(LOG.isDebugEnabled()) {
LOG.debug( "Registered mapping for module '" + uri + "' to '" + source + "'");
}
} else {
// source class attribute info
// Get class of module
final Class<?> moduleClass = lookupModuleClass(uri, clazz);
// Store class if thw module class actually exists
if( moduleClass != null) {
modulesClassMap.put(uri, moduleClass);
}
if(LOG.isDebugEnabled()) {
LOG.debug("Configured module '" + uri + "' implemented in '" + clazz + "'");
}
}
//parse any module parameters
moduleParameters.put(uri, ParametersExtractor.extract(elem.<API key>(ParametersExtractor.<API key>)));
}
}
}
}
/**
* Returns the Class object associated with the with the given module class name. All
* important exceptions are caught. @see org.exist.xquery.Module
*
* @param uri namespace of class. For logging purposes only.
* @param clazz the fully qualified name of the desired module class.
* @return the module Class object for the module with the specified name.
* @throws <API key> if the given module class is not an instance
* of org.exist.xquery.Module
*/
private Class<?> lookupModuleClass(String uri, String clazz) throws <API key>
{
Class<?> mClass = null;
try {
mClass = Class.forName( clazz );
if( !( Module.class.isAssignableFrom( mClass ) ) ) {
throw( new <API key>( "Failed to load module: " + uri
+ ". Class " + clazz + " is not an instance of org.exist.xquery.Module." ) );
}
} catch( final <API key> e ) {
// Note: can't throw an exception here since this would create
// problems with test cases and jar dependencies
LOG.error( "Configuration problem: class not found for module '" + uri
+ "' (<API key>); class:'" + clazz
+ "'; message:'" + e.getMessage() + "'");
} catch( final <API key> e ) {
LOG.error( "Module " + uri + " could not be initialized due to a missing "
+ "dependancy (<API key>): " + e.getMessage(), e );
}
return mClass;
}
/**
* DOCUMENT ME!
*
* @param xupdate
*
* @throws <API key>
*/
private void configureXUpdate( Element xupdate ) throws <API key>
{
final String fragmentation = <API key>( xupdate, DBBroker.<API key> );
if( fragmentation != null ) {
config.put( DBBroker.<API key>, Integer.valueOf(fragmentation) );
LOG.debug( DBBroker.<API key> + ": " + config.get( DBBroker.<API key> ) );
}
final String consistencyCheck = <API key>( xupdate, DBBroker.<API key> );
if( consistencyCheck != null ) {
config.put( DBBroker.<API key>, parseBoolean( consistencyCheck, false ) );
LOG.debug( DBBroker.<API key> + ": " + config.get( DBBroker.<API key> ) );
}
}
private void <API key>( Element transformer )
{
final String className = <API key>( transformer, <API key>.<API key> );
if( className != null ) {
config.put( <API key>.<API key>, className );
LOG.debug( <API key>.<API key> + ": " + config.get( <API key>.<API key> ) );
// Process any specified attributes that should be passed to the transformer factory
final NodeList attrs = transformer.<API key>( <API key>.<API key> );
final Hashtable<Object, Object> attributes = new Properties();
for( int a = 0; a < attrs.getLength(); a++ ) {
final Element attr = (Element)attrs.item( a );
final String name = attr.getAttribute( "name" );
final String value = attr.getAttribute( "value" );
final String type = attr.getAttribute( "type" );
if( ( name == null ) || ( name.length() == 0 ) ) {
LOG.warn( "Discarded invalid attribute for TransformerFactory: '" + className + "', name not specified" );
} else if( ( type == null ) || ( type.length() == 0 ) || type.equalsIgnoreCase( "string" ) ) {
attributes.put( name, value );
} else if( type.equalsIgnoreCase( "boolean" ) ) {
attributes.put( name, Boolean.valueOf( value ) );
} else if( type.equalsIgnoreCase( "integer" ) ) {
try {
attributes.put( name, Integer.valueOf( value ) );
}
catch( final <API key> nfe ) {
LOG.warn("Discarded invalid attribute for TransformerFactory: '" + className + "', name: " + name + ", value not integer: " + value, nfe);
}
} else {
// Assume string type
attributes.put( name, value );
}
}
config.put( <API key>.<API key>, attributes );
}
final String cachingValue = <API key>( transformer, <API key>.<API key> );
if( cachingValue != null ) {
config.put( <API key>.<API key>, parseBoolean( cachingValue, false ) );
LOG.debug( <API key>.<API key> + ": " + config.get( <API key>.<API key> ) );
}
}
private void configureParser(final Element parser) {
configureXmlParser(parser);
<API key>(parser);
}
private void configureXmlParser(final Element parser) {
final NodeList nlXml = parser.<API key>(XMLReaderPool.XmlParser.XML_PARSER_ELEMENT);
if(nlXml.getLength() > 0) {
final Element xml = (Element)nlXml.item(0);
final NodeList nlFeatures = xml.<API key>(XMLReaderPool.XmlParser.<API key>);
if(nlFeatures.getLength() > 0) {
final Properties pFeatures = ParametersExtractor.parseFeatures(nlFeatures.item(0));
if(pFeatures != null) {
final Map<String, Boolean> features = new HashMap<>();
pFeatures.forEach((k,v) -> features.put(k.toString(), Boolean.valueOf(v.toString())));
config.put(XMLReaderPool.XmlParser.<API key>, features);
}
}
}
}
private void <API key>(final Element parser) {
final NodeList nlHtmlToXml = parser.<API key>(HtmlToXmlParser.<API key>);
if(nlHtmlToXml.getLength() > 0) {
final Element htmlToXml = (Element)nlHtmlToXml.item(0);
final String <API key> = <API key>(htmlToXml, HtmlToXmlParser.<API key>);
config.put(HtmlToXmlParser.<API key>, <API key>);
final NodeList nlProperties = htmlToXml.<API key>(HtmlToXmlParser.<API key>);
if(nlProperties.getLength() > 0) {
final Properties pProperties = ParametersExtractor.parseProperties(nlProperties.item(0));
if(pProperties != null) {
final Map<String, Object> properties = new HashMap<>();
pProperties.forEach((k,v) -> properties.put(k.toString(), v));
config.put(HtmlToXmlParser.<API key>, properties);
}
}
final NodeList nlFeatures = htmlToXml.<API key>(HtmlToXmlParser.<API key>);
if(nlFeatures.getLength() > 0) {
final Properties pFeatures = ParametersExtractor.parseFeatures(nlFeatures.item(0));
if(pFeatures != null) {
final Map<String, Boolean> features = new HashMap<>();
pFeatures.forEach((k,v) -> features.put(k.toString(), Boolean.valueOf(v.toString())));
config.put(HtmlToXmlParser.<API key>, features);
}
}
}
}
/**
* DOCUMENT ME!
*
* @param serializer
*/
private void configureSerializer( Element serializer )
{
final String xinclude = <API key>( serializer, Serializer.<API key> );
if( xinclude != null ) {
config.put( Serializer.<API key>, xinclude );
LOG.debug( Serializer.<API key> + ": " + config.get( Serializer.<API key> ) );
}
final String xsl = <API key>( serializer, Serializer.<API key> );
if( xsl != null ) {
config.put( Serializer.PROPERTY_ENABLE_XSL, xsl );
LOG.debug( Serializer.PROPERTY_ENABLE_XSL + ": " + config.get( Serializer.PROPERTY_ENABLE_XSL ) );
}
final String indent = <API key>( serializer, Serializer.INDENT_ATTRIBUTE );
if( indent != null ) {
config.put( Serializer.PROPERTY_INDENT, indent );
LOG.debug( Serializer.PROPERTY_INDENT + ": " + config.get( Serializer.PROPERTY_INDENT ) );
}
final String compress = <API key>( serializer, Serializer.<API key> );
if( compress != null ) {
config.put( Serializer.<API key>, compress );
LOG.debug( Serializer.<API key> + ": " + config.get( Serializer.<API key> ) );
}
final String internalId = <API key>( serializer, Serializer.<API key> );
if( internalId != null ) {
config.put( Serializer.<API key>, internalId );
LOG.debug( Serializer.<API key> + ": " + config.get( Serializer.<API key> ) );
}
final String tagElementMatches = <API key>( serializer, Serializer.<API key> );
if( tagElementMatches != null ) {
config.put( Serializer.<API key>, tagElementMatches );
LOG.debug( Serializer.<API key> + ": " + config.get( Serializer.<API key> ) );
}
final String tagAttributeMatches = <API key>( serializer, Serializer.<API key> );
if( tagAttributeMatches != null ) {
config.put( Serializer.<API key>, tagAttributeMatches );
LOG.debug( Serializer.<API key> + ": " + config.get( Serializer.<API key> ) );
}
final NodeList nlFilters = serializer.<API key>( <API key>.<API key> );
if( nlFilters != null ) {
final List<String> filters = new ArrayList<>(nlFilters.getLength());
for (int i = 0; i < nlFilters.getLength(); i++) {
final Element filterElem = (Element) nlFilters.item(i);
final String filterClass = filterElem.getAttribute(<API key>.<API key>);
if (filterClass != null) {
filters.add(filterClass);
LOG.debug(<API key>.<API key> + ": " + filterClass);
} else {
LOG.warn("Configuration element " + <API key>.<API key> + " needs an attribute 'class'");
}
}
config.put(<API key>.<API key>, filters);
}
final NodeList backupFilters = serializer.<API key>( SystemExport.<API key> );
if( backupFilters != null ) {
final List<String> filters = new ArrayList<>(backupFilters.getLength());
for (int i = 0; i < backupFilters.getLength(); i++) {
final Element filterElem = (Element) backupFilters.item(i);
final String filterClass = filterElem.getAttribute(<API key>.<API key>);
if (filterClass != null) {
filters.add(filterClass);
LOG.debug(<API key>.<API key> + ": " + filterClass);
} else {
LOG.warn("Configuration element " + SystemExport.<API key> + " needs an attribute 'class'");
}
}
if (!filters.isEmpty()) config.put(SystemExport.CONFIG_FILTERS, filters);
}
}
/**
* Reads the scheduler configuration.
*
* @param scheduler DOCUMENT ME!
*/
private void configureScheduler(final Element scheduler)
{
final NodeList nlJobs = scheduler.<API key>(JobConfig.<API key>);
if(nlJobs == null) {
return;
}
final List<JobConfig> jobList = new ArrayList<>();
for(int i = 0; i < nlJobs.getLength(); i++) {
final Element job = (Element)nlJobs.item( i );
//get the job type
final String strJobType = <API key>(job, JobConfig.JOB_TYPE_ATTRIBUTE);
final JobType jobType;
if(strJobType == null) {
jobType = JobType.USER; //default to user if unspecified
} else {
jobType = JobType.valueOf(strJobType.toUpperCase(Locale.ENGLISH));
}
final String jobName = <API key>(job, JobConfig.JOB_NAME_ATTRIBUTE);
//get the job resource
String jobResource = <API key>(job, JobConfig.JOB_CLASS_ATTRIBUTE);
if(jobResource == null) {
jobResource = <API key>(job, JobConfig.<API key>);
}
//get the job schedule
String jobSchedule = <API key>(job, JobConfig.<API key>);
if(jobSchedule == null) {
jobSchedule = <API key>(job, JobConfig.<API key>);
}
final String jobUnschedule = <API key>(job, JobConfig.<API key>);
//create the job config
try {
final JobConfig jobConfig = new JobConfig(jobType, jobName, jobResource, jobSchedule, jobUnschedule);
//get and set the job delay
final String jobDelay = <API key>(job, JobConfig.JOB_DELAY_ATTRIBUTE);
if((jobDelay != null) && (jobDelay.length() > 0)) {
jobConfig.setDelay(Long.parseLong(jobDelay));
}
//get and set the job repeat
final String jobRepeat = <API key>(job, JobConfig.<API key>);
if((jobRepeat != null) && (jobRepeat.length() > 0)) {
jobConfig.setRepeat(Integer.parseInt(jobRepeat));
}
final NodeList nlParam = job.<API key>(ParametersExtractor.<API key>);
final Map<String, List<? extends Object>> params = ParametersExtractor.extract(nlParam);
for(final Entry<String, List<? extends Object>> param : params.entrySet()) {
final List<? extends Object> values = param.getValue();
if(values != null && values.size() > 0) {
jobConfig.addParameter(param.getKey(), values.get(0).toString());
if(values.size() > 1) {
LOG.warn("Parameter '" + param.getKey() + "' for job '" + jobName + "' has more than one value, ignoring further values.");
}
}
}
jobList.add(jobConfig);
LOG.debug("Configured scheduled '" + jobType + "' job '" + jobResource + ((jobSchedule == null) ? "" : ("' with trigger '" + jobSchedule)) + ((jobDelay == null) ? "" : ("' with delay '" + jobDelay)) + ((jobRepeat == null) ? "" : ("' repetitions '" + jobRepeat)) + "'");
} catch(final JobException je) {
LOG.error(je);
}
}
if(jobList.size() > 0 ) {
final JobConfig[] configs = new JobConfig[jobList.size()];
for(int i = 0; i < jobList.size(); i++) {
configs[i] = (JobConfig)jobList.get(i);
}
config.put(JobConfig.<API key>, configs);
}
}
/**
* DOCUMENT ME!
*
* @param dbHome
* @param con
*
* @throws <API key>
*/
private void configureBackend( final Optional<Path> dbHome, Element con ) throws <API key>
{
final String database = <API key>(con, BrokerFactory.PROPERTY_DATABASE);
if (database != null) {
config.put(BrokerFactory.PROPERTY_DATABASE, database);
LOG.debug(BrokerFactory.PROPERTY_DATABASE + ": " + config.get(BrokerFactory.PROPERTY_DATABASE));
}
// directory for database files
final String dataFiles = <API key>( con, BrokerPool.DATA_DIR_ATTRIBUTE );
if (dataFiles != null) {
final Path df = ConfigurationHelper.lookup( dataFiles, dbHome );
if (!Files.isReadable(df)) {
try {
Files.createDirectories(df);
} catch (final IOException ioe) {
throw new <API key>("cannot read data directory: " + df.toAbsolutePath().toString(), ioe);
}
}
config.put(BrokerPool.PROPERTY_DATA_DIR, df.toAbsolutePath());
LOG.debug(BrokerPool.PROPERTY_DATA_DIR + ": " + config.get(BrokerPool.PROPERTY_DATA_DIR));
}
String cacheMem = <API key>( con, DefaultCacheManager.<API key> );
if( cacheMem != null ) {
if( cacheMem.endsWith( "M" ) || cacheMem.endsWith( "m" ) ) {
cacheMem = cacheMem.substring( 0, cacheMem.length() - 1 );
}
try {
config.put( DefaultCacheManager.PROPERTY_CACHE_SIZE, Integer.valueOf(cacheMem) );
LOG.debug( DefaultCacheManager.PROPERTY_CACHE_SIZE + ": " + config.get( DefaultCacheManager.PROPERTY_CACHE_SIZE ) + "m" );
}
catch( final <API key> nfe ) {
LOG.warn("Cannot convert " + DefaultCacheManager.PROPERTY_CACHE_SIZE + " value to integer: " + cacheMem, nfe);
}
}
// Process the Check Max Cache value
String checkMaxCache = <API key>( con, DefaultCacheManager.<API key> );
if( checkMaxCache == null ) {
checkMaxCache = DefaultCacheManager.<API key>;
}
config.put( DefaultCacheManager.<API key>, parseBoolean( checkMaxCache, true ) );
LOG.debug( DefaultCacheManager.<API key> + ": " + config.get( DefaultCacheManager.<API key> ) );
String <API key> = <API key>( con, DefaultCacheManager.<API key> );
if( <API key> == null ) {
<API key> = DefaultCacheManager.<API key>;
}
try {
config.put(DefaultCacheManager.<API key>, Integer.valueOf(<API key>));
LOG.debug(DefaultCacheManager.<API key> + ": " + config.get(DefaultCacheManager.<API key>));
} catch(final <API key> nfe) {
LOG.warn("Cannot convert " + DefaultCacheManager.<API key> + " value to integer: " + <API key>, nfe);
}
String collectionCache = <API key>(con, CollectionCache.<API key>);
if(collectionCache != null) {
collectionCache = collectionCache.toLowerCase();
try {
final int <API key>;
if(collectionCache.endsWith("k")) {
<API key> = 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 1));
} else if(collectionCache.endsWith("kb")) {
<API key> = 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 2));
} else if(collectionCache.endsWith("m")) {
<API key> = 1024 * 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 1));
} else if(collectionCache.endsWith("mb")) {
<API key> = 1024 * 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 2));
} else if(collectionCache.endsWith("g")) {
<API key> = 1024 * 1024 * 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 1));
} else if(collectionCache.endsWith("gb")) {
<API key> = 1024 * 1024 * 1024 * Integer.parseInt(collectionCache.substring(0, collectionCache.length() - 2));
} else {
<API key> = Integer.parseInt(collectionCache);
}
config.put(CollectionCache.<API key>, <API key>);
if(LOG.isDebugEnabled()) {
LOG.debug("Set config {} = {}", CollectionCache.<API key>, config.get(CollectionCache.<API key>));
}
}
catch( final <API key> nfe ) {
LOG.warn("Cannot convert " + CollectionCache.<API key> + " value to integer: " + collectionCache, nfe);
}
}
final String pageSize = <API key>( con, NativeBroker.PAGE_SIZE_ATTRIBUTE );
if( pageSize != null ) {
try {
config.put( BrokerPool.PROPERTY_PAGE_SIZE, Integer.valueOf(pageSize) );
LOG.debug( BrokerPool.PROPERTY_PAGE_SIZE + ": " + config.get( BrokerPool.PROPERTY_PAGE_SIZE ) );
}
catch( final <API key> nfe ) {
LOG.warn("Cannot convert " + BrokerPool.PROPERTY_PAGE_SIZE + " value to integer: " + pageSize, nfe);
}
}
//Not clear : rather looks like a buffers count
final String collCacheSize = <API key>( con, BrokerPool.<API key> );
if( collCacheSize != null ) {
try {
config.put( BrokerPool.<API key>, Integer.valueOf(collCacheSize) );
LOG.debug( BrokerPool.<API key> + ": " + config.get( BrokerPool.<API key> ) );
}
catch( final <API key> nfe ) {
LOG.warn("Cannot convert " + BrokerPool.<API key> + " value to integer: " + collCacheSize, nfe);
}
}
final String nodesBuffer = <API key>( con, BrokerPool.<API key> );
if( nodesBuffer != null ) {
try {
config.put( BrokerPool.<API key>, Integer.valueOf(nodesBuffer) );
LOG.debug( BrokerPool.<API key> + ": " + config.get( BrokerPool.<API key> ) );
}
catch( final <API key> nfe ) {
LOG.warn("Cannot convert " + BrokerPool.<API key> + " value to integer: " + nodesBuffer, nfe);
}
}
String diskSpace = <API key>(con, BrokerPool.<API key>);
if( diskSpace != null ) {
if( diskSpace.endsWith( "M" ) || diskSpace.endsWith( "m" ) ) {
diskSpace = diskSpace.substring( 0, diskSpace.length() - 1 );
}
try {
config.put(BrokerPool.<API key>, Short.valueOf(diskSpace));
}
catch( final <API key> nfe ) {
LOG.warn("Cannot convert " + BrokerPool.<API key> + " value to integer: " + diskSpace, nfe);
}
}
final String <API key> = <API key>(con, DBBroker.<API key>);
final boolean <API key>;
if(<API key> == null) {
<API key> = true; // default
} else {
if(Boolean.parseBoolean(<API key>)) {
<API key> = true;
} else {
// configuration explicitly specifies that posix chown should NOT be restricted
<API key> = false;
}
}
config.put(DBBroker.<API key>, <API key>);
final String preserveOnCopyStr = <API key>(con, DBBroker.<API key>);
final DBBroker.PreserveType preserveOnCopy;
if(preserveOnCopyStr == null) {
preserveOnCopy = DBBroker.PreserveType.NO_PRESERVE; // default
} else {
if(Boolean.parseBoolean(preserveOnCopyStr)) {
// configuration explicitly specifies that attributes should be preserved on copy
preserveOnCopy = DBBroker.PreserveType.PRESERVE;
} else {
preserveOnCopy = DBBroker.PreserveType.NO_PRESERVE;
}
}
config.put(DBBroker.<API key>, preserveOnCopy);
final NodeList startupConf = con.<API key>(BrokerPool.<API key>);
if(startupConf.getLength() > 0) {
configureStartup((Element)startupConf.item(0));
} else {
// Prevent NPE
final List<<API key>> startupTriggers = new ArrayList<>();
config.put(BrokerPool.<API key>, startupTriggers);
}
final NodeList poolConf = con.<API key>( BrokerPool.<API key> );
if( poolConf.getLength() > 0 ) {
configurePool( (Element)poolConf.item( 0 ) );
}
final NodeList queryPoolConf = con.<API key>( XQueryPool.<API key> );
if( queryPoolConf.getLength() > 0 ) {
configureXQueryPool( (Element)queryPoolConf.item( 0 ) );
}
final NodeList watchConf = con.<API key>( XQueryWatchDog.<API key> );
if( watchConf.getLength() > 0 ) {
configureWatchdog( (Element)watchConf.item( 0 ) );
}
final NodeList recoveries = con.<API key>( BrokerPool.<API key> );
if( recoveries.getLength() > 0 ) {
configureRecovery( dbHome, (Element)recoveries.item( 0 ) );
}
}
private void configureRecovery( final Optional<Path> dbHome, Element recovery ) throws <API key>
{
String option = <API key>( recovery, BrokerPool.<API key> );
setProperty( BrokerPool.<API key>, parseBoolean( option, true ) );
LOG.debug( BrokerPool.<API key> + ": " + config.get( BrokerPool.<API key> ) );
option = <API key>( recovery, Journal.<API key> );
setProperty( Journal.<API key>, parseBoolean( option, true ) );
LOG.debug( Journal.<API key> + ": " + config.get( Journal.<API key> ) );
option = <API key>( recovery, BrokerPool.<API key> );
setProperty( BrokerPool.<API key>, parseBoolean( option, false ) );
LOG.debug( BrokerPool.<API key> + ": " + config.get( BrokerPool.<API key> ) );
option = <API key>( recovery, Journal.<API key> );
if(option != null) {
//DWES
final Path rf = ConfigurationHelper.lookup( option, dbHome );
if(!Files.isReadable(rf)) {
throw new <API key>( "cannot read data directory: " + rf.toAbsolutePath());
}
setProperty(Journal.<API key>, rf.toAbsolutePath());
LOG.debug(Journal.<API key> + ": " + config.get(Journal.<API key>));
}
option = <API key>( recovery, Journal.<API key> );
if( option != null ) {
if( option.endsWith( "M" ) || option.endsWith( "m" ) ) {
option = option.substring( 0, option.length() - 1 );
}
try {
final Integer size = Integer.valueOf( option );
setProperty( Journal.<API key>, size );
LOG.debug( Journal.<API key> + ": " + config.get( Journal.<API key> ) + "m" );
}
catch( final <API key> e ) {
throw( new <API key>( "size attribute in recovery section needs to be a number" ) );
}
}
option = <API key>( recovery, BrokerPool.<API key> );
boolean value = false;
if( option != null ) {
value = "yes".equals(option);
}
setProperty( BrokerPool.<API key>, value);
LOG.debug( BrokerPool.<API key> + ": " + config.get( BrokerPool.<API key> ) );
option = <API key>( recovery, BrokerPool.<API key> );
value = false;
if( option != null ) {
value = "yes".equals(option);
}
setProperty( BrokerPool.<API key>, value);
LOG.debug( BrokerPool.<API key> + ": " + config.get( BrokerPool.<API key> ) );
}
/**
* DOCUMENT ME!
*
* @param watchDog
*/
private void configureWatchdog( Element watchDog )
{
final String timeout = <API key>( watchDog, "query-timeout" );
if( timeout != null ) {
try {
config.put( XQueryWatchDog.<API key>, Long.valueOf(timeout) );
LOG.debug( XQueryWatchDog.<API key> + ": " + config.get( XQueryWatchDog.<API key> ) );
}
catch( final <API key> e ) {
LOG.warn( e );
}
}
final String maxOutput = <API key>( watchDog, "output-size-limit" );
if( maxOutput != null ) {
try {
config.put( XQueryWatchDog.<API key>, Integer.valueOf(maxOutput) );
LOG.debug( XQueryWatchDog.<API key> + ": " + config.get( XQueryWatchDog.<API key> ) );
}
catch( final <API key> e ) {
LOG.warn( e );
}
}
}
/**
* DOCUMENT ME!
*
* @param queryPool
*/
private void configureXQueryPool( Element queryPool )
{
final String maxStackSize = <API key>( queryPool, XQueryPool.<API key> );
if( maxStackSize != null ) {
try {
config.put( XQueryPool.<API key>, Integer.valueOf(maxStackSize) );
LOG.debug( XQueryPool.<API key> + ": " + config.get( XQueryPool.<API key> ) );
}
catch( final <API key> e ) {
LOG.warn( e );
}
}
final String maxPoolSize = <API key>( queryPool, XQueryPool.<API key> );
if( maxPoolSize != null ) {
try {
config.put( XQueryPool.PROPERTY_POOL_SIZE, Integer.valueOf(maxPoolSize) );
LOG.debug( XQueryPool.PROPERTY_POOL_SIZE + ": " + config.get( XQueryPool.PROPERTY_POOL_SIZE ) );
}
catch( final <API key> e ) {
LOG.warn( e );
}
}
final String timeout = <API key>( queryPool, XQueryPool.TIMEOUT_ATTRIBUTE );
if( timeout != null ) {
try {
config.put( XQueryPool.PROPERTY_TIMEOUT, Long.valueOf(timeout) );
LOG.debug( XQueryPool.PROPERTY_TIMEOUT + ": " + config.get( XQueryPool.PROPERTY_TIMEOUT ) );
}
catch( final <API key> e ) {
LOG.warn( e );
}
}
}
public static class <API key> {
private final String clazz;
private final Map<String, List<? extends Object>> params;
public <API key>(final String clazz, final Map<String, List<? extends Object>> params) {
this.clazz = clazz;
this.params = params;
}
public String getClazz() {
return clazz;
}
public Map<String, List<? extends Object>> getParams() {
return params;
}
}
private void configureStartup(final Element startup) {
// Retrieve <triggers>
final NodeList nlTriggers = startup.<API key>("triggers");
// If <triggers> exists
if(nlTriggers != null && nlTriggers.getLength() > 0) {
// Get <triggers>
final Element triggers = (Element)nlTriggers.item(0);
// Get <trigger>
final NodeList nlTrigger = triggers.<API key>("trigger");
// If <trigger> exists and there are more than 0
if(nlTrigger != null && nlTrigger.getLength() > 0) {
// Initialize trigger configuration
List<<API key>> startupTriggers = (List<<API key>>)config.get(BrokerPool.<API key>);
if(startupTriggers == null) {
startupTriggers = new ArrayList<>();
config.put(BrokerPool.<API key>, startupTriggers);
}
// Iterate over <trigger> elements
for(int i = 0; i < nlTrigger.getLength(); i++) {
// Get <trigger> element
final Element trigger = (Element)nlTrigger.item(i);
// Get @class
final String startupTriggerClass = trigger.getAttribute("class");
boolean isStartupTrigger = false;
try {
// Verify if class is StartupTrigger
for(final Class iface : Class.forName(startupTriggerClass).getInterfaces()) {
if("org.exist.storage.StartupTrigger".equals(iface.getName())) {
isStartupTrigger = true;
break;
}
}
// if it actually is a StartupTrigger
if(isStartupTrigger) {
// Parse additional parameters
final Map<String, List<? extends Object>> params
= ParametersExtractor.extract(trigger.<API key>(ParametersExtractor.<API key>));
// Register trigger
startupTriggers.add(new <API key>(startupTriggerClass, params));
// Done
LOG.info("Registered StartupTrigger: " + startupTriggerClass);
} else {
LOG.warn("StartupTrigger: " + startupTriggerClass + " does not implement org.exist.storage.StartupTrigger. IGNORING!");
}
} catch(final <API key> cnfe) {
LOG.error("Could not find StartupTrigger class: " + startupTriggerClass + ". " + cnfe.getMessage(), cnfe);
}
}
}
}
}
/**
* DOCUMENT ME!
*
* @param pool
*/
private void configurePool( Element pool )
{
final String min = <API key>( pool, BrokerPool.<API key> );
if( min != null ) {
try {
config.put( BrokerPool.<API key>, Integer.valueOf(min) );
LOG.debug( BrokerPool.<API key> + ": " + config.get( BrokerPool.<API key> ) );
}
catch( final <API key> e ) {
LOG.warn( e );
}
}
final String max = <API key>( pool, BrokerPool.<API key> );
if( max != null ) {
try {
config.put( BrokerPool.<API key>, Integer.valueOf(max) );
LOG.debug( BrokerPool.<API key> + ": " + config.get( BrokerPool.<API key> ) );
}
catch( final <API key> e ) {
LOG.warn( e );
}
}
final String sync = <API key>( pool, BrokerPool.<API key> );
if( sync != null ) {
try {
config.put( BrokerPool.<API key>, Long.valueOf(sync) );
LOG.debug( BrokerPool.<API key> + ": " + config.get( BrokerPool.<API key> ) );
}
catch( final <API key> e ) {
LOG.warn( e );
}
}
final String maxShutdownWait = <API key>( pool, BrokerPool.<API key> );
if( maxShutdownWait != null ) {
try {
config.put( BrokerPool.<API key>, Long.valueOf(maxShutdownWait) );
LOG.debug( BrokerPool.<API key> + ": " + config.get( BrokerPool.<API key> ) );
}
catch( final <API key> e ) {
LOG.warn( e );
}
}
}
private void configureIndexer( final Optional<Path> dbHome, Document doc, Element indexer ) throws <API key>, <API key>
{
final String caseSensitive = <API key>( indexer, NativeValueIndex.<API key> );
if( caseSensitive != null ) {
config.put( NativeValueIndex.<API key>, parseBoolean( caseSensitive, false ) );
LOG.debug( NativeValueIndex.<API key> + ": " + config.get( NativeValueIndex.<API key> ) );
}
int depth = 3;
final String indexDepth = <API key>( indexer, NativeBroker.<API key> );
if( indexDepth != null ) {
try {
depth = Integer.parseInt( indexDepth );
if( depth < 3 ) {
LOG.warn( "parameter index-depth should be >= 3 or you will experience a severe " + "performance loss for node updates (XUpdate or XQuery update extensions)" );
depth = 3;
}
config.put( NativeBroker.<API key>, depth);
LOG.debug( NativeBroker.<API key> + ": " + config.get( NativeBroker.<API key> ) );
}
catch( final <API key> e ) {
LOG.warn( e );
}
}
final String suppressWS = <API key>( indexer, Indexer.<API key> );
if( suppressWS != null ) {
config.put( Indexer.<API key>, suppressWS );
LOG.debug( Indexer.<API key> + ": " + config.get( Indexer.<API key> ) );
}
final String suppressWSmixed = <API key>( indexer, Indexer.<API key> );
if( suppressWSmixed != null ) {
config.put( Indexer.<API key>, parseBoolean( suppressWSmixed, false ) );
LOG.debug( Indexer.<API key> + ": " + config.get( Indexer.<API key> ) );
}
// index settings
final NodeList cl = doc.<API key>( Indexer.<API key> );
if( cl.getLength() > 0 ) {
final Element elem = (Element)cl.item( 0 );
final IndexSpec spec = new IndexSpec( null, elem );
config.put( Indexer.<API key>, spec );
//LOG.debug(Indexer.<API key> + ": " + config.get(Indexer.<API key>));
}
// index modules
NodeList modules = indexer.<API key>( IndexManager.<API key> );
if( modules.getLength() > 0 ) {
modules = ( (Element)modules.item( 0 ) ).<API key>( IndexManager.<API key> );
final IndexModuleConfig[] modConfig = new IndexModuleConfig[modules.getLength()];
for( int i = 0; i < modules.getLength(); i++ ) {
final Element elem = (Element)modules.item( i );
final String className = elem.getAttribute( IndexManager.<API key> );
final String id = elem.getAttribute( IndexManager.<API key> );
if( ( className == null ) || ( className.length() == 0 ) ) {
throw( new <API key>( "Required attribute class is missing for module" ) );
}
if( ( id == null ) || ( id.length() == 0 ) ) {
throw( new <API key>( "Required attribute id is missing for module" ) );
}
modConfig[i] = new IndexModuleConfig( id, className, elem );
}
config.put( IndexManager.<API key>, modConfig );
}
}
private void configureValidation( final Optional<Path> dbHome, Document doc, Element validation ) throws <API key>
{
// Determine validation mode
final String mode = <API key>( validation, <API key>.<API key> );
if( mode != null ) {
config.put( <API key>.<API key>, mode );
LOG.debug( <API key>.<API key> + ": " + config.get( <API key>.<API key> ) );
}
// Extract catalogs
LOG.debug( "Creating eXist catalog resolver" );
final <API key> resolver = new <API key>();
final NodeList entityResolver = validation.<API key>( <API key>.<API key> );
if( entityResolver.getLength() > 0 ) {
final Element r = (Element)entityResolver.item( 0 );
final NodeList catalogs = r.<API key>( <API key>.<API key> );
LOG.debug( "Found " + catalogs.getLength() + " catalog uri entries." );
LOG.debug( "Using dbHome=" + dbHome );
// Determine webapps directory. <API key> cannot
// be used at this phase. Trick is to check wether dbHOME is
// pointing to a WEB-INF directory, meaning inside war file)
final Path webappHome = dbHome.map(h -> {
if(FileUtils.fileName(h).endsWith("WEB-INF")) {
return h.getParent().toAbsolutePath();
} else {
return h.resolve("webapp").toAbsolutePath();
}
}).orElse(Paths.get("webapp").toAbsolutePath());
LOG.debug("using webappHome=" + webappHome.toString());
// Get and store all URIs
final List<String> allURIs = new ArrayList<>();
for( int i = 0; i < catalogs.getLength(); i++ ) {
String uri = ( (Element)catalogs.item( i ) ).getAttribute( "uri" );
if( uri != null ) { // when uri attribute is filled in
// Substitute string, creating an uri from a local file
if( uri.indexOf( "${WEBAPP_HOME}" ) != -1 ) {
uri = uri.replaceAll( "\\$\\{WEBAPP_HOME\\}", webappHome.toUri().toString() );
}
if( uri.indexOf( "${EXIST_HOME}" ) != -1 ) {
uri = uri.replaceAll( "\\$\\{EXIST_HOME\\}", dbHome.toString() );
}
// Add uri to confiuration
LOG.info( "Add catalog uri " + uri + "" );
allURIs.add( uri );
}
}
resolver.setCatalogs( allURIs );
// Store all configured URIs
config.put( <API key>.CATALOG_URIS, allURIs );
}
// Store resolver
config.put( <API key>.CATALOG_RESOLVER, resolver );
// cache
final GrammarPool gp = new GrammarPool();
config.put( <API key>.GRAMMER_POOL, gp );
}
/**
* Gets the value of a configuration attribute
*
* The value typically is specified in the conf.xml file, but can be overridden with using a System Property
*
* @param element The attribute's parent element
* @param attributeName The name of the attribute
*
* @return The value of the attribute
*/
private String <API key>( Element element, String attributeName )
{
String value = null;
if( element != null && attributeName != null ) {
final String property = <API key>( element, attributeName );
value = System.getProperty( property );
// If the value has not been overriden in a system property, then get it from the configuration
if( value != null ) {
LOG.warn( "Configuration value overridden by system property: " + property + ", with value: " + value );
} else {
value = element.getAttribute( attributeName );
}
}
return( value );
}
/**
* Generates a suitable system property name from the given config attribute and parent element.
*
* values are of the form org.element.element.....attribute and follow the heirarchical structure of the conf.xml file.
* For example, the db-connection cacheSize property name would be org.exist.db-connection.cacheSize
*
* @param element The attribute's parent element
* @param attributeName The name of the attribute
*
* @return The generated system property name
*/
private String <API key>( Element element, String attributeName )
{
final StringBuilder property = new StringBuilder( attributeName );
Node parent = element.getParentNode();
property.insert( 0, "." );
property.insert( 0, element.getLocalName() );
while( parent != null && parent instanceof Element ) {
final String parentName = ((Element)parent).getLocalName();
property.insert( 0, "." );
property.insert( 0, parentName );
parent = parent.getParentNode();
}
property.insert( 0, "org." );
return( property.toString() );
}
public Optional<Path> getConfigFilePath() {
return configFilePath;
}
public Optional<Path> getExistHome() {
return existHome;
}
public Object getProperty(final String name) {
return config.get(name);
}
public <T> T getProperty(final String name, final T defaultValue) {
return Optional.ofNullable((T)config.get(name)).orElse(defaultValue);
}
public boolean hasProperty(final String name) {
return config.containsKey(name);
}
public void setProperty(final String name, final Object obj) {
config.put(name, obj);
}
public void removeProperty(final String name) {
config.remove(name);
}
/**
* Takes the passed string and converts it to a non-null <code>Boolean</code> object. If value is null, the specified default value is used.
* Otherwise, Boolean.TRUE is returned if and only if the passed string equals "yes" or "true", ignoring case.
*
* @param value The string to parse
* @param defaultValue The default if the string is null
*
* @return The parsed <code>Boolean</code>
*/
public static boolean parseBoolean(@Nullable final String value, final boolean defaultValue) {
return Optional.ofNullable(value)
.map(v -> v.equalsIgnoreCase("yes") || v.equalsIgnoreCase("true"))
.orElse(defaultValue);
}
/**
* Takes the passed string and converts it to a non-null <code>int</code> value. If value is null, the specified default value is used.
* Otherwise, Boolean.TRUE is returned if and only if the passed string equals "yes" or "true", ignoring case.
*
* @param value The string to parse
* @param defaultValue The default if the string is null or empty
*
* @return The parsed <code>int</code>
*/
public static int parseInt(@Nullable final String value, final int defaultValue) {
if (value == null || value.isEmpty()) {
return defaultValue;
}
try {
return Integer.parseInt(value);
} catch (final <API key> e) {
LOG.warn("Could not parse: " + value + ", as an int: " + e.getMessage());
return defaultValue;
}
}
public int getInteger(final String name) {
return Optional.ofNullable(getProperty(name))
.filter(v -> v instanceof Integer)
.map(v -> (int)v)
.orElse(-1);
}
/**
* (non-Javadoc).
*
* @param exception DOCUMENT ME!
*
* @throws SAXException DOCUMENT ME!
*
* @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
*/
@Override
public void error( SAXParseException exception ) throws SAXException
{
LOG.error( "error occurred while reading configuration file " + "[line: " + exception.getLineNumber() + "]:" + exception.getMessage(), exception );
}
/**
* (non-Javadoc).
*
* @param exception DOCUMENT ME!
*
* @throws SAXException DOCUMENT ME!
*
* @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
*/
@Override
public void fatalError( SAXParseException exception ) throws SAXException
{
LOG.error("error occurred while reading configuration file " + "[line: " + exception.getLineNumber() + "]:" + exception.getMessage(), exception);
}
/**
* (non-Javadoc).
*
* @param exception DOCUMENT ME!
*
* @throws SAXException DOCUMENT ME!
*
* @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
*/
@Override
public void warning( SAXParseException exception ) throws SAXException
{
LOG.error( "error occurred while reading configuration file " + "[line: " + exception.getLineNumber() + "]:" + exception.getMessage(), exception );
}
public static final class IndexModuleConfig {
private final String id;
private final String className;
private final Element config;
public IndexModuleConfig(final String id, final String className, final Element config) {
this.id = id;
this.className = className;
this.config = config;
}
public String getId()
{
return( id );
}
public String getClassName()
{
return( className );
}
public Element getConfig()
{
return( config );
}
}
} |
#include "util.h"
#include <libavcodec/avcodec.h>
#include <libavutil/mathematics.h>
#include <gst/gst.h>
int64_t <API key>(AVCodecContext *ctx, int64_t ts)
{
AVRational bq = { 1, GST_SECOND * ctx->ticks_per_frame };
if (ts == -1)
return AV_NOPTS_VALUE;
return av_rescale_q(ts, bq, ctx->time_base);
}
int64_t <API key>(AVCodecContext *ctx, int64_t pts)
{
AVRational bq = { 1, GST_SECOND * ctx->ticks_per_frame };
if (pts == (int64_t) AV_NOPTS_VALUE)
return -1;
return av_rescale_q(pts, ctx->time_base, bq);
} |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_21) on Wed Apr 16 20:33:32 EDT 2014 -->
<title>net.minecraft.village (Forge API)</title>
<meta name="date" content="2014-04-16">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../net/minecraft/village/package-summary.html" target="classFrame">net.minecraft.village</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="MerchantRecipe.html" title="class in net.minecraft.village" target="classFrame">MerchantRecipe</a></li>
<li><a href="MerchantRecipeList.html" title="class in net.minecraft.village" target="classFrame">MerchantRecipeList</a></li>
<li><a href="Village.html" title="class in net.minecraft.village" target="classFrame">Village</a></li>
<li><a href="VillageCollection.html" title="class in net.minecraft.village" target="classFrame">VillageCollection</a></li>
<li><a href="VillageDoorInfo.html" title="class in net.minecraft.village" target="classFrame">VillageDoorInfo</a></li>
<li><a href="VillageSiege.html" title="class in net.minecraft.village" target="classFrame">VillageSiege</a></li>
</ul>
</div>
</body>
</html> |
package org.exist.xquery.functions.request;
import javax.servlet.http.Cookie;
import org.apache.log4j.Logger;
import org.exist.dom.QName;
import org.exist.http.servlets.RequestWrapper;
import org.exist.xquery.BasicFunction;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.Variable;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.<API key>;
import org.exist.xquery.value.<API key>;
import org.exist.xquery.value.JavaObjectValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.StringValue;
import org.exist.xquery.value.Type;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
/**
* @author Adam Retter (adam.retter@devon.gov.uk)
*/
public class GetCookieValue extends BasicFunction {
protected static final Logger logger = Logger.getLogger(GetCookieValue.class);
public final static FunctionSignature signature =
new FunctionSignature(
new QName(
"get-cookie-value",
RequestModule.NAMESPACE_URI,
RequestModule.PREFIX),
"Returns the value of a named Cookie.",
new SequenceType[] {
new <API key>("cookie-name", Type.STRING, Cardinality.EXACTLY_ONE, "The name of the cookie to retrieve the value from.")
},
new <API key>(Type.STRING, Cardinality.ZERO_OR_ONE, "the value of the named Cookie"));
public GetCookieValue(XQueryContext context) {
super(context, signature);
}
/* (non-Javadoc)
* @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
*/
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException
{
final RequestModule myModule = (RequestModule) context.getModule(RequestModule.NAMESPACE_URI);
// request object is read from global variable $request
final Variable var = myModule.resolveVariable(RequestModule.REQUEST_VAR);
if (var == null || var.getValue() == null || var.getValue().getItemType() != Type.JAVA_OBJECT) {
return Sequence.EMPTY_SEQUENCE;
}
// get the cookieName to match
final String cookieName = args[0].getStringValue();
final JavaObjectValue value = (JavaObjectValue) var.getValue().itemAt(0);
if (value.getObject() instanceof RequestWrapper)
{
final Cookie[] cookies = ((RequestWrapper)value.getObject()).getCookies();
if(cookies != null)
{
for(int c = 0; c < cookies.length; c++)
{
if(cookies[c].getName().equals(cookieName))
{
return new StringValue(decode(cookies[c].getValue()));
}
}
}
return Sequence.EMPTY_SEQUENCE;
}
else
{throw new XPathException(this, "Variable $request is not bound to a Request object.");}
}
// TODO: remove this hack after fixing HTTP 1.1
private String decode (String value)
{
return new String(value.getBytes(ISO_8859_1));
}
} |
package org.exist.management.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.<API key>;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import javax.management.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.<API key>;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.storage.BrokerPool;
import org.exist.util.serializer.DOMSerializer;
import org.w3c.dom.Element;
/**
* A servlet to monitor the database. It returns status information for the database based on the JMX interface. For
* simplicity, the JMX beans provided by eXist are organized into categories. One calls the servlet with one or more
* categories in parameter "c", e.g.:
* <p>
* /exist/jmx?c=instances&c=memory
* <p>
* If no parameter is specified, all categories will be returned. Valid categories are "memory", "instances", "disk",
* "system", "caches", "locking", "processes", "sanity", "all".
* <p>
* The servlet can also be used to test if the database is responsive by using parameter "operation=ping" and a timeout
* (t=<API key>). For example, the following call
* <p>
* /exist/jmx?operation=ping&t=1000
* <p>
* will wait for a response within 1000ms. If the ping returns within the specified timeout, the servlet returns the
* attributes of the SanityReport JMX bean, which will include an element <jmx:Status>PING_OK</jmx:Status>.
* If the ping takes longer than the timeout, you'll instead find an element <jmx:error> in the returned XML. In
* this case, additional information on running queries, memory consumption and database locks will be provided.
*
* @author wolf
*/
public class JMXServlet extends HttpServlet {
protected final static Logger LOG = LogManager.getLogger(JMXServlet.class);
private static final String TOKEN_KEY = "token";
private static final String TOKEN_FILE = "jmxservlet.token";
private static final String WEBINF_DATA_DIR = "WEB-INF/data";
private final static Properties defaultProperties = new Properties();
static {
defaultProperties.setProperty(OutputKeys.INDENT, "yes");
defaultProperties.setProperty(OutputKeys.<API key>, "no");
}
private JMXtoXML client;
private final Set<String> localhostAddresses = new HashSet<>();
private Path dataDir;
private Path tokenFile;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Verify if request is from localhost or if user has specific servlet/container managed role.
if (isFromLocalHost(request)) {
// Localhost is always authorized to access
LOG.debug("Local access granted");
} else if (hasSecretToken(request, getToken())) {
// Correct token is provided
LOG.debug("Correct token provided by " + request.getRemoteHost());
} else {
// Check if user is already authorized, e.g. via MONEX allow user too
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access allowed for localhost, or when correct token has been provided.");
return;
}
// Perform actual writing of data
writeXmlData(request, response);
}
private void writeXmlData(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Element root = null;
final String operation = request.getParameter("operation");
if ("ping".equals(operation)) {
long timeout = 5000;
final String timeoutParam = request.getParameter("t");
if (StringUtils.isNotBlank(timeoutParam)) {
try {
timeout = Long.parseLong(timeoutParam);
} catch (final <API key> e) {
throw new ServletException("timeout parameter needs to be a number. Got: " + timeoutParam);
}
}
final long responseTime = client.ping(BrokerPool.<API key>, timeout);
if (responseTime == JMXtoXML.PING_TIMEOUT) {
root = client.generateXMLReport(String.format("no response on ping after %sms", timeout),
new String[]{"sanity", "locking", "processes", "instances", "memory"});
} else {
root = client.generateXMLReport(null, new String[]{"sanity"});
}
} else if (operation != null && operation.length() > 0) {
final String mbean = request.getParameter("mbean");
if (mbean == null) {
throw new ServletException("to call an operation, you also need to specify parameter 'mbean'");
}
String[] args = request.getParameterValues("args");
try {
root = client.invoke(mbean, operation, args);
if (root == null) {
throw new ServletException("operation " + operation + " not found on " + mbean);
}
} catch (<API key> e) {
throw new ServletException("mbean " + mbean + " not found: " + e.getMessage(), e);
} catch (<API key> | <API key> | ReflectionException | MBeanException e) {
throw new ServletException(e.getMessage(), e);
}
} else {
String[] categories = request.getParameterValues("c");
if (categories == null) {
categories = new String[]{"all"};
}
root = client.generateXMLReport(null, categories);
}
response.setContentType("application/xml");
final Object useAttribute = request.getAttribute("jmx.attribute");
if (useAttribute != null) {
request.setAttribute(useAttribute.toString(), root);
} else {
final Writer writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
final DOMSerializer streamer = new DOMSerializer(writer, defaultProperties);
try {
streamer.serialize(root);
} catch (final <API key> e) {
LOG.error(e.<API key>());
throw new ServletException("Error while serializing result: " + e.getMessage(), e);
}
writer.flush();
}
}
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
// Setup JMS client
client = new JMXtoXML();
client.connect();
// Register all known localhost addresses
<API key>();
// Get directory for token file
final String jmxDataDir = client.getDataDir();
if (jmxDataDir == null) {
dataDir = Paths.get(config.getServletContext().getRealPath(WEBINF_DATA_DIR)).normalize();
} else {
dataDir = Paths.get(jmxDataDir).normalize();
}
if (!Files.isDirectory(dataDir) || !Files.isWritable(dataDir)) {
LOG.error("Cannot access directory " + WEBINF_DATA_DIR);
}
// Setup token and tokenfile
<API key>();
LOG.info(String.format("JMXservlet token: %s", getToken()));
}
/**
* Register all known IP-addresses for localhost.
*/
void <API key>() {
// The external IP address of the server
try {
localhostAddresses.add(InetAddress.getLocalHost().getHostAddress());
} catch (<API key> ex) {
LOG.warn(String.format("Unable to get HostAddress for localhost: %s", ex.getMessage()));
}
// The configured Localhost addresses
try {
for (InetAddress address : InetAddress.getAllByName("localhost")) {
localhostAddresses.add(address.getHostAddress());
}
} catch (<API key> ex) {
LOG.warn(String.format("Unable to retrieve ipaddresses for localhost: %s", ex.getMessage()));
}
if (localhostAddresses.isEmpty()) {
LOG.error("Unable to determine addresses for localhost, jmx servlet might be disfunctional.");
}
}
/**
* Determine if HTTP request is originated from localhost.
*
* @param request The HTTP request
* @return TRUE if request is from LOCALHOST otherwise FALSE
*/
boolean isFromLocalHost(HttpServletRequest request) {
return localhostAddresses.contains(request.getRemoteAddr());
}
/**
* Check if URL contains magic Token
*
* @param request The HTTP request
* @return TRUE if request contains correct value for token, else FALSE
*/
boolean hasSecretToken(HttpServletRequest request, String token) {
String[] tokenValue = request.getParameterValues(TOKEN_KEY);
return ArrayUtils.contains(tokenValue, token);
}
/**
* Obtain reference to token file
*/
private void <API key>() {
if (tokenFile == null) {
tokenFile = dataDir.resolve(TOKEN_FILE);
LOG.info(String.format("Token file: %s", tokenFile.toAbsolutePath().toAbsolutePath()));
}
}
/**
* Get token from file, create if not existent. Data is read for each call so the file can be updated run-time.
*
* @return Toke for servlet
*/
private String getToken() {
Properties props = new Properties();
String token = null;
// Read if possible
if (Files.exists(tokenFile)) {
try (final InputStream is = Files.newInputStream(tokenFile)) {
props.load(is);
token = props.getProperty(TOKEN_KEY);
} catch (IOException ex) {
LOG.error(ex.getMessage());
}
}
// Create and write when needed
if (!Files.exists(tokenFile) || token == null) {
// Create random token
token = UUID.randomUUID().toString();
// Set value to properties
props.setProperty(TOKEN_KEY, token);
// Write data to file
try (final OutputStream os = Files.newOutputStream(tokenFile)) {
props.store(os, "JMXservlet token: http://localhost:8080/exist/status?token=......");
} catch (IOException ex) {
LOG.error(ex.getMessage());
}
LOG.debug(String.format("Token written to file %s", tokenFile.toAbsolutePath().toString()));
}
return token;
}
} |
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <math.h>
#include <fcntl.h>
#include <oauth.h>
#define __STRICT_ANSI__
#include <json/json.h>
#include "kpfs.h"
#include "kpfs_oauth.h"
#include "kpfs_conf.h"
#define OAUTH_TOKEN_ID "oauth_token"
#define O<API key> "oauth_token_secret"
#define KPFS_USER_ID "user_id"
#define <API key> "charged_dir"
kpfs_oauth g_kpfs_oauth;
typedef struct _kpfs_user_info {
char user_id[64];
char charged_dir[KPFS_MAX_PATH];
} kpfs_user_info;
kpfs_user_info g_kpfs_user_info;
void kpfs_oauth_init()
{
memset(&g_kpfs_oauth, 0, sizeof(g_kpfs_oauth));
}
static kpfs_ret <API key>(const char *buf)
{
json_object *jobj = NULL;
if (!buf)
return KPFS_RET_FAIL;
jobj = json_tokener_parse(buf);
if (!jobj || is_error(jobj))
return KPFS_RET_FAIL;
<API key>(jobj, key, val) {
if (!strcmp(key, OAUTH_TOKEN_ID)) {
if (json_type_string == <API key>(val)) {
snprintf(g_kpfs_oauth.oauth_token, sizeof(g_kpfs_oauth.oauth_token), "%s", <API key>(val));
}
} else if (!strcmp(key, O<API key>)) {
if (json_type_string == <API key>(val)) {
snprintf(g_kpfs_oauth.oauth_token_secret, sizeof(g_kpfs_oauth.oauth_token_secret), "%s", <API key>(val));
}
} else if (!strcmp(key, KPFS_USER_ID)) {
if (json_type_int == <API key>(val)) {
snprintf(g_kpfs_user_info.user_id, sizeof(g_kpfs_user_info.user_id), "%d", json_object_get_int(val));
}
} else if (!strcmp(key, <API key>)) {
if (json_type_string == <API key>(val)) {
snprintf(g_kpfs_user_info.charged_dir, sizeof(g_kpfs_user_info.charged_dir), "%s", <API key>(val));
}
}
}
json_object_put(jobj);
return KPFS_RET_OK;
}
static kpfs_ret kpfs_o<API key>(char *file, int len)
{
if (NULL == file)
return KPFS_RET_FAIL;
snprintf(file, len, "%s", <API key>());
return KPFS_RET_OK;
}
static kpfs_ret <API key>(char *buf, int len)
{
int fd = 0;
int ret = 0;
char file[KPFS_MAX_PATH] = { 0 };
if (NULL == buf)
return KPFS_RET_FAIL;
kpfs_o<API key>(file, sizeof(file));
fd = open(file, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (-1 == fd) {
KPFS_LOG("fail to open file (%s)\n", file);
return KPFS_RET_FAIL;
}
ret = write(fd, buf, len);
if (-1 == ret) {
KPFS_LOG("fail to write file (%s)\n", file);
}
close(fd);
return KPFS_RET_OK;
}
kpfs_ret kpfs_oauth_load()
{
struct stat st;
int fd = 0;
int ret = 0;
char file[KPFS_MAX_PATH] = { 0 };
char *buf = NULL;
kpfs_o<API key>(file, sizeof(file));
if (0 != stat(file, &st)) {
return KPFS_RET_FAIL;
}
fd = open(file, O_RDONLY);
if (-1 == fd) {
KPFS_LOG("fail to open file (%s)\n", file);
return KPFS_RET_FAIL;
}
buf = calloc(st.st_size, 1);
ret = read(fd, buf, st.st_size);
if (-1 == ret) {
KPFS_LOG("fail to read file (%s)\n", file);
}
close(fd);
if (KPFS_RET_OK == <API key>(buf)) {
if (g_kpfs_oauth.oauth_token[0] != '\0') {
KPFS_LOG("success to load kpfs json from file (%s)\n", file);
KPFS_SAFE_FREE(buf);
return KPFS_RET_OK;
}
}
KPFS_LOG("could not read oauth token from (%s)\n", file);
KPFS_SAFE_FREE(buf);
return KPFS_RET_FAIL;
}
kpfs_ret <API key>()
{
const char *request_token_uri = <API key>;
char *req_url = NULL;
char *reply = NULL;
kpfs_ret ret = KPFS_RET_OK;
KPFS_LOG("request token ...\n");
req_url =
oauth_sign_url2(request_token_uri, NULL, OA_HMAC, NULL, (const char *)<API key>(),
(const char *)<API key>(), NULL, NULL);
if (!req_url) {
ret = KPFS_RET_FAIL;
goto error_out;
}
reply = oauth_http_get(req_url, NULL);
if (!reply) {
ret = KPFS_RET_FAIL;
goto error_out;
}
KPFS_LOG("response: %s\n", reply);
if (KPFS_RET_OK != <API key>(reply)) {
ret = KPFS_RET_FAIL;
goto error_out;
}
if (g_kpfs_oauth.oauth_token[0] == '\0') {
KPFS_LOG("oauth_token is incorrect.\n");
ret = KPFS_RET_FAIL;
goto error_out;
}
KPFS_LOG("oauth_token: %s\n", g_kpfs_oauth.oauth_token);
error_out:
KPFS_SAFE_FREE(req_url);
KPFS_SAFE_FREE(reply);
return ret;
}
kpfs_ret <API key>()
{
char auth_url[512] = { 0 };
char *str = NULL;
snprintf(auth_url, sizeof(auth_url), "%s&oauth_token=%s", KPFS_API_USER_AUTH, g_kpfs_oauth.oauth_token);
printf("Please open this link in your browser: \n\n%s\n\n", auth_url);
printf("And enter your ID and Password on the page to authorize\n");
printf("this application to access your kuaipan\n");
printf("Please enter the authorization number here: \n");
str = gets(g_kpfs_oauth.oauth_verifier);
KPFS_LOG("\ngets: ret %s, oauth_verifier: %s\n", str, g_kpfs_oauth.oauth_verifier);
if (g_kpfs_oauth.oauth_verifier[0] != '\0') {
return KPFS_RET_OK;
}
return KPFS_RET_FAIL;
}
kpfs_ret <API key>()
{
const char *access_token_uri = <API key>;
char *t_key = g_kpfs_oauth.oauth_token;
char *t_secret = g_kpfs_oauth.oauth_token_secret;
char *req_url = NULL;
char *reply = NULL;
kpfs_ret ret = KPFS_RET_OK;
KPFS_LOG("access token ...\n");
req_url =
oauth_sign_url2(access_token_uri, NULL, OA_HMAC, NULL, (const char *)<API key>(),
(const char *)<API key>(), t_key, t_secret);
if (!req_url) {
ret = KPFS_RET_FAIL;
goto error_out;
}
reply = oauth_http_get(req_url, NULL);
if (!reply) {
ret = KPFS_RET_FAIL;
goto error_out;
}
KPFS_LOG("response: %s\n", reply);
if (0 != <API key>(reply)) {
ret = KPFS_RET_FAIL;
goto error_out;
}
if (g_kpfs_oauth.oauth_token[0] == '\0') {
KPFS_LOG("oauth_token is incorrect.\n");
ret = KPFS_RET_FAIL;
goto error_out;
}
<API key>(reply, strlen(reply));
KPFS_LOG("oauth_token: %s\n", g_kpfs_oauth.oauth_token);
KPFS_LOG("user id: %s\n", g_kpfs_user_info.user_id);
KPFS_LOG("charged dir: %s\n", g_kpfs_user_info.charged_dir);
error_out:
KPFS_SAFE_FREE(req_url);
KPFS_SAFE_FREE(reply);
return ret;
}
char *kpfs_o<API key>()
{
return g_kpfs_oauth.oauth_token_secret;
}
char *<API key>()
{
return g_kpfs_oauth.oauth_token;
} |
package minefantasy.block;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.util.Icon;
import net.minecraftforge.common.MinecraftForge;
public class BlockMudbrick extends BlockMedieval{
public Icon[] types = new Icon[2];
public BlockMudbrick(int i)
{
super(i, Material.ground);
}
@Override
public Icon getIcon(int side, int meta)
{
return types[meta];
}
@Override
public int damageDropped(int meta)
{
return meta;
}
public void registerIcons(IconRegister reg)
{
types[0] = reg.registerIcon("MineFantasy:Basic/mudBrick");
types[1] = reg.registerIcon("MineFantasy:Basic/mudBrick_rough");
}
} |
using PWMIS.DataMap.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OQLTest
{
class UserEntity:EntityBase
{
public UserEntity()
{
TableName = "User";
//PrimaryKeys.Add("");
PrimaryKeys.Add("ID");
}
public int ID
{
get { return getProperty<int>("Id"); }
set { setProperty("Id", value); }
}
public string Name
{
get { return getProperty<string>("User Name"); }
set { setProperty("User Name", value,50); }
}
public int Age
{
get { return getProperty<int>("Age"); }
set { setProperty("Age", value); }
}
}
} |
// The LLVM Compiler Infrastructure
// This file is distributed under the University of Illinois Open Source
// This file defines the RecursiveASTVisitor interface, which recursively
// traverses the entire AST.
#ifndef <API key>
#define <API key>
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclFriend.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclOpenMP.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "clang/AST/StmtOpenMP.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/TemplateName.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeLoc.h"
// The following three macros are used for meta programming. The code
// using them is responsible for defining macro OPERATOR().
// All unary operators.
#define UNARYOP_LIST() \
OPERATOR(PostInc) OPERATOR(PostDec) \
OPERATOR(PreInc) OPERATOR(PreDec) \
OPERATOR(AddrOf) OPERATOR(Deref) \
OPERATOR(Plus) OPERATOR(Minus) \
OPERATOR(Not) OPERATOR(LNot) \
OPERATOR(Real) OPERATOR(Imag) \
OPERATOR(Extension)
// All binary operators (excluding compound assign operators).
#define BINOP_LIST() \
OPERATOR(PtrMemD) OPERATOR(PtrMemI) \
OPERATOR(Mul) OPERATOR(Div) OPERATOR(Rem) \
OPERATOR(Add) OPERATOR(Sub) OPERATOR(Shl) \
OPERATOR(Shr) \
\
OPERATOR(LT) OPERATOR(GT) OPERATOR(LE) \
OPERATOR(GE) OPERATOR(EQ) OPERATOR(NE) \
OPERATOR(And) OPERATOR(Xor) OPERATOR(Or) \
OPERATOR(LAnd) OPERATOR(LOr) \
\
OPERATOR(Assign) \
OPERATOR(Comma)
// All compound assign operators.
#define CAO_LIST() \
OPERATOR(Mul) OPERATOR(Div) OPERATOR(Rem) OPERATOR(Add) OPERATOR(Sub) \
OPERATOR(Shl) OPERATOR(Shr) OPERATOR(And) OPERATOR(Or) OPERATOR(Xor)
namespace clang {
// A helper macro to implement short-circuiting when recursing. It
// invokes CALL_EXPR, which must be a method call, on the derived
// object (s.t. a user of RecursiveASTVisitor can override the method
// in CALL_EXPR).
#define TRY_TO(CALL_EXPR) \
do { if (!getDerived().CALL_EXPR) return false; } while (0)
\brief A class that does preorder depth-first traversal on the
entire Clang AST and visits each node.
This class performs three distinct tasks:
1. traverse the AST (i.e. go to each node);
2. at a given node, walk up the class hierarchy, starting from
the node's dynamic type, until the top-most class (e.g. Stmt,
Decl, or Type) is reached.
3. given a (node, class) combination, where 'class' is some base
class of the dynamic type of 'node', call a user-overridable
function to actually visit the node.
These tasks are done by three groups of methods, respectively:
1. TraverseDecl(Decl *x) does task #1. It is the entry point
for traversing an AST rooted at x. This method simply
dispatches (i.e. forwards) to TraverseFoo(Foo *x) where Foo
is the dynamic type of *x, which calls WalkUpFromFoo(x) and
then recursively visits the child nodes of x.
TraverseStmt(Stmt *x) and TraverseType(QualType x) work
similarly.
2. WalkUpFromFoo(Foo *x) does task #2. It does not try to visit
any child node of x. Instead, it first calls WalkUpFromBar(x)
where Bar is the direct parent class of Foo (unless Foo has
no parent), and then calls VisitFoo(x) (see the next list item).
3. VisitFoo(Foo *x) does task
These three method groups are tiered (Traverse* > WalkUpFrom* >
Visit*). A method (e.g. Traverse*) may call methods from the same
tier (e.g. other Traverse*) or one tier lower (e.g. WalkUpFrom*).
It may not call methods from a higher tier.
Note that since WalkUpFromFoo() calls WalkUpFromBar() (where Bar
is Foo's super class) before calling VisitFoo(), the result is
that the Visit*() methods for a given node are called in the
top-down order (e.g. for a node of type NamespaceDecl, the order will
be VisitDecl(), VisitNamedDecl(), and then VisitNamespaceDecl()).
This scheme guarantees that all Visit*() calls for the same AST
node are grouped together. In other words, Visit*() methods for
different nodes are never interleaved.
Clients of this visitor should subclass the visitor (providing
themselves as the template argument, using the curiously recurring
template pattern) and override any of the Traverse*, WalkUpFrom*,
and Visit* methods for declarations, types, statements,
expressions, or other AST nodes where the visitor should customize
behavior. Most users only need to override Visit*. Advanced
users may override Traverse* and WalkUpFrom* to implement custom
traversal strategies. Returning false from one of these overridden
functions will abort the entire traversal.
By default, this visitor tries to visit every part of the explicit
source code exactly once. The default policy towards templates
is to descend into the 'pattern' class or function body, not any
explicit or implicit instantiations. Explicit specializations
are still visited, and the patterns of partial specializations
are visited separately. This behavior can be changed by
overriding <API key>() in the derived class
to return true, in which case all known implicit and explicit
instantiations will be visited at the same time as the pattern
from which they were produced.
template<typename Derived>
class RecursiveASTVisitor {
public:
\brief Return a reference to the derived class.
Derived &getDerived() { return *static_cast<Derived*>(this); }
\brief Return whether this visitor should recurse into
template instantiations.
bool <API key>() const { return false; }
\brief Return whether this visitor should recurse into the types of
TypeLocs.
bool <API key>() const { return true; }
\brief Return whether this visitor should recurse into implicit
code, e.g., implicit constructors and destructors.
bool <API key>() const { return false; }
\brief Return whether \param S should be traversed using data recursion
to avoid a stack overflow with extreme cases.
bool <API key>(Stmt *S) const {
return isa<BinaryOperator>(S) || isa<UnaryOperator>(S) ||
isa<CaseStmt>(S) || isa<CXXOperatorCallExpr>(S);
}
\brief Recursively visit a statement or expression, by
dispatching to Traverse*() based on the argument's dynamic type.
\returns false if the visitation was terminated early, true
otherwise (including when the argument is NULL).
bool TraverseStmt(Stmt *S);
\brief Recursively visit a type, by dispatching to
Traverse*Type() based on the argument's getTypeClass() property.
\returns false if the visitation was terminated early, true
otherwise (including when the argument is a Null type).
bool TraverseType(QualType T);
\brief Recursively visit a type with location, by dispatching to
Traverse*TypeLoc() based on the argument type's getTypeClass() property.
\returns false if the visitation was terminated early, true
otherwise (including when the argument is a Null type location).
bool TraverseTypeLoc(TypeLoc TL);
\brief Recursively visit a declaration, by dispatching to
Traverse*Decl() based on the argument's dynamic type.
\returns false if the visitation was terminated early, true
otherwise (including when the argument is NULL).
bool TraverseDecl(Decl *D);
\brief Recursively visit a C++ <API key>.
\returns false if the visitation was terminated early, true otherwise.
bool <API key>(NestedNameSpecifier *NNS);
\brief Recursively visit a C++ <API key> with location
information.
\returns false if the visitation was terminated early, true otherwise.
bool <API key>(<API key> NNS);
\brief Recursively visit a name with its location information.
\returns false if the visitation was terminated early, true otherwise.
bool <API key>(DeclarationNameInfo NameInfo);
\brief Recursively visit a template name and dispatch to the
appropriate method.
\returns false if the visitation was terminated early, true otherwise.
bool <API key>(TemplateName Template);
\brief Recursively visit a template argument and dispatch to the
appropriate method for the argument type.
\returns false if the visitation was terminated early, true otherwise.
// FIXME: migrate callers to TemplateArgumentLoc instead.
bool <API key>(const TemplateArgument &Arg);
\brief Recursively visit a template argument location and dispatch to the
appropriate method for the argument type.
\returns false if the visitation was terminated early, true otherwise.
bool <API key>(const TemplateArgumentLoc &ArgLoc);
\brief Recursively visit a set of template arguments.
This can be overridden by a subclass, but it's not expected that
will be needed -- this visitor always dispatches to another.
\returns false if the visitation was terminated early, true otherwise.
// FIXME: take a TemplateArgumentLoc* (or <API key>) instead.
bool <API key>(const TemplateArgument *Args,
unsigned NumArgs);
\brief Recursively visit a constructor initializer. This
automatically dispatches to another visitor for the initializer
expression, but not for the name of the initializer, so may
be overridden for clients that need access to the name.
\returns false if the visitation was terminated early, true otherwise.
bool <API key>(CXXCtorInitializer *Init);
\brief Recursively visit a lambda capture.
\returns false if the visitation was terminated early, true otherwise.
bool <API key>(LambdaExpr *LE, const LambdaExpr::Capture *C);
\brief Recursively visit the body of a lambda expression.
This provides a hook for visitors that need more context when visiting
\c LE->getBody().
\returns false if the visitation was terminated early, true otherwise.
bool TraverseLambdaBody(LambdaExpr *LE);
// Declare Traverse*() for all concrete Stmt classes.
#define ABSTRACT_STMT(STMT)
#define STMT(CLASS, PARENT) \
bool Traverse##CLASS(CLASS *S);
#include "clang/AST/StmtNodes.inc"
// The above header #undefs ABSTRACT_STMT and STMT upon exit.
// Define WalkUpFrom*() and empty Visit*() for all Stmt classes.
bool WalkUpFromStmt(Stmt *S) { return getDerived().VisitStmt(S); }
bool VisitStmt(Stmt *S) { return true; }
#define STMT(CLASS, PARENT) \
bool WalkUpFrom##CLASS(CLASS *S) { \
TRY_TO(WalkUpFrom##PARENT(S)); \
TRY_TO(Visit##CLASS(S)); \
return true; \
} \
bool Visit##CLASS(CLASS *S) { return true; }
#include "clang/AST/StmtNodes.inc"
// Define Traverse*(), WalkUpFrom*(), and Visit*() for unary
// operator methods. Unary operators are not classes in themselves
// (they're all opcodes in UnaryOperator) but do have visitors.
#define OPERATOR(NAME) \
bool TraverseUnary##NAME(UnaryOperator *S) { \
TRY_TO(WalkUpFromUnary##NAME(S)); \
TRY_TO(TraverseStmt(S->getSubExpr())); \
return true; \
} \
bool WalkUpFromUnary##NAME(UnaryOperator *S) { \
TRY_TO(<API key>(S)); \
TRY_TO(VisitUnary##NAME(S)); \
return true; \
} \
bool VisitUnary##NAME(UnaryOperator *S) { return true; }
UNARYOP_LIST()
#undef OPERATOR
// Define Traverse*(), WalkUpFrom*(), and Visit*() for binary
// operator methods. Binary operators are not classes in themselves
// (they're all opcodes in BinaryOperator) but do have visitors.
#define <API key>(NAME, BINOP_TYPE) \
bool TraverseBin##NAME(BINOP_TYPE *S) { \
TRY_TO(WalkUpFromBin##NAME(S)); \
TRY_TO(TraverseStmt(S->getLHS())); \
TRY_TO(TraverseStmt(S->getRHS())); \
return true; \
} \
bool WalkUpFromBin##NAME(BINOP_TYPE *S) { \
TRY_TO(WalkUpFrom##BINOP_TYPE(S)); \
TRY_TO(VisitBin##NAME(S)); \
return true; \
} \
bool VisitBin##NAME(BINOP_TYPE *S) { return true; }
#define OPERATOR(NAME) <API key>(NAME, BinaryOperator)
BINOP_LIST()
#undef OPERATOR
// Define Traverse*(), WalkUpFrom*(), and Visit*() for compound
// assignment methods. Compound assignment operators are not
// classes in themselves (they're all opcodes in
// <API key>) but do have visitors.
#define OPERATOR(NAME) \
<API key>(NAME##Assign, <API key>)
CAO_LIST()
#undef OPERATOR
#undef <API key>
// FIXME: revamp to take TypeLoc's rather than Types.
// Declare Traverse*() for all concrete Type classes.
#define ABSTRACT_TYPE(CLASS, BASE)
#define TYPE(CLASS, BASE) \
bool Traverse##CLASS##Type(CLASS##Type *T);
#include "clang/AST/TypeNodes.def"
// The above header #undefs ABSTRACT_TYPE and TYPE upon exit.
// Define WalkUpFrom*() and empty Visit*() for all Type classes.
bool WalkUpFromType(Type *T) { return getDerived().VisitType(T); }
bool VisitType(Type *T) { return true; }
#define TYPE(CLASS, BASE) \
bool WalkUpFrom##CLASS##Type(CLASS##Type *T) { \
TRY_TO(WalkUpFrom##BASE(T)); \
TRY_TO(Visit##CLASS##Type(T)); \
return true; \
} \
bool Visit##CLASS##Type(CLASS##Type *T) { return true; }
#include "clang/AST/TypeNodes.def"
// FIXME: this currently just calls the matching Type methods
// Declare Traverse*() for all concrete TypeLoc classes.
#define ABSTRACT_TYPELOC(CLASS, BASE)
#define TYPELOC(CLASS, BASE) \
bool Traverse##CLASS##TypeLoc(CLASS##TypeLoc TL);
#include "clang/AST/TypeLocNodes.def"
// The above header #undefs ABSTRACT_TYPELOC and TYPELOC upon exit.
// Define WalkUpFrom*() and empty Visit*() for all TypeLoc classes.
bool WalkUpFromTypeLoc(TypeLoc TL) { return getDerived().VisitTypeLoc(TL); }
bool VisitTypeLoc(TypeLoc TL) { return true; }
// QualifiedTypeLoc and UnqualTypeLoc are not declared in
// TypeNodes.def and thus need to be handled specially.
bool <API key>(QualifiedTypeLoc TL) {
return getDerived().VisitUnqualTypeLoc(TL.getUnqualifiedLoc());
}
bool <API key>(QualifiedTypeLoc TL) { return true; }
bool <API key>(UnqualTypeLoc TL) {
return getDerived().VisitUnqualTypeLoc(TL.getUnqualifiedLoc());
}
bool VisitUnqualTypeLoc(UnqualTypeLoc TL) { return true; }
// Note that BASE includes trailing 'Type' which CLASS doesn't.
#define TYPE(CLASS, BASE) \
bool WalkUpFrom##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
TRY_TO(WalkUpFrom##BASE##Loc(TL)); \
TRY_TO(Visit##CLASS##TypeLoc(TL)); \
return true; \
} \
bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { return true; }
#include "clang/AST/TypeNodes.def"
// Declare Traverse*() for all concrete Decl classes.
#define ABSTRACT_DECL(DECL)
#define DECL(CLASS, BASE) \
bool Traverse##CLASS##Decl(CLASS##Decl *D);
#include "clang/AST/DeclNodes.inc"
// The above header #undefs ABSTRACT_DECL and DECL upon exit.
// Define WalkUpFrom*() and empty Visit*() for all Decl classes.
bool WalkUpFromDecl(Decl *D) { return getDerived().VisitDecl(D); }
bool VisitDecl(Decl *D) { return true; }
#define DECL(CLASS, BASE) \
bool WalkUpFrom##CLASS##Decl(CLASS##Decl *D) { \
TRY_TO(WalkUpFrom##BASE(D)); \
TRY_TO(Visit##CLASS##Decl(D)); \
return true; \
} \
bool Visit##CLASS##Decl(CLASS##Decl *D) { return true; }
#include "clang/AST/DeclNodes.inc"
private:
// These are helper methods used by more than one Traverse* method.
bool <API key>(<API key> *TPL);
#define <API key>(TMPLDECLKIND) \
bool <API key>(TMPLDECLKIND##TemplateDecl *D);
<API key>(Class)
<API key>(Var)
<API key>(Function)
#undef <API key>
bool <API key>(const TemplateArgumentLoc *TAL,
unsigned Count);
bool <API key>(ArrayTypeLoc TL);
bool <API key>(RecordDecl *D);
bool <API key>(CXXRecordDecl *D);
bool <API key>(DeclaratorDecl *D);
bool <API key>(DeclContext *DC);
bool <API key>(FunctionDecl *D);
bool TraverseVarHelper(VarDecl *D);
bool TraverseOMPClause(OMPClause *C);
#define OPENMP_CLAUSE(Name, Class) \
bool Visit##Class(Class *C);
#include "clang/Basic/OpenMPKinds.def"
\brief Process clauses with list of variables.
template <typename T>
void VisitOMPClauseList(T *Node);
struct EnqueueJob {
Stmt *S;
Stmt::child_iterator StmtIt;
EnqueueJob(Stmt *S) : S(S), StmtIt() {}
};
bool dataTraverse(Stmt *S);
bool dataTraverseNode(Stmt *S, bool &EnqueueChildren);
};
template<typename Derived>
bool RecursiveASTVisitor<Derived>::dataTraverse(Stmt *S) {
SmallVector<EnqueueJob, 16> Queue;
Queue.push_back(S);
while (!Queue.empty()) {
EnqueueJob &job = Queue.back();
Stmt *CurrS = job.S;
if (!CurrS) {
Queue.pop_back();
continue;
}
if (getDerived().<API key>(CurrS)) {
if (job.StmtIt == Stmt::child_iterator()) {
bool EnqueueChildren = true;
if (!dataTraverseNode(CurrS, EnqueueChildren)) return false;
if (!EnqueueChildren) {
Queue.pop_back();
continue;
}
job.StmtIt = CurrS->child_begin();
} else {
++job.StmtIt;
}
if (job.StmtIt != CurrS->child_end())
Queue.push_back(*job.StmtIt);
else
Queue.pop_back();
continue;
}
Queue.pop_back();
TRY_TO(TraverseStmt(CurrS));
}
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::dataTraverseNode(Stmt *S,
bool &EnqueueChildren) {
// Dispatch to the corresponding WalkUpFrom* function only if the derived
// class didn't override Traverse* (and thus the traversal is trivial).
#define DISPATCH_WALK(NAME, CLASS, VAR) \
{ \
bool (Derived::*DerivedFn)(CLASS*) = &Derived::Traverse##NAME; \
bool (Derived::*BaseFn)(CLASS*) = &RecursiveASTVisitor::Traverse##NAME; \
if (DerivedFn == BaseFn) \
return getDerived().WalkUpFrom##NAME(static_cast<CLASS*>(VAR)); \
} \
EnqueueChildren = false; \
return getDerived().Traverse##NAME(static_cast<CLASS*>(VAR));
if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
switch (BinOp->getOpcode()) {
#define OPERATOR(NAME) \
case BO_##NAME: DISPATCH_WALK(Bin##NAME, BinaryOperator, S);
BINOP_LIST()
#undef OPERATOR
#define OPERATOR(NAME) \
case BO_##NAME##Assign: \
DISPATCH_WALK(Bin##NAME##Assign, <API key>, S);
CAO_LIST()
#undef OPERATOR
}
} else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(S)) {
switch (UnOp->getOpcode()) {
#define OPERATOR(NAME) \
case UO_##NAME: DISPATCH_WALK(Unary##NAME, UnaryOperator, S);
UNARYOP_LIST()
#undef OPERATOR
}
}
// Top switch stmt: dispatch to TraverseFooStmt for each concrete FooStmt.
switch (S->getStmtClass()) {
case Stmt::NoStmtClass: break;
#define ABSTRACT_STMT(STMT)
#define STMT(CLASS, PARENT) \
case Stmt::CLASS##Class: DISPATCH_WALK(CLASS, CLASS, S);
#include "clang/AST/StmtNodes.inc"
}
#undef DISPATCH_WALK
return true;
}
#define DISPATCH(NAME, CLASS, VAR) \
return getDerived().Traverse##NAME(static_cast<CLASS*>(VAR))
template<typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseStmt(Stmt *S) {
if (!S)
return true;
if (getDerived().<API key>(S))
return dataTraverse(S);
// If we have a binary expr, dispatch to the subcode of the binop. A smart
// optimizer (e.g. LLVM) will fold this comparison into the switch stmt
// below.
if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
switch (BinOp->getOpcode()) {
#define OPERATOR(NAME) \
case BO_##NAME: DISPATCH(Bin##NAME, BinaryOperator, S);
BINOP_LIST()
#undef OPERATOR
#undef BINOP_LIST
#define OPERATOR(NAME) \
case BO_##NAME##Assign: \
DISPATCH(Bin##NAME##Assign, <API key>, S);
CAO_LIST()
#undef OPERATOR
#undef CAO_LIST
}
} else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(S)) {
switch (UnOp->getOpcode()) {
#define OPERATOR(NAME) \
case UO_##NAME: DISPATCH(Unary##NAME, UnaryOperator, S);
UNARYOP_LIST()
#undef OPERATOR
#undef UNARYOP_LIST
}
}
// Top switch stmt: dispatch to TraverseFooStmt for each concrete FooStmt.
switch (S->getStmtClass()) {
case Stmt::NoStmtClass: break;
#define ABSTRACT_STMT(STMT)
#define STMT(CLASS, PARENT) \
case Stmt::CLASS##Class: DISPATCH(CLASS, CLASS, S);
#include "clang/AST/StmtNodes.inc"
}
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseType(QualType T) {
if (T.isNull())
return true;
switch (T->getTypeClass()) {
#define ABSTRACT_TYPE(CLASS, BASE)
#define TYPE(CLASS, BASE) \
case Type::CLASS: DISPATCH(CLASS##Type, CLASS##Type, \
const_cast<Type*>(T.getTypePtr()));
#include "clang/AST/TypeNodes.def"
}
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseTypeLoc(TypeLoc TL) {
if (TL.isNull())
return true;
switch (TL.getTypeLocClass()) {
#define ABSTRACT_TYPELOC(CLASS, BASE)
#define TYPELOC(CLASS, BASE) \
case TypeLoc::CLASS: \
return getDerived().Traverse##CLASS##TypeLoc(TL.castAs<CLASS##TypeLoc>());
#include "clang/AST/TypeLocNodes.def"
}
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseDecl(Decl *D) {
if (!D)
return true;
// As a syntax visitor, by default we want to ignore declarations for
// implicit declarations (ones not typed explicitly by the user).
if (!getDerived().<API key>() && D->isImplicit())
return true;
switch (D->getKind()) {
#define ABSTRACT_DECL(DECL)
#define DECL(CLASS, BASE) \
case Decl::CLASS: DISPATCH(CLASS##Decl, CLASS##Decl, D);
#include "clang/AST/DeclNodes.inc"
}
return true;
}
#undef DISPATCH
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
NestedNameSpecifier *NNS) {
if (!NNS)
return true;
if (NNS->getPrefix())
TRY_TO(<API key>(NNS->getPrefix()));
switch (NNS->getKind()) {
case NestedNameSpecifier::Identifier:
case NestedNameSpecifier::Namespace:
case NestedNameSpecifier::NamespaceAlias:
case NestedNameSpecifier::Global:
return true;
case NestedNameSpecifier::TypeSpec:
case NestedNameSpecifier::<API key>:
TRY_TO(TraverseType(QualType(NNS->getAsType(), 0)));
}
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
<API key> NNS) {
if (!NNS)
return true;
if (<API key> Prefix = NNS.getPrefix())
TRY_TO(<API key>(Prefix));
switch (NNS.<API key>()->getKind()) {
case NestedNameSpecifier::Identifier:
case NestedNameSpecifier::Namespace:
case NestedNameSpecifier::NamespaceAlias:
case NestedNameSpecifier::Global:
return true;
case NestedNameSpecifier::TypeSpec:
case NestedNameSpecifier::<API key>:
TRY_TO(TraverseTypeLoc(NNS.getTypeLoc()));
break;
}
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
DeclarationNameInfo NameInfo) {
switch (NameInfo.getName().getNameKind()) {
case DeclarationName::CXXConstructorName:
case DeclarationName::CXXDestructorName:
case DeclarationName::<API key>:
if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
TRY_TO(TraverseTypeLoc(TSInfo->getTypeLoc()));
break;
case DeclarationName::Identifier:
case DeclarationName::ObjCZeroArgSelector:
case DeclarationName::ObjCOneArgSelector:
case DeclarationName::<API key>:
case DeclarationName::CXXOperatorName:
case DeclarationName::<API key>:
case DeclarationName::CXXUsingDirective:
break;
}
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(TemplateName Template) {
if (<API key> *DTN = Template.<API key>())
TRY_TO(<API key>(DTN->getQualifier()));
else if (<API key> *QTN = Template.<API key>())
TRY_TO(<API key>(QTN->getQualifier()));
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
const TemplateArgument &Arg) {
switch (Arg.getKind()) {
case TemplateArgument::Null:
case TemplateArgument::Declaration:
case TemplateArgument::Integral:
case TemplateArgument::NullPtr:
return true;
case TemplateArgument::Type:
return getDerived().TraverseType(Arg.getAsType());
case TemplateArgument::Template:
case TemplateArgument::TemplateExpansion:
return getDerived().<API key>(
Arg.<API key>());
case TemplateArgument::Expression:
return getDerived().TraverseStmt(Arg.getAsExpr());
case TemplateArgument::Pack:
return getDerived().<API key>(Arg.pack_begin(),
Arg.pack_size());
}
return true;
}
// FIXME: no template name location?
// FIXME: no source locations for a template argument pack?
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
const TemplateArgumentLoc &ArgLoc) {
const TemplateArgument &Arg = ArgLoc.getArgument();
switch (Arg.getKind()) {
case TemplateArgument::Null:
case TemplateArgument::Declaration:
case TemplateArgument::Integral:
case TemplateArgument::NullPtr:
return true;
case TemplateArgument::Type: {
// FIXME: how can TSI ever be NULL?
if (TypeSourceInfo *TSI = ArgLoc.getTypeSourceInfo())
return getDerived().TraverseTypeLoc(TSI->getTypeLoc());
else
return getDerived().TraverseType(Arg.getAsType());
}
case TemplateArgument::Template:
case TemplateArgument::TemplateExpansion:
if (ArgLoc.<API key>())
TRY_TO(getDerived().<API key>(
ArgLoc.<API key>()));
return getDerived().<API key>(
Arg.<API key>());
case TemplateArgument::Expression:
return getDerived().TraverseStmt(ArgLoc.getSourceExpression());
case TemplateArgument::Pack:
return getDerived().<API key>(Arg.pack_begin(),
Arg.pack_size());
}
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
const TemplateArgument *Args,
unsigned NumArgs) {
for (unsigned I = 0; I != NumArgs; ++I) {
TRY_TO(<API key>(Args[I]));
}
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
CXXCtorInitializer *Init) {
if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo())
TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
if (Init->isWritten() || getDerived().<API key>())
TRY_TO(TraverseStmt(Init->getInit()));
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
LambdaExpr *LE, const LambdaExpr::Capture *C) {
if (C->isInitCapture())
TRY_TO(TraverseStmt(LE->getInitCaptureInit(C)));
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseLambdaBody(LambdaExpr *LE) {
TRY_TO(TraverseStmt(LE->getBody()));
return true;
}
// This macro makes available a variable T, the passed-in type.
#define DEF_TRAVERSE_TYPE(TYPE, CODE) \
template<typename Derived> \
bool RecursiveASTVisitor<Derived>::Traverse##TYPE (TYPE *T) { \
TRY_TO(WalkUpFrom##TYPE (T)); \
{ CODE; } \
return true; \
}
DEF_TRAVERSE_TYPE(BuiltinType, { })
DEF_TRAVERSE_TYPE(ComplexType, {
TRY_TO(TraverseType(T->getElementType()));
})
DEF_TRAVERSE_TYPE(PointerType, {
TRY_TO(TraverseType(T->getPointeeType()));
})
DEF_TRAVERSE_TYPE(BlockPointerType, {
TRY_TO(TraverseType(T->getPointeeType()));
})
DEF_TRAVERSE_TYPE(LValueReferenceType, {
TRY_TO(TraverseType(T->getPointeeType()));
})
DEF_TRAVERSE_TYPE(RValueReferenceType, {
TRY_TO(TraverseType(T->getPointeeType()));
})
DEF_TRAVERSE_TYPE(MemberPointerType, {
TRY_TO(TraverseType(QualType(T->getClass(), 0)));
TRY_TO(TraverseType(T->getPointeeType()));
})
DEF_TRAVERSE_TYPE(DecayedType, {
TRY_TO(TraverseType(T->getOriginalType()));
})
DEF_TRAVERSE_TYPE(ConstantArrayType, {
TRY_TO(TraverseType(T->getElementType()));
})
DEF_TRAVERSE_TYPE(IncompleteArrayType, {
TRY_TO(TraverseType(T->getElementType()));
})
DEF_TRAVERSE_TYPE(VariableArrayType, {
TRY_TO(TraverseType(T->getElementType()));
TRY_TO(TraverseStmt(T->getSizeExpr()));
})
DEF_TRAVERSE_TYPE(<API key>, {
TRY_TO(TraverseType(T->getElementType()));
if (T->getSizeExpr())
TRY_TO(TraverseStmt(T->getSizeExpr()));
})
DEF_TRAVERSE_TYPE(<API key>, {
if (T->getSizeExpr())
TRY_TO(TraverseStmt(T->getSizeExpr()));
TRY_TO(TraverseType(T->getElementType()));
})
DEF_TRAVERSE_TYPE(VectorType, {
TRY_TO(TraverseType(T->getElementType()));
})
DEF_TRAVERSE_TYPE(ExtVectorType, {
TRY_TO(TraverseType(T->getElementType()));
})
DEF_TRAVERSE_TYPE(FunctionNoProtoType, {
TRY_TO(TraverseType(T->getResultType()));
})
DEF_TRAVERSE_TYPE(FunctionProtoType, {
TRY_TO(TraverseType(T->getResultType()));
for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
AEnd = T->arg_type_end();
A != AEnd; ++A) {
TRY_TO(TraverseType(*A));
}
for (FunctionProtoType::exception_iterator E = T->exception_begin(),
EEnd = T->exception_end();
E != EEnd; ++E) {
TRY_TO(TraverseType(*E));
}
})
DEF_TRAVERSE_TYPE(UnresolvedUsingType, { })
DEF_TRAVERSE_TYPE(TypedefType, { })
DEF_TRAVERSE_TYPE(TypeOfExprType, {
TRY_TO(TraverseStmt(T->getUnderlyingExpr()));
})
DEF_TRAVERSE_TYPE(TypeOfType, {
TRY_TO(TraverseType(T->getUnderlyingType()));
})
DEF_TRAVERSE_TYPE(DecltypeType, {
TRY_TO(TraverseStmt(T->getUnderlyingExpr()));
})
DEF_TRAVERSE_TYPE(UnaryTransformType, {
TRY_TO(TraverseType(T->getBaseType()));
TRY_TO(TraverseType(T->getUnderlyingType()));
})
DEF_TRAVERSE_TYPE(AutoType, {
TRY_TO(TraverseType(T->getDeducedType()));
})
DEF_TRAVERSE_TYPE(RecordType, { })
DEF_TRAVERSE_TYPE(EnumType, { })
DEF_TRAVERSE_TYPE(<API key>, { })
DEF_TRAVERSE_TYPE(<API key>, { })
DEF_TRAVERSE_TYPE(<API key>, { })
DEF_TRAVERSE_TYPE(<API key>, {
TRY_TO(<API key>(T->getTemplateName()));
TRY_TO(<API key>(T->getArgs(), T->getNumArgs()));
})
DEF_TRAVERSE_TYPE(<API key>, { })
DEF_TRAVERSE_TYPE(AttributedType, {
TRY_TO(TraverseType(T->getModifiedType()));
})
DEF_TRAVERSE_TYPE(ParenType, {
TRY_TO(TraverseType(T->getInnerType()));
})
DEF_TRAVERSE_TYPE(ElaboratedType, {
if (T->getQualifier()) {
TRY_TO(<API key>(T->getQualifier()));
}
TRY_TO(TraverseType(T->getNamedType()));
})
DEF_TRAVERSE_TYPE(DependentNameType, {
TRY_TO(<API key>(T->getQualifier()));
})
DEF_TRAVERSE_TYPE(<API key>, {
TRY_TO(<API key>(T->getQualifier()));
TRY_TO(<API key>(T->getArgs(), T->getNumArgs()));
})
DEF_TRAVERSE_TYPE(PackExpansionType, {
TRY_TO(TraverseType(T->getPattern()));
})
DEF_TRAVERSE_TYPE(ObjCInterfaceType, { })
DEF_TRAVERSE_TYPE(ObjCObjectType, {
// We have to watch out here because an ObjCInterfaceType's base
// type is itself.
if (T->getBaseType().getTypePtr() != T)
TRY_TO(TraverseType(T->getBaseType()));
})
DEF_TRAVERSE_TYPE(<API key>, {
TRY_TO(TraverseType(T->getPointeeType()));
})
DEF_TRAVERSE_TYPE(AtomicType, {
TRY_TO(TraverseType(T->getValueType()));
})
#undef DEF_TRAVERSE_TYPE
// This macro makes available a variable TL, the passed-in TypeLoc.
// If requested, it calls WalkUpFrom* for the Type in the given TypeLoc,
// in addition to WalkUpFrom* for the TypeLoc itself, such that existing
// clients that override the WalkUpFrom*Type() and/or Visit*Type() methods
// continue to work.
#define <API key>(TYPE, CODE) \
template<typename Derived> \
bool RecursiveASTVisitor<Derived>::Traverse##TYPE##Loc(TYPE##Loc TL) { \
if (getDerived().<API key>()) \
TRY_TO(WalkUpFrom##TYPE(const_cast<TYPE*>(TL.getTypePtr()))); \
TRY_TO(WalkUpFrom##TYPE##Loc(TL)); \
{ CODE; } \
return true; \
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
QualifiedTypeLoc TL) {
// Move this over to the 'main' typeloc tree. Note that this is a
// move -- we pretend that we were really looking at the unqualified
// typeloc all along -- rather than a recursion, so we don't follow
// the normal CRTP plan of going through
// getDerived().TraverseTypeLoc. If we did, we'd be traversing
// twice for the same type (once as a QualifiedTypeLoc version of
// the type, once as an UnqualifiedTypeLoc version of the type),
// which in effect means we'd call VisitTypeLoc twice with the
// 'same' type. This solves that problem, at the cost of never
// seeing the qualified version of the type (unless the client
// subclasses <API key> themselves). It's not a
// perfect solution. A perfect solution probably requires making
// QualifiedTypeLoc a wrapper around TypeLoc -- like QualType is a
// wrapper around Type* -- rather than being its own class in the
// type hierarchy.
return TraverseTypeLoc(TL.getUnqualifiedLoc());
}
<API key>(BuiltinType, { })
// FIXME: ComplexTypeLoc is unfinished
<API key>(ComplexType, {
TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
})
<API key>(PointerType, {
TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
})
<API key>(BlockPointerType, {
TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
})
<API key>(LValueReferenceType, {
TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
})
<API key>(RValueReferenceType, {
TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
})
// FIXME: location of base class?
// We traverse this in the type case as well, but how is it not reached through
// the pointee type?
<API key>(MemberPointerType, {
TRY_TO(TraverseType(QualType(TL.getTypePtr()->getClass(), 0)));
TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
})
<API key>(DecayedType, {
TRY_TO(TraverseTypeLoc(TL.getOriginalLoc()));
})
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(ArrayTypeLoc TL) {
// This isn't available for ArrayType, but is for the ArrayTypeLoc.
TRY_TO(TraverseStmt(TL.getSizeExpr()));
return true;
}
<API key>(ConstantArrayType, {
TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
return <API key>(TL);
})
<API key>(IncompleteArrayType, {
TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
return <API key>(TL);
})
<API key>(VariableArrayType, {
TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
return <API key>(TL);
})
<API key>(<API key>, {
TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
return <API key>(TL);
})
// FIXME: order? why not size expr first?
// FIXME: base VectorTypeLoc is unfinished
<API key>(<API key>, {
if (TL.getTypePtr()->getSizeExpr())
TRY_TO(TraverseStmt(TL.getTypePtr()->getSizeExpr()));
TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
})
// FIXME: VectorTypeLoc is unfinished
<API key>(VectorType, {
TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
})
// FIXME: size and attributes
// FIXME: base VectorTypeLoc is unfinished
<API key>(ExtVectorType, {
TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
})
<API key>(FunctionNoProtoType, {
TRY_TO(TraverseTypeLoc(TL.getResultLoc()));
})
// FIXME: location of exception specifications (attributes?)
<API key>(FunctionProtoType, {
TRY_TO(TraverseTypeLoc(TL.getResultLoc()));
const FunctionProtoType *T = TL.getTypePtr();
for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
if (TL.getArg(I)) {
TRY_TO(TraverseDecl(TL.getArg(I)));
} else if (I < T->getNumArgs()) {
TRY_TO(TraverseType(T->getArgType(I)));
}
}
for (FunctionProtoType::exception_iterator E = T->exception_begin(),
EEnd = T->exception_end();
E != EEnd; ++E) {
TRY_TO(TraverseType(*E));
}
})
<API key>(UnresolvedUsingType, { })
<API key>(TypedefType, { })
<API key>(TypeOfExprType, {
TRY_TO(TraverseStmt(TL.getUnderlyingExpr()));
})
<API key>(TypeOfType, {
TRY_TO(TraverseTypeLoc(TL.getUnderlyingTInfo()->getTypeLoc()));
})
// FIXME: location of underlying expr
<API key>(DecltypeType, {
TRY_TO(TraverseStmt(TL.getTypePtr()->getUnderlyingExpr()));
})
<API key>(UnaryTransformType, {
TRY_TO(TraverseTypeLoc(TL.getUnderlyingTInfo()->getTypeLoc()));
})
<API key>(AutoType, {
TRY_TO(TraverseType(TL.getTypePtr()->getDeducedType()));
})
<API key>(RecordType, { })
<API key>(EnumType, { })
<API key>(<API key>, { })
<API key>(<API key>, { })
<API key>(<API key>, { })
// FIXME: use the loc for the template name?
<API key>(<API key>, {
TRY_TO(<API key>(TL.getTypePtr()->getTemplateName()));
for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
TRY_TO(<API key>(TL.getArgLoc(I)));
}
})
<API key>(<API key>, { })
<API key>(ParenType, {
TRY_TO(TraverseTypeLoc(TL.getInnerLoc()));
})
<API key>(AttributedType, {
TRY_TO(TraverseTypeLoc(TL.getModifiedLoc()));
})
<API key>(ElaboratedType, {
if (TL.getQualifierLoc()) {
TRY_TO(<API key>(TL.getQualifierLoc()));
}
TRY_TO(TraverseTypeLoc(TL.getNamedTypeLoc()));
})
<API key>(DependentNameType, {
TRY_TO(<API key>(TL.getQualifierLoc()));
})
<API key>(<API key>, {
if (TL.getQualifierLoc()) {
TRY_TO(<API key>(TL.getQualifierLoc()));
}
for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
TRY_TO(<API key>(TL.getArgLoc(I)));
}
})
<API key>(PackExpansionType, {
TRY_TO(TraverseTypeLoc(TL.getPatternLoc()));
})
<API key>(ObjCInterfaceType, { })
<API key>(ObjCObjectType, {
// We have to watch out here because an ObjCInterfaceType's base
// type is itself.
if (TL.getTypePtr()->getBaseType().getTypePtr() != TL.getTypePtr())
TRY_TO(TraverseTypeLoc(TL.getBaseLoc()));
})
<API key>(<API key>, {
TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
})
<API key>(AtomicType, {
TRY_TO(TraverseTypeLoc(TL.getValueLoc()));
})
#undef <API key>
// For a Decl, we automate (in the DEF_TRAVERSE_DECL macro) traversing
// the children that come from the DeclContext associated with it.
// Therefore each Traverse* only needs to worry about children other
// than those.
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(DeclContext *DC) {
if (!DC)
return true;
for (DeclContext::decl_iterator Child = DC->decls_begin(),
ChildEnd = DC->decls_end();
Child != ChildEnd; ++Child) {
// BlockDecls and CapturedDecls are traversed through BlockExprs and
// CapturedStmts respectively.
if (!isa<BlockDecl>(*Child) && !isa<CapturedDecl>(*Child))
TRY_TO(TraverseDecl(*Child));
}
return true;
}
// This macro makes available a variable D, the passed-in decl.
#define DEF_TRAVERSE_DECL(DECL, CODE) \
template<typename Derived> \
bool RecursiveASTVisitor<Derived>::Traverse##DECL (DECL *D) { \
TRY_TO(WalkUpFrom##DECL (D)); \
{ CODE; } \
TRY_TO(<API key>(dyn_cast<DeclContext>(D))); \
return true; \
}
DEF_TRAVERSE_DECL(AccessSpecDecl, { })
DEF_TRAVERSE_DECL(BlockDecl, {
if (TypeSourceInfo *TInfo = D-><API key>())
TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
TRY_TO(TraverseStmt(D->getBody()));
// This return statement makes sure the traversal of nodes in
// decls_begin()/decls_end() (done in the DEF_TRAVERSE_DECL macro)
// is skipped - don't remove it.
return true;
})
DEF_TRAVERSE_DECL(CapturedDecl, {
TRY_TO(TraverseStmt(D->getBody()));
// This return statement makes sure the traversal of nodes in
// decls_begin()/decls_end() (done in the DEF_TRAVERSE_DECL macro)
// is skipped - don't remove it.
return true;
})
DEF_TRAVERSE_DECL(EmptyDecl, { })
DEF_TRAVERSE_DECL(FileScopeAsmDecl, {
TRY_TO(TraverseStmt(D->getAsmString()));
})
DEF_TRAVERSE_DECL(ImportDecl, { })
DEF_TRAVERSE_DECL(FriendDecl, {
// Friend is either decl or a type.
if (D->getFriendType())
TRY_TO(TraverseTypeLoc(D->getFriendType()->getTypeLoc()));
else
TRY_TO(TraverseDecl(D->getFriendDecl()));
})
DEF_TRAVERSE_DECL(FriendTemplateDecl, {
if (D->getFriendType())
TRY_TO(TraverseTypeLoc(D->getFriendType()->getTypeLoc()));
else
TRY_TO(TraverseDecl(D->getFriendDecl()));
for (unsigned I = 0, E = D-><API key>(); I < E; ++I) {
<API key> *TPL = D-><API key>(I);
for (<API key>::iterator ITPL = TPL->begin(),
ETPL = TPL->end();
ITPL != ETPL; ++ITPL) {
TRY_TO(TraverseDecl(*ITPL));
}
}
})
DEF_TRAVERSE_DECL(<API key>, {
TRY_TO(TraverseDecl(D->getSpecialization()));
if (D-><API key>()) {
const <API key>& args = D->templateArgs();
TRY_TO(<API key>(
args.getArgumentArray(), args.size()));
}
})
DEF_TRAVERSE_DECL(LinkageSpecDecl, { })
DEF_TRAVERSE_DECL(<API key>, {
// FIXME: implement this
})
DEF_TRAVERSE_DECL(StaticAssertDecl, {
TRY_TO(TraverseStmt(D->getAssertExpr()));
TRY_TO(TraverseStmt(D->getMessage()));
})
DEF_TRAVERSE_DECL(TranslationUnitDecl, {
// Code in an unnamed namespace shows up automatically in
// decls_begin()/decls_end(). Thus we don't need to recurse on
// D-><API key>().
})
DEF_TRAVERSE_DECL(NamespaceAliasDecl, {
// We shouldn't traverse an aliased namespace, since it will be
// defined (and, therefore, traversed) somewhere else.
// This return statement makes sure the traversal of nodes in
// decls_begin()/decls_end() (done in the DEF_TRAVERSE_DECL macro)
// is skipped - don't remove it.
return true;
})
DEF_TRAVERSE_DECL(LabelDecl, {
// There is no code in a LabelDecl.
})
DEF_TRAVERSE_DECL(NamespaceDecl, {
// Code in an unnamed namespace shows up automatically in
// decls_begin()/decls_end(). Thus we don't need to recurse on
// D-><API key>().
})
DEF_TRAVERSE_DECL(<API key>, {
// FIXME: implement
})
DEF_TRAVERSE_DECL(ObjCCategoryDecl, {
// FIXME: implement
})
DEF_TRAVERSE_DECL(<API key>, {
// FIXME: implement
})
DEF_TRAVERSE_DECL(<API key>, {
// FIXME: implement
})
DEF_TRAVERSE_DECL(ObjCInterfaceDecl, {
// FIXME: implement
})
DEF_TRAVERSE_DECL(ObjCProtocolDecl, {
// FIXME: implement
})
DEF_TRAVERSE_DECL(ObjCMethodDecl, {
if (D-><API key>()) {
TRY_TO(TraverseTypeLoc(D-><API key>()->getTypeLoc()));
}
for (ObjCMethodDecl::param_iterator
I = D->param_begin(), E = D->param_end(); I != E; ++I) {
TRY_TO(TraverseDecl(*I));
}
if (D-><API key>()) {
TRY_TO(TraverseStmt(D->getBody()));
}
return true;
})
DEF_TRAVERSE_DECL(ObjCPropertyDecl, {
// FIXME: implement
})
DEF_TRAVERSE_DECL(UsingDecl, {
TRY_TO(<API key>(D->getQualifierLoc()));
TRY_TO(<API key>(D->getNameInfo()));
})
DEF_TRAVERSE_DECL(UsingDirectiveDecl, {
TRY_TO(<API key>(D->getQualifierLoc()));
})
DEF_TRAVERSE_DECL(UsingShadowDecl, { })
DEF_TRAVERSE_DECL(<API key>, {
for (<API key>::varlist_iterator I = D->varlist_begin(),
E = D->varlist_end();
I != E; ++I) {
TRY_TO(TraverseStmt(*I));
}
})
// A helper method for TemplateDecl's children.
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
<API key> *TPL) {
if (TPL) {
for (<API key>::iterator I = TPL->begin(), E = TPL->end();
I != E; ++I) {
TRY_TO(TraverseDecl(*I));
}
}
return true;
}
#define <API key>(TMPLDECLKIND) \
/* A helper method for traversing the implicit instantiations of a
class or variable template. */ \
template<typename Derived> \
bool RecursiveASTVisitor<Derived>::<API key>( \
TMPLDECLKIND##TemplateDecl *D) { \
TMPLDECLKIND##TemplateDecl::spec_iterator end = D->spec_end(); \
for (TMPLDECLKIND##TemplateDecl::spec_iterator it = D->spec_begin(); \
it != end; ++it) { \
TMPLDECLKIND##<API key>* SD = *it; \
\
switch (SD-><API key>()) { \
/* Visit the implicit instantiations with the requested pattern. */ \
case TSK_Undeclared: \
case <API key>: \
TRY_TO(TraverseDecl(SD)); \
break; \
\
/* We don't need to do anything on an explicit instantiation
or explicit specialization because there will be an explicit
node for it elsewhere. */ \
case <API key>: \
case <API key>: \
case <API key>: \
break; \
} \
} \
\
return true; \
}
<API key>(Class)
<API key>(Var)
// A helper method for traversing the instantiations of a
// function while skipping its specializations.
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
<API key> *D) {
<API key>::spec_iterator end = D->spec_end();
for (<API key>::spec_iterator it = D->spec_begin(); it != end;
++it) {
FunctionDecl* FD = *it;
switch (FD-><API key>()) {
case TSK_Undeclared:
case <API key>:
// We don't know what kind of FunctionDecl this is.
TRY_TO(TraverseDecl(FD));
break;
// FIXME: For now traverse explicit instantiations here. Change that
// once they are represented as dedicated nodes in the AST.
case <API key>:
case <API key>:
TRY_TO(TraverseDecl(FD));
break;
case <API key>:
break;
}
}
return true;
}
// This macro unifies the traversal of class, variable and function
// template declarations.
#define <API key>(TMPLDECLKIND) \
DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateDecl, { \
TRY_TO(TraverseDecl(D->getTemplatedDecl())); \
TRY_TO(<API key>(D-><API key>())); \
\
/* By default, we do not traverse the instantiations of
class templates since they do not appear in the user code. The
following code optionally traverses them.
We only traverse the class instantiations when we see the canonical
declaration of the template, to ensure we only visit them once. */ \
if (getDerived().<API key>() && \
D == D->getCanonicalDecl()) \
TRY_TO(<API key>(D)); \
\
/* Note that <API key>() is just a link
from a template instantiation back to the template from which
it was instantiated, and thus should not be traversed. */ \
})
<API key>(Class)
<API key>(Var)
<API key>(Function)
DEF_TRAVERSE_DECL(<API key>, {
// D is the "T" in something like
// template <template <typename> class T> class container { };
TRY_TO(TraverseDecl(D->getTemplatedDecl()));
if (D->hasDefaultArgument() && !D-><API key>()) {
TRY_TO(<API key>(D->getDefaultArgument()));
}
TRY_TO(<API key>(D-><API key>()));
})
DEF_TRAVERSE_DECL(<API key>, {
// D is the "T" in something like "template<typename T> class vector;"
if (D->getTypeForDecl())
TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
if (D->hasDefaultArgument() && !D-><API key>())
TRY_TO(TraverseTypeLoc(D-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_DECL(TypedefDecl, {
TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
// We shouldn't traverse D->getTypeForDecl(); it's a result of
// declaring the typedef, not something that was written in the
// source.
})
DEF_TRAVERSE_DECL(TypeAliasDecl, {
TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
// We shouldn't traverse D->getTypeForDecl(); it's a result of
// declaring the type alias, not something that was written in the
// source.
})
DEF_TRAVERSE_DECL(<API key>, {
TRY_TO(TraverseDecl(D->getTemplatedDecl()));
TRY_TO(<API key>(D-><API key>()));
})
DEF_TRAVERSE_DECL(<API key>, {
// A dependent using declaration which was marked with 'typename'.
// template<class T> class A : public B<T> { using typename B<T>::foo; };
TRY_TO(<API key>(D->getQualifierLoc()));
// We shouldn't traverse D->getTypeForDecl(); it's a result of
// declaring the type, not something that was written in the
// source.
})
DEF_TRAVERSE_DECL(EnumDecl, {
if (D->getTypeForDecl())
TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
TRY_TO(<API key>(D->getQualifierLoc()));
// The enumerators are already traversed by
// decls_begin()/decls_end().
})
// Helper methods for RecordDecl and its children.
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
RecordDecl *D) {
// We shouldn't traverse D->getTypeForDecl(); it's a result of
// declaring the type, not something that was written in the source.
TRY_TO(<API key>(D->getQualifierLoc()));
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
CXXRecordDecl *D) {
if (!<API key>(D))
return false;
if (D-><API key>()) {
for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
E = D->bases_end();
I != E; ++I) {
TRY_TO(TraverseTypeLoc(I->getTypeSourceInfo()->getTypeLoc()));
}
// We don't traverse the friends or the conversions, as they are
// already in decls_begin()/decls_end().
}
return true;
}
DEF_TRAVERSE_DECL(RecordDecl, {
TRY_TO(<API key>(D));
})
DEF_TRAVERSE_DECL(CXXRecordDecl, {
TRY_TO(<API key>(D));
})
#define <API key>(TMPLDECLKIND) \
DEF_TRAVERSE_DECL(TMPLDECLKIND##<API key>, { \
/* For implicit instantiations ("set<int> x;"), we don't want to
recurse at all, since the instatiated template isn't written in
the source code anywhere. (Note the instatiated *type* --
set<int> -- is written, and will still get a callback of
<API key>). For explicit instantiations
("template set<int>;"), we do need a callback, since this
is the only callback that's made for this instantiation.
We use getTypeAsWritten() to distinguish. */ \
if (TypeSourceInfo *TSI = D->getTypeAsWritten()) \
TRY_TO(TraverseTypeLoc(TSI->getTypeLoc())); \
\
if (!getDerived().<API key>() && \
D-><API key>() != <API key>) \
/* Returning from here skips traversing the
declaration context of the *<API key>
(embedded in the DEF_TRAVERSE_DECL() macro)
which contains the instantiated members of the template. */ \
return true; \
})
<API key>(Class)
<API key>(Var)
template <typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(
const TemplateArgumentLoc *TAL, unsigned Count) {
for (unsigned I = 0; I < Count; ++I) {
TRY_TO(<API key>(TAL[I]));
}
return true;
}
#define <API key>(TMPLDECLKIND, DECLKIND) \
DEF_TRAVERSE_DECL(TMPLDECLKIND##<API key>, { \
/* The partial specialization. */ \
if (<API key> *TPL = D-><API key>()) { \
for (<API key>::iterator I = TPL->begin(), E = TPL->end(); \
I != E; ++I) { \
TRY_TO(TraverseDecl(*I)); \
} \
} \
/* The args that remains unspecialized. */ \
TRY_TO(<API key>( \
D-><API key>()->getTemplateArgs(), \
D-><API key>()->NumTemplateArgs)); \
\
/* Don't need the *<API key>, even
though that's our parent class -- we already visit all the
template args here. */ \
TRY_TO(Traverse##DECLKIND##Helper(D)); \
\
/* Instantiations will have been visited with the primary template. */ \
})
<API key>(Class, CXXRecord)
<API key>(Var, Var)
DEF_TRAVERSE_DECL(EnumConstantDecl, {
TRY_TO(TraverseStmt(D->getInitExpr()));
})
DEF_TRAVERSE_DECL(<API key>, {
// Like <API key>, but without the 'typename':
// template <class T> Class A : public Base<T> { using Base<T>::foo; };
TRY_TO(<API key>(D->getQualifierLoc()));
TRY_TO(<API key>(D->getNameInfo()));
})
DEF_TRAVERSE_DECL(IndirectFieldDecl, {})
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(DeclaratorDecl *D) {
TRY_TO(<API key>(D->getQualifierLoc()));
if (D->getTypeSourceInfo())
TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
else
TRY_TO(TraverseType(D->getType()));
return true;
}
DEF_TRAVERSE_DECL(MSPropertyDecl, {
TRY_TO(<API key>(D));
})
DEF_TRAVERSE_DECL(FieldDecl, {
TRY_TO(<API key>(D));
if (D->isBitField())
TRY_TO(TraverseStmt(D->getBitWidth()));
else if (D-><API key>())
TRY_TO(TraverseStmt(D-><API key>()));
})
DEF_TRAVERSE_DECL(ObjCAtDefsFieldDecl, {
TRY_TO(<API key>(D));
if (D->isBitField())
TRY_TO(TraverseStmt(D->getBitWidth()));
// FIXME: implement the rest.
})
DEF_TRAVERSE_DECL(ObjCIvarDecl, {
TRY_TO(<API key>(D));
if (D->isBitField())
TRY_TO(TraverseStmt(D->getBitWidth()));
// FIXME: implement the rest.
})
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(FunctionDecl *D) {
TRY_TO(<API key>(D->getQualifierLoc()));
TRY_TO(<API key>(D->getNameInfo()));
// If we're an explicit template specialization, iterate over the
// template args that were explicitly specified. If we were doing
// this in typing order, we'd do it between the return type and
// the function args, but both are handled by the FunctionTypeLoc
// above, so we have to choose one side. I've decided to do before.
if (const <API key> *FTSI =
D-><API key>()) {
if (FTSI-><API key>() != TSK_Undeclared &&
FTSI-><API key>() != <API key>) {
// A specialization might not have explicit template arguments if it has
// a templated return type and concrete arguments.
if (const <API key> *TALI =
FTSI-><API key>) {
TRY_TO(<API key>(TALI->getTemplateArgs(),
TALI->NumTemplateArgs));
}
}
}
// Visit the function type itself, which can be either
// FunctionNoProtoType or FunctionProtoType, or a typedef. This
// also covers the return type and the function parameters,
// including exception specifications.
if (TypeSourceInfo *TSI = D->getTypeSourceInfo()) {
TRY_TO(TraverseTypeLoc(TSI->getTypeLoc()));
} else if (getDerived().<API key>()) {
// Visit parameter variable declarations of the implicit function
// if the traverser is visiting implicit code. Parameter variable
// declarations do not have valid TypeSourceInfo, so to visit them
// we need to traverse the declarations explicitly.
for (FunctionDecl::<API key> I = D->param_begin(),
E = D->param_end(); I != E; ++I)
TRY_TO(TraverseDecl(*I));
}
if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
// Constructor initializers.
for (CXXConstructorDecl::init_iterator I = Ctor->init_begin(),
E = Ctor->init_end();
I != E; ++I) {
TRY_TO(<API key>(*I));
}
}
if (D-><API key>()) {
TRY_TO(TraverseStmt(D->getBody())); // Function body.
}
return true;
}
DEF_TRAVERSE_DECL(FunctionDecl, {
// We skip decls_begin/decls_end, which are already covered by
// <API key>().
return <API key>(D);
})
DEF_TRAVERSE_DECL(CXXMethodDecl, {
// We skip decls_begin/decls_end, which are already covered by
// <API key>().
return <API key>(D);
})
DEF_TRAVERSE_DECL(CXXConstructorDecl, {
// We skip decls_begin/decls_end, which are already covered by
// <API key>().
return <API key>(D);
})
// CXXConversionDecl is the declaration of a type conversion operator.
// It's not a cast expression.
DEF_TRAVERSE_DECL(CXXConversionDecl, {
// We skip decls_begin/decls_end, which are already covered by
// <API key>().
return <API key>(D);
})
DEF_TRAVERSE_DECL(CXXDestructorDecl, {
// We skip decls_begin/decls_end, which are already covered by
// <API key>().
return <API key>(D);
})
template<typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseVarHelper(VarDecl *D) {
TRY_TO(<API key>(D));
// Default params are taken care of when we traverse the ParmVarDecl.
if (!isa<ParmVarDecl>(D) &&
(!D->isCXXForRangeDecl() || getDerived().<API key>()))
TRY_TO(TraverseStmt(D->getInit()));
return true;
}
DEF_TRAVERSE_DECL(VarDecl, {
TRY_TO(TraverseVarHelper(D));
})
DEF_TRAVERSE_DECL(ImplicitParamDecl, {
TRY_TO(TraverseVarHelper(D));
})
DEF_TRAVERSE_DECL(<API key>, {
// A non-type template parameter, e.g. "S" in template<int S> class Foo ...
TRY_TO(<API key>(D));
if (D->hasDefaultArgument() && !D-><API key>())
TRY_TO(TraverseStmt(D->getDefaultArgument()));
})
DEF_TRAVERSE_DECL(ParmVarDecl, {
TRY_TO(TraverseVarHelper(D));
if (D->hasDefaultArg() &&
D-><API key>() &&
!D-><API key>())
TRY_TO(TraverseStmt(D-><API key>()));
if (D->hasDefaultArg() &&
!D-><API key>() &&
!D-><API key>())
TRY_TO(TraverseStmt(D->getDefaultArg()));
})
#undef DEF_TRAVERSE_DECL
// For stmts, we automate (in the DEF_TRAVERSE_STMT macro) iterating
// over the children defined in children() (every stmt defines these,
// though sometimes the range is empty). Each individual Traverse*
// method only needs to worry about children other than those. To see
// what children() does for a given class, see, e.g.,
// This macro makes available a variable S, the passed-in stmt.
#define DEF_TRAVERSE_STMT(STMT, CODE) \
template<typename Derived> \
bool RecursiveASTVisitor<Derived>::Traverse##STMT (STMT *S) { \
TRY_TO(WalkUpFrom##STMT(S)); \
{ CODE; } \
for (Stmt::child_range range = S->children(); range; ++range) { \
TRY_TO(TraverseStmt(*range)); \
} \
return true; \
}
DEF_TRAVERSE_STMT(GCCAsmStmt, {
TRY_TO(TraverseStmt(S->getAsmString()));
for (unsigned I = 0, E = S->getNumInputs(); I < E; ++I) {
TRY_TO(TraverseStmt(S-><API key>(I)));
}
for (unsigned I = 0, E = S->getNumOutputs(); I < E; ++I) {
TRY_TO(TraverseStmt(S-><API key>(I)));
}
for (unsigned I = 0, E = S->getNumClobbers(); I < E; ++I) {
TRY_TO(TraverseStmt(S-><API key>(I)));
}
// children() iterates over inputExpr and outputExpr.
})
DEF_TRAVERSE_STMT(MSAsmStmt, {
// FIXME: MS Asm doesn't currently parse Constraints, Clobbers, etc. Once
// added this needs to be implemented.
})
DEF_TRAVERSE_STMT(CXXCatchStmt, {
TRY_TO(TraverseDecl(S->getExceptionDecl()));
// children() iterates over the handler block.
})
DEF_TRAVERSE_STMT(DeclStmt, {
for (DeclStmt::decl_iterator I = S->decl_begin(), E = S->decl_end();
I != E; ++I) {
TRY_TO(TraverseDecl(*I));
}
// Suppress the default iteration over children() by
// returning. Here's why: A DeclStmt looks like 'type var [=
// initializer]'. The decls above already traverse over the
// initializers, so we don't have to do it again (which
// children() would do).
return true;
})
// These non-expr stmts (most of them), do not need any action except
// iterating over the children.
DEF_TRAVERSE_STMT(BreakStmt, { })
DEF_TRAVERSE_STMT(CXXTryStmt, { })
DEF_TRAVERSE_STMT(CaseStmt, { })
DEF_TRAVERSE_STMT(CompoundStmt, { })
DEF_TRAVERSE_STMT(ContinueStmt, { })
DEF_TRAVERSE_STMT(DefaultStmt, { })
DEF_TRAVERSE_STMT(DoStmt, { })
DEF_TRAVERSE_STMT(ForStmt, { })
DEF_TRAVERSE_STMT(GotoStmt, { })
DEF_TRAVERSE_STMT(IfStmt, { })
DEF_TRAVERSE_STMT(IndirectGotoStmt, { })
DEF_TRAVERSE_STMT(LabelStmt, { })
DEF_TRAVERSE_STMT(AttributedStmt, { })
DEF_TRAVERSE_STMT(NullStmt, { })
DEF_TRAVERSE_STMT(ObjCAtCatchStmt, { })
DEF_TRAVERSE_STMT(ObjCAtFinallyStmt, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(ObjCAtThrowStmt, { })
DEF_TRAVERSE_STMT(ObjCAtTryStmt, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(CXXForRangeStmt, {
if (!getDerived().<API key>()) {
TRY_TO(TraverseStmt(S->getLoopVarStmt()));
TRY_TO(TraverseStmt(S->getRangeInit()));
TRY_TO(TraverseStmt(S->getBody()));
// Visit everything else only if <API key>().
return true;
}
})
DEF_TRAVERSE_STMT(<API key>, {
TRY_TO(<API key>(S->getQualifierLoc()));
TRY_TO(<API key>(S->getNameInfo()));
})
DEF_TRAVERSE_STMT(ReturnStmt, { })
DEF_TRAVERSE_STMT(SwitchStmt, { })
DEF_TRAVERSE_STMT(WhileStmt, { })
DEF_TRAVERSE_STMT(<API key>, {
TRY_TO(<API key>(S->getQualifierLoc()));
TRY_TO(<API key>(S->getMemberNameInfo()));
if (S-><API key>()) {
TRY_TO(<API key>(
S->getTemplateArgs(), S->getNumTemplateArgs()));
}
})
DEF_TRAVERSE_STMT(DeclRefExpr, {
TRY_TO(<API key>(S->getQualifierLoc()));
TRY_TO(<API key>(S->getNameInfo()));
TRY_TO(<API key>(
S->getTemplateArgs(), S->getNumTemplateArgs()));
})
DEF_TRAVERSE_STMT(<API key>, {
TRY_TO(<API key>(S->getQualifierLoc()));
TRY_TO(<API key>(S->getNameInfo()));
if (S-><API key>()) {
TRY_TO(<API key>(
S-><API key>().getTemplateArgs(),
S->getNumTemplateArgs()));
}
})
DEF_TRAVERSE_STMT(MemberExpr, {
TRY_TO(<API key>(S->getQualifierLoc()));
TRY_TO(<API key>(S->getMemberNameInfo()));
TRY_TO(<API key>(
S->getTemplateArgs(), S->getNumTemplateArgs()));
})
DEF_TRAVERSE_STMT(ImplicitCastExpr, {
// We don't traverse the cast type, as it's not written in the
// source code.
})
DEF_TRAVERSE_STMT(CStyleCastExpr, {
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(<API key>, {
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXConstCastExpr, {
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXDynamicCastExpr, {
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(<API key>, {
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXStaticCastExpr, {
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
// InitListExpr is a tricky one, because we want to do all our work on
// the syntactic form of the listexpr, but this method takes the
// semantic form by default. We can't use the macro helper because it
// calls WalkUp*() on the semantic form, before our code can convert
// to the syntactic form.
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(InitListExpr *S) {
if (InitListExpr *Syn = S->getSyntacticForm())
S = Syn;
TRY_TO(<API key>(S));
// All we need are the default actions. FIXME: use a helper function.
for (Stmt::child_range range = S->children(); range; ++range) {
TRY_TO(TraverseStmt(*range));
}
return true;
}
// <API key> is a special case because the types and expressions
// are interleaved. We also need to watch out for null types (default
// generic associations).
template<typename Derived>
bool RecursiveASTVisitor<Derived>::
<API key>(<API key> *S) {
TRY_TO(<API key>(S));
TRY_TO(TraverseStmt(S->getControllingExpr()));
for (unsigned i = 0; i != S->getNumAssocs(); ++i) {
if (TypeSourceInfo *TS = S-><API key>(i))
TRY_TO(TraverseTypeLoc(TS->getTypeLoc()));
TRY_TO(TraverseStmt(S->getAssocExpr(i)));
}
return true;
}
// PseudoObjectExpr is a special case because of the wierdness with
// syntactic expressions and opaque values.
template<typename Derived>
bool RecursiveASTVisitor<Derived>::
<API key>(PseudoObjectExpr *S) {
TRY_TO(<API key>(S));
TRY_TO(TraverseStmt(S->getSyntacticForm()));
for (PseudoObjectExpr::semantics_iterator
i = S->semantics_begin(), e = S->semantics_end(); i != e; ++i) {
Expr *sub = *i;
if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(sub))
sub = OVE->getSourceExpr();
TRY_TO(TraverseStmt(sub));
}
return true;
}
DEF_TRAVERSE_STMT(<API key>, {
// This is called for code like 'return T()' where T is a built-in
// (i.e. non-class) type.
TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXNewExpr, {
// The child-iterator will pick up the other arguments.
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(OffsetOfExpr, {
// The child-iterator will pick up the expression representing
// the field.
// FIMXE: for code like offsetof(Foo, a.b.c), should we get
// making a MemberExpr callbacks for Foo.a, Foo.a.b, and Foo.a.b.c?
TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(<API key>, {
// The child-iterator will pick up the arg if it's an expression,
// but not if it's a type.
if (S->isArgumentType())
TRY_TO(TraverseTypeLoc(S->getArgumentTypeInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXTypeidExpr, {
// The child-iterator will pick up the arg if it's an expression,
// but not if it's a type.
if (S->isTypeOperand())
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(MSPropertyRefExpr, {
TRY_TO(<API key>(S->getQualifierLoc()));
})
DEF_TRAVERSE_STMT(CXXUuidofExpr, {
// The child-iterator will pick up the arg if it's an expression,
// but not if it's a type.
if (S->isTypeOperand())
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(UnaryTypeTraitExpr, {
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(BinaryTypeTraitExpr, {
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(TypeTraitExpr, {
for (unsigned I = 0, N = S->getNumArgs(); I != N; ++I)
TRY_TO(TraverseTypeLoc(S->getArg(I)->getTypeLoc()));
})
DEF_TRAVERSE_STMT(ArrayTypeTraitExpr, {
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(ExpressionTraitExpr, {
TRY_TO(TraverseStmt(S-><API key>()));
})
DEF_TRAVERSE_STMT(VAArgExpr, {
// The child-iterator will pick up the expression argument.
TRY_TO(TraverseTypeLoc(S->getWrittenTypeInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(<API key>, {
// This is called for code like 'return T()' where T is a class type.
TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
})
// Walk only the visible parts of lambda expressions.
template<typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseLambdaExpr(LambdaExpr *S) {
TRY_TO(<API key>(S));
for (LambdaExpr::capture_iterator C = S-><API key>(),
CEnd = S-><API key>();
C != CEnd; ++C) {
TRY_TO(<API key>(S, C));
}
if (S-><API key>() || S-><API key>()) {
TypeLoc TL = S->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
if (S-><API key>() && S-><API key>()) {
// Visit the whole type.
TRY_TO(TraverseTypeLoc(TL));
} else if (<API key> Proto = TL.getAs<<API key>>()) {
if (S-><API key>()) {
// Visit parameters.
for (unsigned I = 0, N = Proto.getNumArgs(); I != N; ++I) {
TRY_TO(TraverseDecl(Proto.getArg(I)));
}
} else {
TRY_TO(TraverseTypeLoc(Proto.getResultLoc()));
}
}
}
TRY_TO(TraverseLambdaBody(S));
return true;
}
DEF_TRAVERSE_STMT(<API key>, {
// This is called for code like 'T()', where T is a template argument.
TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
})
// These expressions all might take explicit template arguments.
// We traverse those if so. FIXME: implement these.
DEF_TRAVERSE_STMT(CXXConstructExpr, { })
DEF_TRAVERSE_STMT(CallExpr, { })
DEF_TRAVERSE_STMT(CXXMemberCallExpr, { })
// These exprs (most of them), do not need any action except iterating
// over the children.
DEF_TRAVERSE_STMT(AddrLabelExpr, { })
DEF_TRAVERSE_STMT(ArraySubscriptExpr, { })
DEF_TRAVERSE_STMT(BlockExpr, {
TRY_TO(TraverseDecl(S->getBlockDecl()));
return true; // no child statements to loop through.
})
DEF_TRAVERSE_STMT(ChooseExpr, { })
DEF_TRAVERSE_STMT(CompoundLiteralExpr, {
TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(CXXBoolLiteralExpr, { })
DEF_TRAVERSE_STMT(CXXDefaultArgExpr, { })
DEF_TRAVERSE_STMT(CXXDefaultInitExpr, { })
DEF_TRAVERSE_STMT(CXXDeleteExpr, { })
DEF_TRAVERSE_STMT(ExprWithCleanups, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(<API key>, {
TRY_TO(<API key>(S->getQualifierLoc()));
if (TypeSourceInfo *ScopeInfo = S->getScopeTypeInfo())
TRY_TO(TraverseTypeLoc(ScopeInfo->getTypeLoc()));
if (TypeSourceInfo *DestroyedTypeInfo = S-><API key>())
TRY_TO(TraverseTypeLoc(DestroyedTypeInfo->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXThisExpr, { })
DEF_TRAVERSE_STMT(CXXThrowExpr, { })
DEF_TRAVERSE_STMT(UserDefinedLiteral, { })
DEF_TRAVERSE_STMT(DesignatedInitExpr, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(GNUNullExpr, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(ObjCBoolLiteralExpr, { })
DEF_TRAVERSE_STMT(ObjCEncodeExpr, {
if (TypeSourceInfo *TInfo = S-><API key>())
TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
})
DEF_TRAVERSE_STMT(ObjCIsaExpr, { })
DEF_TRAVERSE_STMT(ObjCIvarRefExpr, { })
DEF_TRAVERSE_STMT(ObjCMessageExpr, {
if (TypeSourceInfo *TInfo = S-><API key>())
TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
})
DEF_TRAVERSE_STMT(ObjCPropertyRefExpr, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(ObjCProtocolExpr, { })
DEF_TRAVERSE_STMT(ObjCSelectorExpr, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(ObjCBridgedCastExpr, {
TRY_TO(TraverseTypeLoc(S-><API key>()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(ParenExpr, { })
DEF_TRAVERSE_STMT(ParenListExpr, { })
DEF_TRAVERSE_STMT(PredefinedExpr, { })
DEF_TRAVERSE_STMT(ShuffleVectorExpr, { })
DEF_TRAVERSE_STMT(ConvertVectorExpr, { })
DEF_TRAVERSE_STMT(StmtExpr, { })
DEF_TRAVERSE_STMT(<API key>, {
TRY_TO(<API key>(S->getQualifierLoc()));
if (S-><API key>()) {
TRY_TO(<API key>(S->getTemplateArgs(),
S->getNumTemplateArgs()));
}
})
DEF_TRAVERSE_STMT(<API key>, {
TRY_TO(<API key>(S->getQualifierLoc()));
if (S-><API key>()) {
TRY_TO(<API key>(S->getTemplateArgs(),
S->getNumTemplateArgs()));
}
})
DEF_TRAVERSE_STMT(SEHTryStmt, {})
DEF_TRAVERSE_STMT(SEHExceptStmt, {})
DEF_TRAVERSE_STMT(SEHFinallyStmt,{})
DEF_TRAVERSE_STMT(CapturedStmt, {
TRY_TO(TraverseDecl(S->getCapturedDecl()));
})
DEF_TRAVERSE_STMT(CXXOperatorCallExpr, { })
DEF_TRAVERSE_STMT(OpaqueValueExpr, { })
DEF_TRAVERSE_STMT(CUDAKernelCallExpr, { })
// These operators (all of them) do not need any action except
// iterating over the children.
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(ConditionalOperator, { })
DEF_TRAVERSE_STMT(UnaryOperator, { })
DEF_TRAVERSE_STMT(BinaryOperator, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(CXXNoexceptExpr, { })
DEF_TRAVERSE_STMT(PackExpansionExpr, { })
DEF_TRAVERSE_STMT(SizeOfPackExpr, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(<API key>, { })
DEF_TRAVERSE_STMT(AtomicExpr, { })
// These literals (all of them) do not need any action.
DEF_TRAVERSE_STMT(IntegerLiteral, { })
DEF_TRAVERSE_STMT(CharacterLiteral, { })
DEF_TRAVERSE_STMT(FloatingLiteral, { })
DEF_TRAVERSE_STMT(ImaginaryLiteral, { })
DEF_TRAVERSE_STMT(StringLiteral, { })
DEF_TRAVERSE_STMT(ObjCStringLiteral, { })
DEF_TRAVERSE_STMT(ObjCBoxedExpr, { })
DEF_TRAVERSE_STMT(ObjCArrayLiteral, { })
DEF_TRAVERSE_STMT(<API key>, { })
// Traverse OpenCL: AsType, Convert.
DEF_TRAVERSE_STMT(AsTypeExpr, { })
// OpenMP directives.
DEF_TRAVERSE_STMT(<API key>, {
ArrayRef<OMPClause *> Clauses = S->clauses();
for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
I != E; ++I)
if (!TraverseOMPClause(*I)) return false;
})
// OpenMP clauses.
template<typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseOMPClause(OMPClause *C) {
if (!C) return true;
switch (C->getClauseKind()) {
#define OPENMP_CLAUSE(Name, Class) \
case OMPC_##Name: \
return getDerived().Visit
#include "clang/Basic/OpenMPKinds.def"
default: break;
}
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(OMPDefaultClause *C) {
return true;
}
template<typename Derived>
template<typename T>
void RecursiveASTVisitor<Derived>::VisitOMPClauseList(T *Node) {
for (typename T::varlist_iterator I = Node->varlist_begin(),
E = Node->varlist_end();
I != E; ++I)
TraverseStmt(*I);
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(OMPPrivateClause *C) {
VisitOMPClauseList(C);
return true;
}
template<typename Derived>
bool RecursiveASTVisitor<Derived>::<API key>(OMPSharedClause *C) {
VisitOMPClauseList(C);
return true;
}
// FIXME: look at the following tricky-seeming exprs to see if we
// need to recurse on anything. These are ones that have methods
// returning decls or qualtypes or nestednamespecifier -- though I'm
// not sure if they own them -- or just seemed very complicated, or
// had lots of sub-types to explore.
// VisitOverloadExpr and its children: recurse on template args? etc?
// FIXME: go through all the stmts and exprs again, and see which of them
// create new types, and recurse on the types (TypeLocs?) of those.
// Candidates:
// Every class that has getQualifier.
#undef DEF_TRAVERSE_STMT
#undef TRY_TO
} // end namespace clang
#endif // <API key> |
#include "Clip.h"
using namespace lwosg;
Clip::Clip(const lwo2::FORM::CLIP *clip)
{
if (clip)
{
compile(clip);
}
}
void Clip::compile(const lwo2::FORM::CLIP *clip)
{
for (iff::Chunk_list::const_iterator j = clip->attributes.begin(); j != clip->attributes.end(); ++j)
{
const lwo2::FORM::CLIP::STIL *stil = dynamic_cast<const lwo2::FORM::CLIP::STIL*>(*j);
if (stil)
still_filename_ = stil->name.name;
}
} |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="sr@latin" version="2.0">
<context>
<name>ConfigureDialog</name>
<message>
<location filename="../configuredialog/configuredialog.ui" line="14"/>
<source>LXQt-runner Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../configuredialog/configuredialog.ui" line="20"/>
<source>Appearance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../configuredialog/configuredialog.ui" line="26"/>
<source>Positioning:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../configuredialog/configuredialog.ui" line="36"/>
<source>Show on:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../configuredialog/configuredialog.ui" line="56"/>
<source>Shortcut:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../configuredialog/configuredialog.cpp" line="70"/>
<source>Top edge of screen</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../configuredialog/configuredialog.cpp" line="71"/>
<source>Center of screen</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../configuredialog/configuredialog.cpp" line="77"/>
<source>Monitor where the mouse</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../configuredialog/configuredialog.cpp" line="82"/>
<source>Always on %1 monitor</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>Dialog</name>
<message>
<location filename="../dialog.ui" line="26"/>
<source>Application launcher </source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../dialog.cpp" line="91"/>
<source>Configure lxqt-runner</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../dialog.cpp" line="296"/>
<source>Press "%1" to see dialog.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../providers.cpp" line="221"/>
<source>History</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../providers.cpp" line="307"/>
<source>Mathematics</source>
<translation type="unfinished"/>
</message>
</context>
</TS> |
/**
* @file <API key>.c
* @author SangYong Park <sy302.park@samsung.com>
* @date 2012-06-12
* @brief Tests EWK function <API key>()
*/
/* Define those macros _before_ you include the utc_webkit2_ewk.h header file. */
#define TESTED_FUN_NAME <API key>
#define <API key> 1
#define <API key> 2
#include "utc_webkit2_ewk.h"
/* Startup and cleanup functions */
static void startup(void)
{
<API key>();
}
static void cleanup(void)
{
<API key>();
}
static const char* cachePath = "./tempCachePath";
/**
* @brief Tests if can set application cache path.
*/
POS_TEST_FUN(1)
{
Ewk_Context* context = <API key>(test_view.webview);
if (!<API key>(context, cachePath))
utc_fail();
utc_message("Skip to test result because application cache store to storage asynchronous.\n");
utc_pass();
}
/**
* @brief Tests if returns false which context was null.
*/
NEG_TEST_FUN(1)
{
utc_check_eq(<API key>(0, cachePath), EINA_FALSE);
}
/**
* @brief Tests if returns false which path was null.
*/
NEG_TEST_FUN(2)
{
Ewk_Context* context = <API key>(test_view.webview);
utc_check_eq(<API key>(context, 0), EINA_FALSE);
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Vulpine.Core.Data
{
<summary>
A keyed item is any generic item that has a corresponding key associated
with it. When a keyed item is compared with another keyed item, it compares
based on the keys, rather than on the items themselves. Therefore, the key
must not be null and should have a proper hash function defined, to avoid
unnecessary hash collisions. There are no restrictions on the item itself.
This is useful when you want to sort or reference items based on some
other factor, namely the key for that item.
</summary>
<typeparam name="K">The key type of the pair</typeparam>
<typeparam name="E">The value type of the pair</typeparam>
<remarks>Last Update: 2016-06-02</remarks>
public sealed class KeyedItem<K, E> : IComparable<KeyedItem<K, E>>
{
#region Class Definitions...
//stores the key and the item
private K key;
private E item;
<summary>
Constructs a new keyed item.
</summary>
<param name="key">Key for the item</param>
<param name="value">The item contained</param>
<exception cref="<API key>">If the key is null</exception>
public KeyedItem(K key, E value)
{
//we do not allow for null keys to exist
if (key == null) throw new <API key>("key");
this.key = key;
this.item = value;
}
<summary>
Constructs a fake key, which doesn't point to any item. This is
useful in searching for a matching key inside a collection.
</summary>
<param name="key">The fake key</param>
<exception cref="<API key>">If the key is null</exception>
public KeyedItem(K key)
{
//we do not allow for null keys to exist
if (key == null) throw new <API key>("key");
this.key = key;
this.item = default(E);
}
<summary>
Generates a string listing both the key and the item.
</summary>
<returns>The pair as a string</returns>
public override string ToString()
{
string sitem = (item == null) ? "NULL" : item.ToString();
return String.Format("{0} = {1}", key, sitem);
}
<summary>
Determines if two keyed items are equivalent to each other
by comparing their keys. As long as the keys match, they
are considered the same item, even if the items themselves
differ.
</summary>
<param name="obj">Object to compare</param>
<returns>True if the objects are equal</returns>
public override bool Equals(object obj)
{
//makes sure the object is a keyed item
var other = obj as KeyedItem<K, E>;
if (other == null) return false;
//compares the keys
return key.Equals(other.key);
}
<summary>
Hashes the key for the current keyed item pair. The item
itself is not used in constructing the hash code.
</summary>
<returns>Hash value for the key</returns>
public override int GetHashCode()
{
return key.GetHashCode();
}
#endregion /////////////////////////////////////////////////////////////
#region Class Properties...
<summary>
Obtains the item assigned to the current key.
</summary>
public E Item
{
get { return item; }
}
<summary>
Obtains the key referencing the current item.
</summary>
public K Key
{
get { return key; }
}
#endregion /////////////////////////////////////////////////////////////
#region IComparable Implementation...
<summary>
Compares the key of the current keyed item to the key of another
keyed item. The default comparison method for the keys is used.
</summary>
<param name="other">Keyed item to compare</param>
<returns>A negative number if the current pair comes first, a
positive number if it comes second, and zero if they are equal.
</returns>
public int CompareTo(KeyedItem<K, E> other)
{
//checks for a valid target
if (other == null) return -1;
//attempts to use the default comparison method for keys
var comp = key as IComparable<K>;
if (comp != null) return comp.CompareTo(other.Key);
//throws an exception if we are unable to compare keys
throw new <API key>();
}
#endregion /////////////////////////////////////////////////////////////
}
} |
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// File: <API key>.cxx
// Created: Mon Dec 8 11:47:55 2003
// <pkv@irinox>
#include <NMTTools_PaveFiller.ixx>
#include <<API key>.hxx>
#include <<API key>.hxx>
#include <<API key>.hxx>
#include <<API key>.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Vertex.hxx>
#include <<API key>.hxx>
#include <IntTools_Tools.hxx>
#include <<API key>.hxx>
#include <<API key>.hxx>
#include <<API key>.hxx>
#include <NMTDS_Iterator.hxx>
#include <NMTDS_InterfPool.hxx>
#include <<API key>.hxx>
#include <NMTTools_Tools.hxx>
// function: PerformVV
// purpose:
void NMTTools_PaveFiller::PerformVV()
{
myIsDone=Standard_False;
Standard_Integer aNbVVs, aBL, aNbVSD, nVnew, i, j, n1, n2;
<API key> aIt1;
<API key> aItX, aItY;
<API key> aLIX;
<API key> aLV;
TopoDS_Vertex aVnew;
myVSD.Clear();
const <API key>& aMVSD=myDSIt->SDVertices();
aNbVSD=aMVSD.Extent();
if (!aNbVSD) {
return;
}
<API key>& aVVs=myIP->VVInterferences();
// BlockLength correction
myDSIt->Initialize(TopAbs_VERTEX, TopAbs_VERTEX);
aNbVVs=myDSIt->BlockLength();
aBL=aVVs.BlockLength();
if (aNbVVs > aBL) {
aVVs.SetBlockLength(aNbVVs);
}
aIt1.Initialize(aMVSD);
for (; aIt1.More(); aIt1.Next()) {
aLV.Clear();
n1=aIt1.Key();
const <API key>& aLIV=aIt1.Value();
// new vertex
const TopoDS_Shape& aS1=myDS->Shape(n1);
aLV.Append(aS1);
aItX.Initialize(aLIV);
for (; aItX.More(); aItX.Next()) {
n2=aItX.Value();
const TopoDS_Shape& aS2=myDS->Shape(n2);
aLV.Append(aS2);
}
NMTTools_Tools::MakeNewVertex(aLV, aVnew);
<API key> anASSeq;
myDS-><API key>(aVnew, anASSeq);
nVnew=myDS-><API key>();
myDS->SetState (nVnew, <API key>);
// myVSD, aLIX
aLIX.Clear();
aLIX.Append(n1);
myVSD.Bind(n1, nVnew);
aItX.Initialize(aLIV);
for (; aItX.More(); aItX.Next()) {
n2=aItX.Value();
aLIX.Append(n2);
myVSD.Bind(n2, nVnew);
}
// interferences
aItX.Initialize(aLIX);
for (i=0; aItX.More(); aItX.Next(), ++i) {
aItY.Initialize(aLIX);
for (j=0; aItY.More(); aItY.Next(), ++j) {
if (j>i) {
n1=aItX.Value();
n2=aItY.Value();
myIP->Add(n1, n2, Standard_True, NMTDS_TI_VV);
<API key> aVV(n1, n2);
aVV.SetNewShape(nVnew);
aVVs.Append(aVV);
}
}
}
}//for (; aIt1.More(); aIt1.Next()) {
myIsDone=Standard_True;
}
// function: FindSDVertex
// purpose:
Standard_Integer NMTTools_PaveFiller::FindSDVertex(const Standard_Integer nV)const
{
Standard_Integer nVSD;
nVSD=0;
if (myVSD.IsBound(nV)) {
nVSD=myVSD.Find(nV);
}
return nVSD;
} |
package fr.toss.FF7itemsc;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import fr.toss.FF7.ItemRegistry1;
public class itemc2 extends Item
{
public itemc2(int id)
{
super();
setCreativeTab(ItemRegistry1.FF7itemsC);
setUnlocalizedName("itemc2");
}
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister iconRegister)
{
this.itemIcon = iconRegister.registerIcon("FF7:" + getUnlocalizedName().substring(5));
}
} |
package org.pentaho.reporting.libraries.formula.function.information;
import org.pentaho.reporting.libraries.formula.EvaluationException;
import org.pentaho.reporting.libraries.formula.FormulaContext;
import org.pentaho.reporting.libraries.formula.function.Function;
import org.pentaho.reporting.libraries.formula.function.ParameterCallback;
import org.pentaho.reporting.libraries.formula.lvalues.TypeValuePair;
import org.pentaho.reporting.libraries.formula.typing.coretypes.LogicalType;
public class HasChangedFunction implements Function {
private static final TypeValuePair RETURN_FALSE = new TypeValuePair( LogicalType.TYPE, Boolean.FALSE );
private static final TypeValuePair RETURN_TRUE = new TypeValuePair( LogicalType.TYPE, Boolean.TRUE );
private static final long serialVersionUID = <API key>;
public HasChangedFunction() {
}
public String getCanonicalName() {
return "HASCHANGED";
}
public TypeValuePair evaluate( final FormulaContext context,
final ParameterCallback parameters )
throws EvaluationException {
// we expect strings and will check, whether the reference for theses
// strings is dirty.
final int parCount = parameters.getParameterCount();
for ( int i = 0; i < parCount; i++ ) {
final Object value = parameters.getValue( i );
if ( value == null ) {
continue;
}
if ( context.isReferenceDirty( value ) ) {
return RETURN_TRUE;
}
}
return RETURN_FALSE;
}
} |
package demo.domain;
import org.springframework.data.annotation.Id;
import java.io.Serializable;
public class Project implements Serializable {
public static final String ID = "project";
@Id
private final String id = ID;
private final String name;
public Project(String name) {
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
} |
#ifndef <API key>
#define <API key>
#include <glib-object.h>
#include <gio/gio.h>
G_BEGIN_DECLS
#define TPL_TYPE_LOG_WALKER (<API key> ())
#define TPL_LOG_WALKER(obj) \
(<API key> ((obj), \
TPL_TYPE_LOG_WALKER, TplLogWalker))
#define <API key>(klass) \
(<API key> ((klass), \
TPL_TYPE_LOG_WALKER, TplLogWalkerClass))
#define TPL_IS_LOG_WALKER(obj) \
(<API key> ((obj), \
TPL_TYPE_LOG_WALKER))
#define <API key>(klass) \
(<API key> ((klass), \
TPL_TYPE_LOG_WALKER))
#define <API key>(obj) \
(<API key> ((obj), \
TPL_TYPE_LOG_WALKER, TplLogWalkerClass))
typedef struct _TplLogWalker TplLogWalker;
typedef struct _TplLogWalkerClass TplLogWalkerClass;
typedef struct _TplLogWalkerPriv TplLogWalkerPriv;
struct _TplLogWalker
{
GObject parent_instance;
TplLogWalkerPriv *priv;
};
struct _TplLogWalkerClass
{
/*< private >*/
GObjectClass parent_class;
};
GType <API key> (void) G_GNUC_CONST;
void <API key> (TplLogWalker *walker,
guint num_events,
GAsyncReadyCallback callback,
gpointer user_data);
gboolean <API key> (TplLogWalker *walker,
GAsyncResult *result,
GList **events,
GError **error);
void <API key> (TplLogWalker *walker,
guint num_events,
GAsyncReadyCallback callback,
gpointer user_data);
gboolean <API key> (TplLogWalker *walker,
GAsyncResult *result,
GError **error);
gboolean <API key> (TplLogWalker *walker);
gboolean <API key> (TplLogWalker *walker);
G_END_DECLS
#endif /* <API key> */ |
package org.jboss.as.jaxrs;
import static org.jboss.as.controller.descriptions.<API key>.NAME;
import static org.jboss.as.controller.descriptions.<API key>.SUBSYSTEM;
import static org.wildfly.extension.undertow.<API key>.CONTEXT_ROOT;
import static org.wildfly.extension.undertow.<API key>.SERVER;
import static org.wildfly.extension.undertow.<API key>.VIRTUAL_HOST;
import io.undertow.server.HttpServerExchange;
import io.undertow.servlet.api.ThreadSetupHandler;
import io.undertow.servlet.handlers.ServletHandler;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.CookieParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.<API key>;
import org.jboss.as.controller.<API key>;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.<API key>;
import org.jboss.as.controller.<API key>;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.<API key>;
import org.jboss.as.controller.<API key>;
import org.jboss.as.controller.<API key>;
import org.jboss.as.controller.OperationContext.AttachmentKey;
import org.jboss.as.controller.descriptions.<API key>;
import org.jboss.as.controller.registry.<API key>;
import org.jboss.as.jaxrs.logging.JaxrsLogger;
import org.jboss.as.server.Services;
import org.jboss.as.server.moduleservice.ServiceModuleLoader;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.logmanager.Level;
import org.jboss.modules.Module;
import org.jboss.msc.service.ServiceController;
import org.jboss.resteasy.core.ResourceInvoker;
import org.jboss.resteasy.core.<API key>;
import org.jboss.resteasy.core.<API key>;
import org.jboss.resteasy.core.<API key>;
import org.jboss.resteasy.plugins.server.servlet.<API key>;
import org.jboss.resteasy.spi.metadata.ResourceBuilder;
import org.jboss.resteasy.spi.metadata.ResourceClass;
import org.jboss.resteasy.spi.metadata.ResourceLocator;
import org.jboss.resteasy.spi.metadata.ResourceMethod;
import org.wildfly.extension.undertow.UndertowExtension;
import org.wildfly.extension.undertow.UndertowService;
import org.wildfly.extension.undertow.deployment.<API key>;
/**
* @author <a href="mailto:lgao@redhat.com">Lin Gao</a>
*/
@SuppressWarnings("deprecation")
public class <API key> extends <API key> {
public static <API key> INSTANCE = new <API key>();
public static final String REST_RESOURCE_NAME = "rest-resource";
public static final AttributeDefinition RESOURCE_CLASS = new <API key>("resource-class",
ModelType.STRING, true).setStorageRuntime().build();
public static final AttributeDefinition RESOURCE_PATH = new <API key>("resource-path", ModelType.STRING, true)
.setStorageRuntime().build();
public static final AttributeDefinition RESOURCE_METHOD = new <API key>("resource-method",
ModelType.STRING, false).setStorageRuntime().build();
public static final AttributeDefinition RESOURCE_METHODS = new <API key>.Builder("resource-methods", RESOURCE_METHOD)
.setStorageRuntime().build();
public static final AttributeDefinition CONSUME = new <API key>("consume", ModelType.STRING, true)
.setStorageRuntime().build();
public static final AttributeDefinition CONSUMES = new <API key>.Builder("consumes", CONSUME)
.setStorageRuntime().build();
public static final AttributeDefinition PRODUCE = new <API key>("produce", ModelType.STRING, true)
.setStorageRuntime().build();
public static final AttributeDefinition PRODUCES = new <API key>.Builder("produces", PRODUCE)
.setStorageRuntime().build();
public static final AttributeDefinition JAVA_METHOD = new <API key>("java-method", ModelType.STRING,
true).setStorageRuntime().build();
public static final <API key> RESOURCE_PATH_GRP = new <API key>.Builder(
"<API key>", RESOURCE_PATH, CONSUMES, PRODUCES, JAVA_METHOD, RESOURCE_METHODS).build();
public static final <API key> RESOURCE_PATHS = new <API key>.Builder(
"rest-resource-paths", RESOURCE_PATH_GRP).build();
public static final <API key> <API key> = new <API key>.Builder(
"<API key>", RESOURCE_CLASS, RESOURCE_PATH, CONSUMES, PRODUCES, JAVA_METHOD, RESOURCE_METHODS).build();
public static final <API key> <API key> = new <API key>.Builder(
"<API key>", <API key>).build();
private AttachmentKey<Map<PathAddress, <API key>>> <API key> = AttachmentKey.create(Map.class);
private AttachmentKey<Map<PathAddress, Module>> deploymentModuleKey = AttachmentKey.create(Map.class);
private AttachmentKey<Map<String, ResourceMeta>> resourceMetaKey = AttachmentKey.create(Map.class);
private <API key>() {
super(PathElement.pathElement(REST_RESOURCE_NAME), JaxrsExtension.getResolver("deployment"));
}
@Override
public void registerAttributes(<API key> <API key>) {
<API key>.registerMetric(RESOURCE_CLASS, new <API key>() {
@Override
void handleAttribute(String className, List<<API key>> methodInvokers,
List<<API key>> locatorIncokers, Collection<String> servletMappings,
ModelNode response) {
response.set(className);
}
});
<API key>.registerMetric(RESOURCE_PATHS, new <API key>() {
@Override
void handleAttribute(String className, List<<API key>> methodInvokers,
List<<API key>> locatorIncokers, Collection<String> servletMappings,
ModelNode response) {
for (<API key> methodDesc: methodInvokers) {
response.add(methodDesc.toModelNode());
}
}
});
<API key>.registerMetric(<API key>, new <API key>() {
@Override
void handleAttribute(String className, List<<API key>> methodInvokers,
List<<API key>> locatorIncokers, Collection<String> servletMappings,
ModelNode response) {
for (<API key> methodDesc: locatorIncokers) {
response.add(methodDesc.toModelNode());
}
}
});
}
abstract class <API key> implements <API key> {
@Override
public void execute(OperationContext context, ModelNode operation) throws <API key> {
PathAddress address = context.getCurrentAddress();
String clsName = address.getLastElement().getValue();
final PathAddress parentAddress = address.getParent();
final ModelNode subModel = context.<API key>(parentAddress.subAddress(0, parentAddress.size() - 1).append(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), false).getModel();
final String host = VIRTUAL_HOST.<API key>(context, subModel).asString();
final String contextPath = CONTEXT_ROOT.<API key>(context, subModel).asString();
final String server = SERVER.<API key>(context, subModel).asString();
Map<PathAddress, <API key>> <API key> = context.getAttachment(<API key>);
if (<API key> == null) {
<API key> = Collections.synchronizedMap(new HashMap<PathAddress, <API key>>());
context.attach(<API key>, <API key>);
}
<API key> <API key> = <API key>.get(parentAddress);
if (<API key> == null) {
final ServiceController<?> controller = context.getServiceRegistry(false).getService(UndertowService.<API key>(server, host, contextPath));
<API key> = (<API key>) controller.getService();
<API key>.put(parentAddress, <API key>);
}
final <API key> deploymentService = <API key>;
Map<String, ResourceMeta> resourceMetaMap = context.getAttachment(resourceMetaKey);
if (resourceMetaMap == null) {
resourceMetaMap = Collections.synchronizedMap(new HashMap<String, ResourceMeta>());
context.attach(resourceMetaKey, resourceMetaMap);
}
ResourceMeta resMeta = resourceMetaMap.get(clsName);
if (resMeta == null) {
resMeta = new ResourceMeta();
resourceMetaMap.put(clsName, resMeta);
}
final ResourceMeta resourceMeta = resMeta;
try {
deploymentService.getDeployment().<API key>(new ThreadSetupHandler.Action<Object, Object>() {
@Override
public Object call(HttpServerExchange exchange, Object ctxObject) throws Exception {
List<<API key>> resteasyServlets = new ArrayList<>();
for (Map.Entry<String, ServletHandler> servletHandler : deploymentService.getDeployment().getServlets().getServletHandlers().entrySet()) {
if (<API key>.class.isAssignableFrom(servletHandler.getValue().getManagedServlet().getServletInfo().getServletClass())) {
resteasyServlets.add((<API key>) servletHandler.getValue().getManagedServlet().getServlet().getInstance());
}
}
if (resteasyServlets.size() > 0) {
context.addStep(new <API key>() {
@Override
public void execute(OperationContext context, ModelNode operation) throws <API key> {
final ModelNode response = new ModelNode();
List<<API key>> resMethodInvokers = resourceMeta.methodInvokers;
List<<API key>> resLocatorInvokers = resourceMeta.resLocatorInvokers;
for (<API key> resteasyServlet: resteasyServlets) {
final Collection<String> servletMappings = resteasyServlet.getServletConfig().getServletContext().<API key>(resteasyServlet.getServletConfig().getServletName()).getMappings();
if (!resourceMeta.metaComplete) {
resourceMeta.metaComplete = true;
final <API key> registry = (<API key>) resteasyServlet.getDispatcher().getRegistry();
for (Map.Entry<String, List<ResourceInvoker>> resource : registry.getBounded().entrySet()) {
String mapping = resource.getKey();
List<ResourceInvoker> resouceInvokers = resource.getValue();
for (ResourceInvoker resourceInvoker : resouceInvokers) {
if (<API key>.class.isAssignableFrom(resourceInvoker.getClass())) {
<API key> methodInvoker = (<API key>) resourceInvoker;
Class<?> resClass = methodInvoker.getResourceClass();
if (resClass.getCanonicalName().equals(clsName)) {
<API key> resMethodDesc = <API key>(methodInvoker, contextPath, mapping, servletMappings, clsName);
resMethodInvokers.add(resMethodDesc);
} else if (resClass.isInterface()){
Class<?> resClsInModel = <API key>(clsName, context);
if (resClass.isAssignableFrom(resClsInModel)) {
<API key> resMethodDesc = <API key>(methodInvoker, contextPath, mapping, servletMappings, clsName);
resMethodInvokers.add(resMethodDesc);
}
}
} else if (<API key>.class.isAssignableFrom(resourceInvoker.getClass())) {
<API key> locatorInvoker = (<API key>) resourceInvoker;
Class<?> resLocatorClass = locatorInvoker.getMethod().getDeclaringClass();
if (clsName.equals(resLocatorClass.getCanonicalName())) {
ResourceClass resClass = ResourceBuilder.<API key>(locatorInvoker.getMethod().getReturnType());
<API key> resLocatorDesc = <API key>(resClass, contextPath, mapping, servletMappings, new ArrayList<Class<?>>());
resLocatorInvokers.add(resLocatorDesc);
} else if (resLocatorClass.isInterface()) {
Class<?> resClsInModel = <API key>(clsName, context);
if (resLocatorClass.isAssignableFrom(resClsInModel)) {
ResourceClass resClass = ResourceBuilder.<API key>(locatorInvoker.getMethod().getReturnType());
<API key> resLocatorDesc = <API key>(resClass, contextPath, mapping, servletMappings, new ArrayList<Class<?>>());
resLocatorInvokers.add(resLocatorDesc);
}
}
}
}
}
Collections.sort(resMethodInvokers);
Collections.sort(resLocatorInvokers);
}
handleAttribute(clsName, resMethodInvokers, resLocatorInvokers, servletMappings, response);
}
context.getResult().set(response);
}
private Class<?> <API key>(String clsName, OperationContext context) throws <API key>{
try {
Map<PathAddress, Module> deploymentModuleMap = context.getAttachment(deploymentModuleKey);
if (deploymentModuleMap == null) {
deploymentModuleMap = Collections.synchronizedMap(new HashMap<PathAddress, Module>());
context.attach(deploymentModuleKey, deploymentModuleMap);
}
Module deployModule = deploymentModuleMap.get(parentAddress);
if (deployModule == null) {
final StringBuilder sb = new StringBuilder(<API key>.DEPLOYMENT);
sb.append(".");
String deployRuntimeName = address.getElement(0).getValue();
final ModelNode deployModel = context.<API key>(address.subAddress(0, 1)).getModel();
if (deployModel.isDefined() && deployModel.hasDefined(<API key>.RUNTIME_NAME)) {
deployRuntimeName = deployModel.get(<API key>.RUNTIME_NAME).asString();
}
sb.append(deployRuntimeName);
if (address.size() > 1 && address.getElement(1).getKey().equals(<API key>.SUBDEPLOYMENT)) {
sb.append(".");
sb.append(address.getElement(1).getValue());
}
String moduleName = sb.toString();
ServiceModuleLoader srvModuleLoader = (ServiceModuleLoader) context.getServiceRegistry(false).getRequiredService(Services.<API key>).getValue();
deployModule = srvModuleLoader.loadModule(moduleName);
deploymentModuleMap.put(parentAddress, deployModule);
}
return Class.forName(clsName, false, deployModule.getClassLoader());
} catch (Exception e) {
throw new <API key>(e);
}
}
}, OperationContext.Stage.RUNTIME);
}
return null;
}
}).call(null, null);
} catch (Exception ex) {
//WFLY-10222 we don't want a failure to read the attribute to break everything
JaxrsLogger.JAXRS_LOGGER.<API key>(ex, address, operation.get(NAME));
context.addResponseWarning(Level.WARN, ex.getMessage());
}
}
abstract void handleAttribute(String className, List<<API key>> methodInvokers,
List<<API key>> locatorIncokers, Collection<String> servletMappings, ModelNode response);
}
private class ResourceMeta {
private List<<API key>> methodInvokers;
private List<<API key>> resLocatorInvokers;
private boolean metaComplete = false;
private ResourceMeta() {
this.methodInvokers = new ArrayList<>();
this.resLocatorInvokers = new ArrayList<>();
}
}
private <API key> <API key>(ResourceClass resClass, String contextPath, String mapping,
Collection<String> servletMappings, List<Class<?>> resolvedCls) {
<API key> locatorRes = new <API key>();
locatorRes.resourceClass = resClass.getClazz();
resolvedCls.add(resClass.getClazz());
for (ResourceMethod resMethod : resClass.getResourceMethods()) {
<API key> jaxrsRes = new <API key>();
jaxrsRes.consumeTypes = resMethod.getConsumes();
jaxrsRes.contextPath = contextPath;
jaxrsRes.httpMethods = resMethod.getHttpMethods();
jaxrsRes.method = resMethod.getMethod();
jaxrsRes.produceTypes = resMethod.getProduces();
jaxrsRes.resourceClass = resClass.getClazz().getCanonicalName();
String resPath = new StringBuilder(mapping).append("/").append(resMethod.getFullpath()).toString().replace("
jaxrsRes.resourcePath = resPath;
jaxrsRes.servletMappings = servletMappings;
addMethodParameters(jaxrsRes, resMethod.getMethod());
locatorRes.methodsDescriptions.add(jaxrsRes);
}
for (ResourceLocator resLocator: resClass.getResourceLocators()) {
Class<?> clz = resLocator.getReturnType();
if (clz.equals(resClass.getClazz())) {
break;
}
if (resolvedCls.contains(clz)) {
break;
} else {
resolvedCls.add(clz);
}
ResourceClass subResClass = ResourceBuilder.<API key>(clz);
String subMapping = new StringBuilder(mapping).append("/").append(resLocator.getFullpath()).toString().replace("
<API key> inner = <API key>(subResClass, contextPath, subMapping, servletMappings, resolvedCls);
if (inner.<API key>()) {
locatorRes.<API key>.add(inner);
}
}
return locatorRes;
}
private <API key> <API key>(<API key> methodInvoker, String contextPath,
String mapping, Collection<String> servletMappings, String clsName) {
<API key> jaxrsRes = new <API key>();
jaxrsRes.consumeTypes = methodInvoker.getConsumes();
jaxrsRes.contextPath = contextPath;
jaxrsRes.httpMethods = methodInvoker.getHttpMethods();
jaxrsRes.method = methodInvoker.getMethod();
jaxrsRes.produceTypes = methodInvoker.getProduces();
jaxrsRes.resourceClass = clsName;
jaxrsRes.resourcePath = mapping;
jaxrsRes.servletMappings = servletMappings;
addMethodParameters(jaxrsRes, methodInvoker.getMethod());
return jaxrsRes;
}
private void addMethodParameters(<API key> jaxrsRes, Method method) {
for (Parameter param : method.getParameters()) {
ParamInfo paramInfo = new ParamInfo();
paramInfo.cls = param.getType();
paramInfo.defaultValue = null;
paramInfo.name = null;
paramInfo.type = null;
Annotation annotation;
if ((annotation = param.getAnnotation(PathParam.class)) != null) {
PathParam pathParam = (PathParam) annotation;
paramInfo.name = pathParam.value();
paramInfo.type = "@" + PathParam.class.getSimpleName();
} else if ((annotation = param.getAnnotation(QueryParam.class)) != null) {
QueryParam queryParam = (QueryParam) annotation;
paramInfo.name = queryParam.value();
paramInfo.type = "@" + QueryParam.class.getSimpleName();
} else if ((annotation = param.getAnnotation(HeaderParam.class)) != null) {
HeaderParam headerParam = (HeaderParam) annotation;
paramInfo.name = headerParam.value();
paramInfo.type = "@" + HeaderParam.class.getSimpleName();
} else if ((annotation = param.getAnnotation(CookieParam.class)) != null) {
CookieParam cookieParam = (CookieParam) annotation;
paramInfo.name = cookieParam.value();
paramInfo.type = "@" + CookieParam.class.getSimpleName();
} else if ((annotation = param.getAnnotation(MatrixParam.class)) != null) {
MatrixParam matrixParam = (MatrixParam) annotation;
paramInfo.name = matrixParam.value();
paramInfo.type = "@" + MatrixParam.class.getSimpleName();
} else if ((annotation = param.getAnnotation(FormParam.class)) != null) {
FormParam formParam = (FormParam) annotation;
paramInfo.name = formParam.value();
paramInfo.type = "@" + FormParam.class.getSimpleName();
}
if (paramInfo.name == null) {
paramInfo.name = param.getName();
}
if ((annotation = param.getAnnotation(DefaultValue.class)) != null) {
DefaultValue defaultValue = (DefaultValue) annotation;
paramInfo.defaultValue = defaultValue.value();
}
jaxrsRes.parameters.add(paramInfo);
}
}
private static class <API key> implements Comparable<<API key>> {
private Class<?> resourceClass;
private List<<API key>> methodsDescriptions = new ArrayList<>();
private List<<API key>> <API key> = new ArrayList<>();
@Override
public int compareTo(<API key> o) {
return resourceClass.getCanonicalName().compareTo(o.resourceClass.getCanonicalName());
}
public ModelNode toModelNode() {
ModelNode node = new ModelNode();
node.get(RESOURCE_CLASS.getName()).set(resourceClass.getCanonicalName());
ModelNode resPathNode = node.get(RESOURCE_PATHS.getName());
Collections.sort(methodsDescriptions);
for (<API key> methodRes : methodsDescriptions) {
resPathNode.add(methodRes.toModelNode());
}
ModelNode subResNode = node.get(<API key>.getName());
Collections.sort(<API key>);
for (<API key> subLocator : <API key>) {
subResNode.add(subLocator.toModelNode());
}
return node;
}
private boolean <API key>() {
if (this.methodsDescriptions.size() > 0) {
return true;
}
for (<API key> p : this.<API key>) {
if (p.<API key>()) {
return true;
}
}
return false;
}
}
private static class <API key> implements Comparable<<API key>> {
private String resourceClass;
private String resourcePath;
private Method method;
private List<ParamInfo> parameters = new ArrayList<>();
private Set<String> httpMethods = Collections.emptySet();
private MediaType[] consumeTypes;
private MediaType[] produceTypes;
private Collection<String> servletMappings = Collections.emptyList();
private String contextPath;
@Override
public int compareTo(<API key> other) {
int result = this.resourcePath.compareTo(other.resourcePath);
if (result == 0) {
result = this.resourceClass.compareTo(other.resourceClass);
}
if (result == 0) {
result = this.method.getName().compareTo(other.method.getName());
}
return result;
}
ModelNode toModelNode() {
ModelNode node = new ModelNode();
node.get(RESOURCE_PATH.getName()).set(resourcePath);
ModelNode consumeNode = node.get(CONSUMES.getName());
if (consumeTypes != null && consumeTypes.length > 0) {
for (MediaType consume : consumeTypes) {
consumeNode.add(consume.toString());
}
}
ModelNode produceNode = node.get(PRODUCES.getName());
if (produceTypes != null && produceTypes.length > 0) {
for (MediaType produce : produceTypes) {
produceNode.add(produce.toString());
}
}
node.get(JAVA_METHOD.getName()).set(formatJavaMethod());
for (final String servletMapping : servletMappings) {
for (final String httpMethod : httpMethods) {
node.get(RESOURCE_METHODS.getName()).add(httpMethod + " " + formatPath(servletMapping, contextPath, resourcePath));
}
}
return node;
}
private String formatPath(String servletMapping, String ctxPath, String resPath) {
StringBuilder sb = new StringBuilder();
String servletPath = servletMapping.replaceAll("\\*", "");
if (servletPath.charAt(0) == '/') {
servletPath = servletPath.substring(1);
}
sb.append(ctxPath).append('/').append(servletPath).append(resPath);
return sb.toString().replace("
}
private String formatJavaMethod() {
StringBuilder sb = new StringBuilder();
sb.append(method.getReturnType().getCanonicalName()).append(" ").append(resourceClass)
.append(".").append(method.getName()).append('(');
int i = 0;
for (ParamInfo param : this.parameters) {
if (param.type != null) {
sb.append(param.type).append(" ");
}
sb.append(param.cls.getCanonicalName()).append(" ").append(param.name);
if (param.defaultValue != null) {
sb.append(" = '");
sb.append(param.defaultValue);
sb.append("'");
}
if (++i < this.parameters.size()) {
sb.append(", ");
}
}
sb.append(")");
return sb.toString();
}
}
private static class ParamInfo {
private String name;
private Class<?> cls;
private String type; // @PathParam, or @CookieParam, or @QueryParam, etc
private String defaultValue;
}
} |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /><title>GetSubscriptionIDs xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />
</head>
<body>
<div id="overview"><a href="../../../../../apidocs/org/accada/epcis/soapapi/GetSubscriptionIDs.html">View Javadoc</a></div><pre>
<a name="20" href="#20">20</a>
<a name="21" href="#21">21</a> <strong>package</strong> org.accada.epcis.soapapi;
<a name="22" href="#22">22</a>
<a name="23" href="#23">23</a> <strong>public</strong> <strong>class</strong> <a href="../../../../org/accada/epcis/soapapi/GetSubscriptionIDs.html">GetSubscriptionIDs</a> implements java.io.Serializable {
<a name="24" href="#24">24</a> <strong>private</strong> java.lang.String queryName;
<a name="25" href="#25">25</a>
<a name="26" href="#26">26</a> <strong>public</strong> <a href="../../../../org/accada/epcis/soapapi/GetSubscriptionIDs.html">GetSubscriptionIDs</a>() {
<a name="27" href="#27">27</a> }
<a name="28" href="#28">28</a>
<a name="29" href="#29">29</a> <strong>public</strong> <a href="../../../../org/accada/epcis/soapapi/GetSubscriptionIDs.html">GetSubscriptionIDs</a>(
<a name="30" href="#30">30</a> java.lang.String queryName) {
<a name="31" href="#31">31</a> <strong>this</strong>.queryName = queryName;
<a name="32" href="#32">32</a> }
<a name="33" href="#33">33</a>
<a name="34" href="#34">34</a>
<a name="35" href="#35">35</a> <em>/**</em>
<a name="36" href="#36">36</a> <em> * Gets the queryName value for this GetSubscriptionIDs.</em>
<a name="37" href="#37">37</a> <em> * </em>
<a name="38" href="#38">38</a> <em> * @return queryName</em>
<a name="39" href="#39">39</a> <em> */</em>
<a name="40" href="#40">40</a> <strong>public</strong> java.lang.String getQueryName() {
<a name="41" href="#41">41</a> <strong>return</strong> queryName;
<a name="42" href="#42">42</a> }
<a name="43" href="#43">43</a>
<a name="44" href="#44">44</a>
<a name="45" href="#45">45</a> <em>/**</em>
<a name="46" href="#46">46</a> <em> * Sets the queryName value for this GetSubscriptionIDs.</em>
<a name="47" href="#47">47</a> <em> * </em>
<a name="48" href="#48">48</a> <em> * @param queryName</em>
<a name="49" href="#49">49</a> <em> */</em>
<a name="50" href="#50">50</a> <strong>public</strong> <strong>void</strong> setQueryName(java.lang.String queryName) {
<a name="51" href="#51">51</a> <strong>this</strong>.queryName = queryName;
<a name="52" href="#52">52</a> }
<a name="53" href="#53">53</a>
<a name="54" href="#54">54</a> <strong>private</strong> java.lang.Object __equalsCalc = <strong>null</strong>;
<a name="55" href="#55">55</a> <strong>public</strong> <strong>synchronized</strong> <strong>boolean</strong> equals(java.lang.Object obj) {
<a name="56" href="#56">56</a> <strong>if</strong> (!(obj instanceof GetSubscriptionIDs)) <strong>return</strong> false;
<a name="57" href="#57">57</a> <a href="../../../../org/accada/epcis/soapapi/GetSubscriptionIDs.html">GetSubscriptionIDs</a> other = (GetSubscriptionIDs) obj;
<a name="58" href="#58">58</a> <strong>if</strong> (obj == <strong>null</strong>) <strong>return</strong> false;
<a name="59" href="#59">59</a> <strong>if</strong> (<strong>this</strong> == obj) <strong>return</strong> <strong>true</strong>;
<a name="60" href="#60">60</a> <strong>if</strong> (__equalsCalc != <strong>null</strong>) {
<a name="61" href="#61">61</a> <strong>return</strong> (__equalsCalc == obj);
<a name="62" href="#62">62</a> }
<a name="63" href="#63">63</a> __equalsCalc = obj;
<a name="64" href="#64">64</a> <strong>boolean</strong> _equals;
<a name="65" href="#65">65</a> _equals = <strong>true</strong> &&
<a name="66" href="#66">66</a> ((<strong>this</strong>.queryName==<strong>null</strong> && other.getQueryName()==<strong>null</strong>) ||
<a name="67" href="#67">67</a> (<strong>this</strong>.queryName!=<strong>null</strong> &&
<a name="68" href="#68">68</a> <strong>this</strong>.queryName.equals(other.getQueryName())));
<a name="69" href="#69">69</a> __equalsCalc = <strong>null</strong>;
<a name="70" href="#70">70</a> <strong>return</strong> _equals;
<a name="71" href="#71">71</a> }
<a name="72" href="#72">72</a>
<a name="73" href="#73">73</a> <strong>private</strong> <strong>boolean</strong> __hashCodeCalc = false;
<a name="74" href="#74">74</a> <strong>public</strong> <strong>synchronized</strong> <strong>int</strong> hashCode() {
<a name="75" href="#75">75</a> <strong>if</strong> (__hashCodeCalc) {
<a name="76" href="#76">76</a> <strong>return</strong> 0;
<a name="77" href="#77">77</a> }
<a name="78" href="#78">78</a> __hashCodeCalc = <strong>true</strong>;
<a name="79" href="#79">79</a> <strong>int</strong> _hashCode = 1;
<a name="80" href="#80">80</a> <strong>if</strong> (getQueryName() != <strong>null</strong>) {
<a name="81" href="#81">81</a> _hashCode += getQueryName().hashCode();
<a name="82" href="#82">82</a> }
<a name="83" href="#83">83</a> __hashCodeCalc = false;
<a name="84" href="#84">84</a> <strong>return</strong> _hashCode;
<a name="85" href="#85">85</a> }
<a name="86" href="#86">86</a>
<a name="87" href="#87">87</a> <em class="comment">// Type metadata</em>
<a name="88" href="#88">88</a> <strong>private</strong> <strong>static</strong> org.apache.axis.description.TypeDesc typeDesc =
<a name="89" href="#89">89</a> <strong>new</strong> org.apache.axis.description.TypeDesc(GetSubscriptionIDs.<strong>class</strong>, <strong>true</strong>);
<a name="90" href="#90">90</a>
<a name="91" href="#91">91</a> <strong>static</strong> {
<a name="92" href="#92">92</a> typeDesc.setXmlType(<strong>new</strong> javax.xml.namespace.QName(<span class="string">"urn:epcglobal:epcis-query:xsd:1"</span>, <span class="string">"GetSubscriptionIDs"</span>));
<a name="93" href="#93">93</a> org.apache.axis.description.ElementDesc elemField = <strong>new</strong> org.apache.axis.description.ElementDesc();
<a name="94" href="#94">94</a> elemField.setFieldName(<span class="string">"queryName"</span>);
<a name="95" href="#95">95</a> elemField.setXmlName(<strong>new</strong> javax.xml.namespace.QName(<span class="string">""</span>, <span class="string">"queryName"</span>));
<a name="96" href="
<a name="97" href="#97">97</a> elemField.setNillable(false);
<a name="98" href="#98">98</a> typeDesc.addFieldDesc(elemField);
<a name="99" href="#99">99</a> }
<a name="100" href="#100">100</a>
<a name="101" href="#101">101</a> <em>/**</em>
<a name="102" href="#102">102</a> <em> * Return type metadata object</em>
<a name="103" href="#103">103</a> <em> */</em>
<a name="104" href="#104">104</a> <strong>public</strong> <strong>static</strong> org.apache.axis.description.TypeDesc getTypeDesc() {
<a name="105" href="#105">105</a> <strong>return</strong> typeDesc;
<a name="106" href="#106">106</a> }
<a name="107" href="#107">107</a>
<a name="108" href="#108">108</a> <em>/**</em>
<a name="109" href="#109">109</a> <em> * Get Custom Serializer</em>
<a name="110" href="#110">110</a> <em> */</em>
<a name="111" href="#111">111</a> <strong>public</strong> <strong>static</strong> org.apache.axis.encoding.Serializer getSerializer(
<a name="112" href="#112">112</a> java.lang.String mechType,
<a name="113" href="#113">113</a> java.lang.Class _javaType,
<a name="114" href="#114">114</a> javax.xml.namespace.QName _xmlType) {
<a name="115" href="#115">115</a> <strong>return</strong>
<a name="116" href="#116">116</a> <strong>new</strong> org.apache.axis.encoding.ser.BeanSerializer(
<a name="117" href="#117">117</a> _javaType, _xmlType, typeDesc);
<a name="118" href="#118">118</a> }
<a name="119" href="#119">119</a>
<a name="120" href="#120">120</a> <em>/**</em>
<a name="121" href="#121">121</a> <em> * Get Custom Deserializer</em>
<a name="122" href="#122">122</a> <em> */</em>
<a name="123" href="#123">123</a> <strong>public</strong> <strong>static</strong> org.apache.axis.encoding.Deserializer getDeserializer(
<a name="124" href="#124">124</a> java.lang.String mechType,
<a name="125" href="#125">125</a> java.lang.Class _javaType,
<a name="126" href="#126">126</a> javax.xml.namespace.QName _xmlType) {
<a name="127" href="#127">127</a> <strong>return</strong>
<a name="128" href="#128">128</a> <strong>new</strong> org.apache.axis.encoding.ser.BeanDeserializer(
<a name="129" href="#129">129</a> _javaType, _xmlType, typeDesc);
<a name="130" href="#130">130</a> }
<a name="131" href="#131">131</a>
<a name="132" href="#132">132</a> }
</pre>
<hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body>
</html> |
<?php
/**
* @see Zend_Gdata_Photos
*/
require_once 'Zend/Gdata/Photos.php';
/**
* @see Zend_Gdata_Feed
*/
require_once 'Zend/Gdata/Feed.php';
/**
* @see <API key>
*/
require_once 'Zend/Gdata/Photos/AlbumEntry.php';
class <API key> extends Zend_Gdata_Feed
{
protected $_entryClassName = '<API key>';
protected $_feedClassName = '<API key>';
/**
* gphoto:id element
*
* @var <API key>
*/
protected $_gphotoId = null;
/**
* gphoto:user element
*
* @var <API key>
*/
protected $_gphotoUser = null;
/**
* gphoto:access element
*
* @var <API key>
*/
protected $_gphotoAccess = null;
/**
* gphoto:location element
*
* @var <API key>
*/
protected $_gphotoLocation = null;
/**
* gphoto:nickname element
*
* @var <API key>
*/
protected $_gphotoNickname = null;
/**
* gphoto:timestamp element
*
* @var <API key>
*/
protected $_gphotoTimestamp = null;
/**
* gphoto:name element
*
* @var <API key>
*/
protected $_gphotoName = null;
/**
* gphoto:numphotos element
*
* @var <API key>
*/
protected $_gphotoNumPhotos = null;
/**
* gphoto:commentCount element
*
* @var <API key>
*/
protected $_gphotoCommentCount = null;
/**
* gphoto:commentingEnabled element
*
* @var <API key>
*/
protected $<API key> = null;
protected $<API key> = array(
'http://schemas.google.com/photos/2007#photo' => '<API key>',
'http://schemas.google.com/photos/2007#comment' => '<API key>',
'http://schemas.google.com/photos/2007#tag' => '<API key>'
);
public function __construct($element = null)
{
foreach (Zend_Gdata_Photos::$namespaces as $nsPrefix => $nsUri) {
$this->registerNamespace($nsPrefix, $nsUri);
}
parent::__construct($element);
}
public function getDOM($doc = null)
{
$element = parent::getDOM($doc);
if ($this->_gphotoId != null) {
$element->appendChild($this->_gphotoId->getDOM($element->ownerDocument));
}
if ($this->_gphotoUser != null) {
$element->appendChild($this->_gphotoUser->getDOM($element->ownerDocument));
}
if ($this->_gphotoNickname != null) {
$element->appendChild($this->_gphotoNickname->getDOM($element->ownerDocument));
}
if ($this->_gphotoName != null) {
$element->appendChild($this->_gphotoName->getDOM($element->ownerDocument));
}
if ($this->_gphotoLocation != null) {
$element->appendChild($this->_gphotoLocation->getDOM($element->ownerDocument));
}
if ($this->_gphotoAccess != null) {
$element->appendChild($this->_gphotoAccess->getDOM($element->ownerDocument));
}
if ($this->_gphotoTimestamp != null) {
$element->appendChild($this->_gphotoTimestamp->getDOM($element->ownerDocument));
}
if ($this->_gphotoNumPhotos != null) {
$element->appendChild($this->_gphotoNumPhotos->getDOM($element->ownerDocument));
}
if ($this-><API key> != null) {
$element->appendChild($this-><API key>->getDOM($element->ownerDocument));
}
if ($this->_gphotoCommentCount != null) {
$element->appendChild($this->_gphotoCommentCount->getDOM($element->ownerDocument));
}
return $element;
}
protected function takeChildFromDOM($child)
{
$absoluteNodeName = $child->namespaceURI . ':' . $child->localName;
switch ($absoluteNodeName) {
case $this->lookupNamespace('gphoto') . ':' . 'id';
$id = new <API key>();
$id->transferFromDOM($child);
$this->_gphotoId = $id;
break;
case $this->lookupNamespace('gphoto') . ':' . 'user';
$user = new <API key>();
$user->transferFromDOM($child);
$this->_gphotoUser = $user;
break;
case $this->lookupNamespace('gphoto') . ':' . 'nickname';
$nickname = new <API key>();
$nickname->transferFromDOM($child);
$this->_gphotoNickname = $nickname;
break;
case $this->lookupNamespace('gphoto') . ':' . 'name';
$name = new <API key>();
$name->transferFromDOM($child);
$this->_gphotoName = $name;
break;
case $this->lookupNamespace('gphoto') . ':' . 'location';
$location = new <API key>();
$location->transferFromDOM($child);
$this->_gphotoLocation = $location;
break;
case $this->lookupNamespace('gphoto') . ':' . 'access';
$access = new <API key>();
$access->transferFromDOM($child);
$this->_gphotoAccess = $access;
break;
case $this->lookupNamespace('gphoto') . ':' . 'timestamp';
$timestamp = new <API key>();
$timestamp->transferFromDOM($child);
$this->_gphotoTimestamp = $timestamp;
break;
case $this->lookupNamespace('gphoto') . ':' . 'numphotos';
$numphotos = new <API key>();
$numphotos->transferFromDOM($child);
$this->_gphotoNumPhotos = $numphotos;
break;
case $this->lookupNamespace('gphoto') . ':' . 'commentingEnabled';
$commentingEnabled = new <API key>();
$commentingEnabled->transferFromDOM($child);
$this-><API key> = $commentingEnabled;
break;
case $this->lookupNamespace('gphoto') . ':' . 'commentCount';
$commentCount = new <API key>();
$commentCount->transferFromDOM($child);
$this->_gphotoCommentCount = $commentCount;
break;
case $this->lookupNamespace('atom') . ':' . 'entry':
$entryClassName = $this->_entryClassName;
$tmpEntry = new <API key>($child);
$categories = $tmpEntry->getCategory();
foreach ($categories as $category) {
if ($category->scheme == Zend_Gdata_Photos::KIND_PATH &&
$this-><API key>[$category->term] != "") {
$entryClassName = $this-><API key>[$category->term];
break;
} else {
require_once 'Zend/Gdata/App/Exception.php';
throw new <API key>('Entry is missing kind declaration.');
}
}
$newEntry = new $entryClassName($child);
$newEntry->setHttpClient($this->getHttpClient());
$this->_entry[] = $newEntry;
break;
default:
parent::takeChildFromDOM($child);
break;
}
}
/**
* Get the value for this element's gphoto:user attribute.
*
* @see setGphotoUser
* @return string The requested attribute.
*/
public function getGphotoUser()
{
return $this->_gphotoUser;
}
/**
* Set the value for this element's gphoto:user attribute.
*
* @param string $value The desired value for this attribute.
* @return <API key> The element being modified.
*/
public function setGphotoUser($value)
{
$this->_gphotoUser = $value;
return $this;
}
/**
* Get the value for this element's gphoto:access attribute.
*
* @see setGphotoAccess
* @return string The requested attribute.
*/
public function getGphotoAccess()
{
return $this->_gphotoAccess;
}
/**
* Set the value for this element's gphoto:access attribute.
*
* @param string $value The desired value for this attribute.
* @return <API key> The element being modified.
*/
public function setGphotoAccess($value)
{
$this->_gphotoAccess = $value;
return $this;
}
/**
* Get the value for this element's gphoto:location attribute.
*
* @see setGphotoLocation
* @return string The requested attribute.
*/
public function getGphotoLocation()
{
return $this->_gphotoLocation;
}
/**
* Set the value for this element's gphoto:location attribute.
*
* @param string $value The desired value for this attribute.
* @return <API key> The element being modified.
*/
public function setGphotoLocation($value)
{
$this->_gphotoLocation = $value;
return $this;
}
/**
* Get the value for this element's gphoto:name attribute.
*
* @see setGphotoName
* @return string The requested attribute.
*/
public function getGphotoName()
{
return $this->_gphotoName;
}
/**
* Set the value for this element's gphoto:name attribute.
*
* @param string $value The desired value for this attribute.
* @return <API key> The element being modified.
*/
public function setGphotoName($value)
{
$this->_gphotoName = $value;
return $this;
}
/**
* Get the value for this element's gphoto:numphotos attribute.
*
* @see setGphotoNumPhotos
* @return string The requested attribute.
*/
public function getGphotoNumPhotos()
{
return $this->_gphotoNumPhotos;
}
/**
* Set the value for this element's gphoto:numphotos attribute.
*
* @param string $value The desired value for this attribute.
* @return <API key> The element being modified.
*/
public function setGphotoNumPhotos($value)
{
$this->_gphotoNumPhotos = $value;
return $this;
}
/**
* Get the value for this element's gphoto:commentCount attribute.
*
* @see <API key>
* @return string The requested attribute.
*/
public function <API key>()
{
return $this->_gphotoCommentCount;
}
/**
* Set the value for this element's gphoto:commentCount attribute.
*
* @param string $value The desired value for this attribute.
* @return <API key> The element being modified.
*/
public function <API key>($value)
{
$this->_gphotoCommentCount = $value;
return $this;
}
/**
* Get the value for this element's gphoto:commentingEnabled attribute.
*
* @see <API key>
* @return string The requested attribute.
*/
public function <API key>()
{
return $this-><API key>;
}
/**
* Set the value for this element's gphoto:commentingEnabled attribute.
*
* @param string $value The desired value for this attribute.
* @return <API key> The element being modified.
*/
public function <API key>($value)
{
$this-><API key> = $value;
return $this;
}
/**
* Get the value for this element's gphoto:id attribute.
*
* @see setGphotoId
* @return string The requested attribute.
*/
public function getGphotoId()
{
return $this->_gphotoId;
}
/**
* Set the value for this element's gphoto:id attribute.
*
* @param string $value The desired value for this attribute.
* @return <API key> The element being modified.
*/
public function setGphotoId($value)
{
$this->_gphotoId = $value;
return $this;
}
/**
* Get the value for this element's georss:where attribute.
*
* @see setGeoRssWhere
* @return string The requested attribute.
*/
public function getGeoRssWhere()
{
return $this->_geoRssWhere;
}
/**
* Set the value for this element's georss:where attribute.
*
* @param string $value The desired value for this attribute.
* @return <API key> The element being modified.
*/
public function setGeoRssWhere($value)
{
$this->_geoRssWhere = $value;
return $this;
}
/**
* Get the value for this element's gphoto:nickname attribute.
*
* @see setGphotoNickname
* @return string The requested attribute.
*/
public function getGphotoNickname()
{
return $this->_gphotoNickname;
}
/**
* Set the value for this element's gphoto:nickname attribute.
*
* @param string $value The desired value for this attribute.
* @return <API key> The element being modified.
*/
public function setGphotoNickname($value)
{
$this->_gphotoNickname = $value;
return $this;
}
/**
* Get the value for this element's gphoto:timestamp attribute.
*
* @see setGphotoTimestamp
* @return string The requested attribute.
*/
public function getGphotoTimestamp()
{
return $this->_gphotoTimestamp;
}
/**
* Set the value for this element's gphoto:timestamp attribute.
*
* @param string $value The desired value for this attribute.
* @return <API key> The element being modified.
*/
public function setGphotoTimestamp($value)
{
$this->_gphotoTimestamp = $value;
return $this;
}
} |
/* drvVmi3113A.c */
#include <vxWorks.h>
#include <stdlib.h>
#include <stdio.h>
#include <vxLib.h>
#include <sysLib.h>
#include <vme.h>
#include <dbDefs.h>
#include <drvSup.h>
#include <epicsVersion.h>
#if (EPICS_VERSION==3) && (EPICS_REVISION>=14)
#include <epicsExport.h>
#endif
#include "drvVmi3113A.h"
#define NUM_CHANNELS 64 /* number of channels in board */
/* these can be changed in st.cmd before iocInit if necessary */
unsigned int numVmi3113Acards = 2; /* number of cards in crate */
unsigned int vmi3113A_base = 0x8500; /* base address of card 0 */
/* set card 0 jumpers J9:A08-A15 to 0x8500 */
/* set card 1 jumpers J9:A08-A15 to 0x8600 */
/* set J9:17,18 and J9:19,20 to open for short supervisory access */
/* All other jumbers to factory configuration */
struct {
long number;
DRVSUPFUN report;
DRVSUPFUN init;
} drvVmi3113A={
2,
vmi3113A_report,
vmi3113A_init};
#if (EPICS_VERSION==3) && (EPICS_REVISION>=14)
epicsExportAddress(drvet,drvVmi3113A);
#endif
static unsigned short **pai_vmi3113A;
static int vmi3113A_addr;
/* initialize the 3113A analog input */
long vmi3113A_init(void)
{
unsigned short **boards_present;
short shval;
int status;
register short i;
vmic3113A * board;
pai_vmi3113A = (unsigned short **)
calloc(numVmi3113Acards,sizeof(*pai_vmi3113A));
if(!pai_vmi3113A){
return ERROR;
}
boards_present = pai_vmi3113A;
if ((status = sysBusToLocalAdrs(VME_AM_SUP_SHORT_IO,(char *)(long)vmi3113A_base, (char **)&vmi3113A_addr)) != OK){
printf("Addressing error in vmi3113A driver");
return ERROR;
}
board = ((vmic3113A * )((int)vmi3113A_addr));
for ( i = 0; i < numVmi3113Acards; i++, board ++, boards_present ++ ) {
if (vxMemProbe((char *)board,VX_READ,sizeof(short),(char *)&shval) == OK) {
*boards_present = (unsigned short *)board;
board->csr = ( SOFTWARE_RESET ); /* clear the board */
board->csr = ( FAIL_LED_OFF | AUTOSCANNING ); /* begin autoscanning mode */
}
else {
*boards_present = 0;
}
}
return(0);
}
/* 3113A analog input driver */
int vmi3113A_driver(
unsigned short card,
unsigned int signal,
unsigned long *pval
) {
register vmic3113A *paiVMI;
if ((paiVMI= (vmic3113A *)pai_vmi3113A[card]) == 0)
return(-1);
*pval = paiVMI->chan[signal];
return(0);
}
/* dbior */
long vmi3113A_report(int level)
{
int i, j;
vmic3113A *paiVMI;
unsigned long value;
for (i = 0; i < numVmi3113Acards; i++) {
if (pai_vmi3113A[i]) {
printf(" AI: VMIVME-3113A ADC: card %d is present.\n",i);
if ( level > 0 ){
paiVMI = (vmic3113A *)pai_vmi3113A[i];
printf(" Address = %p, Board ID = 0x%x, CSR = 0x%x, CFR = 0x%x\n",paiVMI,paiVMI->bid,paiVMI->csr,paiVMI->cfr);
if ( level > 1 ) {
for ( j = 0; j < NUM_CHANNELS; j++) {
vmi3113A_driver(i,j,&value);
printf(" Signal %.2d = 0x%.4lx\n",j,value);
}
}
}
}
}
return(0);
} |
use strict;
use warnings;
use SOOT ':all';
use constant NBINS => 20;
my $stack = shift;
my $c1 = TCanvas->new;
my $hs = THStack->new("hs","three plots")->keep;
my @colors = (kBlue, kRed, kYellow);
my @names = qw(h1 h2 h3);
my @h = map {
my $h = TH2F->new(($names[$_]) x 2, NBINS,-4,4, NBINS,-4,4);
$h->keep;
$h->SetFillColor($colors[$_]);
$hs->Add($h);
$h
} 0..$#names;
my $r = TRandom->new;
$h[0]->Fill($r->Gaus(), $r->Gaus()) for 1..20000;
foreach (1..200) {
my $ix = int($r->Uniform(0, NBINS));
my $iy = int($r->Uniform(0, NBINS));
my $bin = $h[0]->GetBin($ix, $iy);
my $val = $h[0]->GetBinContent($bin);
next if $val <= 0;
$h[0]->SetBinContent($bin,0) if not $stack;
if ($r->Rndm() > 0.5) {
$h[1]->SetBinContent($bin, 0) if not $stack;
$h[2]->SetBinContent($bin, $val);
}
else {
$h[2]->SetBinContent($bin, 0) if not $stack;
$h[1]->SetBinContent($bin, $val);
}
}
$hs->Draw("lego1");
$gApplication->Run; |
package jade.core.messaging;
import jade.core.Service;
import jade.core.AID;
import jade.core.ContainerID;
import jade.core.Location;
import jade.core.IMTPException;
import jade.core.ServiceException;
import jade.core.NotFoundException;
import jade.core.NameClashException;
import jade.security.<API key>;
import jade.lang.acl.ACLMessage;
import jade.mtp.MTPDescriptor;
import jade.mtp.MTPException;
import jade.domain.FIPAAgentManagement.Envelope;
/**
The horizontal interface for the JADE kernel-level service managing
the message passing subsystem installed in the platform.
@author Giovanni Rimassa - FRAMeTech s.r.l.
*/
public interface MessagingSlice extends Service.Slice {
// Constants for the names of the service vertical commands
/**
The name of this service.
*/
static final String NAME = "jade.core.messaging.Messaging";
/**
This command name represents the action of sending an ACL
message from an agent to another.
*/
static final String SEND_MESSAGE = "Send-Message";
/**
This command name represents the action of sending back a
FAILURE ACL message to notify the message originator of a
failed delivery.
*/
static final String NOTIFY_FAILURE = "Notify-Failure";
/**
This command name represents the <code>install-mtp</code>
action.
*/
static final String INSTALL_MTP = "Install-MTP";
/**
This command name represents the <code>uninstall-mtp</code>
action.
*/
static final String UNINSTALL_MTP = "Uninstall-MTP";
/**
This command name represents the <code>new-mtp</code>
event.
*/
static final String NEW_MTP = "New-MTP";
/**
This command name represents the <code>dead-mtp</code>
action.
*/
static final String DEAD_MTP = "Dead-MTP";
/**
This command name represents the <code><API key></code>
action.
*/
static final String <API key> = "<API key>";
// Constants for the names of horizontal commands associated to methods
static final String H_DISPATCHLOCALLY = "1";
static final String H_ROUTEOUT = "2";
static final String H_GETAGENTLOCATION = "3";
static final String H_INSTALLMTP = "4";
static final String H_UNINSTALLMTP ="5";
static final String H_NEWMTP = "6";
static final String H_DEADMTP = "7";
static final String H_ADDROUTE = "8";
static final String H_REMOVEROUTE = "9";
void dispatchLocally(AID senderAID, GenericMessage msg, AID receiverID) throws IMTPException, NotFoundException, <API key>;
void routeOut(Envelope env, byte[] payload, AID receiverID, String address) throws IMTPException, MTPException;
ContainerID getAgentLocation(AID agentID) throws IMTPException, NotFoundException;
MTPDescriptor installMTP(String address, String className) throws IMTPException, ServiceException, MTPException;
void uninstallMTP(String address) throws IMTPException, ServiceException, NotFoundException, MTPException;
void newMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException;
void deadMTP(MTPDescriptor mtp, ContainerID cid) throws IMTPException, ServiceException;
void addRoute(MTPDescriptor mtp, String sliceName) throws IMTPException, ServiceException;
void removeRoute(MTPDescriptor mtp, String sliceName) throws IMTPException, ServiceException;
} |
#ifndef COLOREDITOR_H
#define COLOREDITOR_H
#include <QVariant>
#include <QDialog>
#include "ui_coloreditor.h"
class ColorEditor : public QDialog, public Ui::ColorEditor
{
Q_OBJECT
public:
ColorEditor(QWidget* parent = 0, Qt::WindowFlags fl = 0);
~ColorEditor();
public slots:
virtual void _btnColor_clicked();
virtual void setColorName( QString name );
virtual void setColor( const QColor & col );
virtual QColor getColor();
virtual QString getColorName();
protected slots:
virtual void languageChange();
};
#endif // COLOREDITOR_H |
#ifdef ASM_X86
extern void window_mpg_asm(float *a, int b, short *c);
extern void window_dual_asm(float *a, int b, short *c);
extern void window16_asm(float *a, int b, short *c);
extern void window16_dual_asm(float *a, int b, short *c);
extern void window8_asm(float *a, int b, short *c);
extern void window8_dual_asm(float *a, int b, short *c);
#endif /* ASM_X86 */
#include "mhead.h"
void window(MPEG *m, float *vbuf, int vb_ptr, short *pcm)
{
#ifdef ASM_X86
window_mpg_asm(vbuf, vb_ptr, pcm);
#else
int i, j;
int si, bx;
float *coef;
float sum;
long tmp;
si = vb_ptr + 16;
bx = (si + 32) & 511;
coef = wincoef;
/*-- first 16 --*/
for (i = 0; i < 16; i++)
{
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef++) * vbuf[si];
si = (si + 64) & 511;
sum -= (*coef++) * vbuf[bx];
bx = (bx + 64) & 511;
}
si++;
bx
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm++ = tmp;
}
/*-- special case --*/
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef++) * vbuf[bx];
bx = (bx + 64) & 511;
}
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm++ = tmp;
/*-- last 15 --*/
coef = wincoef + 255; /* back pass through coefs */
for (i = 0; i < 15; i++)
{
si
bx++;
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef--) * vbuf[si];
si = (si + 64) & 511;
sum += (*coef--) * vbuf[bx];
bx = (bx + 64) & 511;
}
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm++ = tmp;
}
#endif
}
void window_dual(MPEG *m, float *vbuf, int vb_ptr, short *pcm)
{
#ifdef ASM_X86
window_dual_asm(vbuf, vb_ptr, pcm);
#else
int i, j; /* dual window interleaves output */
int si, bx;
float *coef;
float sum;
long tmp;
si = vb_ptr + 16;
bx = (si + 32) & 511;
coef = wincoef;
/*-- first 16 --*/
for (i = 0; i < 16; i++)
{
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef++) * vbuf[si];
si = (si + 64) & 511;
sum -= (*coef++) * vbuf[bx];
bx = (bx + 64) & 511;
}
si++;
bx
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm = tmp;
pcm += 2;
}
/*-- special case --*/
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef++) * vbuf[bx];
bx = (bx + 64) & 511;
}
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm = tmp;
pcm += 2;
/*-- last 15 --*/
coef = wincoef + 255; /* back pass through coefs */
for (i = 0; i < 15; i++)
{
si
bx++;
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef--) * vbuf[si];
si = (si + 64) & 511;
sum += (*coef--) * vbuf[bx];
bx = (bx + 64) & 511;
}
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm = tmp;
pcm += 2;
}
#endif
}
void window16(MPEG *m, float *vbuf, int vb_ptr, short *pcm)
{
#ifdef ASM_X86
window16_asm(vbuf, vb_ptr, pcm);
#else
int i, j;
unsigned char si, bx;
float *coef;
float sum;
long tmp;
si = vb_ptr + 8;
bx = si + 16;
coef = wincoef;
/*-- first 8 --*/
for (i = 0; i < 8; i++)
{
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef++) * vbuf[si];
si += 32;
sum -= (*coef++) * vbuf[bx];
bx += 32;
}
si++;
bx
coef += 16;
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm++ = tmp;
}
/*-- special case --*/
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef++) * vbuf[bx];
bx += 32;
}
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm++ = tmp;
/*-- last 7 --*/
coef = wincoef + 255; /* back pass through coefs */
for (i = 0; i < 7; i++)
{
coef -= 16;
si
bx++;
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef--) * vbuf[si];
si += 32;
sum += (*coef--) * vbuf[bx];
bx += 32;
}
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm++ = tmp;
}
#endif
}
void window16_dual(MPEG *m, float *vbuf, int vb_ptr, short *pcm)
{
#ifdef ASM_X86
window16_dual_asm(vbuf, vb_ptr, pcm);
#else
int i, j;
unsigned char si, bx;
float *coef;
float sum;
long tmp;
si = vb_ptr + 8;
bx = si + 16;
coef = wincoef;
/*-- first 8 --*/
for (i = 0; i < 8; i++)
{
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef++) * vbuf[si];
si += 32;
sum -= (*coef++) * vbuf[bx];
bx += 32;
}
si++;
bx
coef += 16;
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm = tmp;
pcm += 2;
}
/*-- special case --*/
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef++) * vbuf[bx];
bx += 32;
}
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm = tmp;
pcm += 2;
/*-- last 7 --*/
coef = wincoef + 255; /* back pass through coefs */
for (i = 0; i < 7; i++)
{
coef -= 16;
si
bx++;
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef--) * vbuf[si];
si += 32;
sum += (*coef--) * vbuf[bx];
bx += 32;
}
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm = tmp;
pcm += 2;
}
#endif
}
void window8(MPEG8 *m, float *vbuf, int vb_ptr, short *pcm)
{
#ifdef ASM_X86
window8_asm(vbuf, vb_ptr, pcm);
#else
int i, j;
int si, bx;
float *coef;
float sum;
long tmp;
si = vb_ptr + 4;
bx = (si + 8) & 127;
coef = wincoef;
/*-- first 4 --*/
for (i = 0; i < 4; i++)
{
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef++) * vbuf[si];
si = (si + 16) & 127;
sum -= (*coef++) * vbuf[bx];
bx = (bx + 16) & 127;
}
si++;
bx
coef += 48;
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm++ = tmp;
}
/*-- special case --*/
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef++) * vbuf[bx];
bx = (bx + 16) & 127;
}
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm++ = tmp;
/*-- last 3 --*/
coef = wincoef + 255; /* back pass through coefs */
for (i = 0; i < 3; i++)
{
coef -= 48;
si
bx++;
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef--) * vbuf[si];
si = (si + 16) & 127;
sum += (*coef--) * vbuf[bx];
bx = (bx + 16) & 127;
}
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm++ = tmp;
}
#endif
}
void window8_dual(MPEG8 *m, float *vbuf, int vb_ptr, short *pcm)
{
#ifdef ASM_X86
window8_dual_asm(vbuf, vb_ptr, pcm);
#else
int i, j;
int si, bx;
float *coef;
float sum;
long tmp;
si = vb_ptr + 4;
bx = (si + 8) & 127;
coef = wincoef;
/*-- first 4 --*/
for (i = 0; i < 4; i++)
{
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef++) * vbuf[si];
si = (si + 16) & 127;
sum -= (*coef++) * vbuf[bx];
bx = (bx + 16) & 127;
}
si++;
bx
coef += 48;
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm = tmp;
pcm += 2;
}
/*-- special case --*/
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef++) * vbuf[bx];
bx = (bx + 16) & 127;
}
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm = tmp;
pcm += 2;
/*-- last 3 --*/
coef = wincoef + 255; /* back pass through coefs */
for (i = 0; i < 3; i++)
{
coef -= 48;
si
bx++;
sum = 0.0F;
for (j = 0; j < 8; j++)
{
sum += (*coef--) * vbuf[si];
si = (si + 16) & 127;
sum += (*coef--) * vbuf[bx];
bx = (bx + 16) & 127;
}
tmp = (long) sum;
if (tmp > 32767)
tmp = 32767;
else if (tmp < -32768)
tmp = -32768;
*pcm = tmp;
pcm += 2;
}
#endif
} |
// The LLVM Compiler Infrastructure
// This file is distributed under the University of Illinois Open Source
// This file defines the interface for setting and retrieving previously
// entered input, with a persistent backend (i.e. a history file).
// Axel Naumann <axel@cern.ch>, 2011-05-12
#include "textinput/History.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <assert.h>
#ifdef WIN32
# include <stdio.h>
extern "C" unsigned long __stdcall GetCurrentProcessId(void);
#else
# include <unistd.h>
#endif
namespace textinput {
History::History(const char* filename, bool linematch):
fHistFileName(filename ? filename : ""), fMaxDepth((size_t) -1),
fPruneLength(0), fNumHistFileLines(0), LineSearch(nullptr) {
// Create a history object, initialize from filename if the file
// exists. Append new lines to filename taking into account the
// maximal number of lines allowed by SetMaxDepth().
if (filename) ReadFile(filename);
if (linematch) EnableLineMatching(linematch);
}
History::~History() {}
void
History::AddLine(const std::string& line) {
// Standard history search until text entered
if (LineSearch) LineSearch->Enabled = false;
// Add a line to entries and file.
if (line.empty()) return;
fEntries.push_back(line);
AppendToFile();
}
void
History::ReadFile(const char* FileName) {
// Inject all lines of FileName.
// Intentionally ignore fMaxDepth
std::ifstream InHistFile(FileName);
if (!InHistFile) return;
std::string line;
while (std::getline(InHistFile, line)) {
while (!line.empty()) {
size_t len = line.length();
char c = line[len - 1];
if (c != '\n' && c != '\r') break;
line.erase(len - 1);
}
if (!line.empty()) {
fEntries.push_back(line);
}
}
fNumHistFileLines = fEntries.size();
}
void
History::AppendToFile() {
// Write last entry to hist file.
// Prune if needed.
if (fHistFileName.empty() || !fMaxDepth) return;
// Calculate prune length to use
size_t nPrune = fPruneLength;
if (nPrune == (size_t)kPruneLengthDefault) {
nPrune = (size_t)(fMaxDepth * 0.8);
} else if (nPrune > fMaxDepth) {
nPrune = fMaxDepth - 1; // fMaxDepth is guaranteed to be > 0.
}
// Don't check for the actual line count of the history file after every
// single line. Once every 50% on the way between nPrune and fMaxDepth is
// enough.
if (fNumHistFileLines < fMaxDepth
&& (fNumHistFileLines % (fMaxDepth - nPrune)) == 0) {
fNumHistFileLines = 0;
std::string line;
std::ifstream in(fHistFileName.c_str());
while (std::getline(in, line))
++fNumHistFileLines;
}
size_t numLines = fNumHistFileLines;
if (numLines >= fMaxDepth) {
// Prune! But don't simply write our lines - other processes might have
// added their own.
std::string line;
std::ifstream in(fHistFileName.c_str());
std::stringstream pruneFileNameStream;
pruneFileNameStream << fHistFileName + "_prune"
#if _WIN32
<< ::GetCurrentProcessId();
#else
<< ::getpid();
#endif
std::ofstream out(pruneFileNameStream.str().c_str());
if (out) {
if (in) {
while (numLines >= nPrune && std::getline(in, line)) {
// skip
--numLines;
}
while (std::getline(in, line)) {
out << line << '\n';
}
}
out << fEntries.back() << '\n';
in.close();
out.close();
#ifdef WIN32
::_unlink(fHistFileName.c_str());
#else
::unlink(fHistFileName.c_str());
#endif
if (::rename(pruneFileNameStream.str().c_str(), fHistFileName.c_str()) == -1){
std::cerr << "ERROR in textinput::History::AppendToFile(): "
"cannot rename " << pruneFileNameStream.str() << " to " << fHistFileName;
}
fNumHistFileLines = nPrune;
}
} else {
std::ofstream out(fHistFileName.c_str(), std::ios_base::app);
out << fEntries.back() << '\n';
++fNumHistFileLines;
}
}
void History::EnableLineMatching(bool B) {
if (LineSearch) {
if (!B)
delete LineSearch;
} else if (B)
LineSearch = new LineSearcher;
}
void History::TextEntered(size_t& SearchStart) {
if (LineSearch) {
LineSearch->Enabled = true;
SearchStart = 0;
}
}
static size_t IncrWithOverflow(size_t Idx, int Incr, size_t Max, bool& Over) {
const size_t Val = Idx + Incr;
if (Incr < 0) {
if (Val > Idx || Val >= Max) {
Over = true;
return 0;
}
} else if (Val < Idx || Val>= Max) {
Over = true;
return Max;
}
Over = false;
return Idx + Incr;
}
static size_t IncrWithOverflow(size_t Idx, int Incr, size_t Max) {
bool Drop;
return IncrWithOverflow(Idx, Incr, Max, Drop);
}
const std::string& History::GetLine(size_t& InOuIdx, int Incr,
const std::string& InStr) {
assert(Incr != 0 && "Choose a direction!");
const size_t LastEntry = fEntries.empty() ? 0 : fEntries.size() - 1;
if (!LineSearch || !LineSearch->Enabled || InStr.empty() ||
fEntries.empty()) {
if (LineSearch) {
// Free the string buffer
if (!LineSearch->Match.empty())
std::string().swap(LineSearch->Match);
// Disable filtering until text entered
LineSearch->Enabled = false;
}
InOuIdx = IncrWithOverflow(InOuIdx, Incr, LastEntry);
return GetLine(InOuIdx);
}
assert(InOuIdx != (size_t) -1 && InOuIdx <= LastEntry);
size_t Idx = InOuIdx;
std::string& Search = LineSearch->Match;
// Set the Search to InStr when:
// Search.empty(), first search
// InStr doesn't begin with previous Search, new search
// InStr doesn't match last hit, characters added or deleted
if (Search.empty() || InStr.find(Search) != 0 ||
InStr != fEntries[LastEntry - Idx]) {
Search = InStr;
if (fEntries[LastEntry - Idx].find(Search) == 0) {
// Edited a previos match 'A' -> 'AB', drop the first match (a repeat)
Idx = IncrWithOverflow(Idx, Incr, LastEntry);
} else {
// Restart from end or beginning of history
Idx = Incr > 0 ? 0 : LastEntry;
}
} else
Idx = IncrWithOverflow(Idx, Incr, LastEntry);
bool Wrapped = false;
const size_t StartIdx = Idx;
while (!Wrapped && (Incr < 0 ? Idx <= StartIdx : Idx >= StartIdx)) {
const std::string& Line = fEntries[LastEntry - Idx];
if (Line.find(Search) == 0) {
InOuIdx = Idx;
return Line;
}
Idx = IncrWithOverflow(Idx, Incr, LastEntry, Wrapped);
}
if (false) {
// Block history to matches only
return InStr;
}
// When hits exhausted switch to regular mode
InOuIdx = IncrWithOverflow(InOuIdx, Incr, LastEntry);
return GetLine(InOuIdx);
}
} |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_05) on Sun Jul 13 14:54:47 CEST 2008 -->
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
org.accada.epcis.captureclient (epcis 0.3.3-SNAPSHOT Test API)
</TITLE>
<META NAME="date" CONTENT="2008-07-13">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.accada.epcis.captureclient (epcis 0.3.3-SNAPSHOT Test API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV PACKAGE
<A HREF="../../../../org/accada/epcis/queryclient/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/accada/epcis/captureclient/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<H2>
Package org.accada.epcis.captureclient
</H2>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/accada/epcis/captureclient/MassCaptureTest.html" title="class in org.accada.epcis.captureclient">MassCaptureTest</A></B></TD>
<TD>Test which sends 1000 events to the capture interface and checks if HTTP
status code 200 OK returns.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/accada/epcis/captureclient/<API key>.html" title="class in org.accada.epcis.captureclient"><API key></A></B></TD>
<TD>A simple utility class to generate some simple EPCIS events with some sample
contents.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../../org/accada/epcis/captureclient/SimpleCaptureTest.html" title="class in org.accada.epcis.captureclient">SimpleCaptureTest</A></B></TD>
<TD>A simple test utility class for sending a single or multiple capture
request(s) to the Accada EPCIS capture interface and bootstrapping the
capture module.</TD>
</TR>
</TABLE>
<P>
<DL>
</DL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV PACKAGE
<A HREF="../../../../org/accada/epcis/queryclient/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/accada/epcis/captureclient/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
Copyright &
</BODY>
</HTML> |
package org.hibernate.loader.plan.build.spi;
import org.hibernate.loader.plan.spi.LoadPlan;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.walking.spi.<API key>;
/**
* A metadata-driven builder of LoadPlans. Coordinates between the {@link <API key>} and a
* {@link <API key>}.
*
* @author Steve Ebersole
*
* @see org.hibernate.persister.walking.spi.<API key>
*/
public final class <API key> {
private <API key>() {
}
/**
* Coordinates building a LoadPlan that defines just a single root entity return (may have fetches).
* <p/>
* Typically this includes building load plans for entity loading or cascade loading.
*
* @param strategy The strategy defining the load plan shaping
* @param persister The persister for the entity forming the root of the load plan.
*
* @return The built load plan.
*/
public static LoadPlan <API key>(
<API key> strategy,
EntityPersister persister) {
<API key>.visitEntity( strategy, persister );
return strategy.buildLoadPlan();
}
/**
* Coordinates building a LoadPlan that defines just a single root collection return (may have fetches).
*
* @param strategy The strategy defining the load plan shaping
* @param persister The persister for the collection forming the root of the load plan.
*
* @return The built load plan.
*/
public static LoadPlan <API key>(
<API key> strategy,
CollectionPersister persister) {
<API key>.visitCollection( strategy, persister );
return strategy.buildLoadPlan();
}
} |
// checkstyle: Checks Java source code for adherence to a set of rules.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.puppycrawl.tools.checkstyle.api;
import java.util.BitSet;
import antlr.CommonAST;
import antlr.Token;
import antlr.collections.AST;
public final class DetailAST extends CommonAST
{
/** For Serialisation that will never happen. */
private static final long serialVersionUID = -<API key>;
/** constant to indicate if not calculated the child count */
private static final int NOT_INITIALIZED = Integer.MIN_VALUE;
/** the line number **/
private int mLineNo = NOT_INITIALIZED;
/** the column number **/
private int mColumnNo = NOT_INITIALIZED;
/** number of children */
private int mChildCount = NOT_INITIALIZED;
/** the parent token */
private DetailAST mParent;
/** previous sibling */
private DetailAST mPreviousSibling;
/**
* All token types in this branch.
* Token 'x' (where x is an int) is in this branch
* if mBranchTokenTypes.get(x) is true.
*/
private BitSet mBranchTokenTypes;
@Override
public void initialize(Token aTok)
{
super.initialize(aTok);
mLineNo = aTok.getLine();
mColumnNo = aTok.getColumn() - 1; // expect columns to start @ 0
}
@Override
public void initialize(AST aAST)
{
final DetailAST da = (DetailAST) aAST;
setText(da.getText());
setType(da.getType());
mLineNo = da.getLineNo();
mColumnNo = da.getColumnNo();
}
@Override
public void setFirstChild(AST aAST)
{
mChildCount = NOT_INITIALIZED;
super.setFirstChild(aAST);
if (aAST != null) {
((DetailAST) aAST).setParent(this);
}
}
@Override
public void setNextSibling(AST aAST)
{
super.setNextSibling(aAST);
if ((aAST != null) && (mParent != null)) {
((DetailAST) aAST).setParent(mParent);
}
if (aAST != null) {
((DetailAST) aAST).setPreviousSibling(this);
}
}
/**
* Sets previous sibling.
* @param aAST a previous sibling
*/
void setPreviousSibling(DetailAST aAST)
{
mPreviousSibling = aAST;
}
@Override
public void addChild(AST aAST)
{
super.addChild(aAST);
if (aAST != null) {
((DetailAST) aAST).setParent(this);
(getFirstChild()).setParent(this);
}
}
/**
* Returns the number of child nodes one level below this node. That is is
* does not recurse down the tree.
* @return the number of child nodes
*/
public int getChildCount()
{
// lazy init
if (mChildCount == NOT_INITIALIZED) {
mChildCount = 0;
AST child = getFirstChild();
while (child != null) {
mChildCount += 1;
child = child.getNextSibling();
}
}
return mChildCount;
}
/**
* Set the parent token.
* @param aParent the parent token
*/
// TODO: should be private but that breaks the DetailASTTest
// until we manage parent in DetailAST instead of externally
void setParent(DetailAST aParent)
{
// TODO: Check visibility, could be private
// if set in setFirstChild() and friends
mParent = aParent;
final DetailAST nextSibling = getNextSibling();
if (nextSibling != null) {
nextSibling.setParent(aParent);
nextSibling.setPreviousSibling(this);
}
}
/**
* Returns the parent token.
* @return the parent token
*/
public DetailAST getParent()
{
return mParent;
}
/** @return the line number **/
public int getLineNo()
{
if (mLineNo == NOT_INITIALIZED) {
// an inner AST that has been initialized
// with initialize(String text)
final DetailAST child = getFirstChild();
final DetailAST sibling = getNextSibling();
if (child != null) {
return child.getLineNo();
}
else if (sibling != null) {
return sibling.getLineNo();
}
}
return mLineNo;
}
/** @return the column number **/
public int getColumnNo()
{
if (mColumnNo == NOT_INITIALIZED) {
// an inner AST that has been initialized
// with initialize(String text)
final DetailAST child = getFirstChild();
final DetailAST sibling = getNextSibling();
if (child != null) {
return child.getColumnNo();
}
else if (sibling != null) {
return sibling.getColumnNo();
}
}
return mColumnNo;
}
/** @return the last child node */
public DetailAST getLastChild()
{
DetailAST ast = getFirstChild();
while ((ast != null) && (ast.getNextSibling() != null)) {
ast = ast.getNextSibling();
}
return ast;
}
/**
* @return the token types that occur in the branch as a sorted set.
*/
private BitSet getBranchTokenTypes()
{
// lazy init
if (mBranchTokenTypes == null) {
mBranchTokenTypes = new BitSet();
mBranchTokenTypes.set(getType());
// add union of all childs
DetailAST child = getFirstChild();
while (child != null) {
final BitSet childTypes = child.getBranchTokenTypes();
mBranchTokenTypes.or(childTypes);
child = child.getNextSibling();
}
}
return mBranchTokenTypes;
}
/**
* Checks if this branch of the parse tree contains a token
* of the provided type.
* @param aType a TokenType
* @return true if and only if this branch (including this node)
* contains a token of type <code>aType</code>.
*/
public boolean branchContains(int aType)
{
return getBranchTokenTypes().get(aType);
}
/**
* Returns the number of direct child tokens that have the specified type.
* @param aType the token type to match
* @return the number of matching token
*/
public int getChildCount(int aType)
{
int count = 0;
for (AST i = getFirstChild(); i != null; i = i.getNextSibling()) {
if (i.getType() == aType) {
count++;
}
}
return count;
}
/**
* Returns the previous sibling or null if no such sibling exists.
* @return the previous sibling or null if no such sibling exists.
*/
public DetailAST getPreviousSibling()
{
return mPreviousSibling;
}
/**
* Returns the first child token that makes a specified type.
* @param aType the token type to match
* @return the matching token, or null if no match
*/
public DetailAST findFirstToken(int aType)
{
DetailAST retVal = null;
for (DetailAST i = getFirstChild(); i != null; i = i.getNextSibling()) {
if (i.getType() == aType) {
retVal = i;
break;
}
}
return retVal;
}
@Override
public String toString()
{
return super.toString() + "[" + getLineNo() + "x" + getColumnNo() + "]";
}
@Override
public DetailAST getNextSibling()
{
return (DetailAST) super.getNextSibling();
}
@Override
public DetailAST getFirstChild()
{
return (DetailAST) super.getFirstChild();
}
} |
#include <QtCore>
#include <QtGui>
#include <qtest.h>
class tst_qmetaobject: public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void <API key>();
void indexOfProperty();
void indexOfMethod_data();
void indexOfMethod();
void indexOfSignal_data();
void indexOfSignal();
void indexOfSlot_data();
void indexOfSlot();
};
void tst_qmetaobject::initTestCase()
{
}
void tst_qmetaobject::cleanupTestCase()
{
}
void tst_qmetaobject::<API key>()
{
QTest::addColumn<QByteArray>("name");
const QMetaObject *mo = &QTreeView::staticMetaObject;
for (int i = 0; i < mo->propertyCount(); ++i) {
QMetaProperty prop = mo->property(i);
QTest::newRow(prop.name()) << QByteArray(prop.name());
}
}
void tst_qmetaobject::indexOfProperty()
{
QFETCH(QByteArray, name);
const char *p = name.constData();
const QMetaObject *mo = &QTreeView::staticMetaObject;
QBENCHMARK {
(void)mo->indexOfProperty(p);
}
}
void tst_qmetaobject::indexOfMethod_data()
{
QTest::addColumn<QByteArray>("method");
const QMetaObject *mo = &QTreeView::staticMetaObject;
for (int i = 0; i < mo->methodCount(); ++i) {
QMetaMethod method = mo->method(i);
QByteArray sig = method.signature();
QTest::newRow(sig) << sig;
}
}
void tst_qmetaobject::indexOfMethod()
{
QFETCH(QByteArray, method);
const char *p = method.constData();
const QMetaObject *mo = &QTreeView::staticMetaObject;
QBENCHMARK {
(void)mo->indexOfMethod(p);
}
}
void tst_qmetaobject::indexOfSignal_data()
{
QTest::addColumn<QByteArray>("signal");
const QMetaObject *mo = &QTreeView::staticMetaObject;
for (int i = 0; i < mo->methodCount(); ++i) {
QMetaMethod method = mo->method(i);
if (method.methodType() != QMetaMethod::Signal)
continue;
QByteArray sig = method.signature();
QTest::newRow(sig) << sig;
}
}
void tst_qmetaobject::indexOfSignal()
{
QFETCH(QByteArray, signal);
const char *p = signal.constData();
const QMetaObject *mo = &QTreeView::staticMetaObject;
QBENCHMARK {
(void)mo->indexOfSignal(p);
}
}
void tst_qmetaobject::indexOfSlot_data()
{
QTest::addColumn<QByteArray>("slot");
const QMetaObject *mo = &QTreeView::staticMetaObject;
for (int i = 0; i < mo->methodCount(); ++i) {
QMetaMethod method = mo->method(i);
if (method.methodType() != QMetaMethod::Slot)
continue;
QByteArray sig = method.signature();
QTest::newRow(sig) << sig;
}
}
void tst_qmetaobject::indexOfSlot()
{
QFETCH(QByteArray, slot);
const char *p = slot.constData();
const QMetaObject *mo = &QTreeView::staticMetaObject;
QBENCHMARK {
(void)mo->indexOfSlot(p);
}
}
QTEST_MAIN(tst_qmetaobject)
#include "main.moc" |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>DDT: MainModel Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">DDT
</div>
<div id="projectbrief">Debate Distribution Tool</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.5 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Properties</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-types">Public Types</a> |
<a href="#signals">Signals</a> |
<a href="#pub-methods">Public Member Functions</a> |
<a href="#properties">Properties</a> |
<a href="<API key>.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">MainModel Class Reference</div> </div>
</div><!--header
<div class="contents">
<p>Offers access to all parts of the application's model.
<a href="classMainModel.html#details">More...</a></p>
<p><code>#include <<a class="el" href="mainmodel_8h_source.html">mainmodel.h</a>></code></p>
<div class="dynheader">
Inheritance diagram for MainModel:</div>
<div class="dyncontent">
<div class="center">
<img src="classMainModel.png" usemap="#MainModel_map" alt=""/>
<map id="MainModel_map" name="MainModel_map">
</map>
</div></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-types"></a>
Public Types</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">enum  </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">SolutionState</a> { <a class="el" href="classMainModel.html#<API key>">UNKNOWN</a>,
<a class="el" href="classMainModel.html#<API key>">SOLUTION_EXISTS</a>,
<a class="el" href="classMainModel.html#<API key>">NO_SOLUTION_EXISTS</a>,
<a class="el" href="classMainModel.html#<API key>">CALCULATING</a>
}</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Specifies the application's solution state. <a href="classMainModel.html#<API key>">More...</a><br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="signals"></a>
Signals</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
void </td><td class="memItemRight" valign="bottom"><b><API key></b> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
void </td><td class="memItemRight" valign="bottom"><b><API key></b> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
void </td><td class="memItemRight" valign="bottom"><b>numPlacesChanged</b> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">MainModel</a> (QString configFile="options.xml", QObject *parent=0)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Constructs a new <code><a class="el" href="classMainModel.html" title="Offers access to all parts of the application's model. ">MainModel</a></code>. <a href="#<API key>">More...</a><br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
 </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">~MainModel</a> ()</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Deletes the main model and releases all ressources. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
<a class="el" href="<API key>.html">QListQmlWrapper</a> * </td><td class="memItemRight" valign="bottom"><b>debates</b> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
<a class="el" href="<API key>.html">QListQmlWrapper</a> * </td><td class="memItemRight" valign="bottom"><b>speakerList</b> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
<a class="el" href="<API key>.html">QListQmlWrapper</a> * </td><td class="memItemRight" valign="bottom"><b>teams</b> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
<a class="el" href="<API key>.html">AutoCompleteModel</a> * </td><td class="memItemRight" valign="bottom"><b>autoCompleteModel</b> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">addSpeaker</a> ()</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Same as. <a href="#<API key>">More...</a><br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">addSpeaker</a> (QString name)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Creates a new speaker with a given name and adds him to the speaker list. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">removeSpeaker</a> (int index)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Removes a speaker at a given position in the speaker list. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">removeSpeaker</a> (<a class="el" href="classSpeakerModel.html">SpeakerModel</a> *speaker)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Removes a given speaker. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">addOpDebate</a> ()</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Adds a new OP-Debate to the application's debate list. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">addBpsDebate</a> ()</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Adds a new BPS-Debate to the application's debate list. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">removeDebate</a> (int index)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Removes a debate from the debate list with a given index.;. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
int </td><td class="memItemRight" valign="bottom"><b>numPlaces</b> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">Q_INVOKABLE <a class="el" href="classTeam.html">Team</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">addTeam</a> ()</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Adds a new, empty team to the application's team list. <a href="#<API key>">More...</a><br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="el" href="classTeam.html">Team</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">addTeam</a> (QString name)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">addTeam Adds a new, empty team with a given name to the team list. <a href="#<API key>">More...</a><br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">removeTeam</a> (<a class="el" href="classTeam.html">Team</a> *team)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Removes a given team from the applications team list. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
int </td><td class="memItemRight" valign="bottom"><b>solutionCount</b> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
<a class="el" href="classMainModel.html#<API key>">SolutionState</a> </td><td class="memItemRight" valign="bottom"><b>solutionState</b> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">Q_INVOKABLE QStringList </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">errors</a> ()</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Returns a list of error descriptions. <a href="#<API key>">More...</a><br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">initSolver</a> ()</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Prepares a calculation. The methods takes the current speaker, debate and team list and creates an passes them to an internal solver to prepare further solution calculations. After calling this method solutions can be generated with <a class="el" href="classMainModel.html#<API key>" title="Generates a new solution and stores it internally. ">generateNewSolution()</a>;. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">clearSolutions</a> ()</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Resets the applications solution state Deletes all calculated solutions and frees the internal solver setup. The solutionState is set to UNKNOWN afterwards. <br/>
Remember to call <a class="el" href="classMainModel.html#<API key>" title="Prepares a calculation. The methods takes the current speaker, debate and team list and creates an pa...">initSolver()</a>; before attempting to generate new solutions. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
Q_INVOKABLE <a class="el" href="<API key>.html">SeatToSpeakerMapper</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">getSolution</a> (int index)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Returns a stored solution with a given index. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">generateNewSolution</a> ()</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Generates a new solution and stores it internally. <a href="#<API key>">More...</a><br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>"><API key></a> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">updateNames</a> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">writeConfiguration</a> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">Q_INVOKABLE void </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">setLanguage</a> (QString lang)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="properties"></a>
Properties</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
<a class="el" href="<API key>.html">QListQmlWrapper</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">speakerList</a></td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">List of the application's speakers. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
<a class="el" href="<API key>.html">QListQmlWrapper</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">debates</a></td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">List of the application's debates. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
<a class="el" href="<API key>.html">QListQmlWrapper</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">teams</a></td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">List of the application's teams. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
<a class="el" href="<API key>.html">AutoCompleteModel</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">autoCompleteModel</a></td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">A completion model for name autocompletion. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
<a class="el" href="classMainModel.html#<API key>">SolutionState</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">solutionState</a></td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">The application's solution state. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
int </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">solutionCount</a></td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Holds the number of calculated and stored solutions. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
int </td><td class="memItemRight" valign="bottom"><a class="el" href="classMainModel.html#<API key>">numPlaces</a></td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Holds the complete number of seats in all debate's. <br/></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>Offers access to all parts of the application's model. </p>
<p>The <code><a class="el" href="classMainModel.html" title="Offers access to all parts of the application's model. ">MainModel</a></code> models the application's state. It stores the current speakers, debates and solution. Furthermore, it allows various operations on the model elements. </p>
</div><h2 class="groupheader">Member Enumeration Documentation</h2>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">enum <a class="el" href="classMainModel.html#<API key>">MainModel::SolutionState</a></td>
</tr>
</table>
</div><div class="memdoc">
<p>Specifies the application's solution state. </p>
<table class="fieldtable">
<tr><th colspan="2">Enumerator</th></tr><tr><td class="fieldname"><em><a class="anchor" id="<API key>"></a>UNKNOWN</em> </td><td class="fielddoc">
<p>It is unknown whether one, none or more solutions exist </p>
</td></tr>
<tr><td class="fieldname"><em><a class="anchor" id="<API key>"></a>SOLUTION_EXISTS</em> </td><td class="fielddoc">
<p>At least one solution exists </p>
</td></tr>
<tr><td class="fieldname"><em><a class="anchor" id="<API key>"></a>NO_SOLUTION_EXISTS</em> </td><td class="fielddoc">
<p>No solution exists </p>
</td></tr>
<tr><td class="fieldname"><em><a class="anchor" id="<API key>"></a>CALCULATING</em> </td><td class="fielddoc">
<p>A calculation is in progress, solutionState is updated when the calculation is done </p>
</td></tr>
</table>
</div>
</div>
<h2 class="groupheader">Constructor & Destructor Documentation</h2>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">MainModel::MainModel </td>
<td>(</td>
<td class="paramtype">QString </td>
<td class="paramname"><em>configFile</em> = <code>"options.xml"</code>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">QObject * </td>
<td class="paramname"><em>parent</em> = <code>0</code> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">explicit</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Constructs a new <code><a class="el" href="classMainModel.html" title="Offers access to all parts of the application's model. ">MainModel</a></code>. </p>
<p>The main model is initialized with options from a given configuration file. </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">configFile</td><td>a (relative) path to a configuration file </td></tr>
<tr><td class="paramname">parent</td><td>the object's parent </td></tr>
</table>
</dd>
</dl>
<dl class="section see"><dt>See Also</dt><dd><a class="el" href="<API key>.html" title="Reads options from a file. ">DDTConfiguration</a> </dd></dl>
</div>
</div>
<h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void MainModel::addSpeaker </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Same as. </p>
<div class="fragment"><div class="line"><a class="code" href="classMainModel.html#<API key>">addSpeaker</a>(<span class="stringliteral">""</span>) </div>
</div><!-- fragment -->
</div>
</div>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="classTeam.html">Team</a> * MainModel::addTeam </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Adds a new, empty team to the application's team list. </p>
<dl class="section return"><dt>Returns</dt><dd>the added team </dd></dl>
</div>
</div>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="classTeam.html">Team</a> * MainModel::addTeam </td>
<td>(</td>
<td class="paramtype">QString </td>
<td class="paramname"><em>name</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>addTeam Adds a new, empty team with a given name to the team list. </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">name</td><td>the team's name </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>the added team </dd></dl>
</div>
</div>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">Q_INVOKABLE QStringList MainModel::errors </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Returns a list of error descriptions. </p>
<p>The errors need to be fixed before a solution can be generated. They can be presented to the users and give clues why no solution exists (see <a class="el" href="classMainModel.html#<API key>">solutionState</a>). The return value is undefined if the solution state is different than <a class="el" href="classMainModel.html#<API key>">NO_SOLUTION_EXISTS</a> . </p>
</div>
</div>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void MainModel::generateNewSolution </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Generates a new solution and stores it internally. </p>
<p>Call <a class="el" href="classMainModel.html#<API key>" title="Prepares a calculation. The methods takes the current speaker, debate and team list and creates an pa...">initSolver()</a>; before attempting to call this method. The solution state will be set to CALCULATING, once the solution is finished the state changes to NO_SOLUTION_EXISTS or SOLUTION_EXISTS. The generated solution is stored internally and can be read with getSolution. </p>
<dl class="section see"><dt>See Also</dt><dd><a class="el" href="classMainModel.html#<API key>" title="Holds the number of calculated and stored solutions. ">solutionCount</a> </dd></dl>
</div>
</div>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void MainModel::<API key> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Interrupts the current calculation. Calling this method when no calculation takes place has no effect. </p>
</div>
</div>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void MainModel::setLanguage </td>
<td>(</td>
<td class="paramtype">QString </td>
<td class="paramname"><em>lang</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Sets the applications language. The change will only take effect if the configuration file is written (writeConfiguration) and the application restarted. </p>
</div>
</div>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void MainModel::updateNames </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Reads all names of the application's speakers and adds them to the name pool of autoCompleteModel. Furthermore, all names will be stored in a configuration file once writeConfiguration is called. </p>
</div>
</div>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">void MainModel::writeConfiguration </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Writes all options into a configuration file. </p>
</div>
</div>
<hr/>The documentation for this class was generated from the following files:<ul>
<li>/home/stoef/qt/projects/ddt/ddt/src/<a class="el" href="mainmodel_8h_source.html">mainmodel.h</a></li>
<li>/home/stoef/qt/projects/ddt/ddt/src/mainmodel.cpp</li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Oct 22 2013 18:21:59 for DDT by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.5
</small></address>
</body>
</html> |
#define NB_CYCLES 16
#define NB_SAMPLES 64
#include <iostream>
#include <cstdlib>
#include "fifo_ports.h"
#include "mapping_table.h"
#include "mips.h"
#include "vci_vgmn.h"
#include "vci_ram.h"
#include "vci_multi_tty.h"
#include "vci_xcache_wrapper.h"
#include "ississ2.h"
#include "vci_locks.h"
#include "mwmr_controller.h"
#include "vci_mwmr_controller.h"
#include "downsampling.h"
#include "segmentation.h"
int _main(int argc, char *argv[])
{
using namespace sc_core;
// Avoid repeating these everywhere
using soclib::common::IntTab;
using soclib::common::Segment;
// Define our VCI parameters
typedef soclib::caba::VciParams<4,8,32,1,1,1,8,1,1,1> vci_param;
// Mapping table
soclib::common::MappingTable maptab(32, IntTab(8), IntTab(8), 0x00300000);
maptab.add(Segment("reset", RESET_BASE, RESET_SIZE, IntTab(0), true));
maptab.add(Segment("excep", EXCEP_BASE, EXCEP_SIZE, IntTab(0), true));
maptab.add(Segment("text" , TEXT_BASE , TEXT_SIZE , IntTab(0), true));
maptab.add(Segment("data" , DATA_BASE , DATA_SIZE , IntTab(1), true));
maptab.add(Segment("tty", TTY_BASE, TTY_SIZE , IntTab(2), false));
maptab.add(Segment("mwmr0", MWMR_BASE , MWMR_SIZE , IntTab(3), false));
maptab.add(Segment("mwmr_ram", MWMRd_BASE , MWMRd_SIZE , IntTab(4), false));
maptab.add(Segment("locks" , LOCKS_BASE , LOCKS_SIZE , IntTab(5), false));
/*maptab.add(Segment("loc1" , LOC1_BASE , LOC1_SIZE , IntTab(5), true));
maptab.add(Segment("loc2" , LOC2_BASE , LOC2_SIZE , IntTab(6), true));
maptab.add(Segment("loc3" , LOC3_BASE , LOC3_SIZE , IntTab(7), true));*/
// Signals
sc_clock signal_clk("signal_clk");
sc_signal<bool> signal_resetn("signal_resetn");
sc_signal<bool> signal_mips0_it0("signal_mips_it0");
sc_signal<bool> signal_mips0_it1("signal_mips_it1");
sc_signal<bool> signal_mips0_it2("signal_mips_it2");
sc_signal<bool> signal_mips0_it3("signal_mips_it3");
sc_signal<bool> signal_mips0_it4("signal_mips_it4");
sc_signal<bool> signal_mips0_it5("signal_mips_it5");
soclib::caba::VciSignals<vci_param> signal_vci_m0("signal_vci_m0");
soclib::caba::VciSignals<vci_param> signal_mwmr0_target("signal_mwmr0_target") ;
soclib::caba::VciSignals<vci_param> <API key>("<API key>") ;
soclib::caba::FifoSignals<uint32_t> signal_fifo_to_ctrl("signal_fifo_to_ctrl");
soclib::caba::FifoSignals<uint32_t> <API key>("<API key>");
soclib::caba::VciSignals<vci_param> signal_vci_tty("signal_vci_tty");
soclib::caba::VciSignals<vci_param> <API key>("<API key>");
soclib::caba::VciSignals<vci_param> <API key>("<API key>");
soclib::caba::VciSignals<vci_param> <API key>("<API key>");
soclib::caba::VciSignals<vci_param> signal_vci_locks("signal_vci_locks");
sc_signal<bool> signal_tty_irq0("signal_tty_irq0");
// Components
soclib::caba::VciXcacheWrapper<vci_param, soclib::common::IssIss2<soclib::common::MipsElIss> > mips0("mips0", 0,maptab,IntTab(0),1,8,4,1,8,4);
soclib::common::Loader loader("soft/bin.soft");
soclib::caba::VciRam<vci_param> vcimultiram0("vcimultiram0", IntTab(0), maptab, loader);
soclib::caba::VciRam<vci_param> vcimultiram1("vcimultiram1", IntTab(1), maptab, loader);
soclib::caba::VciRam<vci_param> vcimultiram2("vcimultiram2", IntTab(4), maptab, loader);
soclib::caba::VciMultiTty<vci_param> vcitty("vcitty", IntTab(2), maptab, "vcitty0", NULL);
soclib::caba::VciVgmn<vci_param> vgmn("vgmn",maptab,2,6,2,8);
soclib::caba::VciLocks<vci_param> vcilocks("vcilocks", IntTab(5), maptab);
// MWMR AND COPROCESSOR 0
//soclib::caba::VciMwmrController<vci_param> mwmr0("mwmr0", maptab, IntTab(3), IntTab(3), plaps, <API key>, <API key>, n_to_coproc, n_from_coproc, n_config, n_status, use_llsc);
soclib::caba::VciMwmrController<vci_param> mwmr0("mwmr0", maptab, IntTab(1), IntTab(3), 64, 8, 8, 1, 1, 0, 0, false);
soclib::caba::Downsampling<vci_param, NB_SAMPLES> downsampling("downsampling", NB_CYCLES);
// Net-List
mips0.p_clk(signal_clk);
vcimultiram0.p_clk(signal_clk);
vcimultiram1.p_clk(signal_clk);
vcimultiram2.p_clk(signal_clk);
mips0.p_resetn(signal_resetn);
vcimultiram0.p_resetn(signal_resetn);
vcimultiram1.p_resetn(signal_resetn);
vcimultiram2.p_resetn(signal_resetn);
mips0.p_irq[0](signal_mips0_it0);
mips0.p_irq[1](signal_mips0_it1);
mips0.p_irq[2](signal_mips0_it2);
mips0.p_irq[3](signal_mips0_it3);
mips0.p_irq[4](signal_mips0_it4);
mips0.p_irq[5](signal_mips0_it5);
mips0.p_vci(signal_vci_m0);
vcimultiram0.p_vci(<API key>);
vcimultiram1.p_vci(<API key>);
vcimultiram2.p_vci(<API key>);
vcitty.p_clk(signal_clk);
vcitty.p_resetn(signal_resetn);
vcitty.p_vci(signal_vci_tty);
vcitty.p_irq[0](signal_tty_irq0);
mwmr0.p_clk(signal_clk);
mwmr0.p_resetn(signal_resetn);
mwmr0.p_vci_initiator(<API key>);
mwmr0.p_vci_target(signal_mwmr0_target);
mwmr0.p_from_coproc[0](signal_fifo_to_ctrl);
mwmr0.p_to_coproc[0](<API key>);
downsampling.p_clk(signal_clk);
downsampling.p_resetn(signal_resetn);
downsampling.p_to_ctrl(signal_fifo_to_ctrl);
downsampling.p_from_ctrl(<API key>);
vgmn.p_clk(signal_clk);
vgmn.p_resetn(signal_resetn);
vgmn.p_to_initiator[1](<API key>);
vgmn.p_to_initiator[0](signal_vci_m0);
vgmn.p_to_target[3](signal_mwmr0_target);
vgmn.p_to_target[0](<API key>);
vgmn.p_to_target[1](<API key>);
vgmn.p_to_target[4](<API key>);
vgmn.p_to_target[2](signal_vci_tty);
vgmn.p_to_target[5](signal_vci_locks);
vcilocks.p_clk(signal_clk);
vcilocks.p_resetn(signal_resetn);
vcilocks.p_vci(signal_vci_locks);
// Trace
sc_trace_file *my_trace_file;
my_trace_file = <API key> ("system_trace");
sc_trace(my_trace_file, signal_clk, "CLK");
sc_trace(my_trace_file, signal_resetn, "RESETN");
signal_vci_m0.trace(my_trace_file, "vci_cache");
<API key>.trace(my_trace_file, "vci_mwmr_data");
signal_vci_locks.trace(my_trace_file, "vci_locks");
// START
int ncycles;
#ifndef SOCVIEW
if (argc == 2) {
ncycles = std::atoi(argv[1]);
} else {
std::cerr
<< std::endl
<< "The number of simulation cycles must "
"be defined in the command line"
<< std::endl;
exit(1);
}
sc_start(sc_core::sc_time(0, SC_NS));
signal_resetn = false;
sc_start(sc_core::sc_time(1, SC_NS));
signal_resetn = true;
for (int i = 0; i < ncycles ; i+=10000) {
sc_start(sc_core::sc_time(100000, SC_NS));
std::cout << "Time elapsed: "<<i<<" cycles." << std::endl;
}
// TRACE
<API key> (my_trace_file);
return EXIT_SUCCESS;
sc_start();
#else
ncycles = 1;
sc_start(sc_core::sc_time(0, SC_NS));
signal_resetn = false;
sc_start(sc_core::sc_time(1, SC_NS));
signal_resetn = true;
debug();
return EXIT_SUCCESS;
#endif
}
int sc_main (int argc, char *argv[])
{
try {
return _main(argc, argv);
} catch (std::exception &e) {
std::cout << e.what() << std::endl;
} catch (...) {
std::cout << "Unknown exception occured" << std::endl;
throw;
}
return 1;
} |
#include "genall.h"
#include "../planets.h"
static bool <API key> (SOLARSYS_STATE *solarSys);
static bool <API key> (SOLARSYS_STATE *solarSys,
PLANET_DESC *world);
const GenerateFunctions <API key> = {
/* .initNpcs = */ <API key>,
/* .reinitNpcs = */ <API key>,
/* .uninitNpcs = */ <API key>,
/* .generatePlanets = */ <API key>,
/* .generateMoons = */ <API key>,
/* .generateName = */ <API key>,
/* .generateOrbital = */ <API key>,
/* .generateMinerals = */ <API key>,
/* .generateEnergy = */ <API key>,
/* .generateLife = */ <API key>,
};
static bool
<API key> (SOLARSYS_STATE *solarSys)
{
COUNT angle;
<API key> (solarSys);
solarSys->PlanetDesc[0].data_index = TELLURIC_WORLD;
solarSys->PlanetDesc[0].NumPlanets = 1;
solarSys->PlanetDesc[0].radius = EARTH_RADIUS * 203L / 100;
angle = ARCTAN (solarSys->PlanetDesc[0].location.x,
solarSys->PlanetDesc[0].location.y);
solarSys->PlanetDesc[0].location.x =
COSINE (angle, solarSys->PlanetDesc[0].radius);
solarSys->PlanetDesc[0].location.y =
SINE (angle, solarSys->PlanetDesc[0].radius);
return true;
}
static bool
<API key> (SOLARSYS_STATE *solarSys, PLANET_DESC *world)
{
<API key> (solarSys, world);
if (matchWorld (solarSys, world, 0, MATCH_PLANET))
{
solarSys->SysInfo.PlanetInfo.AtmoDensity = EARTH_ATMOSPHERE * 2;
solarSys->SysInfo.PlanetInfo.SurfaceTemperature = 35;
solarSys->SysInfo.PlanetInfo.Weather = 3;
solarSys->SysInfo.PlanetInfo.Tectonics = 1;
}
return true;
} |
#ifndef <API key>
#define <API key>
#ifdef __sgi
#pragma once
#endif
#include <OSGConfig.h>
#include <OSGWindowQTDef.h>
#include <<API key>.h>
#include <string>
class QHBoxLayout;
class QLabel;
class QLineEdit;
OSG_BEGIN_NAMESPACE
class <API key> QGenericValueEditor : public <API key>
{
Q_OBJECT;
public:
static <API key> *create(QWidget *pParent, const char *name);
QGenericValueEditor(QWidget *pParent, const char *name);
virtual ~QGenericValueEditor(void);
inline void getValue( std::string &value) const;
inline void setValue(const std::string &value);
public slots:
virtual void setLabelsVisible(bool bLabelsVisible);
virtual void setReadOnly (bool bReadOnly );
virtual void readField (FieldContainerPtr pFC,
UInt32 uiFieldId,
UInt32 uiValueIndex,
UInt32 uiAspect );
virtual void readField (FieldContainerPtr pFC,
UInt32 uiFieldId,
UInt32 uiValueIndex );
virtual void writeField (FieldContainerPtr pFC,
UInt32 uiFieldId,
UInt32 uiValueIndex );
virtual void addFieldElem (FieldContainerPtr pFC,
UInt32 uiFieldId,
UInt32 uiValueIndex );
virtual void removeFieldElem(FieldContainerPtr pFC,
UInt32 uiFieldId,
UInt32 uiValueIndex );
protected slots:
void <API key>(void);
private:
typedef <API key> Inherited;
void createChildWidgets(void);
void layoutChildWidgets(void);
void initSelf (void);
void removeQuotes (std::string &str);
QHBoxLayout *_pHBox;
QLabel *_pLabel;
QLineEdit *_pLineEdit;
};
OSG_END_NAMESPACE
#include "<API key>.inl"
#define <API key> "@(#)$Id: <API key>.h,v 1.3 2005/05/18 11:02:50 a-m-z Exp $"
#endif /* <API key> */ |
#include "<API key>.h"
#include <qsensorplugin.h>
#include <qsensorbackend.h>
#include <qsensormanager.h>
QTM_USE_NAMESPACE
// API is used as name since underlying symbian API is called sensor API
class <API key> : public QObject, public <API key>, public <API key>
{
Q_OBJECT
Q_INTERFACES(QtMobility::<API key>)
public:
void registerSensors()
{
#if !defined(<API key>)
QSensorManager::registerBackend(QAccelerometer::type, <API key>::id, this);
#endif
}
QSensorBackend *createBackend(QSensor *sensor)
{
#if !defined(<API key>)
if (sensor->identifier() == <API key>::id)
return new <API key>(sensor);
#endif
return 0;
}
};
Q_EXPORT_PLUGIN2(<API key>, <API key>)
#include "main.moc" |
#pragma once
#include "database/DatabaseHelpers.h"
#include "medialibrary/IArtist.h"
#include "medialibrary/IMediaLibrary.h"
#include "Thumbnail.h"
namespace medialibrary
{
class Album;
class Media;
class Artist : public IArtist, public DatabaseHelpers<Artist>
{
public:
struct Table
{
static const std::string Name;
static const std::string PrimaryKeyColumn;
static int64_t Artist::*const PrimaryKey;
};
struct FtsTable
{
static const std::string Name;
};
struct MediaRelationTable
{
static const std::string Name;
};
enum class Triggers : uint8_t
{
HasTrackPresent,
HasAlbumRemaining,
<API key>,
IncrementNbTracks,
DecrementNbTracks,
UpdateNbAlbums,
DecrementNbAlbums,
IncrementNbAlbums,
InsertFts,
DeleteFts,
};
enum class Indexes : uint8_t
{
MediaRelArtistId,
};
Artist( MediaLibraryPtr ml, sqlite::Row& row );
Artist( MediaLibraryPtr ml, std::string name );
virtual int64_t id() const override;
virtual const std::string& name() const override;
virtual const std::string& shortBio() const override;
bool setShortBio( const std::string& shortBio );
virtual Query<IAlbum> albums( const QueryParameters* params ) const override;
virtual Query<IAlbum> searchAlbums( const std::string& pattern,
const QueryParameters* params = nullptr ) const override;
virtual Query<IMedia> tracks( const QueryParameters* params ) const override;
virtual Query<IMedia> searchTracks( const std::string& pattern,
const QueryParameters* params = nullptr ) const override;
bool addMedia( const Media& tracks );
virtual ThumbnailStatus thumbnailStatus( ThumbnailSizeType sizeType ) const override;
virtual const std::string& thumbnailMrl( ThumbnailSizeType sizeType ) const override;
std::shared_ptr<Thumbnail> thumbnail( ThumbnailSizeType sizeType ) const;
/**
* @brief setThumbnail Set a new thumbnail for this artist.
* @param newThumbnail A thumbnail object. It can be already inserted in DB or not
* @param origin The origin for this thumbnail
* @return true if the thumbnail was updated (or wilfully ignored), false in case of failure
*
* The origin parameter is there in case the thumbnail was create for an entity
* but shared through another one.
* For instance, if an artist gets assigned the cover from an album, the
* thumbnail object is likely to have the Media origin if the album was just
* created.
* Specifying the origin explicitely allows for a finer control on the hierarchy
*
* The implementation may chose to ignore a thumbnail update based on the
* current & new origin. In this case, `true` will still be returned.
*/
bool setThumbnail( std::shared_ptr<Thumbnail> newThumbnail );
virtual bool setThumbnail( const std::string& thumbnailMrl,
ThumbnailSizeType sizeType ) override;
std::shared_ptr<Album> unknownAlbum();
std::shared_ptr<Album> createUnknownAlbum();
virtual const std::string& musicBrainzId() const override;
bool setMusicBrainzId( const std::string& musicBrainzId );
virtual unsigned int nbAlbums() const override;
virtual unsigned int nbTracks() const override;
virtual unsigned int nbPresentTracks() const override;
static void createTable( sqlite::Connection* dbConnection );
static void createTriggers( sqlite::Connection* dbConnection );
static void createIndexes( sqlite::Connection* dbConnection );
static std::string schema( const std::string& tableName, uint32_t dbModelVersion );
static std::string trigger( Triggers trigger, uint32_t dbModelVersion );
static std::string triggerName( Triggers trigger, uint32_t dbModelVersion );
static std::string index( Indexes index, uint32_t dbModel );
static std::string indexName( Indexes index, uint32_t dbModel );
static bool checkDbModel( MediaLibraryPtr ml );
static bool <API key>( sqlite::Connection* dbConnection );
static std::shared_ptr<Artist> create( MediaLibraryPtr ml, std::string name );
static Query<IArtist> search( MediaLibraryPtr ml, const std::string& name,
ArtistIncluded included, const QueryParameters* params );
static Query<IArtist> listAll( MediaLibraryPtr ml, ArtistIncluded included,
const QueryParameters* params );
static Query<IArtist> searchByGenre( MediaLibraryPtr ml, const std::string& pattern,
const QueryParameters* params, int64_t genreId );
/**
* @brief <API key> Drops any relation between a media and N artists
* @param ml A media library instance
* @param mediaId The media to drop the relation with
*
* This is intended to remove any link between media & artist(s) when none
* of them is deleted. When any of those 2 entities is deleted, any relation
* will automatically get dropped.
* Effectively, this is meant to be used when refreshing a media, since we
* can't delete it, at the risk of dropping it from any playlist, and we
* won't delete an artist when a media gets updated.
*/
static bool <API key>( MediaLibraryPtr ml, int64_t mediaId );
/**
* @brief checkDBConsistency Checks the consistency of all artists records
* @return false in case of an inconsistency
*
* This is meant for testing only, and expected all devices to be back to
* present once this is called
*/
static bool checkDBConsistency( MediaLibraryPtr ml );
private:
static std::string sortRequest( const QueryParameters* params );
static bool <API key>( const Thumbnail& currentThumbnail );
static std::string addRequestJoin( const QueryParameters* params );
private:
MediaLibraryPtr m_ml;
int64_t m_id;
const std::string m_name;
std::string m_shortBio;
unsigned int m_nbAlbums;
unsigned int m_nbTracks;
std::string m_mbId;
unsigned int m_nbPresentTracks;
mutable std::shared_ptr<Thumbnail> m_thumbnails[Thumbnail::SizeToInt( ThumbnailSizeType::Count )];
friend struct Artist::Table;
};
} |
#include <vrj/Draw/OGL/Config.h>
#include <vrj/Draw/OGL/<API key>.h>
namespace vrj
{
vprSingletonImp(<API key>)
} |
<?php
/**
* @deprecated
*/
class <API key> extends Kajona\Packagemanager\System\<API key>
{
} |
/**
* @file sch_polyline.h
*
*/
#ifndef _SCH_POLYLINE_H_
#define _SCH_POLYLINE_H_
#include <sch_item_struct.h>
class SCH_POLYLINE : public SCH_ITEM
{
int m_width; // Thickness
std::vector<wxPoint> m_points; // list of points (>= 2)
public:
SCH_POLYLINE( int layer = LAYER_NOTES );
// Do not create a copy constructor. The one generated by the compiler is adequate.
~SCH_POLYLINE();
virtual wxString GetClass() const
{
return wxT( "SCH_POLYLINE" );
}
virtual void Draw( EDA_DRAW_PANEL* aPanel, wxDC* aDC, const wxPoint& aOffset,
int aDrawMode, int aColor = -1 );
/**
* Function Save
* writes the data structures for this object out to a FILE in "*.sch"
* format.
* @param aFile The FILE to write to.
* @return bool - true if success writing else false.
*/
bool Save( FILE* aFile ) const;
/**
* Load schematic poly line entry from \a aLine in a .sch file.
*
* @param aLine - Essentially this is file to read schematic poly line from.
* @param aErrorMsg - Description of the error if an error occurs while loading the
* schematic poly line.
* @return True if the schematic poly line loaded successfully.
*/
virtual bool Load( LINE_READER& aLine, wxString& aErrorMsg );
/**
* Function AddPoint
* add a corner to m_points
*/
void AddPoint( const wxPoint& point )
{
m_points.push_back( point );
}
/**
* Function SetPoint
* sets the point at \a aIndex in the list to \a aPoint.
*
* @param aIndex The index in the point list.
* @param aPoint The new point value.
*/
void SetPoint( int aIndex, const wxPoint& aPoint )
{
// (unsigned) excludes aIndex<0 also
wxCHECK_RET( (unsigned)aIndex < m_points.size(),
wxT( "Invalid SCH_POLYLINE point list index." ) );
m_points[ aIndex ] = aPoint;
}
/**
* Function GetCornerCount
* @return the number of corners
*/
unsigned GetCornerCount() const { return m_points.size(); }
/**
* Function GetPenSize
* @return the size of the "pen" that be used to draw or plot this item
*/
virtual int GetPenSize() const;
/** @copydoc SCH_ITEM::Move() */
virtual void Move( const wxPoint& aMoveVector )
{
for( unsigned ii = 0; ii < GetCornerCount(); ii++ )
m_points[ii] += aMoveVector;
}
/** @copydoc SCH_ITEM::MirrorY() */
virtual void MirrorY( int aYaxis_position );
/** @copydoc SCH_ITEM::MirrorX() */
virtual void MirrorX( int aXaxis_position );
/** @copydoc SCH_ITEM::Rotate() */
virtual void Rotate( wxPoint aPosition );
/** @copydoc EDA_ITEM::GetSelectMenuText() */
virtual wxString GetSelectMenuText() const;
/** @copydoc EDA_ITEM::GetMenuImage() */
virtual BITMAP_DEF GetMenuImage() const;
/**
* Function operator[]
* is used for read only access and returns the point at \a aIndex.
* @param aIndex The index of the list of points to return.
* @return A wxPoint object containing the point at \a aIndex.
*/
wxPoint operator[]( int aIndex ) const
{
// (unsigned) excludes aIndex<0 also
wxCHECK_MSG( (unsigned)aIndex < m_points.size(), wxDefaultPosition,
wxT( "Invalid SCH_POLYLINE point list index." ) );
return m_points[ aIndex ];
}
/** @copydoc SCH_ITEM::GetPosition() */
virtual wxPoint GetPosition() const { return m_points[0]; }
/** @copydoc SCH_ITEM::SetPosition() */
virtual void SetPosition( const wxPoint& aPosition );
/** @copydoc SCH_ITEM::HitTest(const wxPoint&,int)const */
virtual bool HitTest( const wxPoint& aPosition, int aAccuracy ) const;
/** @copydoc SCH_ITEM::HitTest(const EDA_RECT&,bool,int)const */
virtual bool HitTest( const EDA_RECT& aRect, bool aContained = false,
int aAccuracy = 0 ) const;
/** @copydoc EDA_ITEM::Clone() */
virtual EDA_ITEM* Clone() const;
#if defined(DEBUG)
void Show( int nestLevel, std::ostream& os ) const { ShowDummy( os ); } // override
#endif
};
#endif // _SCH_POLYLINE_H_ |
#ifndef <API key>
#define <API key>
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <string.h>
#include "myencoding/myosi.h"
#include "mycore/utils.h"
#include "mycore/mystring.h"
struct myencoding_result {
unsigned long first;
unsigned long second;
unsigned long third;
unsigned long result;
unsigned long result_aux;
unsigned long flag;
};
struct myencoding_trigram {
const unsigned char trigram[3];
size_t value;
};
struct <API key> {
size_t count;
size_t value;
};
struct <API key> {
size_t count_ascii;
size_t count_good;
size_t count_bad;
};
struct <API key> {
const char* name;
size_t name_length;
const char* label;
size_t label_length;
myencoding_t encoding;
size_t next;
size_t curr;
};
struct <API key> {
size_t key_begin;
size_t key_length;
size_t value_begin;
size_t value_length;
<API key> *next;
};
struct <API key> {
const char *name;
size_t length;
};
typedef myencoding_status_t (*myencoding_custom_f)(unsigned const char data, myencoding_result_t *res);
myencoding_custom_f <API key>(myencoding_t idx);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
myencoding_status_t <API key>(unsigned const char data, myencoding_result_t *res);
size_t <API key>(size_t codepoint);
size_t <API key>(const unsigned char data);
size_t <API key>(size_t codepoint, char *data);
size_t <API key>(size_t codepoint, char *data);
size_t <API key>(size_t codepoint, char *data);
size_t <API key>(const unsigned char* data, size_t* codepoint);
void <API key>(myencoding_result_t *res);
bool myencoding_detect(const char *text, size_t length, myencoding_t *encoding);
bool <API key>(const char *text, size_t length, myencoding_t *encoding);
bool <API key>(const char *text, size_t length, myencoding_t *encoding);
bool <API key>(const char *text, size_t length, myencoding_t *encoding);
bool <API key>(const char *text, size_t length, myencoding_t *encoding, const char **new_text, size_t *new_size);
size_t <API key>(mycore_string_raw_t* raw_str, const char* buff, size_t length, myencoding_t encoding);
const <API key> * <API key>(const char* name, size_t length);
bool myencoding_by_name(const char *name, size_t length, myencoding_t *encoding);
const char * <API key>(myencoding_t encoding, size_t *length);
bool <API key>(const char *data, size_t data_size, myencoding_t *encoding);
myencoding_t <API key>(const char *data, size_t data_size);
bool <API key>(const char *data, size_t data_size, myencoding_t *encoding, const char **found, size_t *found_lenght);
myencoding_t <API key>(const char *data, size_t data_size, const char **found, size_t *found_lenght);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* <API key> */ |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>llrp 0.0.1-SNAPSHOT Reference Package org.accada.llrp.client.adaptor.config</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="style" />
</head>
<body>
<div class="overview">
<ul>
<li>
<a href="../../../../../../overview-summary.html">Overview</a>
</li>
<li class="selected">Package</li>
</ul>
</div>
<div class="framenoframe">
<ul>
<li>
<a href="../../../../../../index.html" target="_top">FRAMES</a>
</li>
<li>
<a href="package-summary.html" target="_top">NO FRAMES</a>
</li>
</ul>
</div>
<h2>Package org.accada.llrp.client.adaptor.config</h2>
<table class="summary">
<thead>
<tr>
<th>Class Summary</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="<API key>.html" target="classFrame"><API key></a>
</td>
</tr>
<tr>
<td>
<a href="ConfigurationLoader.html" target="classFrame">ConfigurationLoader</a>
</td>
</tr>
<tr>
<td>
<a href="ReaderConfiguration.html" target="classFrame">ReaderConfiguration</a>
</td>
</tr>
</tbody>
</table>
<div class="overview">
<ul>
<li>
<a href="../../../../../../overview-summary.html">Overview</a>
</li>
<li class="selected">Package</li>
</ul>
</div>
<div class="framenoframe">
<ul>
<li>
<a href="../../../../../../index.html" target="_top">FRAMES</a>
</li>
<li>
<a href="package-summary.html" target="_top">NO FRAMES</a>
</li>
</ul>
</div>
<hr />
Copyright © 2008. All Rights Reserved.
</body>
</html> |
#include "arb_mat.h"
void
arb_mat_mul(arb_mat_t C, const arb_mat_t A, const arb_mat_t B, slong prec)
{
if (<API key>() > 1 &&
((double) arb_mat_nrows(A) *
(double) arb_mat_nrows(B) *
(double) arb_mat_ncols(B) *
(double) prec > 100000))
{
<API key>(C, A, B, prec);
}
else
{
<API key>(C, A, B, prec);
}
} |
#include <stdlib.h>
#include <glib.h>
#include <gtk/gtk.h>
#include "config.h"
#include "options.h"
static gboolean version = FALSE;
static gboolean debug = FALSE;
static int volume_max = 0;
static int volume_inc = 1;
static gboolean no_notify = FALSE;
static gboolean always_notify = FALSE;
static gboolean monitors = FALSE;
static GOptionEntry entries[] =
{
{ "version", 'V', 0, G_OPTION_ARG_NONE, &version, "print version and exit", NULL },
{ "debug", 'd', 0, G_OPTION_ARG_NONE, &debug, "print debugging information", NULL },
{ "max-volume", 0, 0, G_OPTION_ARG_INT, &volume_max, "deprecated, use volume-max instead", "N" },
{ "volume-max", 'm', 0, G_OPTION_ARG_INT, &volume_max, "maximum volume (in percent)", "N" },
{ "volume-inc", 'i', 0, G_OPTION_ARG_INT, &volume_inc, "volume increment", "N" },
{ "no-notify", 'n', 0, G_OPTION_ARG_NONE, &no_notify, "disable all notifications", NULL },
{ "always-notify", 'a', 0, G_OPTION_ARG_NONE, &always_notify,
"enable notifications for all changes in pulsaudio", NULL },
{ "include-monitors", 'n', 0, G_OPTION_ARG_NONE, &monitors, "include monitor sources", NULL },
{ .long_name = NULL }
};
GOptionEntry* get_options()
{
return entries;
}
void parse_options(settings_t* settings)
{
if(version)
{
g_print("%s\n", VERSION);
exit(0);
}
if(debug)
{
setenv("G_MESSAGES_DEBUG", "pasystray", 1);
}
settings->volume_max = 0;
if(volume_max > 0)
{
settings->volume_max = volume_max;
}
settings->volume_inc = 1;
if(volume_inc > 0)
{
settings->volume_inc = volume_inc;
}
settings->notify = NOTIFY_DEFAULT;
if(no_notify)
{
settings->notify = NOTIFY_NEVER;
}
if(always_notify)
{
settings->notify = NOTIFY_ALWAYS;
}
settings->monitors = monitors;
} |
#ifndef <API key>
#define <API key>
#include <QtCore/qglobal.h>
QT_BEGIN_NAMESPACE
#ifndef QT_STATIC
# if defined(<API key>)
# define <API key> Q_DECL_EXPORT
# else
# define <API key> Q_DECL_IMPORT
# endif
#else
# define <API key>
#endif
QT_END_NAMESPACE
#endif // <API key> |
package org.jfree.chart.plot.dial;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import org.jfree.chart.TestUtils;
import org.jfree.chart.internal.CloneUtils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for the {@link DialTextAnnotation} class.
*/
public class <API key> {
/**
* Confirm that the equals method can distinguish all the required fields.
*/
@Test
public void testEquals() {
DialTextAnnotation a1 = new DialTextAnnotation("A1");
DialTextAnnotation a2 = new DialTextAnnotation("A1");
assertEquals(a1, a2);
// angle
a1.setAngle(1.1);
assertNotEquals(a1, a2);
a2.setAngle(1.1);
assertEquals(a1, a2);
// radius
a1.setRadius(9.9);
assertNotEquals(a1, a2);
a2.setRadius(9.9);
assertEquals(a1, a2);
// font
Font f = new Font("SansSerif", Font.PLAIN, 14);
a1.setFont(f);
assertNotEquals(a1, a2);
a2.setFont(f);
assertEquals(a1, a2);
// paint
a1.setPaint(Color.RED);
assertNotEquals(a1, a2);
a2.setPaint(Color.RED);
assertEquals(a1, a2);
// label
a1.setLabel("ABC");
assertNotEquals(a1, a2);
a2.setLabel("ABC");
assertEquals(a1, a2);
// check an inherited attribute
a1.setVisible(false);
assertNotEquals(a1, a2);
a2.setVisible(false);
assertEquals(a1, a2);
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
@Test
public void testHashCode() {
DialTextAnnotation a1 = new DialTextAnnotation("A1");
DialTextAnnotation a2 = new DialTextAnnotation("A1");
assertEquals(a1, a2);
int h1 = a1.hashCode();
int h2 = a2.hashCode();
assertEquals(h1, h2);
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws <API key> {
// test a default instance
DialTextAnnotation a1 = new DialTextAnnotation("A1");
DialTextAnnotation a2 = CloneUtils.clone(a1);
assertNotSame(a1, a2);
assertSame(a1.getClass(), a2.getClass());
assertEquals(a1, a2);
// check that the listener lists are independent
<API key> l1 = new <API key>();
a1.addChangeListener(l1);
assertTrue(a1.hasListener(l1));
assertFalse(a2.hasListener(l1));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
// test a default instance
DialTextAnnotation a1 = new DialTextAnnotation("A1");
DialTextAnnotation a2 = TestUtils.serialised(a1);
assertEquals(a1, a2);
// test a custom instance
a1 = new DialTextAnnotation("A1");
a1.setPaint(new GradientPaint(1.0f, 2.0f, Color.RED, 3.0f, 4.0f,
Color.BLUE));
a2 = TestUtils.serialised(a1);
assertEquals(a1, a2);
}
} |
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1-b02-fcs
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.12.16 at 05:01:18 PM GMT
package org.deegree.portal.cataloguemanager.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"dcpList"
})
@XmlRootElement(name = "DCP", namespace = "http:
public class DCP {
@XmlElement(name = "DCPList", namespace = "http:
protected DCPList dcpList;
/**
* Gets the value of the dcpList property.
*
* @return
* possible object is
* {@link DCPList }
*
*/
public DCPList getDCPList() {
return dcpList;
}
/**
* Sets the value of the dcpList property.
*
* @param value
* allowed object is
* {@link DCPList }
*
*/
public void setDCPList(DCPList value) {
this.dcpList = value;
}
} |
#if !defined(_MOBJ_DATA_H_)
#define _MOBJ_DATA_H_
#include <stdint.h>
typedef struct {
unsigned int sub_grp : 3; /* command sub-group */
unsigned int op_cnt : 3; /* operand count */
unsigned int grp : 2; /* command group */
unsigned int branch_opt : 4; /* branch option */
unsigned int reserved1 : 2;
unsigned int imm_op2 : 1; /* I-flag for operand 2 */
unsigned int imm_op1 : 1; /* I-flag for operand 1 */
unsigned int cmp_opt : 4; /* compare option */
unsigned int reserved2 : 4;
unsigned int set_opt : 5; /* set option */
unsigned int reserved3 : 3;
} HDMV_INSN;
typedef struct mobj_cmd {
HDMV_INSN insn;
uint32_t dst;
uint32_t src;
} MOBJ_CMD;
typedef struct {
uint8_t <API key> ;
uint8_t menu_call_mask ;
uint8_t title_search_mask ;
uint16_t num_cmds;
MOBJ_CMD *cmds;
} MOBJ_OBJECT;
typedef struct mobj_objects {
uint32_t mobj_version;
uint16_t num_objects;
MOBJ_OBJECT *objects;
} MOBJ_OBJECTS;
#endif // _MOBJ_DATA_H_ |
#ifndef KEYACTIONS_H
#define KEYACTIONS_H
#include <QObject>
class QimsysKeySequence;
namespace Japanese {
namespace Standard {
class KeyActions : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(KeyActions)
public:
explicit KeyActions(QObject *parent = 0);
bool contains(const QimsysKeySequence &keySequence) const;
void trigger(const QimsysKeySequence &keySequence);
private:
class Private;
Private *d;
};
}
}
#endif // KEYACTIONS_H |
#include "Config.h"
#include "reg.h"
#include "typedefs.h"
#include "TW8835.h"
#include "Global.h"
#include "CPU.h"
#include "Printf.h"
#include "util.h"
#include "Monitor.h"
#include "I2C.h"
#include "spi.h"
#include "main.h"
#include "SOsd.h"
#include "FOsd.h"
#include "decoder.h"
#include "Scaler.h"
#include "InputCtrl.h"
#include "EEPROM.h"
#include "ImageCtrl.h"
#include "Settings.h"
#include "measure.h"
#include "vadc.h"
#include "dtv.h"
#include "InputCtrl.h"
#include "OutputCtrl.h"
#include "SOsdMenu.h"
#ifdef SUPPORT_HDMI_SiIRX
#include "hdmi_SIL9127.H"
#endif
#ifdef SUPPORT_HDMI_EP9351
#include "hdmi_EP9351.H"
#endif
/*
SDTV 480i/60M
576i/50
480p SMPTE 267M-1995
HDTV 1080i/60M
1080i/50
720p/60M
720p/50
1080p = SMPTE 274M-1995 1080p/24 & 1080p/24M
1080p/50 1080p/60M
scan lines field1 field2 half
480i/60M 525 23~262 285~524 142x
576i/50 625 23~310 335~622
1080i 1125
720p 750
standard
480i/60M SMPTE 170M-1994.
ITU-R BT.601-4
SMPTE 125M-1995
SMPTE 259M-1997
*/
// INPUT CONTROL
// Input Module
// start from 0x040
//0x040~0x049
//R040[1:0] Input Select 0:InternalDecoder,1:ARGB/YUV(YPbPr),2:DTV(BT656)
//R041[0] Input data format 0:YCbCr 1:RGB
XDATA BYTE InputMain;
XDATA BYTE InputSubMode;
/**
* Get InputMain value
*
* friend function.
* Other bank, specially Menu Bank(Bank2) needs this InputMain global variable.
*/
BYTE GetInputMain(void)
{
return InputMain;
}
/**
* Set InputMain value
*
* @see GetInputMain
*/
void SetInputMain(BYTE input)
{
InputMain = input;
//update EE
}
#ifdef MODEL_TW8835_EXTI2C
#define VBLANK_WAIT_VALUE 0x0100
#else
#define VBLANK_WAIT_VALUE 0xFFFE
#endif
/**
* wait Vertical Blank
*
* You can use this function after you turn off the PD_SSPLL(REG0FC[7]).
* 0xFFFE value uses max 40ms on Cache + 72MHz.
*/
void WaitVBlank(BYTE cnt)
{
XDATA BYTE i;
WORD loop;
DECLARE_LOCAL_page
ReadTW88Page(page);
WriteTW88Page(PAGE0_GENERAL );
for ( i=0; i<cnt; i++ ) {
WriteTW88(REG002, 0xff );
loop = 0;
while (!( ReadTW88(REG002 ) & 0x40 ) ) {
// wait VBlank
loop++;
if(loop > VBLANK_WAIT_VALUE ) {
wPrintf("\nERR:WaitVBlank");
break;
}
}
}
WriteTW88Page(page);
}
/**
* wait Vertical Blank
*
* @see WaitVBlank
*/
void Wait1VBlank(void)
{
WORD loop;
DECLARE_LOCAL_page
ReadTW88Page(page);
WriteTW88Page(PAGE0_GENERAL );
WriteTW88(REG002, 0xff );
loop = 0;
while (!( ReadTW88(REG002 ) & 0x40 ) ) {
// wait VBlank
loop++;
if(loop > VBLANK_WAIT_VALUE ) {
wPrintf("\nERR:WaitVBlank");
break;
}
}
WriteTW88Page(page);
}
//class:Input
/**
* Set input path & color domain
*
* register
* REG040[1:0]
* REG041[0]
*
* @param path: input mode
* - 0:InternalDecoder
* - 1:AnalogRGB/Component. PC or Component
* - 2:BT656(DTV). Note, HDTV use BT709.
* - 3:DTV2 ?? <--TW8835 do not support
* @param format: data format.
* - 0:YCbCr 1:RGB
*/
void InputSetSource(BYTE path, BYTE format)
{
BYTE r040, r041;
WriteTW88Page( PAGE0_GENERAL );
r040 = ReadTW88(REG040_INPUT_CTRL_I) & ~0x17; //clear [2] also.
r041 = ReadTW88(<API key>) & ~0x3F;
r040 |= path;
r041 |= format;
if(path==INPUT_PATH_DECODER) { //InternalDecoder
r041 |= 0x0C; //input sync detion edge control. falling edge
}
else if(path==INPUT_PATH_VADC) { //ARGB(PC or Component)
r040 |= 0x10; //invert clock
if(InputMain==INPUT_COMP) {
r041 |= 0x20; //progressive
r041 |= 0x10; //implicit DE mode.(Component, don't care)
r041 |= 0x0C; //input sync detion edge control. falling edge
r041 |= 0x02; //input field inversion
}
else {
//??r041 |= 0x20; //progressive
r041 |= 0x10; //implicit DE mode.(Component, don't care)
r041 |= 0x0C; //input sync detion edge control. falling edge
}
}
else if(path==INPUT_PATH_DTV) { //DTV
//clock normal
r040 |= 0x08; //INT_4 pin is turn into dtvde pin
//r041 |= 0x20; // progressive
r041 |= 0x10; //implicit DE mode
//r041 |= 0x0C; //input sync detion edge control. falling edge
}
else if(path==INPUT_PATH_BT656) {
//target r040:0x06 r041:0x00
}
dPrintf("\nInputSetSource r040:%bx r041:%bx",r040,r041);
WriteTW88(REG040_INPUT_CTRL_I,r040);
WriteTW88(<API key>,r041);
}
#ifdef UNCALLED_SEGMENT
//class:Input
void <API key>(fOn)
{
WriteTW88Page(PAGE0_INPUT);
if(fOn) WriteTW88(<API key>, ReadTW88(<API key>) | 0x20); //On Field for Prog
else WriteTW88(<API key>, ReadTW88(<API key>) & ~0x20); //Off Field for Prog
}
#endif
#ifdef UNCALLED_SEGMENT
//class:Input
void InputSetPolarity(BYTE V,BYTE H, BYTE F)
{
BYTE r041;
WriteTW88Page( PAGE0_INPUT );
r041 = ReadTW88(<API key> ) & ~0x0E;
if(V) r041 |= 0x08;
if(H) r041 |= 0x04;
if(F) r041 |= 0x02;
WriteTW88(<API key>, r041);
}
//class:Input
BYTE InputGetVPolarity(void)
{
BYTE r041;
WriteTW88Page( PAGE0_INPUT );
r041 = ReadTW88(<API key> );
if(r041 & 0x08) return ON; //detect falling edge
else return OFF; //detect rising edge
}
//class:Input
BYTE InputGetHPolarity(void)
{
BYTE r041;
WriteTW88Page( PAGE0_INPUT );
r041 = ReadTW88(<API key> );
if(r041 & 0x04) return ON; //detect falling edge
else return OFF; //detect rising edge
}
//class:Input
BYTE <API key>(void)
{
BYTE r041;
WriteTW88Page( PAGE0_INPUT );
r041 = ReadTW88(<API key> );
if(r041 & 0x02) return ON; //input field inversion
else return OFF;
}
#endif
#if defined(SUPPORT_COMPONENT)
//class:Input
/**
* set Field Polarity
*
* R041[1] input field control. 1:inversion
*/
void <API key>(BYTE fInv)
{
BYTE r041;
WriteTW88Page( PAGE0_INPUT );
r041 = ReadTW88(<API key> );
if(fInv) WriteTW88(<API key>, r041 | 0x02);
else WriteTW88(<API key>, r041 & ~0x02);
}
#endif
#ifdef UNCALLED_SEGMENT
//class:Input
/*
* R041[0] Input data format selection 1:RGB
*/
BYTE InputGetColorDomain(void)
{
BYTE r041;
WriteTW88Page( PAGE0_INPUT );
r041 = ReadTW88(<API key> );
if(r041 & 0x01) return ON; //RGB color
else return OFF; //YUV color
}
#endif
//class:Input
/**
* set input crop
*
* input cropping for implicit DE.
* NOTE:InternalDecoder is not an implicit DE.
*
* register
* REG040[7:6]REG045[7:0] HCropStart
* REG043[7:0] VCropStart
* REG042[6:4]REG044[7:0] VCropLength
* REG042[3:0]REG046[7:0] HCropLength
*/
void InputSetCrop( WORD x, WORD y, WORD w, WORD h )
{
WriteTW88Page( PAGE0_INPUT );
WriteTW88(REG040_INPUT_CTRL_I, (ReadTW88(REG040_INPUT_CTRL_I) & 0x3F) | ((x & 0x300)>>2) );
WriteTW88(REG045, (BYTE)x);
WriteTW88(REG043, (BYTE)y);
WriteTW88(REG042, ((h&0xF00) >> 4)|(w >>8) );
WriteTW88(REG044, (BYTE)h);
WriteTW88(REG046, (BYTE)w);
//dPrintf("\nInput Crop Window: x = %d, y = %d, w = %d, h = %d", x, y, w, h );
}
#if 0
//class:Input
void InputSetCropStart( WORD x, WORD y)
{
WriteTW88Page( PAGE0_INPUT );
WriteTW88(REG040, (ReadTW88(REG040) & 0x3F) | ((x & 0xF00)>>2) );
WriteTW88(REG045, (BYTE)x);
WriteTW88(REG043, (BYTE)y);
//dPrintf("\nInput Crop Window: x = %d, y = %d", x, y);
}
#endif
#ifdef SUPPORT_PC
//class:Input
/**
* set Horizontal Start at InputCrop
*/
void InputSetHStart( WORD x)
{
WriteTW88Page( PAGE0_INPUT );
WriteTW88(REG040, (ReadTW88(REG040) & 0x3F) | ((x & 0xF00)>>2) );
WriteTW88(REG045, (BYTE)x);
//dPrintf("\nInput Crop Window: x = %d", x);
}
#endif
//class:Input
/**
* get Horizontal Start at InputCrop
*/
WORD InputGetHStart(void)
{
WORD wValue;
WriteTW88Page( PAGE0_INPUT );
wValue = ReadTW88(REG040) & 0xC0;
wValue <<= 2;
wValue |= ReadTW88(REG045);
return wValue;
}
#if 0
//class:Input
void InputSetVStart( WORD y)
{
WriteTW88Page( PAGE0_INPUT );
WriteTW88(REG043, (BYTE)y);
dPrintf("\nInput Crop Window: y = %d", y);
}
//class:Input
WORD InputGetVStart(void)
{
WORD wValue;
WriteTW88Page( PAGE0_INPUT );
wValue = ReadTW88(REG043 );
return wValue;
}
#endif
#if 0
//class:Input
WORD InputGetHLen(void)
{
WORD len;
WriteTW88Page( PAGE0_INPUT );
len =ReadTW88(REG042) & 0x0F;
len <<=8;
len |= ReadTW88(REG046);
return len;
}
//class:Input
WORD InputGetVLen(void)
{
WORD len;
WriteTW88Page( PAGE0_INPUT );
len =ReadTW88(REG042) & 0x70;
len <<=4;
len |= ReadTW88(REG044);
return len;
}
#endif
#if 0
//class:BT656Input
//register
// R047[7] BT656 input control 0:External input, 1:Internal pattern generator
void <API key>(BYTE fOn)
{
WriteTW88Page(PAGE0_INPUT);
if(fOn) WriteTW88(REG047,ReadTW88(REG047) | 0x80);
else WriteTW88(REG047,ReadTW88(REG047) & ~0x80);
}
#endif
//class:BT656Input
/**
* set Freerun and invert clock flag on BT656
*
* R047[7]
* R047[5]
*/
void <API key>(BYTE fFreerun, BYTE fInvClk)
{
BYTE value;
WriteTW88Page(PAGE0_INPUT);
value = ReadTW88(REG047);
if(fFreerun) value |= 0x80;
else value &= ~0x80;
if(fInvClk) value |= 0x20;
else value &= ~0x20;
WriteTW88(REG047, value);
}
/**
* print Input string
*/
void PrintfInput(BYTE Input, BYTE debug)
{
if(debug==3) {
dPuts("\nInput:");
switch(Input) {
case 0: dPrintf("CVBS"); break;
case 1: dPrintf("SVIDEO"); break;
case 2: dPrintf("Component"); break;
case 3: dPrintf("PC"); break;
case 4: dPrintf("DVI"); break;
case 5: dPrintf("HDMIPC"); break;
case 6: dPrintf("HDMITV"); break;
case 7: dPrintf("BT656"); break;
default: dPrintf("unknown:%02bd",Input); break;
}
}
else {
Puts("\nInput:");
switch(Input) {
case 0: Printf("CVBS"); break;
case 1: Printf("SVIDEO"); break;
case 2: Printf("Component"); break;
case 3: Printf("PC"); break;
case 4: Printf("DVI"); break;
case 5: Printf("HDMIPC"); break;
case 6: Printf("HDMITV"); break;
case 7: Printf("BT656"); break;
default: Printf("unknown:%02bd",Input); break;
}
}
}
/**
* Change Video Input.
*
* @param mode
* - INPUT_CVBS : ChangeCVBS
* - INPUT_SVIDEO: ChangeCVBS
* - INPUT_COMP : ChangeCOMPONENT
* - INPUT_PC : ChangePC
* - INPUT_DVI : ChangeDVI
* - INPUT_HDMIPC:
* - INPUT_HDMITV: ChangeHDMI
* - INPUT_BT656: ChangeBT656
* @see ChangeCVBS
*/
void ChangeInput( BYTE mode )
{
dPrintf("\nChangeInput:%02bx", mode);
if(<API key>())
RemoveLogo();
PrintfInput(mode,3);
switch ( mode ) {
#ifdef SUPPORT_CVBS
case INPUT_CVBS:
ChangeCVBS();
break;
#endif
#ifdef SUPPORT_SVIDEO
case INPUT_SVIDEO:
ChangeSVIDEO();
break;
#endif
#ifdef SUPPORT_COMPONENT
case INPUT_COMP:
ChangeCOMPONENT();
break;
#endif
#ifdef SUPPORT_PC
case INPUT_PC:
ChangePC();
break;
#endif
#ifdef SUPPORT_DVI
case INPUT_DVI:
ChangeDVI();
break;
#endif
#if defined(SUPPORT_HDMI_EP9351) || defined(SUPPORT_HDMI_SiIRX)
case INPUT_HDMIPC:
case INPUT_HDMITV:
ChangeHDMI();
break;
#endif
#ifdef SUPPORT_BT656
case INPUT_BT656:
ChangeBT656();
break;
#endif
default:
ChangeCVBS();
break;
}
}
/**
* move to next video input
*/
void InputModeNext( void )
{
BYTE next_input;
#if defined(SUPPORT_HDMI_EP9351) || defined(SUPPORT_HDMI_SiIRX)
if(InputMain==INPUT_HDMIPC)
next_input = InputMain + 2;
else
#endif
next_input = InputMain + 1;
do {
if(next_input == INPUT_TOTAL)
next_input = INPUT_CVBS;
#ifndef SUPPORT_CVBS
if(next_input==INPUT_CVBS)
next_input++;
#endif
#ifndef SUPPORT_SVIDEO
if(next_input==INPUT_SVIDEO)
next_input++;
#endif
#ifndef SUPPORT_COMPONENT
if(next_input==INPUT_COMP)
next_input++;
#endif
#ifndef SUPPORT_PC
if(next_input==INPUT_PC)
next_input++;
#endif
#ifndef SUPPORT_DVI
if(next_input==INPUT_DVI)
next_input++;
#endif
#if defined(SUPPORT_HDMI_EP9351) || defined(SUPPORT_HDMI_SiIRX)
if(next_input==INPUT_HDMIPC)
next_input+=2;
else if(next_input==INPUT_HDMITV)
next_input++;
#endif
#ifndef SUPPORT_BT656
if(next_input==INPUT_COMP)
next_input++;
#endif
#if defined(SUPPORT_HDMI_EP9351) || defined(SUPPORT_HDMI_SiIRX)
if(next_input==INPUT_HDMIPC) {
if(GetHdmiModeEE()) next_input = INPUT_HDMITV;
}
#endif
} while(next_input==INPUT_TOTAL);
ChangeInput(next_input);
}
// Input Control routine
extern CODE BYTE DataInitNTSC[];
/**
* prepare video input register after FW download the default init values.
*
* select input path
* turnoff freerun manual & turnon freerun auto.
* assign default freerun Htotal&Vtotal
*
* @see I2CDeviceInitialize
*/
void InitInputAsDefault(void)
{
//step1:
//Before FW starts the ChangeInput,
// link ISR & turnoff signal interrupt & NoSignal task,
// turn off LCD.
FOsdIndexMsgPrint(FOSD_STR5_INPUTMAIN); //prepare InputMain string
<API key>(); //link CheckAndSetInput
<API key>(OFF); //turnoff Video Signal Interrupt
TaskNoSignal_setCmd(TASK_CMD_DONE); //turnoff NoSignal Task
LedBackLight(OFF); //turnoff LedBackLight
//step2:
//set system default
// Download the default register values.
// set sspll
// select MCU/SPI Clock
dPuts("\nI2CDownload DataInitNTSC");
I2CDeviceInitialize( DataInitNTSC, 0 ); //Pls, do not use this ....
#ifdef <API key>
WriteTW88Page(PAGE4_CLOCK);
WriteTW88(REG4E0, 0x00); //use PCLK
#endif
if(SpiFlashVendor==SFLASH_VENDOR_MX) {
WriteTW88Page(PAGE4_CLOCK);
WriteTW88(REG4E1, (ReadTW88(REG4E1) & 0xF8) | 0x02); //if Macronix SPI Flash, SPI_CK_DIV[2:0]=2
}
#if defined(MODEL_TW8835FPGA) || defined(MODEL_TW8836FPGA)
//If you want CKLPLL, select MCUSPI_CLK_PCLK
McuSpiClkSelect(MCUSPI_CLK_PCLK);
#endif
//step3:
// InputSource=>InMux=>Decoder=>VAdc=>BT656=>DTV=>Scaler=>Measure
//InputSource
switch(InputMain) {
case INPUT_CVBS:
case INPUT_SVIDEO:
InputSetSource(INPUT_PATH_DECODER,INPUT_FORMAT_YCBCR);
break;
case INPUT_COMP: //target R040:31 R041:3E
InputSetSource(INPUT_PATH_VADC,INPUT_FORMAT_YCBCR);
break;
case INPUT_PC: //target R040:31 R041:1D
InputSetSource(INPUT_PATH_VADC,INPUT_FORMAT_RGB);
break;
case INPUT_DVI: //target R040:2A R041:11. Note:DtvInitDVI() overwite R040.
InputSetSource(INPUT_PATH_DTV,INPUT_FORMAT_RGB);
break;
case INPUT_HDMIPC:
case INPUT_HDMITV: //target R040: R041:
InputSetSource(INPUT_PATH_DTV,INPUT_FORMAT_RGB);
break;
case INPUT_BT656: //target R040:2A R041:00
InputSetSource(INPUT_PATH_BT656,INPUT_FORMAT_YCBCR);
break;
}
//InMux
InMuxSetInput(InputMain);
//Decoder
DecoderFreerun(<API key>); //component,pc,dvi removed
//aRGB(VAdc)
VAdcSetDefaultFor();
if(InputMain==INPUT_BT656)
BT656OutputEnable(ON,0); //R007[3]=1.DataInitNTSC clear it.
else
BT656OutputEnable(OFF, 1);
//BT656Input
switch(InputMain) {
case INPUT_CVBS:
case INPUT_SVIDEO:
case INPUT_COMP:
case INPUT_PC:
break;
case INPUT_DVI:
<API key>(OFF, OFF); //BT656 turnoff FreeRun
break;
case INPUT_HDMIPC:
case INPUT_HDMITV:
<API key>(OFF, OFF); //BT656 turnoff FreeRun
break;
case INPUT_BT656:
<API key>(OFF, ON); //off freerun, on invert_clk
break;
}
//DTV
switch(InputMain) {
case INPUT_CVBS:
case INPUT_SVIDEO:
case INPUT_COMP:
case INPUT_PC:
break;
#ifdef SUPPORT_DVI
case INPUT_DVI:
DtvSetClockDelay(1);
DtvSetVSyncDelay(4);
<API key>(ON,0x11); // set Det field by WIN
DtvSetPolarity(0,0);
DtvSetRouteFormat(DTV_ROUTE_YPbPr,DTV_FORMAT_RGB565);
#ifdef MODEL_TW8835FPGA
SetExtVAdcI2C(0x9A, 0); //AD9883. VGA
// SetExtVAdcI2C(0x9A, 6); //480P
#endif
break;
#endif
case INPUT_HDMIPC:
case INPUT_HDMITV:
#if defined(SUPPORT_HDMI_EP9351) || defined(SUPPORT_HDMI_SiIRX)
#ifdef SUPPORT_HDMI_EP9351
//default is RGB565. test RGB24.
#ifdef SUPPORT_HDMI_24BIT
DtvSetRouteFormat(DTV_ROUTE_PrYPb,DTV_FORMAT_RGB); //RGB24. 120720
#else
DtvSetRouteFormat(DTV_ROUTE_YPbPr,DTV_FORMAT_RGB565);
#endif
#endif
#ifdef SUPPORT_HDMI_SiIRX
DtvSetRouteFormat(DTV_ROUTE_RGB, DTV_FORMAT_RGB);
#endif
#ifdef MODEL_TW8835FPGA
SetExtVAdcI2C(0x9A, 0); //AD9883. VGA
// SetExtVAdcI2C(0x9A, 6); //480P
#endif
DtvSetClockDelay(1); //BK111201
DtvSetVSyncDelay(4); //BK111201
<API key>(ON,0x11); // set Det field by WIN
#endif
break;
case INPUT_BT656:
#ifdef SUPPORT_BT656
DtvSetRouteFormat(DTV_ROUTE_PrYPb,<API key>);
#endif
#ifdef MODEL_TW8835FPGA
SetExtVAdcI2C(0x9A, 0); //AD9883. VGA
// SetExtVAdcI2C(0x9A, 6); //480P
#endif
break;
}
//BKTODO:120423. power down the external chip.
//#if defined(SUPPORT_HDMI_EP9351)
// if(InputMain != INPUT_HDMIPC && InputMain != INPUT_HDMITV) {
// //power down
//#endif
//scaler
<API key>( OFF ); //component,pc,dvi removed
//measure
switch(InputMain) {
case INPUT_CVBS:
case INPUT_SVIDEO:
case INPUT_COMP:
case INPUT_PC:
//BKFYI. CVBS&SVIDEO was MeasSetWindow( 0, 0, 2200,1125 );
MeasSetWindow( 0, 0, 0xfff, 0xfff ); //set dummy window. 1600x600
MeasSetField(2); // field:Both
MeasEnableDeMeasure(OFF); // Disable DE Measure
MeasSetThreshold(0x40); // Threshold active detection
break;
case INPUT_DVI:
case INPUT_HDMIPC:
case INPUT_HDMITV:
MeasSetWindow( 0, 0, 0xfff, 0xfff ); //set dummy window. 1600x600
MeasSetField(2); //field:Both
MeasEnableDeMeasure(ON); //Enable DE Measure
MeasSetThreshold(0x40); //Threshold active detection
MeasSetErrTolerance(4); //tolerance set to 32
<API key>(ON); //set EN. Changed Detection
break;
case INPUT_BT656:
break;
}
//image effect
SetImage(InputMain); //set saved image effect(contrast,....)
}
/**
* enable video Output
*
* call when CheckAndSet[Input] is successed.
*/
void VInput_enableOutput(BYTE fRecheck)
{
if(fRecheck) {
dPrintf("====Found Recheck:%d",VH_Loss_Changed);
// do not turn on here. We need a retry.
}
else {
ScalerSetMuteManual( OFF ); //TurnOn Video Output. Remove Black Video
<API key>( OFF ); //FreeRunOff,UseVideoInputSource
<API key>(0); //caclulate freerun value
SpiOsdSetDeValue();
FOsdSetDeValue();
LedBackLight(ON); //TurnOn Display
}
TaskNoSignal_setCmd(TASK_CMD_DONE);
<API key>(ON);
if(InputMain == INPUT_DVI
|| InputMain == INPUT_HDMIPC
|| InputMain == INPUT_HDMITV
|| InputMain == INPUT_BT656 ) {
//digital input.
; //SKIP
}
else
<API key>(ON);
#ifdef PICO_GENERIC
FLCOS_toggle();
#endif
}
/**
* goto Freerun move
*
* call when CheckAndSet[Input] is failed.
* oldname: VInputGotoFreerun
* input
* reason
* 0: No Signal
* 1: No STD
* 2: Out of range
*/
void VInput_gotoFreerun(BYTE reason)
{
<API key>();
//Freerun
if(InputMain == INPUT_BT656) {
//??WHY
}
else {
DecoderFreerun(<API key>);
}
<API key>( ON );
if(InputMain == INPUT_HDMIPC
|| InputMain == INPUT_HDMITV
|| InputMain == INPUT_BT656) {
//??WHY
}
else {
ScalerSetMuteManual( ON );
}
// Prepare NoSignal Task...
if(reason==0 && MenuGetLevel()==0) { //0:NoSignal 1:NO STD,...
if(access) {
FOsdSetDeValue();
FOsdIndexMsgPrint(FOSD_STR2_NOSIGNAL);
tic_task = 0;
#ifdef NOSIGNAL_LOGO
if(<API key>() == 0)
InitLogo1();
#endif
TaskNoSignal_setCmd(TASK_CMD_WAIT_VIDEO);
}
}
if(InputMain == INPUT_PC) {
//BK111019. I need a default RGB_START,RGB_VDE value for position menu.
RGB_HSTART = InputGetHStart();
RGB_VDE = ScalerReadVDEReg();
}
LedBackLight(ON);
<API key>(ON);
}
// Change to DECODER. (CVBS & SVIDEO)
/**
* check and set the decoder input
*
* @return
* 0: success
* 1: VDLOSS
* 2: No Standard
* 3: Not Support Mode
*
* extern
* InputSubMode
*/
BYTE <API key>( void )
{
BYTE mode;
DWORD vPeriod, vDelay;
BYTE vDelayAdd;
DWORD x_ratio, y_ratio;
dPrintf("\<API key> start.");
if ( DecoderCheckVDLOSS(100) ) {
ePuts("\<API key> VDLOSS");
DecoderFreerun(<API key>);
<API key>( ON );
return( 1 );
}
//get standard
mode = DecoderCheckSTD(100);
if ( mode == 0x80 ) {
ePrintf("\<API key> NoSTD");
return( 2 );
}
mode >>= 4;
InputSubMode = mode;
VideoAspect = GetAspectModeEE();
//read VSynch Time+VBackPorch value
vDelay = DecoderGetVDelay();
//reduce VPeriod to scale up.
//and adjust V-DE start.
//720x240 => 800x480
x_ratio = PANEL_H;
x_ratio *=100;
x_ratio /= 720;
y_ratio = PANEL_V;
y_ratio *=100;
y_ratio /= 480;
dPrintf("\nXYRatio X:%ld Y:%ld",x_ratio,y_ratio);
if(VideoAspect==VIDEO_ASPECT_ZOOM) {
if(x_ratio > y_ratio) {
dPrintf(" use x. adjust Y");
y_ratio = 0;
}
else {
dPrintf(" use y. adjust X");
x_ratio = 0;
}
}
else if(VideoAspect==VIDEO_ASPECT_NORMAL) {
if(x_ratio > y_ratio) {
dPrintf(" use y. adjust X");
x_ratio = 0;
}
else {
dPrintf(" use x. adjust Y");
y_ratio = 0;
}
}
else {
x_ratio = 0;
y_ratio = 0;
}
//720x288 => 800x480
if ( mode == 0 ) { // NTSC(M)
vPeriod = 228; // NTSC line number.(reduced from 240 to 228)
//vDelay += 12; // (6 = ( 240-228 ) / 2) times 2 because. 240->480
//vDelay += 27; // for V Back Porch & V top border
vDelayAdd = 39;
if(VideoAspect==VIDEO_ASPECT_ZOOM) {
vDelayAdd += 30;
vDelayAdd += 5;
}
DecoderSetVActive(240); //set:240 0x0F0
//prepare info
<API key>(); //GetInputMainString(FOsdMsgBuff);
TWstrcat(FOsdMsgBuff," NTSC"); //BK110811. call <API key>(OFF); to draw
}
else if ( mode == 1 ) { //PAL(B,D,G,H,I)
vPeriod = 275; // PAL line number,(Reduced from 288 to 275)
#if 0
//vDelay += 7; // 6.7 = ( 288-275 ) / 2
//vDelay += 2; // add some more for V Back Porch & V Top border
vDelayAdd = 25;
#else
//vDelay += 14; // (6.7 = ( 288-275 ) / 2 ) * 2
//vDelay += 25; // add some more for V Back Porch & V Top border
vDelayAdd = 39;
#endif
if(VideoAspect==VIDEO_ASPECT_ZOOM)
vDelayAdd += 33;
DecoderSetVActive(288); //set:288. 0x120
//prepare info
<API key>(); //GetInputMainString(FOsdMsgBuff);
TWstrcat(FOsdMsgBuff," PAL"); //BK110811. call <API key>(OFF); to draw
}
//BKTODO: Support more mode
//0 = NTSC(M)
//1 = PAL (B,D,G,H,I)
//2 = SECAM
//3 = NTSC4.43
//4 = PAL (M)
//5 = PAL (CN)
//6 = PAL 60
else if ( mode == 3 //MTSC4
|| mode == 4 //PAL-M
|| mode == 6 //PAL-60
) {
vPeriod = 228;
vDelayAdd = 39;
if(VideoAspect==VIDEO_ASPECT_ZOOM) {
vDelayAdd += 30;
vDelayAdd += 5;
}
DecoderSetVActive(240); //set:240 0x0F0
//prepare info
<API key>();
if(mode==3) TWstrcat(FOsdMsgBuff," NTSC4");
if(mode==4) TWstrcat(FOsdMsgBuff," PAL-M");
if(mode==6) TWstrcat(FOsdMsgBuff," PAL-60");
}
else if ( mode == 2 //SECAM
|| mode == 4 //PAL-CN
) {
vPeriod = 275;
vDelayAdd = 39;
if(VideoAspect==VIDEO_ASPECT_ZOOM)
vDelayAdd += 33;
DecoderSetVActive(288); //set:288. 0x120
//prepare info
<API key>();
if(mode==2) TWstrcat(FOsdMsgBuff," SECAM");
if(mode==4) TWstrcat(FOsdMsgBuff," PAL-CN");
}
else {
ePrintf( "\<API key> Input Mode %bd does not support now", mode );
return(3);
}
<API key>(720); //BK120116 - temp location. pls remove
if(y_ratio) <API key>(720, (WORD)y_ratio);
else ScalerSetHScale(720); //PC->CVBS need it.
if(x_ratio) <API key>(vPeriod, (WORD)x_ratio);
else ScalerSetVScale(vPeriod); //R206[7:0]R205[7:0] = vPeriod
ScalerWriteVDEReg(vDelay+vDelayAdd); //R215[7:0]=vDelay, R217[3:0]R216[7:0]=PANEL_V
//dPrintf( "\nInput_Mode:%02bx VDE_width:%ld, vBackPorch:%ld", mode, vPeriod, vDelay );
ePrintf( "\nInput_Mode:%s <API key>:%ld, V-DE:%ld+%bd", mode ? "PAL":"NTSC", vPeriod, vDelay,vDelayAdd );
return(0);
}
/**
* Change to Decoder
*
* extern
* InputMain
* InputSubMode
* @param
* fSVIDEO 0:CVBS, 1:SVIDEO
* @return
* - 0: success
* - 1: No Update happen
* - 2: No Signal or unknown video sidnal.
* - 3: NO STD
* @see InitInputAsDefault
* @see <API key>
* @see VInput_enableOutput
* @see VInput_gotoFreerun
*/
BYTE ChangeDecoder(BYTE fSVIDEO)
{
BYTE ret;
if(fSVIDEO) {
if ( InputMain == INPUT_SVIDEO ) {
dPrintf("\nSkip ChangeSVIDEO");
return(1);
}
InputMain = INPUT_SVIDEO;
}
else {
if ( InputMain == INPUT_CVBS ) {
dPrintf("\nSkip ChangeCVBS");
return(1);
}
InputMain = INPUT_CVBS;
}
InputSubMode = 7;
if(GetInputEE() != InputMain)
SaveInputEE( InputMain );
// initialize video input
InitInputAsDefault();
//BKFYI: We need a delay before call DecoderCheckVDLOSS() on <API key>()
//But, if fRCDMode, InputMode comes from others, not CVBS, not SVIDEO. We don't need a delay
delay1ms(350);
// Check and Set
ret = <API key>(); //same as CheckAndSetInput()
if(ret==ERR_SUCCESS) {
//success
VInput_enableOutput(0);
return 0;
}
// NO SIGNAL
VInput_gotoFreerun(ret-1); //1->0:NoSignal 2->1:NO STD
return (ret+1); //2:NoSignal 3:NO STD
}
/**
* Change to CVBS
*
* @return
* - 0: success
* - 1: No Update happen
* - 2: No Signal or unknown video sidnal.
* - 3: NO STD
* @see ChangeDecoder
*/
BYTE ChangeCVBS( void )
{
return ChangeDecoder(0);
}
/**
* Change to SVIDEO
*
* @return
* - 0: success
* - 1: No Update happen
* - 2: No Signal or unknown video sidnal.
* - 3: NO STD
* @see ChangeDecoder
*/
BYTE ChangeSVIDEO( void )
{
return ChangeDecoder(1);
}
// Change to COMPONENT (YPBPR)
#ifdef SUPPORT_COMPONENT
/**
* Change to Component
*
* @return
* - 0: success
* - 1: No Update happen
* - 2: No Signal or unknown video sidnal.
*/
BYTE ChangeCOMPONENT( void )
{
BYTE ret;
if ( InputMain == INPUT_COMP ) {
dPrintf("\nSkip ChangeCOMPONENT");
return(1);
}
InputMain = INPUT_COMP;
InputSubMode = 7; //N/A.Note:7 is a correct value.
if(GetInputEE() != InputMain)
SaveInputEE( InputMain );
// initialize video input
InitInputAsDefault();
// Check and Set with measure
// Check and Set VADC,mesaure,Scaler for Component input
ret = <API key>(); //same as CheckAndSetInput()
if(ret==ERR_SUCCESS) {
//success
VInput_enableOutput(0);
return 0;
}
// NO SIGNAL
//InputVAdcMode = 0;
//start recover & force some test image.
VInput_gotoFreerun(0);
return(2); //fail
}
#endif
// Change to PC
//BYTE last_position_h;
//BYTE last_position_v;
//BYTE temp_position_h;
//BYTE temp_position_v;
#ifdef SUPPORT_PC
/**
* Change to PC
*
* @return
* - 0: success
* - 1: No Update happen
* - 2: No Signal or unknown video sidnal.
*/
BYTE ChangePC( void )
{
BYTE ret;
if ( InputMain == INPUT_PC ) {
dPrintf("\nSkip ChangePC");
return(1);
}
InputMain = INPUT_PC;
InputSubMode = 0;
if(GetInputEE() != InputMain)
SaveInputEE( InputMain );
// initialize video input
InitInputAsDefault();
// Check and Set VADC,mesaure,Scaler for Analog PC input
ret = CheckAndSetPC(); //same as CheckAndSetInput()
if(ret==ERR_SUCCESS) {
//success
VInput_enableOutput(0);
return 0;
}
// NO SIGNAL
// Prepare NoSignal Task...
//free run
//start recover & force some test image.
VInput_gotoFreerun(0);
return 2; //fail..
}
#endif
// Change to DVI
#ifdef SUPPORT_DVI
/**
* Change to DVI
*
* linked with SIL151
* @return
* - 0: success
* - 1: No Update happen
* - 2: No Signal or unknown video sidnal.
*/
BYTE ChangeDVI( void )
{
BYTE ret;
if ( InputMain == INPUT_DVI ) {
dPrintf("\nSkip ChangeDVI");
return(1);
}
InputMain = INPUT_DVI;
if(GetInputEE() != InputMain)
SaveInputEE( InputMain );
// initialize video input
InitInputAsDefault();
// Check and Set VADC,mesaure,Scaler for Analog PC input
ret = CheckAndSetDVI(); //same as CheckAndSetInput()
if(ret==0) {
//success
VInput_enableOutput(0);
return 0;
}
// NO SIGNAL
// Prepare NoSignal Task...
VInput_gotoFreerun(0);
//dPrintf("\nChangeDVI--END");
return(2);
}
#endif
// Change to HDMI
/**
* Change to HDMI
*
* linked with EP9351
* @return
* - 0: success
* - 1: No Update happen
* - 2: No Signal or unknown video sidnal.
*/
BYTE ChangeHDMI(void)
{
BYTE ret;
#ifdef SUPPORT_HDMI_EP9351
// BYTE i;
// volatile BYTE r3C, r3D;
#endif
if ( InputMain == INPUT_HDMIPC || InputMain == INPUT_HDMITV ) {
dPrintf("\nSkip ChangeHDMI");
return(1);
}
if(GetHdmiModeEE()) InputMain = INPUT_HDMITV;
else InputMain = INPUT_HDMIPC;
if(GetInputEE() != InputMain)
SaveInputEE( InputMain );
dPrintf("\nChangeHDMI InputMain:%02bx",InputMain);
// initialize video input
InitInputAsDefault();
#ifdef SUPPORT_HDMI_SiIRX
HdmiCheckDeviceId();
<API key>();
#endif
#ifdef SUPPORT_HDMI_EP9351
//wakeup(turn off the power down)
HdmiInitEp9351Chip();
#endif
// Check and Set
#if defined(SUPPORT_HDMI_EP9351) || defined(SUPPORT_HDMI_SiIRX)
ret = CheckAndSetHDMI();
#else
ret=ERR_FAIL;
#endif
if(ret==ERR_SUCCESS) {
//success
VInput_enableOutput(0);
return 0;
}
// NO SIGNAL
// Prepare NoSignal Task...
VInput_gotoFreerun(0);
//dPrintf("\nChangeHDMI--END");
return(2);
}
// Change to BT656
#ifdef SUPPORT_BT656
/**
* Check and Set BT656
*
* @return
* - 0: success
* - other: error
* @todo REG04A[0] does not work.
*/
BYTE CheckAndSetBT656(void)
{
BYTE value;
#if 0
WriteTW88Page(PAGE0_BT656);
value=ReadTW88(REG04A);
if(value & 0x01) return 1; //NO Signal
else return 0; //found signal
#else
value = ScalerCalcHDE();
ScalerWriteHDEReg(value+3);
//R04A[0] is not working
return 0;
#endif
}
#endif
// BYTE ChangeBT656( void )
#ifdef SUPPORT_BT656
/**
* Change to BT656
*
* @return
* - 0: success
* - 1: No Update happen
* - 2: No Signal or unknown video sidnal.
*/
BYTE ChangeBT656(void)
{
BYTE ret;
if ( InputMain == INPUT_BT656 ) {
dPrintf("\nSkip ChangeBT656");
return(1);
}
InputMain = INPUT_BT656;
if(GetInputEE() != InputMain)
SaveInputEE( InputMain );
// initialize video input
InitInputAsDefault();
// Check and Set VADC,mesaure,Scaler for Analog PC input
ret = CheckAndSetBT656(); //same as CheckAndSetInput()
//dPrintf("\nBT656 input Detect: %s", ret ? "No" : "Yes" );
if(ret==0) {
//success
VInput_enableOutput(0);
return 0;
}
// NO SIGNAL
// Prepare NoSignal Task...
VInput_gotoFreerun(0);
return(2);
}
#endif |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Example of using Iterator Operations to retrieve instances from a
WBEM Server. This example executes the <API key> and the
corresponding IterEnumeratePaths operations.
It:
Creates a connection
Opens an enumeration session with <API key>
Executes a pull loop until the result.eos =True
Displays overall statistics on the returns
It also displays the results of the open and each pull in detail
"""
from __future__ import print_function
import sys
import argparse as _argparse
from pywbem import WBEMConnection, CIMError, Error
from pywbem._cliutils import SmartFormatter as _SmartFormatter
def _str_to_bool(str_):
"""Convert string to bool (in argparse context)."""
if str_.lower() not in ['true', 'false', 'none']:
raise ValueError('Need bool; got %r' % str_)
return {'true': True, 'false': False, 'none': None}[str_.lower()]
def <API key>(parser, name, default=None, help_=None):
"""Add a boolean argument to an ArgumentParser instance."""
group = parser.<API key>()
group.add_argument(
'--' + name, nargs='?', default=default, const=True, type=_str_to_bool,
help=help_)
group.add_argument('--no' + name, dest=name, action='store_false',
help=help_)
def create_parser(prog):
"""
Parse command line arguments, connect to the WBEM server and open the
interactive shell.
"""
usage = '%(prog)s [options] server'
desc = 'Provide an interactive shell for issuing operations against' \
' a WBEM server.'
argparser = _argparse.ArgumentParser(
prog=prog, usage=usage, description=desc, epilog=epilog,
add_help=False, formatter_class=_SmartFormatter)
pos_arggroup = argparser.add_argument_group(
'Positional arguments')
pos_arggroup.add_argument(
'server', metavar='server', nargs='?',
help='R|Host name or url of the WBEM server in this format:\n'
' [{scheme}://]{host}[:{port}]\n'
'- scheme: Defines the protocol to use;\n'
' - "https" for HTTPs protocol\n'
' - "http" for HTTP protocol.\n'
' Default: "https".\n'
'- host: Defines host name as follows:\n'
' - short or fully qualified DNS hostname,\n'
' - literal IPV4 address(dotted)\n'
' - literal IPV6 address (RFC 3986) with zone\n'
' identifier extensions(RFC 6874)\n'
' supporting "-" or %%25 for the delimiter.\n'
'- port: Defines the WBEM server port to be used\n'
' Defaults:\n'
' - HTTP - 5988\n'
' - HTTPS - 5989\n')
server_arggroup = argparser.add_argument_group(
'Server related options',
'Specify the WBEM server namespace and timeout')
server_arggroup.add_argument(
'-n', '--namespace', dest='namespace', metavar='namespace',
default='root/cimv2',
help='R|Default namespace in the WBEM server for operation\n'
'requests when namespace option not supplied with\n'
'operation request.\n'
'Default: %(default)s')
server_arggroup.add_argument(
'-t', '--timeout', dest='timeout', metavar='timeout', type=int,
default=None,
help='R|Timeout of the completion of WBEM Server operation\n'
'in seconds(integer between 0 and 300).\n'
'Default: No timeout')
server_arggroup.add_argument(
'-c', '--classname', dest='classname', metavar='classname',
default='CIM_ManagedElement',
help='R|Classname in the WBEM server for operation\n'
'request.\n'
'Default: %(default)s')
security_arggroup = argparser.add_argument_group(
'Connection security related options',
'Specify user name and password or certificates and keys')
security_arggroup.add_argument(
'-u', '--user', dest='user', metavar='user',
help='R|User name for authenticating with the WBEM server.\n'
'Default: No user name.')
security_arggroup.add_argument(
'-p', '--password', dest='password', metavar='password',
help='R|Password for authenticating with the WBEM server.\n'
'Default: Will be prompted for, if user name\nspecified.')
security_arggroup.add_argument(
'-nvc', '--no-verify-cert', dest='no_verify_cert',
action='store_true',
help='Client will not verify certificate returned by the WBEM'
' server (see cacerts). This bypasses the client-side'
' verification of the server identity, but allows'
' encrypted communication with a server for which the'
' client does not have certificates.')
security_arggroup.add_argument(
'--cacerts', dest='ca_certs', metavar='cacerts',
help='R|File or directory containing certificates that will be\n'
'matched against a certificate received from the WBEM\n'
'server. Set the --no-verify-cert option to bypass\n'
'client verification of the WBEM server certificate.\n')
security_arggroup.add_argument(
'--certfile', dest='cert_file', metavar='certfile',
help='R|Client certificate file for authenticating with the\n'
'WBEM server. If option specified the client attempts\n'
'to execute mutual authentication.\n'
'Default: Simple authentication.')
security_arggroup.add_argument(
'--keyfile', dest='key_file', metavar='keyfile',
help='R|Client private key file for authenticating with the\n'
'WBEM server. Not required if private key is part of the\n'
'certfile option. Not allowed if no certfile option.\n'
'Default: No client key file. Client private key should\n'
'then be part of the certfile')
general_arggroup = argparser.add_argument_group(
'General options')
general_arggroup.add_argument(
'-v', '--verbose', dest='verbose',
action='store_true', default=False,
help='Print more messages while processing')
general_arggroup.add_argument(
'-m', '--MaxObjectCount', dest='max_object_count',
metavar='MaxObjectCount', default=100,
help='R|Maximum object count in pull responses.\n'
'Default: 100.')
<API key>(
general_arggroup, 'usepull',
help_='Use Pull Operations. If --usepull, pull will be used. If'
' --nousepull will execute Enumerate operation. Default is'
' `None` where the system decides.')
general_arggroup.add_argument(
'-h', '--help', action='help',
help='Show this help message and exit')
return argparser
def parse_cmdline(argparser_):
""" Parse the command line. This tests for any required args"""
opts = argparser_.parse_args()
if not opts.server:
argparser_.error('No WBEM server specified')
return None
return opts
def main():
"""
Get arguments and call the execution function
"""
prog = sys.argv[0]
arg_parser = create_parser(prog)
opts = parse_cmdline(arg_parser)
print('Parameters: server=%s\n username=%s\n namespace=%s\n'
' classname=%s\n max_pull_size=%s\n use_pull=%s' %
(opts.server, opts.user, opts.namespace, opts.classname,
opts.max_object_count, opts.usepull))
# call method to connect to the server
conn = WBEMConnection(opts.server, (opts.user, opts.password),
default_namespace=opts.namespace,
no_verification=True,
use_pull_operations=opts.usepull)
#Call method to create iterator
instances = []
try:
iter_instances = conn.<API key>(
opts.classname,
MaxObjectCount=opts.max_object_count)
# generate instances with
for instance in iter_instances:
print(' %s %s' % (type(instances), type(instance)))
instances.append(instance)
print('\npath=%s\n%s' % (instance.path, instance.tomof()))
# handle exceptions
except CIMError as ce:
print('Operation Failed: CIMError: code=%s, Description=%s' %
(ce.status_code_name, ce.status_description))
sys.exit(1)
except Error as err:
print ("Operation failed: %s" % err)
sys.exit(1)
inst_paths = [inst.path for inst in instances]
paths = []
try:
iter_paths = conn.<API key>(
opts.classname,
MaxObjectCount=opts.max_object_count)
# generate instances with
for path in iter_paths:
print('path=%s' % path)
paths.append(path)
if len(paths) != len(paths):
print('Error path and enum response sizes different enum=%s path=%s'
% (len(paths), len(paths)))
for path in paths:
found = False
for inst_path in inst_paths:
if path == inst_path:
found = True
break
else:
print('No match \n%s\n%s' %(path, inst_path))
if not found:
print('Path %s not found in insts' % path)
# handle exceptions
except CIMError as ce:
print('Operation Failed: CIMError: code=%s, Description=%s' %
(ce.status_code_name, ce.status_description))
sys.exit(1)
except Error as err:
print ("Operation failed: %s" % err)
sys.exit(1)
return 0
if __name__ == '__main__':
sys.exit(main()) |
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <signal.h>
extern __typeof(vfork) __vfork attribute_hidden;
#ifdef __NR_clone
pid_t __vfork(void)
{
pid_t pid;
pid = INLINE_SYSCALL(clone, 4, SIGCHLD, NULL, NULL, NULL);
/*
// Kernel bug prevents us from doing this
pid = INLINE_SYSCALL(clone, 4, CLONE_VFORK | CLONE_VM | SIGCHLD,
NULL, NULL, NULL);
*/
if (pid < 0) {
__set_errno (-pid);
return -1;
}
return pid;
}
weak_alias(__vfork,vfork)
libc_hidden_weak(vfork)
#elif defined __NR_vfork
_syscall0(pid_t, __vfork)
weak_alias(__vfork,vfork)
libc_hidden_weak(vfork)
#elif defined __ARCH_USE_MMU__ && defined __NR_fork
/* Trivial implementation for arches that lack vfork */
pid_t __vfork(void)
{
return fork();
}
weak_alias(__vfork,vfork)
libc_hidden_weak(vfork)
#endif |
#ifndef STORAGEADAPTER_H
#define STORAGEADAPTER_H
#include <QMap>
#include <QVector>
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#include <buteosyncfw5/StoragePlugin.h>
#include <buteosyncml5/StoragePlugin.h>
#include <buteosyncml5/DataStore.h>
#include <buteosyncml5/SyncItemKey.h>
#else
#include <buteosyncfw/StoragePlugin.h>
#include <buteosyncml/StoragePlugin.h>
#include <buteosyncml/DataStore.h>
#include <buteosyncml/SyncItemKey.h>
#endif
#include "ItemIdMapper.h"
class StoragePlugin;
class StorageItem;
class StorageAdapter : public DataSync::StoragePlugin
{
public:
/*! \brief Constructor
*
* @param aPlugin Plugin that this instance should adapt. Not owned
*/
StorageAdapter( Buteo::StoragePlugin* aPlugin );
/*! \brief Destructor
*
*/
virtual ~StorageAdapter();
/*! \brief Returns if this adapter instance is valid
*
* @return True if this adapter instance is valid, otherwise false
*/
bool isValid();
/*! \brief Returns the FW plugin instance
*
* @return Plugin
*/
Buteo::StoragePlugin* getPlugin() const;
/*! \brief Initializes adapter
*
* Sets up SyncML storage plugin based on FW plugin properties
*
* @return True if initialization was successful, otherwise false
*/
bool init();
/*! \brief Uninitializes adapter
*
* @return True if uninitialization was successful, otherwise false
*/
bool uninit();
/*! \see DataSync::StoragePlugin::getSourceURI()
*
*/
virtual const QString& getSourceURI() const;
/*! \see DataSync::StoragePlugin::getSourceURI()
*
*/
virtual const DataSync::<API key>& getFormatInfo() const;
/*! \see DataSync::StoragePlugin::getMaxObjSize()
*
*/
virtual qint64 getMaxObjSize() const;
/*! \see DataSync::StoragePlugin::getPluginCTCaps()
*
*/
virtual QByteArray getPluginCTCaps( DataSync::ProtocolVersion aVersion ) const;
/*! \see DataSync::StoragePlugin::getPluginExts()
*
*/
virtual QByteArray getPluginExts() const;
/*! \see DataSync::StoragePlugin::getAll()
*
*/
virtual bool getAll( QList<DataSync::SyncItemKey>& aKeys );
/*! \see DataSync::StoragePlugin::getModifications()
*
*/
virtual bool getModifications( QList<DataSync::SyncItemKey>& aNewKeys,
QList<DataSync::SyncItemKey>& aReplacedKeys,
QList<DataSync::SyncItemKey>& aDeletedKeys,
const QDateTime& aTimeStamp );
/*! \see DataSync::StoragePlugin::newItem()
*
*/
virtual DataSync::SyncItem* newItem();
/*! \see DataSync::StoragePlugin::getSyncItem()
*
*/
virtual DataSync::SyncItem* getSyncItem( const DataSync::SyncItemKey& aKey );
/*! \see DataSync::StoragePlugin::getSyncItems()
*
*/
virtual QList<DataSync::SyncItem*> getSyncItems( const QList <DataSync::SyncItemKey>& aKeyList );
/*! \see DataSync::StoragePlugin::addItems()
*
*/
virtual QList<StoragePluginStatus> addItems( const QList<DataSync::SyncItem*>& aItems );
/*! \see DataSync::StoragePlugin::replaceItems()
*
*/
virtual QList<StoragePluginStatus> replaceItems( const QList<DataSync::SyncItem*>& aItems );
/*! \see DataSync::StoragePlugin::deleteItems()
*
*/
virtual QList<StoragePluginStatus> deleteItems( const QList<DataSync::SyncItemKey>& aKeys );
protected:
private:
DataSync::StoragePlugin::StoragePluginStatus convertStatus( Buteo::StoragePlugin::OperationStatus aStatus ) const;
Buteo::StorageItem* toStorageItem( const DataSync::SyncItem* aSyncItem ) const;
Buteo::StoragePlugin* iPlugin;
QString iType;
DataSync::<API key> iFormats;
QString iSourceDB;
QString iTargetDB;
ItemIdMapper iIdMapper;
};
#endif // STORAGEADAPTER_H |
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# This library is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# You should have received a copy of the GNU Lesser General Public
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# This case corresponds to: /visu/GaussPoints/C1 case
# Create Gauss Points on the field of the MED file
import os
import sys
from paravistest import datadir, pictureext, get_picture_dir
from presentations import GaussPointsOnField, EntityType, get_time, <API key>
import pvserver as paravis
import pvsimple
# Directory for saving snapshots
picturedir = get_picture_dir("GaussPoints/C1")
if not picturedir.endswith(os.sep):
picturedir += os.sep
# MED file
file_name = datadir + "T_COUPLEX1.med"
field_name = "Conc. I129"
timestamp_nb = -1 # last timestamp
paravis.OpenDataFile(file_name)
med_reader = pvsimple.GetActiveSource()
if med_reader is None:
raise RuntimeError("File wasn't imported!!!")
# Create Gauss Points presentation
prs = GaussPointsOnField(med_reader, EntityType.CELL, field_name, timestamp_nb)
if prs is None:
raise RuntimeError, "Created presentation is None!!!"
# Display presentation and get snapshot
view = pvsimple.GetRenderView()
time = get_time(med_reader, timestamp_nb)
pic_name = picturedir + field_name + "_" + str(time) + "_GAUSSPOINTS." + pictureext
<API key>(prs, view, pic_name) |
#endregion
using System;
using System.Text;
using System.Threading;
using CommandMessenger.TransportLayer;
namespace CommandMessenger
{
<summary>
Manager for data over transport layer.
</summary>
public class <API key> : DisposableObject
{
private ITransport _transport;
public readonly Encoding StringEncoder = Encoding.GetEncoding("ISO-8859-1"); // The string encoder
private string _buffer = ""; // The buffer
private ReceiveCommandQueue <API key>;
private IsEscaped _isEscaped; // The is escaped
private char _fieldSeparator; // The field separator
private char _commandSeparator; // The command separator
private char _escapeCharacter; // The escape character
private object _parseLinesLock = new object();
<summary> Default constructor. </summary>
/// <param name="disposeStack"> The DisposeStack</param>
<param name="transport"> The Transport Layer</param>
<param name="receiveCommandQueue"></param>
public <API key>(DisposeStack disposeStack, ITransport transport, ReceiveCommandQueue receiveCommandQueue)
{
Initialize(disposeStack,transport, receiveCommandQueue, ';', ',', '/');
}
<summary> Constructor. </summary>
<param name="receiveCommandQueue"></param>
<param name="commandSeparator"> The End-Of-Line separator. </param>
<param name="fieldSeparator"></param>
<param name="escapeCharacter"> The escape character. </param>
<param name="disposeStack"> The DisposeStack</param>
<param name="transport"> The Transport Layer</param>
public <API key>(DisposeStack disposeStack,ITransport transport, ReceiveCommandQueue receiveCommandQueue, char commandSeparator, char fieldSeparator, char escapeCharacter)
{
Initialize(disposeStack, transport, receiveCommandQueue, commandSeparator, fieldSeparator, escapeCharacter);
}
<summary> Finaliser. </summary>
~<API key>()
{
Dispose(false);
}
<summary> Initializes this object. </summary>
<param name="receiveCommandQueue"></param>
<param name="commandSeparator"> The End-Of-Line separator. </param>
<param name="fieldSeparator"></param>
<param name="escapeCharacter"> The escape character. </param>
<param name="disposeStack"> The DisposeStack</param>
/// <param name="transport"> The Transport Layer</param>
public void Initialize(DisposeStack disposeStack, ITransport transport, ReceiveCommandQueue receiveCommandQueue, char commandSeparator, char fieldSeparator, char escapeCharacter)
{
disposeStack.Push(this);
_transport = transport;
<API key> = receiveCommandQueue;
_transport.NewDataReceived += NewDataReceived;
_commandSeparator = commandSeparator;
_fieldSeparator = fieldSeparator;
_escapeCharacter = escapeCharacter;
_isEscaped = new IsEscaped();
}
#region Fields
<summary> Gets or sets the time stamp of the last received line. </summary>
<value> time stamp of the last received line. </value>
public long LastLineTimeStamp { get; set; }
#endregion
#region Properties
#endregion
#region Event handlers
<summary> transport layer data received. </summary>
private void NewDataReceived(object o, EventArgs e)
{
ParseLines();
}
#endregion
#region Methods
<summary> Connects to a transport layer defined through the current settings. </summary>
<returns> true if it succeeds, false if it fails. </returns>
public bool Connect()
{
return _transport.Connect();
}
<summary> Stops listening to the transport layer </summary>
<returns> true if it succeeds, false if it fails. </returns>
public bool Disconnect()
{
return _transport.Disconnect();
}
<summary> Starts polling. </summary>
public void StartPolling()
{
_transport.StartPolling();
}
<summary> Stop polling. </summary>
public void StopPolling()
{
_transport.StopPolling();
}
<summary> Writes a string to the transport layer. </summary>
<param name="value"> The string to write. </param>
public void WriteLine(string value)
{
byte[] writeBytes = StringEncoder.GetBytes(value + '\n');
_transport.Write(writeBytes);
}
<summary> Writes a parameter to the transport layer followed by a NewLine. </summary>
<typeparam name="T"> Generic type parameter. </typeparam>
<param name="value"> The value. </param>
public void WriteLine<T>(T value)
{
var writeString = value.ToString();
byte[] writeBytes = StringEncoder.GetBytes(writeString + '\n');
_transport.Write(writeBytes);
}
<summary> Writes a parameter to the transport layer. </summary>
<typeparam name="T"> Generic type parameter. </typeparam>
<param name="value"> The value. </param>
public void Write<T>(T value)
{
var writeString = value.ToString();
byte[] writeBytes = StringEncoder.GetBytes(writeString);
_transport.Write(writeBytes);
}
public void <API key>()
{
_transport.Poll();
}
<summary> Reads the transport buffer into the string buffer. </summary>
private void ReadInBuffer()
{
var data = _transport.Read();
_buffer += StringEncoder.GetString(data);
}
private void ParseLines()
{
//if (Monitor.TryEnter(_parseLinesLock)) {
lock(_parseLinesLock) {
LastLineTimeStamp = TimeUtils.Millis;
ReadInBuffer();
var currentLine = ParseLine();
while (!String.IsNullOrEmpty(currentLine))
{
ProcessLine(currentLine);
currentLine = ParseLine();
}
}
}
<summary> Processes the byte message and add to queue. </summary>
public void ProcessLine(string line)
{
// Read line from raw buffer and make command
var <API key> = ParseMessage(line);
<API key>.RawString = line;
// Set time stamp
<API key>.TimeStamp = LastLineTimeStamp;
// And put on queue
<API key>.QueueCommand(<API key>);
}
<summary> Parse message. </summary>
<param name="line"> The received command line. </param>
<returns> The received command. </returns>
private ReceivedCommand ParseMessage(string line)
{
// Trim and clean line
var cleanedLine = line.Trim('\r', '\n');
cleanedLine = Escaping.Remove(cleanedLine, _commandSeparator, _escapeCharacter);
return
new ReceivedCommand(Escaping.Split(cleanedLine, _fieldSeparator, _escapeCharacter,
StringSplitOptions.RemoveEmptyEntries));
}
<summary> Reads a float line from the buffer, if complete. </summary>
<returns> Whether a complete line was present in the buffer. </returns>
private string ParseLine()
{
if (_buffer != "")
{
// Check if an End-Of-Line is present in the string, and split on first
//var i = _buffer.IndexOf(CommandSeparator);
var i = FindNextEol();
if (i >= 0 && i < _buffer.Length)
{
var line = _buffer.Substring(0, i + 1);
if (!String.IsNullOrEmpty(line))
{
_buffer = _buffer.Substring(i + 1);
return line;
}
_buffer = _buffer.Substring(i + 1);
return "";
}
}
return "";
}
<summary> Searches for the next End-Of-Line. </summary>
<returns> The the location in the string of the next End-Of-Line. </returns>
private int FindNextEol()
{
int pos = 0;
while (pos < _buffer.Length)
{
var escaped = _isEscaped.EscapedChar(_buffer[pos]);
if (_buffer[pos] == _commandSeparator && !escaped)
{
return pos;
}
pos++;
}
return pos;
}
// Dispose
<summary> Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. </summary>
<param name="disposing"> true if resources should be disposed, false if not. </param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Stop polling
_transport.NewDataReceived -= NewDataReceived;
}
base.Dispose(disposing);
}
#endregion
}
} |
/**
* TnyMsg:
*
* A special kind of #TnyMimePart that has a header
*
* free-function: g_object_free
**/
#include <config.h>
#ifdef DBC
#include <string.h>
#endif
#include <tny-msg.h>
#include <tny-header.h>
#include <tny-folder.h>
/**
* <API key>:
* @self: a #TnyMsg
*
* API WARNING: This API might change
*
* Uncache the attachments of @self.
*
* since: 1.0
* audience: <API key>
**/
void
<API key> (TnyMsg *self)
{
#ifdef DBC /* require */
g_assert (TNY_IS_MSG (self));
g_assert (TNY_MSG_GET_IFACE (self)->uncache_attachments!= NULL);
#endif
TNY_MSG_GET_IFACE (self)->uncache_attachments(self);
#ifdef DBC /* ensure */
#endif
return;
}
/**
* <API key>:
* @self: a #TnyMsg
*
* API WARNING: This API might change
*
* Rewrite the message to cache, purging mime parts marked for purge.
*
* since: 1.0
* audience: <API key>
**/
void
<API key> (TnyMsg *self)
{
#ifdef DBC /* require */
g_assert (TNY_IS_MSG (self));
g_assert (TNY_MSG_GET_IFACE (self)->rewrite_cache!= NULL);
#endif
TNY_MSG_GET_IFACE (self)->rewrite_cache(self);
#ifdef DBC /* ensure */
#endif
return;
}
/**
* <API key>:
* @self: a #TnyMsg
* @allow: a #gboolean
*
* API WARNING: This API might change
*
* Set if views should fetch external images referenced
* in this message or not.
*
* since: 1.0
* audience: <API key>
**/
void
<API key> (TnyMsg *self, gboolean allow)
{
#ifdef DBC /* require */
g_assert (TNY_IS_MSG (self));
g_assert (TNY_MSG_GET_IFACE (self)-><API key> != NULL);
#endif
TNY_MSG_GET_IFACE (self)-><API key> (self, allow);
#ifdef DBC /* ensure */
#endif
return;
}
/**
* <API key>:
* @self: a #TnyMsg
*
* API WARNING: This API might change
*
* Get if views should fetch external images into message.
*
* Returns: a #gboolean
*
* since: 1.0
* audience: <API key>
**/
gboolean
<API key> (TnyMsg *self)
{
gboolean retval;
#ifdef DBC /* require */
g_assert (TNY_IS_MSG (self));
g_assert (TNY_MSG_GET_IFACE (self)-><API key> != NULL);
#endif
retval = TNY_MSG_GET_IFACE (self)-><API key> (self);
#ifdef DBC /* ensure */
#endif
return retval;
}
/**
* <API key>:
* @self: a #TnyMsg
*
* Get the url string for @self or NULL if it's impossible to determine the url
* string of @self. If not NULL, the returned value must be freed after use.
*
* The url string is specified in RFC 1808 and looks for example like this:
* imap://user@hostname/INBOX/folder/000 where 000 is the UID of the message on
* the IMAP server. Note that it doesn't necessarily contain the password of the
* IMAP account.
*
* returns: (null-ok): The url string or NULL.
* since: 1.0
* audience: <API key>
**/
gchar*
<API key> (TnyMsg *self)
{
gchar *retval;
#ifdef DBC /* require */
g_assert (TNY_IS_MSG (self));
g_assert (TNY_MSG_GET_IFACE (self)->get_url_string!= NULL);
#endif
retval = TNY_MSG_GET_IFACE (self)->get_url_string(self);
#ifdef DBC /* ensure */
if (retval) {
g_assert (strlen (retval) > 0);
/*g_assert (strstr (retval, "://") != NULL);*/
}
#endif
return retval;
}
/**
* tny_msg_get_folder:
* @self: a #TnyMsg
*
* Get the parent folder of @self or NULL if @self is not contained in a folder.
* If not NULL, the returned value must be unreferenced after use.
*
* returns: (null-ok) (caller-owns): The parent folder of this message or NULL
* since: 1.0
* audience: <API key>
**/
TnyFolder*
tny_msg_get_folder (TnyMsg *self)
{
TnyFolder *retval;
#ifdef DBC /* require */
g_assert (TNY_IS_MSG (self));
g_assert (TNY_MSG_GET_IFACE (self)->get_folder!= NULL);
#endif
retval = TNY_MSG_GET_IFACE (self)->get_folder(self);
#ifdef DBC /* ensure */
if (retval)
g_assert (TNY_IS_FOLDER (retval));
#endif
return retval;
}
/**
* tny_msg_get_header:
* @self: a #TnyMsg
*
* Get the header of @self. The returned header object must be unreferenced
* after use. You can't use the returned instance with #TnyFolder operations
* like <API key>() and <API key>()!
*
* If @self is a writable message, you can write to the returned #TnyHeader
* too.
*
* returns: (caller-owns): header of the message
* since: 1.0
* audience: <API key>
**/
TnyHeader*
tny_msg_get_header (TnyMsg *self)
{
TnyHeader *retval;
#ifdef DBC /* require */
g_assert (TNY_IS_MSG (self));
g_assert (TNY_MSG_GET_IFACE (self)->get_header!= NULL);
#endif
retval = TNY_MSG_GET_IFACE (self)->get_header(self);
#ifdef DBC /* ensure */
g_assert (TNY_IS_HEADER (retval));
#endif
return retval;
}
static void
tny_msg_base_init (gpointer g_class)
{
static gboolean initialized = FALSE;
if (!initialized) {
/* create interface signals here. */
initialized = TRUE;
}
}
static gpointer
<API key> (gpointer notused)
{
GType type = 0;
static const GTypeInfo info =
{
sizeof (TnyMsgIface),
tny_msg_base_init, /* base_init */
NULL, /* base_finalize */
NULL, /* class_init */
NULL, /* class_finalize */
NULL, /* class_data */
0,
0, /* n_preallocs */
NULL, /* instance_init */
NULL
};
type = <API key> (G_TYPE_INTERFACE,
"TnyMsg", &info, 0);
<API key> (type, TNY_TYPE_MIME_PART);
<API key> (type, G_TYPE_OBJECT);
return GSIZE_TO_POINTER (type);
}
GType
tny_msg_get_type (void)
{
static GOnce once = G_ONCE_INIT;
g_once (&once, <API key>, NULL);
return GPOINTER_TO_SIZE (once.retval);
} |
#include <cstring>
#include <string>
#include <binfile.h>
#include "adplug.h"
#include "debug.h"
#include "version.h"
#include "hsc.h"
#include "amd.h"
#include "a2m.h"
#include "imf.h"
#include "sng.h"
#include "adtrack.h"
#include "bam.h"
#include "cmf.h"
#include "d00.h"
#include "dfm.h"
#include "hsp.h"
#include "ksm.h"
#include "mad.h"
#include "mid.h"
#include "mkj.h"
#include "cff.h"
#include "dmo.h"
#include "s3m.h"
#include "dtm.h"
#include "fmc.h"
#include "mtk.h"
#include "rad2.h"
#include "raw.h"
#include "sa2.h"
#include "bmf.h"
#include "flash.h"
#include "hybrid.h"
#include "hyp.h"
#include "psi.h"
#include "rat.h"
#include "lds.h"
#include "u6m.h"
#include "rol.h"
#include "xsm.h"
#include "dro.h"
#include "dro2.h"
#include "msc.h"
#include "rix.h"
#include "adl.h"
#include "jbm.h"
#include "got.h"
#include "mus.h"
#include "mdi.h"
#include "cmfmcsop.h"
#include "vgm.h"
#include "sop.h"
#include "herad.h"
// List of all players that come with the standard AdPlug distribution
const CPlayerDesc CAdPlug::allplayers[] = {
CPlayerDesc(ChscPlayer::factory, "HSC-Tracker", ".hsc\0"),
CPlayerDesc(CsngPlayer::factory, "SNGPlay", ".sng\0"),
CPlayerDesc(CimfPlayer::factory, "Apogee IMF", ".imf\0.wlf\0.adlib\0"),
CPlayerDesc(Ca2mLoader::factory, "Adlib Tracker 2", ".a2m\0"),
CPlayerDesc(CadtrackLoader::factory, "Adlib Tracker", ".sng\0"),
CPlayerDesc(CamdLoader::factory, "AMUSIC", ".amd\0"),
CPlayerDesc(CbamPlayer::factory, "Bob's Adlib Music", ".bam\0"),
CPlayerDesc(CcmfPlayer::factory, "Creative Music File", ".cmf\0"),
CPlayerDesc(Cd00Player::factory, "Packed EdLib", ".d00\0"),
CPlayerDesc(CdfmLoader::factory, "Digital-FM", ".dfm\0"),
CPlayerDesc(ChspLoader::factory, "HSC Packed", ".hsp\0"),
CPlayerDesc(CksmPlayer::factory, "Ken Silverman Music", ".ksm\0"),
CPlayerDesc(CmadLoader::factory, "Mlat Adlib Tracker", ".mad\0"),
CPlayerDesc(CmusPlayer::factory, "AdLib MIDI/IMS Format", ".mus\0.ims\0"),
CPlayerDesc(CmdiPlayer::factory, "AdLib MIDIPlay File", ".mdi\0"),
CPlayerDesc(CmidPlayer::factory, "MIDI", ".mid\0.sci\0.laa\0"),
CPlayerDesc(CmkjPlayer::factory, "MKJamz", ".mkj\0"),
CPlayerDesc(CcffLoader::factory, "Boomtracker", ".cff\0"),
CPlayerDesc(CdmoLoader::factory, "TwinTeam", ".dmo\0"),
CPlayerDesc(Cs3mPlayer::factory, "Scream Tracker 3", ".s3m\0"),
CPlayerDesc(CdtmLoader::factory, "DeFy Adlib Tracker", ".dtm\0"),
CPlayerDesc(CfmcLoader::factory, "Faust Music Creator", ".sng\0"),
CPlayerDesc(CmtkLoader::factory, "MPU-401 Trakker", ".mtk\0"),
CPlayerDesc(Crad2Player::factory, "Reality Adlib Tracker", ".rad\0"),
CPlayerDesc(CrawPlayer::factory, "Raw AdLib Capture", ".rac\0.raw\0"),
CPlayerDesc(Csa2Loader::factory, "Surprise! Adlib Tracker", ".sat\0.sa2\0"),
CPlayerDesc(CxadbmfPlayer::factory, "BMF Adlib Tracker", ".xad\0.bmf\0"),
CPlayerDesc(CxadflashPlayer::factory, "Flash", ".xad\0"),
CPlayerDesc(CxadhybridPlayer::factory, "Hybrid", ".xad\0"),
CPlayerDesc(CxadhypPlayer::factory, "Hypnosis", ".xad\0"),
CPlayerDesc(CxadpsiPlayer::factory, "PSI", ".xad\0"),
CPlayerDesc(CxadratPlayer::factory, "rat", ".xad\0"),
CPlayerDesc(CldsPlayer::factory, "LOUDNESS Sound System", ".lds\0"),
CPlayerDesc(Cu6mPlayer::factory, "Ultima 6 Music", ".m\0"),
CPlayerDesc(CrolPlayer::factory, "Adlib Visual Composer", ".rol\0"),
CPlayerDesc(CxsmPlayer::factory, "eXtra Simple Music", ".xsm\0"),
CPlayerDesc(CdroPlayer::factory, "DOSBox Raw OPL v0.1", ".dro\0"),
CPlayerDesc(Cdro2Player::factory, "DOSBox Raw OPL v2.0", ".dro\0"),
CPlayerDesc(CmscPlayer::factory, "Adlib MSC Player", ".msc\0"),
CPlayerDesc(CrixPlayer::factory, "Softstar RIX OPL Music", ".rix\0"),
CPlayerDesc(CadlPlayer::factory, "Westwood ADL", ".adl\0"),
CPlayerDesc(CjbmPlayer::factory, "JBM Adlib Music", ".jbm\0"),
CPlayerDesc(CgotPlayer::factory, "God of Thunder Music", ".got\0"),
CPlayerDesc(CcmfmacsoperaPlayer::factory, "SoundFX Macs Opera CMF", ".cmf\0"),
CPlayerDesc(CvgmPlayer::factory, "Video Game Music", ".vgm\0.vgz\0"),
CPlayerDesc(CsopPlayer::factory, "Note Sequencer by sopepos", ".sop\0"),
CPlayerDesc(CheradPlayer::factory, "Herbulot AdLib System", ".hsq\0.sqx\0.sdb\0.agd\0.ha2\0"),
CPlayerDesc()
};
const CPlayers &CAdPlug::init_players(const CPlayerDesc pd[])
{
static CPlayers initplayers;
unsigned int i;
for(i = 0; pd[i].factory; i++)
initplayers.push_back(&pd[i]);
return initplayers;
}
const CPlayers CAdPlug::players = CAdPlug::init_players(CAdPlug::allplayers);
CAdPlugDatabase *CAdPlug::database = 0;
CPlayer *CAdPlug::factory(const std::string &fn, Copl *opl, const CPlayers &pl,
const CFileProvider &fp)
{
CPlayer *p;
CPlayers::const_iterator i;
unsigned int j;
AdPlug_LogWrite("*** CAdPlug::factory(\"%s\",opl,fp) ***\n", fn.c_str());
// Try a direct hit by file extension
for(i = pl.begin(); i != pl.end(); i++)
for(j = 0; (*i)->get_extension(j); j++)
if(fp.extension(fn, (*i)->get_extension(j))) {
AdPlug_LogWrite("Trying direct hit: %s\n", (*i)->filetype.c_str());
if((p = (*i)->factory(opl))) {
if(p->load(fn, fp)) {
AdPlug_LogWrite("got it!\n");
AdPlug_LogWrite("
return p;
} else
delete p;
}
}
// Try all players, one by one
for(i = pl.begin(); i != pl.end(); i++) {
AdPlug_LogWrite("Trying: %s\n", (*i)->filetype.c_str());
if((p = (*i)->factory(opl))) {
if(p->load(fn, fp)) {
AdPlug_LogWrite("got it!\n");
AdPlug_LogWrite("
return p;
} else
delete p;
}
}
// Unknown file
AdPlug_LogWrite("End of list!\n");
AdPlug_LogWrite("
return 0;
}
void CAdPlug::set_database(CAdPlugDatabase *db)
{
database = db;
}
std::string CAdPlug::get_version()
{
return std::string(ADPLUG_VERSION);
}
void CAdPlug::debug_output(const std::string &filename)
{
AdPlug_LogFile(filename.c_str());
AdPlug_LogWrite("CAdPlug::debug_output(\"%s\"): Redirected.\n",filename.c_str());
} |
// FMNServer.h
// FMN
#import <Cocoa/Cocoa.h>
@protocol FMNServer
- (BOOL) activateFMN;
- (BOOL) deactivateFMN;
- (BOOL) isActiveFMN;
- (oneway void) quitFMN;
@end |
#include "yasscriptmanager.h"
#include "core/vfs/filesystem.h"
#include "yasscriptobject.h"
#include "<API key>.h"
YasScriptManager::YasScriptManager():
ScriptManager(),
mVirtualContext(),
mVirtualMachine(mVirtualContext)
{
FileSystem::getInstance().addPath(UTEXT("data.zip\\scripts"));
mVirtualMachine.initialize();
}
// - Get/set
VirtualMachine& YasScriptManager::getVM()
{
return mVirtualMachine;
}
// - Overrides
c2d::ScriptRegistrator* YasScriptManager::getRegistrator()
{
return new <API key>(*this);
}
c2d::ScriptObject* YasScriptManager::load(const String& classname)
{
VirtualObject* pobject = mVirtualMachine.instantiate(classname);
YasScriptObject* pscript = new YasScriptObject(*this);
pscript->setThis(*pobject);
return pscript;
}
c2d::ScriptObject* YasScriptManager::load(const String& classname, void* pobject, bool owned)
{
VirtualObject& object = mVirtualMachine.instantiateNative(classname, pobject, owned);
YasScriptObject* pscript = new YasScriptObject(*this);
pscript->setThis(object);
return pscript;
}
void YasScriptManager::addRootObject(c2d::ScriptObject& object)
{
YasScriptObject& yasobject = static_cast<YasScriptObject&>(object);
mVirtualMachine.addRootObject(yasobject.getThis());
}
// - Operations
void YasScriptManager::registerObject(VirtualObject& object)
{
mVirtualMachine.registerNative(object);
}
// - Execution
Variant YasScriptManager::execute(VirtualObject& object, const String& function, int argc, VirtualValue* pargv)
{
VirtualValue result = mVirtualMachine.execute(object, function, argc, pargv);
return toVariant(result);
}
// - Conversion
Variant YasScriptManager::toVariant(const VirtualValue& value)
{
if ( value.isBoolean() )
{
return Variant(value.asBoolean());
}
else if ( value.isNumber() )
{
return Variant(value.asNumber());
}
else if ( value.isReal() )
{
return Variant(value.asReal());
}
else if ( value.isChar() )
{
return Variant(value.asChar());
}
else if ( value.isString() )
{
return Variant(value.asString());
}
return Variant();
}
VirtualValue YasScriptManager::toValue(const Variant& value)
{
if ( value.isInt() )
{
return VirtualValue(value.asInt());
}
else if ( value.isReal() )
{
return VirtualValue(value.asReal());
}
else if ( value.isBool() )
{
return VirtualValue(value.asBool());
}
else if ( value.isChar() )
{
return VirtualValue(value.asChar());
}
else if ( value.isString() )
{
return VirtualValue(mVirtualContext.mStringCache.lookup(value.asString()));
}
return VirtualValue();
} |
#ifndef COMMONDEFS_H
#define COMMONDEFS_H
#include <QString>
// Define string constants for different XML elements.
namespace Buteo {
const QString ATTR_NAME("name");
const QString ATTR_TYPE("type");
const QString ATTR_VALUE("value");
const QString ATTR_DEFAULT("default");
const QString ATTR_LABEL("label");
const QString ATTR_VISIBLE("visible");
const QString ATTR_READONLY("readonly");
const QString ATTR_ADDED("added");
const QString ATTR_DELETED("deleted");
const QString ATTR_MODIFIED("modified");
const QString ATTR_TIME("time");
const QString ATTR_INTERVAL("interval");
const QString ATTR_BEGIN("begin");
const QString ATTR_END("end");
const QString ATTR_DAYS("days");
const QString ATTR_MAJOR_CODE("majorcode");
const QString ATTR_MINOR_CODE("minorcode");
const QString ATTR_ENABLED("enabled");
const QString ATTR_SYNC_CONFIGURE("syncconfiguredtime");
const QString TAG_FIELD("field");
const QString TAG_PROFILE("profile");
const QString TAG_KEY("key");
const QString TAG_OPTION("option");
const QString TAG_TARGET_RESULTS("target");
const QString TAG_SYNC_RESULTS("syncresults");
const QString TAG_SYNC_LOG("synclog");
const QString TAG_LOCAL("local");
const QString TAG_REMOTE("remote");
const QString TAG_SCHEDULE("schedule");
const QString TAG_RUSH("rush");
const QString TAG_ERROR_ATTEMPTS("attempts");
const QString TAG_ATTEMPT_DELAY("attemptdelay");
const QString KEY_ENABLED("enabled");
const QString KEY_DISPLAY_NAME("displayname");
const QString KEY_ACTIVE("active");
const QString KEY_USE_ACCOUNTS("use_accounts");
const QString KEY_SYNC_SCHEDULED("scheduled");
const QString KEY_PLUGIN("plugin");
const QString KEY_BACKEND("backend");
const QString KEY_ACCOUNT_ID("accountid");
const QString KEY_USERNAME("Username");
const QString KEY_PASSWORD("Password");
const QString KEY_HIDDEN("hidden");
const QString KEY_PROTECTED("protected");
const QString <API key>("destinationtype");
const QString KEY_SYNC_DIRECTION("Sync Direction");
const QString KEY_FORCE_SLOW_SYNC("force_slow_sync");
const QString <API key>("conflictpolicy");
const QString KEY_BT_ADDRESS("bt_address");
const QString KEY_REMOTE_ID("remote_id");
const QString KEY_REMOTE_DATABASE("Remote database");
const QString KEY_BT_NAME("bt_name");
const QString KEY_BT_TRANSPORT("bt_transport");
const QString KEY_USB_TRANSPORT("usb_transport");
const QString <API key>("internet_transport");
const QString <API key>("<API key>");
const QString KEY_CAPS_MODIFIED("caps_modified");
const QString <API key>("<API key>"); // sync from this many days before the current date
const QString <API key>("<API key>");
const QString KEY_SOC("sync_on_change");
const QString KEY_SOC_AFTER("<API key>");
const QString KEY_LOCAL_URI("Local URI");
const QString <API key>("always_on_enabled");
const QString KEY_REMOTE_NAME("remote_name");
const QString KEY_UUID("uuid");
const QString KEY_NOTES_UUID("notes_uuid");
const QString KEY_STORAGE_UPDATED("storage_updated");
const QString KEY_HTTP_PROXY_HOST("http_proxy_host");
const QString KEY_HTTP_PROXY_PORT("http_proxy_port");
const QString KEY_PROFILE_ID("profile_id");
const QString BOOLEAN_TRUE("true");
const QString BOOLEAN_FALSE("false");
const QString VALUE_ONLINE("online");
const QString VALUE_DEVICE("device");
const QString VALUE_TWO_WAY("two-way");
const QString VALUE_FROM_REMOTE("from-remote");
const QString VALUE_TO_REMOTE("to-remote");
const QString VALUE_PREFER_REMOTE("prefer remote");
const QString VALUE_PREFER_LOCAL("prefer local");
// Indent size for profile XML output.
const int PROFILE_INDENT = 4;
const QString PC_SYNC("PC-SYNC");
//For account online_template
const QString <API key>("online_template");
}
#endif // COMMONDEFS_H |
package cc.arduino.utils.network;
import cc.arduino.net.CustomProxySelector;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.compress.utils.IOUtils;
import processing.app.PreferencesData;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.<API key>;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Observable;
public class FileDownloader extends Observable {
public enum Status {
CONNECTING,
<API key>,
DOWNLOADING,
COMPLETE,
CANCELLED,
ERROR,
}
private Status status;
private long initialSize;
private Long downloadSize = null;
private long downloaded;
private final URL downloadUrl;
private final File outputFile;
private InputStream stream = null;
private Exception error;
public FileDownloader(URL url, File file) {
downloadUrl = url;
outputFile = file;
downloaded = 0;
initialSize = 0;
}
public long getInitialSize() {
return initialSize;
}
public Long getDownloadSize() {
return downloadSize;
}
public void setDownloadSize(Long downloadSize) {
this.downloadSize = downloadSize;
setChanged();
notifyObservers();
}
public long getDownloaded() {
return downloaded;
}
private void setDownloaded(long downloaded) {
this.downloaded = downloaded;
setChanged();
notifyObservers();
}
public float getProgress() {
if (downloadSize == null)
return 0;
if (downloadSize == 0)
return 100;
return ((float) downloaded / downloadSize) * 100;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
setChanged();
notifyObservers();
}
public void download() throws <API key> {
if ("file".equals(downloadUrl.getProtocol())) {
saveLocalFile();
} else {
downloadFile();
}
}
private void saveLocalFile() {
try {
Files.write(outputFile.toPath(), Files.readAllBytes(Paths.get(downloadUrl.getPath())));
setStatus(Status.COMPLETE);
} catch (Exception e) {
setStatus(Status.ERROR);
setError(e);
}
}
private void downloadFile() throws <API key> {
RandomAccessFile file = null;
try {
// Open file and seek to the end of it
file = new RandomAccessFile(outputFile, "rw");
initialSize = file.length();
file.seek(initialSize);
setStatus(Status.CONNECTING);
Proxy proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(downloadUrl.toURI());
if ("true".equals(System.getProperty("DEBUG"))) {
System.err.println("Using proxy " + proxy);
}
HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(proxy);
if (downloadUrl.getUserInfo() != null) {
String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes()));
connection.setRequestProperty("Authorization", auth);
}
connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
connection.setConnectTimeout(5000);
setDownloaded(0);
// Connect
connection.connect();
int resp = connection.getResponseCode();
if (resp == HttpURLConnection.HTTP_MOVED_PERM || resp == HttpURLConnection.HTTP_MOVED_TEMP) {
URL newUrl = new URL(connection.getHeaderField("Location"));
proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(newUrl.toURI());
// open the new connnection again
connection = (HttpURLConnection) newUrl.openConnection(proxy);
if (downloadUrl.getUserInfo() != null) {
String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes()));
connection.setRequestProperty("Authorization", auth);
}
connection.setRequestProperty("Range", "bytes=" + initialSize + "-");
connection.setConnectTimeout(5000);
connection.connect();
resp = connection.getResponseCode();
}
if (resp < 200 || resp >= 300) {
throw new IOException("Received invalid http status code from server: " + resp);
}
// Check for valid content length.
long len = connection.getContentLength();
if (len >= 0) {
setDownloadSize(len);
}
setStatus(Status.DOWNLOADING);
synchronized (this) {
stream = connection.getInputStream();
}
byte buffer[] = new byte[10240];
while (status == Status.DOWNLOADING) {
int read = stream.read(buffer);
if (read == -1)
break;
file.write(buffer, 0, read);
setDownloaded(getDownloaded() + read);
if (Thread.interrupted()) {
file.close();
throw new <API key>();
}
}
if (getDownloadSize() != null) {
if (getDownloaded() < getDownloadSize())
throw new Exception("Incomplete download");
}
setStatus(Status.COMPLETE);
} catch (<API key> e) {
setStatus(Status.CANCELLED);
// lets <API key> go up to the caller
throw e;
} catch (<API key> e) {
setStatus(Status.<API key>);
setError(e);
} catch (Exception e) {
setStatus(Status.ERROR);
setError(e);
} finally {
IOUtils.closeQuietly(file);
synchronized (this) {
IOUtils.closeQuietly(stream);
}
}
}
private void setError(Exception e) {
error = e;
}
public Exception getError() {
return error;
}
public boolean isCompleted() {
return status == Status.COMPLETE;
}
} |
# Project: MXCuBE
# This file is part of MXCuBE software.
# MXCuBE is free software: you can redistribute it and/or modify
# (at your option) any later version.
# MXCuBE is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import logging
from gui.utils import QtImport
from gui.BaseComponents import BaseWidget
from gui.widgets.task_toolbox_widget import TaskToolBoxWidget
from HardwareRepository import HardwareRepository as HWR
__credits__ = ["MXCuBE collaboration"]
__license__ = "LGPLv3+"
__category__ = "General"
class TaskToolBoxBrick(BaseWidget):
request_tree_brick = QtImport.pyqtSignal()
def __init__(self, *args):
BaseWidget.__init__(self, *args)
self.ispyb_logged_in = False
self.tree_brick = None
self.add_property("useOscStartCbox", "boolean", False)
self.add_property("useCompression", "boolean", False)
#self.add_property("availableTasks", "string", "discrete char helical")
self.add_property("showDiscreetTask", "boolean", True)
self.add_property("showHelicalTask", "boolean", True)
self.add_property("showCharTask", "boolean", True)
self.add_property("showAdvancedTask", "boolean", True)
self.add_property("showStillScanTask", "boolean", False)
self.add_property("<API key>", "boolean", False)
self.define_signal("request_tree_brick", ())
self.define_slot("logged_in", ())
self.define_slot("set_session", ())
self.define_slot("selection_changed", ())
self.define_slot("user_group_saved", ())
self.define_slot("set_tree_brick", ())
self.<API key> = TaskToolBoxWidget(self)
self.main_layout = QtImport.QVBoxLayout(self)
self.main_layout.addWidget(self.<API key>)
self.main_layout.setSpacing(0)
self.main_layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.main_layout)
# self.setSizePolicy(QtImport.QSizePolicy.MinimumExpanding,
# QtImport.QSizePolicy.MinimumExpanding)
HWR.beamline.sample_view.connect("pointSelected", self.point_selected)
def set_expert_mode(self, expert):
self.<API key>.set_expert_mode(expert)
def run(self):
if HWR.beamline.session.session_id:
self.setEnabled(True)
#self.<API key>.set_available_tasks(self["availableTasks"])
self.request_tree_brick.emit()
self.<API key>.adjust_width(self.width())
def user_group_saved(self, new_user_group):
HWR.beamline.session.set_user_group(str(new_user_group))
self.<API key>.<API key>()
path = (
HWR.beamline.session.<API key>()
+ "/"
+ str(new_user_group)
)
msg = "Image path is: %s" % path
logging.getLogger("GUI").info(msg)
@QtImport.pyqtSlot(BaseWidget)
def set_tree_brick(self, brick):
self.tree_brick = brick
self.tree_brick.compression_state = self["useCompression"] == 1
self.<API key>.set_tree_brick(brick)
@QtImport.pyqtSlot(int, str, str, int, str, str, bool)
def set_session(
self,
session_id,
t_prop_code=None,
prop_number=None,
prop_id=None,
start_date=None,
prop_code=None,
is_inhouse=None,
):
"""
Connected to the slot set_session and is called after a
request to get the current session from LIMS (ISPyB) is
made. The signal is normally emitted by the brick that
handles LIMS login, ie ProposalBrick.
The session_id is '' if no session could be retrieved.
"""
if session_id is "":
self.logged_in(True)
@QtImport.pyqtSlot(bool)
def logged_in(self, logged_in):
"""
Handels the signal logged_in from the brick the handles
LIMS (ISPyB) login, ie ProposalBrick. The signal is
emitted when a user was succesfully logged in.
"""
logged_in = True
self.ispyb_logged_in = logged_in
if HWR.beamline.session is not None:
HWR.beamline.session.set_user_group("")
self.setEnabled(logged_in)
self.<API key>.ispyb_logged_in(logged_in)
def property_changed(self, property_name, old_value, new_value):
if property_name == "useOscStartCbox":
self.<API key>.use_osc_start_cbox(new_value)
elif property_name == "useCompression":
self.<API key>.enable_compression(new_value)
elif property_name == "<API key>":
self.<API key>.collect_now_button.setVisible(new_value)
elif property_name == "showDiscreetTask":
if not new_value:
self.<API key>.hide_task(
self.<API key>.discrete_page
)
elif property_name == "showHelicalTask":
if not new_value:
self.<API key>.hide_task(
self.<API key>.helical_page
)
elif property_name == "showCharTask":
if not new_value:
self.<API key>.hide_task(self.<API key>.char_page)
elif property_name == "showAdvancedTask":
if not new_value:
self.<API key>.hide_task(
self.<API key>.advanced_page
)
elif property_name == "showStillScanTask":
if not new_value:
self.<API key>.hide_task(
self.<API key>.still_scan_page
)
def selection_changed(self, items):
"""
Connected to the signal "selection_changed" of the TreeBrick.
Called when the selection in the tree changes.
"""
self.<API key>.selection_changed(items)
def point_selected(self, selected_position):
self.<API key>.helical_page.<API key>(
selected_position
)
self.<API key>.discrete_page.<API key>(
selected_position
)
self.<API key>.char_page.<API key>(
selected_position
)
self.<API key>.energy_scan_page.<API key>(
selected_position
)
self.<API key>.xrf_spectrum_page.<API key>(
selected_position
)
self.<API key>.discrete_page.<API key>()
self.<API key>.helical_page.<API key>()
self.<API key>.char_page.<API key>()
self.<API key>.energy_scan_page.<API key>()
self.<API key>.xrf_spectrum_page.<API key>() |
package org.sonar.css.model.property.standard;
import org.sonar.css.model.property.StandardProperty;
public class GridRows extends StandardProperty {
public GridRows() {
addLinks("http://www.w3.org/TR/2011/<API key>/#grid-rows-property");
setObsolete(true);
}
} |
#ifndef <API key>
#define <API key>
#include "appsyncresponse.h"
#include "<API key>.h"
namespace QtAws {
namespace AppSync {
class <API key>;
class QTAWSAPPSYNC_EXPORT <API key> : public AppSyncResponse {
Q_OBJECT
public:
<API key>(const <API key> &request, QNetworkReply * const reply, QObject * const parent = 0);
virtual const <API key> * request() const Q_DECL_OVERRIDE;
protected slots:
virtual void parseSuccess(QIODevice &response) Q_DECL_OVERRIDE;
private:
Q_DECLARE_PRIVATE(<API key>)
Q_DISABLE_COPY(<API key>)
};
} // namespace AppSync
} // namespace QtAws
#endif |
package net.redstonelamp.item;
import net.redstonelamp.block.*;
import org.spout.nbt.CompoundTag;
import java.lang.reflect.Constructor;
import java.lang.reflect.<API key>;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Represents an Item.
*
* @author RedstoneLamp Team
*/
public class Item implements Items {
private static final Map<Integer, Class<? extends Item>> items = new HashMap<>();
private static final List<Item> creativeItems = new ArrayList<>();
private final int id;
private final short meta;
private final int count;
private CompoundTag compoundTag;
public Item(int id, short meta, int count){
this.id = id;
this.meta = meta;
this.count = count;
}
public static void init(){
creativeItems.clear();
items.clear();
initItems();
initCreativeItems();
}
private static void initItems() {
items.put(BED_BLOCK, BedBlock.class);
items.put(BEDROCK, Bedrock.class);
items.put(BOOKSHELF, Bookshelf.class);
items.put(BRICKS, Bricks.class);
items.put(BROWN_MUSHROOM, BrownMushroom.class);
items.put(CLAY_BLOCK, ClayBlock.class);
items.put(COAL_ORE, CoalOre.class);
items.put(COBBLESTONE, Cobblestone.class);
items.put(COBWEB, Cobweb.class);
items.put(DANDELION, Dandelion.class);
items.put(DEAD_BUSH, DeadBush.class);
items.put(DIAMOND_BLOCK, DiamondBlock.class);
items.put(DIAMOND_ORE, DiamondOre.class);
items.put(DIRT, Dirt.class);
items.put(FIRE, Fire.class);
items.put(GLASS, Glass.class);
items.put(<API key>, GlowingRedstoneOre.class);
items.put(GOLD_BLOCK, GoldBlock.class);
items.put(GOLD_ORE, GoldOre.class);
items.put(GRASS, Grass.class);
items.put(GRAVEL, Gravel.class);
items.put(ICE, Ice.class);
items.put(IRON_BLOCK, IronBlock.class);
items.put(IRON_ORE, IronOre.class);
items.put(LAPIS_BLOCK, LapisBlock.class);
items.put(LAPIS_ORE, LapisOre.class);
items.put(LAVA, Lava.class);
items.put(LEAVES, Leaves.class);
items.put(LOG, Log.class);
items.put(MOSSY_STONE, MossyStone.class);
items.put(MYCELIUM, Mycelium.class);
items.put(OBSIDIAN, Obsidian.class);
items.put(QUARTZ_BLOCK, Quartz.class);
items.put(RED_MUSHROOM, RedMushroom.class);
items.put(REDSTONE_ORE, RedstoneOre.class);
items.put(ROSE, Rose.class);
items.put(SAND, Sand.class);
items.put(SANDSTONE, Sandstone.class);
items.put(SAPLING, Sapling.class);
items.put(SNOW_BLOCK, SnowBlock.class);
items.put(MONSTER_SPAWNER, Spawner.class);
items.put(SPONGE, Sponge.class);
items.put(STILL_LAVA, StillLava.class);
items.put(STILL_WATER, StillWater.class);
items.put(STONE, Stone.class);
items.put(STONE_BRICKS, StoneBricks.class);
items.put(TALL_GRASS, TallGrass.class);
items.put(TNT, TNT.class);
items.put(TORCH, Torch.class);
items.put(WATER, Water.class);
items.put(WOODEN_PLANKS, WoodPlanks.class);
items.put(WOOL, Wool.class);
}
private static void initCreativeItems() {
addCreativeItem(get(BED_BLOCK, (short) 0));
addCreativeItem(get(BEDROCK, (short) 0));
addCreativeItem(get(BOOKSHELF, (short) 0));
addCreativeItem(get(BRICKS, (short) 0));
addCreativeItem(get(BROWN_MUSHROOM, (short) 0));
addCreativeItem(get(CLAY_BLOCK, (short) 0));
addCreativeItem(get(COAL_ORE, (short) 0));
addCreativeItem(get(COBBLESTONE, (short) 0));
addCreativeItem(get(COBWEB, (short) 0));
addCreativeItem(get(DANDELION, (short) 0));
addCreativeItem(get(DEAD_BUSH, (short) 0));
addCreativeItem(get(DIAMOND_BLOCK, (short) 0));
addCreativeItem(get(DIAMOND_ORE, (short) 0));
addCreativeItem(get(DIRT, (short) 0));
//addCreativeItem(get(FIRE, (short) 0));
addCreativeItem(get(GLASS, (short) 0));
addCreativeItem(get(<API key>, (short) 0));
addCreativeItem(get(GOLD_BLOCK, (short) 0));
addCreativeItem(get(GOLD_ORE, (short) 0));
addCreativeItem(get(GRASS, (short) 0));
addCreativeItem(get(GRAVEL, (short) 0));
addCreativeItem(get(ICE, (short) 0));
addCreativeItem(get(IRON_BLOCK, (short) 0));
addCreativeItem(get(IRON_ORE, (short) 0));
addCreativeItem(get(LAPIS_BLOCK, (short) 0));
addCreativeItem(get(LAPIS_ORE, (short) 0));
//addCreativeItem(get(LAVA, (short) 0));
addCreativeItem(get(LEAVES, (short) 0));
addCreativeItem(get(LOG, (short) 0));
addCreativeItem(get(MOSSY_STONE, (short) 0));
addCreativeItem(get(MYCELIUM, (short) 0));
addCreativeItem(get(OBSIDIAN, (short) 0));
addCreativeItem(get(QUARTZ_BLOCK, (short) 0));
addCreativeItem(get(RED_MUSHROOM, (short) 0));
addCreativeItem(get(REDSTONE_ORE, (short) 0));
addCreativeItem(get(ROSE, (short) 0));
addCreativeItem(get(SAND, (short) 0));
addCreativeItem(get(SANDSTONE, (short) 0));
addCreativeItem(get(SAPLING, (short) 0));
addCreativeItem(get(SNOW_BLOCK, (short) 0));
addCreativeItem(get(MONSTER_SPAWNER, (short) 0));
addCreativeItem(get(SPONGE, (short) 0));
//addCreativeItem(get(STILL_LAVA, (short) 0));
//addCreativeItem(get(STILL_WATER, (short) 0));
addCreativeItem(get(STONE, (short) 0));
addCreativeItem(get(STONE_BRICKS, (short) 0));
addCreativeItem(get(TALL_GRASS, (short) 0));
addCreativeItem(get(TNT, (short) 0));
addCreativeItem(get(TORCH, (short) 0));
//addCreativeItem(get(WATER, (short) 0));
addCreativeItem(get(WOODEN_PLANKS, (short) WoodPlanks.PlankType.OAK.getMetaId()));
addCreativeItem(get(WOODEN_PLANKS, (short) WoodPlanks.PlankType.SPRUCE.getMetaId()));
addCreativeItem(get(WOODEN_PLANKS, (short) WoodPlanks.PlankType.ACACIA.getMetaId()));
addCreativeItem(get(WOODEN_PLANKS, (short) WoodPlanks.PlankType.JUNGLE.getMetaId()));
addCreativeItem(get(WOODEN_PLANKS, (short) WoodPlanks.PlankType.BIRCH.getMetaId()));
addCreativeItem(get(WOODEN_PLANKS, (short) WoodPlanks.PlankType.DARK_OAK.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.WHITE.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.ORANGE.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.MAGENTA.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.LIGHT_BLUE.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.YELLOW.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.LIME.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.PINK.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.GRAY.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.LIGHT_GRAY.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.CYAN.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.PURPLE.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.BLUE.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.BROWN.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.GREEN.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.RED.getMetaId()));
addCreativeItem(get(WOOL, (short) Wool.Color.BLACK.getMetaId()));
}
public static synchronized void addCreativeItem(Item item) {
creativeItems.add(get(item.getId(), item.getMeta()));
}
public static Item get(int id) {
return get(id, (short) 0, 1);
}
public static Item get(int id, short meta) {
return get(id, meta, 1);
}
public static Item get(int id, short meta, int count) {
if(items.containsKey(id)) {
try {
Constructor c = items.get(id).getConstructor(int.class, short.class, int.class);
return (Item) c.newInstance(id, meta, count);
} catch (<API key> | <API key> | <API key> | <API key> e) {
e.printStackTrace();
return null;
}
} else if(id < 256) {
return new Block(id, meta, count);
} else {
return new Item(id, meta, count);
}
}
public static List<Item> getCreativeItems() {
return creativeItems;
}
public int getId(){
return id;
}
public short getMeta(){
return meta;
}
public int getCount(){
return count;
}
public CompoundTag getCompoundTag() {
return compoundTag;
}
public void setCompoundTag(CompoundTag compoundTag) {
this.compoundTag = compoundTag;
}
} |
package org.sonar.server.charts.deprecated;
import org.jfree.chart.renderer.category.BarRenderer;
import java.awt.*;
public class CustomBarRenderer extends BarRenderer {
public static final Paint[] COLORS = {
Color.red, Color.blue, Color.green,
Color.yellow, Color.orange, Color.cyan,
Color.magenta, Color.blue};
/**
* The colors.
*/
private Paint[] colors;
/**
* Creates a new renderer.
*
* @param colors the colors.
*/
public CustomBarRenderer(final Paint[] colors) {
this.colors = colors;
}
/**
* Returns the paint for an item. Overrides the default behaviour inherited from
* <API key>.
*
* @param row the series.
* @param column the category.
* @return The item color.
*/
@Override
public Paint getItemPaint(final int row, final int column) {
return this.colors[column % this.colors.length];
}
public Paint[] getColors() {
return colors;
}
public void setColors(Paint[] colors) {
this.colors = colors;
}
} |
# Makefile.in generated by automake 1.11.3 from Makefile.am.
# include/nfc/Makefile. Generated from Makefile.in by configure.
# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software
# Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# PARTICULAR PURPOSE.
pkgdatadir = $(datadir)/libnfc
pkgincludedir = $(includedir)/libnfc
pkglibdir = $(libdir)/libnfc
pkglibexecdir = $(libexecdir)/libnfc
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(<API key>)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = <API key>
host_triplet = <API key>
subdir = include/nfc
DIST_COMMON = $(nfcinclude_HEADERS) $(srcdir)/Makefile.am \
$(srcdir)/Makefile.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/libnfc_check_libusb.m4 \
$(top_srcdir)/m4/libnfc_check_pcsc.m4 \
$(top_srcdir)/m4/libnfc_drivers.m4 $(top_srcdir)/m4/libtool.m4 \
$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
$(top_srcdir)/m4/readline.m4 $(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(<API key>) \
$(ACLOCAL_M4)
mkinstalldirs = $(install_sh) -d
CONFIG_HEADER = $(top_builddir)/config.h
CONFIG_CLEAN_FILES =
<API key> =
AM_V_GEN = $(am__v_GEN_$(V))
am__v_GEN_ = $(am__v_GEN_$(<API key>))
am__v_GEN_0 = @echo " GEN " $@;
AM_V_at = $(am__v_at_$(V))
am__v_at_ = $(am__v_at_$(<API key>))
am__v_at_0 = @
SOURCES =
DIST_SOURCES =
am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
am__vpath_adj = case $$p in \
$(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
*) f=$$p;; \
esac;
am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
am__install_max = 40
<API key> = \
srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
am__nobase_strip = \
for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
am__nobase_list = $(<API key>); \
for p in $$list; do echo "$$p $$p"; done | \
sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
$(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
if (++n[$$2] == $(am__install_max)) \
{ print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
END { for (dir in files) print dir, files[dir] }'
am__base_list = \
sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
<API key> = { \
test -z "$$files" \
|| { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
|| { echo " ( cd '$$dir' && rm -f" $$files ")"; \
$(am__cd) "$$dir" && rm -f $$files; }; \
}
am__installdirs = "$(DESTDIR)$(nfcincludedir)"
HEADERS = $(nfcinclude_HEADERS)
ETAGS = etags
CTAGS = ctags
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = ${SHELL} /home/mark/Desktop/MaxusTech/MaxusNFC/lib/libnfc-1.7.1/missing --run aclocal-1.11
AMTAR = $${TAR-tar}
<API key> = 0
AR = ar
AUTOCONF = ${SHELL} /home/mark/Desktop/MaxusTech/MaxusNFC/lib/libnfc-1.7.1/missing --run autoconf
AUTOHEADER = ${SHELL} /home/mark/Desktop/MaxusTech/MaxusNFC/lib/libnfc-1.7.1/missing --run autoheader
AUTOMAKE = ${SHELL} /home/mark/Desktop/MaxusTech/MaxusNFC/lib/libnfc-1.7.1/missing --run automake-1.11
AWK = mawk
CC = gcc
CCDEPMODE = depmode=gcc3
CFLAGS = -g -O2 -Wall -pedantic -Wextra -std=c99 -Du_int8_t=uint8_t -Du_int16_t=uint16_t
CPP = gcc -E
CPPFLAGS =
CUTTER =
CUTTER_CFLAGS =
CUTTER_LIBS =
CYGPATH_W = echo
DEFS = -DHAVE_CONFIG_H
DEPDIR = .deps
DLLTOOL = false
DOXYGEN =
DRIVERS_CFLAGS = -<API key>
DSYMUTIL =
DUMPBIN =
ECHO_C =
ECHO_N = -n
ECHO_T =
EGREP = /bin/grep -E
EXEEXT =
FGREP = /bin/grep -F
GREP = /bin/grep
INSTALL = /usr/bin/install -c
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
<API key> = $(install_sh) -c -s
LD = /usr/bin/ld -m elf_x86_64
LDFLAGS =
LIBNFC_CFLAGS = -I$(top_srcdir)/libnfc -I$(top_builddir)/include -I$(top_srcdir)/include
LIBOBJS =
LIBS =
LIBTOOL = $(SHELL) $(top_builddir)/libtool
LIPO =
LN_S = ln -s
LTLIBOBJS =
MAKEINFO = ${SHELL} /home/mark/Desktop/MaxusTech/MaxusNFC/lib/libnfc-1.7.1/missing --run makeinfo
MANIFEST_TOOL = :
MKDIR_P = /bin/mkdir -p
NM = /usr/bin/nm -B
NMEDIT =
OBJDUMP = objdump
OBJEXT = o
OTOOL =
OTOOL64 =
PACKAGE = libnfc
PACKAGE_BUGREPORT = nfc-tools@googlegroups.com
PACKAGE_NAME = libnfc
PACKAGE_STRING = libnfc 1.7.1
PACKAGE_TARNAME = libnfc
PACKAGE_URL =
PACKAGE_VERSION = 1.7.1
PATH_SEPARATOR = :
PKG_CONFIG = /usr/bin/pkg-config
PKG_CONFIG_LIBDIR =
PKG_CONFIG_PATH =
PKG_CONFIG_REQUIRES =
RANLIB = ranlib
READLINE_INCLUDES =
READLINE_LIBS =
SED = /bin/sed
SET_MAKE =
SHELL = /bin/bash
STRIP = strip
VERSION = 1.7.1
abs_builddir = /home/mark/Desktop/MaxusTech/MaxusNFC/lib/libnfc-1.7.1/include/nfc
abs_srcdir = /home/mark/Desktop/MaxusTech/MaxusNFC/lib/libnfc-1.7.1/include/nfc
abs_top_builddir = /home/mark/Desktop/MaxusTech/MaxusNFC/lib/libnfc-1.7.1
abs_top_srcdir = /home/mark/Desktop/MaxusTech/MaxusNFC/lib/libnfc-1.7.1
ac_ct_AR = ar
ac_ct_CC = gcc
ac_ct_DUMPBIN =
am__include = include
am__leading_dot = .
am__quote =
am__tar = $${TAR-tar} chof - "$$tardir"
am__untar = $${TAR-tar} xf -
bindir = ${exec_prefix}/bin
build = <API key>
build_alias =
build_cpu = x86_64
build_os = linux-gnu
build_vendor = unknown
builddir = .
datadir = ${datarootdir}
datarootdir = ${prefix}/share
docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
dvidir = ${docdir}
exec_prefix = ${prefix}
host = <API key>
host_alias =
host_cpu = x86_64
host_os = linux-gnu
host_vendor = unknown
htmldir = ${docdir}
includedir = ${prefix}/include
infodir = ${datarootdir}/info
install_sh = ${SHELL} /home/mark/Desktop/MaxusTech/MaxusNFC/lib/libnfc-1.7.1/install-sh
libdir = ${exec_prefix}/lib
libexecdir = ${exec_prefix}/libexec
libpcsclite_CFLAGS =
libpcsclite_LIBS =
libusb_CFLAGS =
libusb_CONFIG =
libusb_LIBS =
localedir = ${datarootdir}/locale
localstatedir = ${prefix}/var
mandir = ${datarootdir}/man
mkdir_p = /bin/mkdir -p
oldincludedir = /usr/include
pdfdir = ${docdir}
prefix = /usr
<API key> = s,x,x,
psdir = ${docdir}
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
srcdir = .
sysconfdir = /etc
target_alias =
top_build_prefix = ../../
top_builddir = ../..
top_srcdir = ../..
nfcinclude_HEADERS = \
nfc.h \
nfc-emulation.h \
nfc-types.h
nfcincludedir = $(includedir)/nfc
EXTRA_DIST = CMakeLists.txt
all: all-am
.SUFFIXES:
$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
&& { if test -f $@; then exit 0; else break; fi; }; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu include/nfc/Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --gnu include/nfc/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(<API key>)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
<API key>: $(nfcinclude_HEADERS)
@$(NORMAL_INSTALL)
test -z "$(nfcincludedir)" || $(MKDIR_P) "$(DESTDIR)$(nfcincludedir)"
@list='$(nfcinclude_HEADERS)'; test -n "$(nfcincludedir)" || list=; \
for p in $$list; do \
if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
echo "$$d$$p"; \
done | $(am__base_list) | \
while read files; do \
echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(nfcincludedir)'"; \
$(INSTALL_HEADER) $$files "$(DESTDIR)$(nfcincludedir)" || exit $$?; \
done
<API key>:
@$(NORMAL_UNINSTALL)
@list='$(nfcinclude_HEADERS)'; test -n "$(nfcincludedir)" || list=; \
files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
dir='$(DESTDIR)$(nfcincludedir)'; $(<API key>)
ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
mkid -fID $$unique
tags: TAGS
TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
set x; \
here=`pwd`; \
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
shift; \
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
if test $$# -gt 0; then \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
"$$@" $$unique; \
else \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$unique; \
fi; \
fi
ctags: CTAGS
CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
$(TAGS_FILES) $(LISP)
list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | \
$(AWK) '{ files[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in files) print i; }; }'`; \
test -z "$(CTAGS_ARGS)$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& $(am__cd) $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) "$$here"
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile $(HEADERS)
installdirs:
for dir in "$(DESTDIR)$(nfcincludedir)"; do \
test -z "$$dir" || $(MKDIR_P) "$$dir"; \
done
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
if test -z '$(STRIP)'; then \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(<API key>)" \
install_sh_PROGRAM="$(<API key>)" INSTALL_STRIP_FLAG=-s \
install; \
else \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(<API key>)" \
install_sh_PROGRAM="$(<API key>)" INSTALL_STRIP_FLAG=-s \
"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
fi
mostlyclean-generic:
clean-generic:
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(<API key>)" || rm -f $(<API key>)
<API key>:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic clean-libtool mostlyclean-am
distclean: distclean-am
-rm -f Makefile
distclean-am: clean-am distclean-generic distclean-tags
dvi: dvi-am
dvi-am:
html: html-am
html-am:
info: info-am
info-am:
install-data-am: <API key>
install-dvi: install-dvi-am
install-dvi-am:
install-exec-am:
install-html: install-html-am
install-html-am:
install-info: install-info-am
install-info-am:
install-man:
install-pdf: install-pdf-am
install-pdf-am:
install-ps: install-ps-am
install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -f Makefile
maintainer-clean-am: distclean-am <API key>
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-generic mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am: <API key>
.MAKE: install-am install-strip
.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
clean-libtool ctags distclean distclean-generic \
distclean-libtool distclean-tags distdir dvi dvi-am html \
html-am info info-am install install-am install-data \
install-data-am install-dvi install-dvi-am install-exec \
install-exec-am install-html install-html-am install-info \
install-info-am install-man <API key> \
install-pdf install-pdf-am install-ps install-ps-am \
install-strip installcheck installcheck-am installdirs \
maintainer-clean <API key> mostlyclean \
mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
tags uninstall uninstall-am <API key>
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT: |
$(document).ready(function(){
/** Object representing the control Dialog DOM Tree within the specified div element. */
var <API key> = new DOMKOL.<API key>($("#control-dialog"));
/** The Control Dialog itself (as an object which can be connected to the Complex Plane & graph view)*/
var controlDialog = new DOMKOL.ControlDialog(<API key>);
/** Add additional instructions about the function to the control dialog */
controlDialog.<API key>("Drag the blue number to change the zero of the linear polynomial " +
"(initially located on the origin).");
/** Initial complex zeroes for linear polynomial, i.e. 0+0i. */
var zeroes = [[0, 0]];
/** Object representing the cubic polynomial*/
var polynomialFunction = new DOMKOL.PolynomialFunction(zeroes);
/** Explorer view - consisting of complex plane, coordinates and circular graph,
(and to which can be added handles for controlling values of the zeroes of the polynomial) */
var explorerView = DOMKOL.createExplorerView($("#domkol"), // div element in which to insert the complex plane view
polynomialFunction, // the (linear) polynomial
controlDialog.values, // initial values for the explorer view settings
200, // pixels per unit
[310, 350], // pixel location of complex origin
[700, 700], // width * height in pixels of complex plane
200); // initial radius in pixels of the circle
/** Create draggable "number handles" to control values of the zeroes of the polynomial */
var numZeroes = zeroes.length;
for (i=numZeroes-1; i >= 0; i--) { // create in reverse order, because last one created is first one to be dragged
var zeroHandle = explorerView.<API key>(i, zeroes[i]);
// When the dragged number changes, update the corresponding zero in the polynomial
$(zeroHandle).on("numberChanged",
function(event, index, number, changing) {
polynomialFunction.updateZero(index, number, changing);
});
}
/** Connect the control dialog so that it actually controls the explorer view */
controlDialog.connect(explorerView);
}); |
<?php
global $php;
$config = $php->config['redis'][$php->factory_key];
if (empty($config) or empty($config['host']))
{
throw new Exception("require redis[$php->factory_key] config.");
}
if (empty($config['port']))
{
$config['port'] = 6379;
}
if (empty($config['timeout']))
{
$config['timeout'] = 0.5;
}
$config['object_id'] = $php->factory_key;
$redis = new Swoole\Coroutine\Component\Hook\Redis($config);
return $redis; |
#ifndef <API key>
#define <API key>
#include <ui/CocosGUI.h>
#include <2d/CCLayer.h>
#include <base/CCDirector.h>
#include <2d/CCMenu.h>
#include <GameSettings.h>
class GameMainMenuScene : cocos2d::Layer
{
public:
static cocos2d::Scene *createScene();
GameMainMenuScene();
virtual ~GameMainMenuScene();
CREATE_FUNC(GameMainMenuScene);
virtual bool init();
void switchToMainMenu();
void <API key>();
private:
cocos2d::Director *director_;
GameSettings *gameSettings_;
cocos2d::Menu *menu_;
};
#endif //<API key> |
package org.eobjects.analyzer.connection;
/**
* Simple implementation of the performance characteristics interface.
*/
public final class <API key> implements <API key> {
private final boolean <API key>;
private final boolean <API key>;
/**
*
* @param <API key>
*
* @deprecated use {@link #<API key>(boolean, boolean)}
* instead.
*/
@Deprecated
public <API key>(boolean <API key>) {
this(<API key>, true);
}
public <API key>(boolean <API key>, boolean <API key>) {
<API key> = <API key>;
<API key> = <API key>;
}
@Override
public boolean <API key>() {
return <API key>;
}
@Override
public boolean <API key>() {
return <API key>;
}
} |
<ul>
<li class="green">MySQL-Verbindung aufgebaut</li>
<li class="green">"cache"-Ordner hat Schreibrechte</li>
{if WRITEABLE_UPLOADS}<li class="green">"uploads"-Ordner hat Schreibrechte</li>{else}{FAILED=1}<li class="red">"uploads"-Ordner hat KEINE Schreibrechte</li>{/if}
</ul>
{if FAILED}
<p>Es sind Fehler aufgetreten! Beheben Sie die Fehler, und starten Sie die Installation neu.</p>
{else}
<form action="index.php" method="post">
<p align="right"><input type="submit" name="next" value="Weiter »" class="button" /></p>
</form>
{/if} |
h3 {
margin-left: 20px !important;
}
h5 {
margin-left: 20px !important;
font-style: italic;
color: #080 !important;
}
p{
margin: 15px;
padding-left: 10px;
border-left: 4px #ddd solid;
}
ol, ul{
display: block;
list-style: none;
}
a, a:focus, input, textarea{
outline: none;
}
a, a:link, a:visited{
color: blue;
font-weight: bold;
text-decoration: none;
}
a:hover{
text-decoration: underline;
}
#wrapper{
position:relative;
width:100%;
overflow:hidden;
min-height: 100%;
}
#main{
width: 960px;
position: relative;
overflow: visible;
margin: 0 auto 140px;
padding: 0;
/*padding: 0 0 70px; sticky footer */
background: #fff;
-webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, .3);
-moz-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, .3);
box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, .3);
}
.section{
padding: 40px;
}
.topNav{
position: fixed !important;
width: 100%;
top: 0;
left: 0;
height: 65px;
background: #fff;
-webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, .3);
-moz-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, .3);
box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, .3);
}
.topNav.dark{
background: #000;
background: rgba(0,0,0,.92);
border-bottom: 4px solid #222;
}
.topNav ul{
position: relative;
overflow: hidden;
width: 960px;
margin: 0 auto;
display: block;
}
.topNavLink{
float: left;
margin: 0 5px 0;
}
.topNavLink a{
display: block;
height: 18px;
margin: 15px 0 0;
line-height: 16px;
padding: 7px 12px;
color: #666;
border: 1px solid #fff;
font-weight: normal;
}
.white .topNavLink.active a{
background: #ccc;
color: #333;
-<API key>: 13px;
-moz-border-radius: 13px;
border-radius: 13px;
background: #ffffff; /* Old browsers */
background: -moz-linear-gradient(top, #fcfcfc 3%, #eeeeee 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(3%,#fcfcfc), color-stop(100%,#eeeeee)); /* Chrome,Safari4+ */
background: -<API key>(top, #fcfcfc 3%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #fcfcfc 3%,#eeeeee 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #fcfcfc 3%,#eeeeee 100%); /* IE10+ */
background: linear-gradient(top, #fcfcfc 3%,#eeeeee 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#eeeeee',GradientType=0 ); /* IE6-9 */
border-color: #ddd;
}
.dark .topNavLink.active a{
background: #222;
color: #fff;
-<API key>: 13px;
-moz-border-radius: 13px;
border-radius: 13px;
background: #ffffff; /* Old browsers */
background: -moz-linear-gradient(top, #4c4c4c 3%, #333333 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(3%,#4c4c4c), color-stop(100%,#333333)); /* Chrome,Safari4+ */
background: -<API key>(top, #4c4c4c 3%,#333333 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #4c4c4c 3%,#333333 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #4c4c4c 3%,#333333 100%); /* IE10+ */
background: linear-gradient(top, #4c4c4c 3%,#333333 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#4c4c4c', endColorstr='#333333',GradientType=0 ); /* IE6-9 */
border: none;
}
.dark .topNavLink a{
border: none;
}
.white .topNavLink a:hover{
color: #444444;
text-decoration: none;
}
.dark .topNavLink a:hover{
color: #ccc;
text-decoration: none;
}
.topNav .colors{
position: relative;
overflow: hidden;
float: right;
width: 100px;
margin: 22px 0 0;
}
.topNav .colors span{
display: block;
position: relative;
overflow: hidden;
width: 14px;
height: 0;
padding: 14px 0 0;
-<API key>: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
cursor: pointer;
float: left;
}
.topNav .colors .label{
width: 40px;
font-size: 10px;
padding: 0;
height: 16px;
line-height: 16px;
color: #999;
}
.topNav .colors span.white{
background: #fff;
border: 1px solid #fff;
}
.topNav .colors span.dark{
background: #111;
border: 1px solid #000;
margin: 0 0 0 5px;
}
.topNav .colors.white span.white{
border: 1px solid #999;
}
.topNav .colors.dark span.dark{
background: #000;
border: 1px solid #999;
}
.pageScroll{
position: fixed !important;
top: 50%;
left: 50%;
margin-top: -250px;
width: 167px;
border: 7px solid #fff;
-<API key>: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
-webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, .3);
-moz-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, .3);
box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, .3);
}
.pageScroll.left{
margin-left: -680px;
}
.pageScroll.right{
margin-left: 500px;
}
.scrollNav a{
display: block;
color: #666;
font-weight: normal;
padding: 8px 10px;
background: #f9f9f9; /* Old browsers */
background: -moz-linear-gradient(top, #f9f9f9 0%, #f3f3f3 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f9f9f9), color-stop(100%,#f3f3f3)); /* Chrome,Safari4+ */
background: -<API key>(top, #f9f9f9 0%,#f3f3f3 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #f9f9f9 0%,#f3f3f3 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #f9f9f9 0%,#f3f3f3 100%); /* IE10+ */
background: linear-gradient(top, #f9f9f9 0%,#f3f3f3 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f9f9f9', endColorstr='#f3f3f3',GradientType=0 ); /* IE6-9 */
border-top: 1px solid #fcfcfc;
}
.scrollNav{
border-top: 1px solid #ebeded;
}
.scrollNav_1,
.scrollNav_1 a{
border:none;
-<API key>: 10px;
-<API key>: 10px;
-<API key>: 10px;
-<API key>: 10px;
<API key>: 10px;
<API key>: 10px;
}
.scrollNav a:hover{
color: #444;
text-decoration: none;
}
li.scrollNav.active a{
background: #fff;
color: #333;
font-weight: bold;
}
#controls{
position: fixed;
z-index: 999;
height: 94%;
top: 3%;
right: 5%;
width: 20px;
text-align: center;
}
#controls a{
display: block;
position: absolute;
margin-top: 40px;
width: 20px;
padding: 12px 10px 5px;
-<API key>: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
-webkit-box-shadow: 1px 1px 5px 0px rgba(0, 0, 0, .3);
-moz-box-shadow: 1px 1px 5px 0px rgba(0, 0, 0, .3);
box-shadow: 1px 1px 5px 0px rgba(0, 0, 0, .3);
}
#controls.light a{
border: 7px solid #fff;
background: #f8f6f6; /* Old browsers */
background: -moz-linear-gradient(top, #f8f6f6 0%, #e8e7e7 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f8f6f6), color-stop(100%,#e8e7e7)); /* Chrome,Safari4+ */
background: -<API key>(top, #f8f6f6 0%,#e8e7e7 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #f8f6f6 0%,#e8e7e7 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #f8f6f6 0%,#e8e7e7 100%); /* IE10+ */
background: linear-gradient(top, #f8f6f6 0%,#e8e7e7 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f8f6f6', endColorstr='#e8e7e7',GradientType=0 ); /* IE6-9 */
}
#controls.dark a{
border: 7px solid #1c1c1c;
-webkit-box-shadow: 1px 1px 5px 0px rgba(0, 0, 0, .3);
-moz-box-shadow: 1px 1px 5px 0px rgba(0, 0, 0, .3);
box-shadow: 1px 1px 5px 0px rgba(0, 0, 0, .3);
background: #f8f6f6; /* Old browsers */
background: -moz-linear-gradient(top, #3f3f3f 0%, #292929 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#3f3f3f), color-stop(100%,#292929)); /* Chrome,Safari4+ */
background: -<API key>(top, #3f3f3f 0%,#292929 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #3f3f3f 0%,#292929 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #3f3f3f 0%,#292929 100%); /* IE10+ */
background: linear-gradient(top, #3f3f3f 0%,#292929 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#3f3f3f', endColorstr='#292929',GradientType=0 ); /* IE6-9 */
}
#controls a:hover{
text-decoration: none;
color: #fff;
}
#controls a.next{
bottom: 0;
}
#controls a.prev{
top: 0;
}
ul{
list-style: none !important;
} |
#include <sstream>
#include <boost/test/included/unit_test.hpp>
using namespace boost::unit_test_framework;
#include "DFMC_MD22Dummy.h"
#include "MotorControlerDummy.h"
#include "<API key>.h"
#include "<API key>.h"
#include "StepperMotor.h"
#include "<API key>.h"
#include "TMC429Constants.h"
#include "testConfigConstants.h"
#include <ChimeraTK/Utilities.h>
#include <boost/thread.hpp>
using namespace mtca4u;
// static const unsigned int THE_ID = 17;
static const std::string <API key>("<API key>.xml");
static const std::string moduleName("");
static TMC429OutputWord <API key>(boost::shared_ptr<DFMC_MD22Dummy>& dfmc_md22);
static <API key> <API key>(boost::shared_ptr<DFMC_MD22Dummy>& dfmc_md2);
class TestUnitConveter : public <API key> {
public:
TestUnitConveter(){};
virtual float stepsToUnits(int steps) { return float(steps / 10.0); };
virtual int unitsToSteps(float units) { return int(10.0 * units); };
};
class StepperMotorTest {
public:
StepperMotorTest();
void testSoftLimits();
void testAutostart();
void testStart();
void testStop();
void testEmergencyStop();
void testEnabledDisabled();
void testDebugLevel();
void testCalibration();
void testSetPositionAs();
void testSetGetSpeed();
void testMoveToPosition();
void thread(int i);
void testUnitConverter();
void <API key>();
void <API key>();
void testSetGetCurrent();
private:
boost::shared_ptr<mtca4u::StepperMotor> _stepperMotor;
boost::shared_ptr<MotorControlerDummy> <API key>;
boost::shared_ptr<TestUnitConveter> _testUnitConveter;
};
class <API key> : public test_suite {
public:
<API key>() : test_suite("StepperMotor suite") {
// create an instance of the test class
boost::shared_ptr<StepperMotorTest> stepperMotorTest(new StepperMotorTest);
add(<API key>(&StepperMotorTest::testUnitConverter, stepperMotorTest));
add(<API key>(&StepperMotorTest::testSoftLimits, stepperMotorTest));
add(<API key>(&StepperMotorTest::testAutostart, stepperMotorTest));
add(<API key>(&StepperMotorTest::testStart, stepperMotorTest));
add(<API key>(&StepperMotorTest::testEnabledDisabled, stepperMotorTest));
add(<API key>(&StepperMotorTest::testDebugLevel, stepperMotorTest));
add(<API key>(&StepperMotorTest::testCalibration, stepperMotorTest));
add(<API key>(&StepperMotorTest::testStop, stepperMotorTest));
add(<API key>(&StepperMotorTest::testEmergencyStop, stepperMotorTest));
add(<API key>(&StepperMotorTest::testSetPositionAs, stepperMotorTest));
add(<API key>(&StepperMotorTest::testSetGetSpeed, stepperMotorTest));
add(<API key>(&StepperMotorTest::testMoveToPosition, stepperMotorTest));
add(<API key>(&StepperMotorTest::<API key>, stepperMotorTest));
add(<API key>(&StepperMotorTest::<API key>, stepperMotorTest));
add(<API key>(&StepperMotorTest::testSetGetCurrent, stepperMotorTest));
}
};
test_suite* <API key>(int /*argc*/, char* /*argv*/ []) {
framework::master_test_suite().p_name.value = "StepperMotor test suite";
return new <API key>;
}
StepperMotorTest::StepperMotorTest() : _stepperMotor(), <API key>(), _testUnitConveter() {
_testUnitConveter.reset(new TestUnitConveter);
<API key>::instance().setDummyMode();
<API key> = boost::<API key><MotorControlerDummy>(
<API key>::instance()
.<API key>(<API key>, moduleName, <API key>)
->getMotorControler(0));
_stepperMotor.reset(new mtca4u::StepperMotor(<API key>, moduleName, 0, <API key>));
//!!!! CHANGE THIS FOR LINEAR STEPER MOTOR TESTS
<API key>-><API key>(false);
<API key>-><API key>(false);
}
void StepperMotorTest::testSoftLimits() {
_stepperMotor->setEnabled(true);
_testUnitConveter.reset(new TestUnitConveter());
_stepperMotor-><API key>(_testUnitConveter);
_stepperMotor-><API key>(true);
BOOST_CHECK(_stepperMotor-><API key>() == true);
_stepperMotor-><API key>(false);
BOOST_CHECK(_stepperMotor-><API key>() == false);
_stepperMotor-><API key>(150);
_stepperMotor-><API key>(50);
BOOST_CHECK(_stepperMotor->getMaxPositionLimit() == 15);
BOOST_CHECK(_stepperMotor->getMinPositionLimit() == 5);
BOOST_CHECK(_stepperMotor-><API key>() == 150);
BOOST_CHECK(_stepperMotor-><API key>() == 50);
_stepperMotor->setMaxPositionLimit(150);
_stepperMotor->setMinPositionLimit(50);
BOOST_CHECK(_stepperMotor->getMaxPositionLimit() == 150);
BOOST_CHECK(_stepperMotor->getMinPositionLimit() == 50);
BOOST_CHECK(_stepperMotor-><API key>() == 1500);
BOOST_CHECK(_stepperMotor-><API key>() == 500);
/*
_stepperMotor-><API key>(true);// out dated tests. to remove in
the future
_stepperMotor->setTargetPosition(200);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 150 );
BOOST_CHECK( _stepperMotor-><API key>() == 1500 );
_stepperMotor->setTargetPosition(0);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 50 );
BOOST_CHECK( _stepperMotor-><API key>() == 500 );
_stepperMotor->setTargetPosition(100);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 100 );
BOOST_CHECK( _stepperMotor-><API key>() == 1000 );
_stepperMotor-><API key>(3245);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 150 );
BOOST_CHECK( _stepperMotor-><API key>() == 1500 );
_stepperMotor-><API key>(0);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 50 );
BOOST_CHECK( _stepperMotor-><API key>() == 500 );
_stepperMotor-><API key>(1245);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 124.5 );
BOOST_CHECK( _stepperMotor-><API key>() == 1245 );
_stepperMotor-><API key>(false);
_stepperMotor->setTargetPosition(200);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 200 );
BOOST_CHECK( _stepperMotor-><API key>() == 2000 );
_stepperMotor->setTargetPosition(0);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 0 );
BOOST_CHECK( _stepperMotor-><API key>() == 0 );
_stepperMotor->setTargetPosition(100);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 100 );
BOOST_CHECK( _stepperMotor-><API key>() == 1000 );
//should trigger error state - target position should not be changed
_stepperMotor->setMaxPositionLimit(50);
_stepperMotor->setMinPositionLimit(150);
_stepperMotor-><API key>(true);
_stepperMotor->setTargetPosition(200);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 100 );
BOOST_CHECK( _stepperMotor-><API key>() == 1000 );
_stepperMotor->setTargetPosition(0);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 100 );
BOOST_CHECK( _stepperMotor-><API key>() == 1000 );
_stepperMotor->setTargetPosition(100);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 100 );
BOOST_CHECK( _stepperMotor-><API key>() == 1000 );
_stepperMotor-><API key>(false);
_stepperMotor->setTargetPosition(200);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 200 );
_stepperMotor->setTargetPosition(0);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 0 );
_stepperMotor->setTargetPosition(100);
BOOST_CHECK( _stepperMotor->getTargetPosition() == 100 );
_stepperMotor->setMaxPositionLimit(150);
_stepperMotor->setMinPositionLimit(50);
_stepperMotor->setTargetPosition(200);
_stepperMotor-><API key>(true);
BOOST_CHECK ( (_stepperMotor->getStatusAndError().status ==
<API key>::<API key>) == true);
_stepperMotor-><API key>(false);
_stepperMotor->setTargetPosition(10);
_stepperMotor-><API key>(true);
BOOST_CHECK ( (_stepperMotor->getStatusAndError().status ==
<API key>::<API key>) == true);
_stepperMotor-><API key>(false);
_stepperMotor->setEnabled(false);*/
}
void StepperMotorTest::testAutostart() {
_stepperMotor->setEnabled(true);
_stepperMotor->setAutostart(true);
BOOST_CHECK(_stepperMotor->getAutostart() == true);
_stepperMotor->setAutostart(false);
BOOST_CHECK(_stepperMotor->getAutostart() == false);
int initTargetPosition = <API key>->getTargetPosition();
_stepperMotor->setAutostart(false);
_stepperMotor->setTargetPosition(1000);
BOOST_CHECK(<API key>->getTargetPosition() == initTargetPosition);
_stepperMotor->setAutostart(true);
BOOST_CHECK(<API key>->getTargetPosition() == 10000);
_stepperMotor->setTargetPosition(2000);
BOOST_CHECK(<API key>->getTargetPosition() == 20000);
_stepperMotor->setTargetPosition(-2000);
BOOST_CHECK(<API key>->getTargetPosition() == -20000);
_stepperMotor->setAutostart(false);
}
void StepperMotorTest::testStart() {
<API key>->setTargetPosition(0);
<API key>->setActualPosition(0);
_stepperMotor->setEnabled(true);
_stepperMotor->setAutostart(false);
// test start function
_stepperMotor->setTargetPosition(5000);
BOOST_CHECK(<API key>->getTargetPosition() == 0);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_NOT_IN_POSITION);
_stepperMotor->start();
BOOST_CHECK(<API key>->getTargetPosition() == (5000 * 10));
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_IN_MOVE);
<API key>->moveTowardsTarget(0.5);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_IN_MOVE);
BOOST_CHECK(_stepperMotor->getCurrentPosition() == (5000 * 0.5));
BOOST_CHECK(_stepperMotor-><API key>() == (5000 * 0.5 * 10));
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getActualPosition());
<API key>->moveTowardsTarget(1);
BOOST_CHECK(_stepperMotor->getCurrentPosition() == (5000));
BOOST_CHECK(_stepperMotor-><API key>() == (5000 * 10));
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getActualPosition());
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_OK);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_OK); // FIXME, just a repetition?
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getActualPosition());
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getTargetPosition());
_stepperMotor->setTargetPosition(3000);
_stepperMotor->setMaxPositionLimit(942);
_stepperMotor->setMinPositionLimit(24);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_NOT_IN_POSITION);
_stepperMotor-><API key>(true);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_NOT_IN_POSITION);
_stepperMotor->start();
BOOST_CHECK(<API key>->getTargetPosition() == (942 * 10));
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_IN_MOVE);
<API key>->moveTowardsTarget(1);
BOOST_CHECK(_stepperMotor->getCurrentPosition() == (942));
BOOST_CHECK(_stepperMotor-><API key>() == (942 * 10));
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getActualPosition());
BOOST_CHECK(
(_stepperMotor->getStatusAndError().status == <API key>::<API key>) == true);
_stepperMotor->setTargetPosition(12);
_stepperMotor->setMaxPositionLimit(45);
_stepperMotor->setMinPositionLimit(23);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_NOT_IN_POSITION);
_stepperMotor-><API key>(true);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_NOT_IN_POSITION);
_stepperMotor->start();
BOOST_CHECK(<API key>->getTargetPosition() == (23 * 10));
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_IN_MOVE);
<API key>->moveTowardsTarget(1);
BOOST_CHECK(_stepperMotor->getCurrentPosition() == (23));
BOOST_CHECK(_stepperMotor-><API key>() == (23 * 10));
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getActualPosition());
BOOST_CHECK(
(_stepperMotor->getStatusAndError().status == <API key>::<API key>) == true);
}
void StepperMotorTest::testStop() {
<API key>->setTargetPosition(0);
<API key>->setActualPosition(0);
_stepperMotor->setEnabled(true);
_stepperMotor->setAutostart(false);
// test start function
_stepperMotor->setTargetPosition(5000);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_NOT_IN_POSITION);
_stepperMotor->start();
BOOST_CHECK(<API key>->getTargetPosition() == (5000 * 10));
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_IN_MOVE);
<API key>->moveTowardsTarget(0.5);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_IN_MOVE);
BOOST_CHECK(_stepperMotor->getCurrentPosition() == (5000 * 0.5));
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getActualPosition());
<API key>->moveTowardsTarget(0.5);
_stepperMotor->stop();
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_OK);
BOOST_CHECK(_stepperMotor->getCurrentPosition() == (5000 * 0.75));
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getActualPosition());
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getTargetPosition());
}
void StepperMotorTest::testEmergencyStop() {
<API key>->setTargetPosition(0);
<API key>->setActualPosition(0);
_stepperMotor->setEnabled(true);
_stepperMotor->setAutostart(false);
// test start function
_stepperMotor-><API key>(5000);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_NOT_IN_POSITION);
_stepperMotor->start();
BOOST_CHECK(<API key>->getTargetPosition() == (5000));
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_IN_MOVE);
<API key>->moveTowardsTarget(0.5);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_IN_MOVE);
BOOST_CHECK(_stepperMotor->getCurrentPosition() == (500 * 0.5));
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getActualPosition());
<API key>->moveTowardsTarget(0.5);
_stepperMotor->emergencyStop();
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_DISABLED);
BOOST_CHECK(_stepperMotor->getCurrentPosition() == (500 * 0.75));
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getActualPosition());
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getTargetPosition());
BOOST_CHECK(<API key>->getTargetPosition() == <API key>->getActualPosition());
}
void StepperMotorTest::testEnabledDisabled() {
_stepperMotor->setEnabled(true);
_stepperMotor-><API key>(false);
_stepperMotor-><API key>(<API key>->getActualPosition());
BOOST_CHECK(<API key>->isEnabled() == true);
BOOST_CHECK(_stepperMotor->getEnabled() == true);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_OK);
_stepperMotor->setEnabled(false);
BOOST_CHECK(<API key>->isEnabled() == false);
BOOST_CHECK(_stepperMotor->getEnabled() == false);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_DISABLED);
}
void StepperMotorTest::testDebugLevel() {
_stepperMotor->setLogLevel(Logger::NO_LOGGING);
BOOST_CHECK(_stepperMotor->getLogLevel() == Logger::NO_LOGGING);
_stepperMotor->setLogLevel(Logger::ERROR);
BOOST_CHECK(_stepperMotor->getLogLevel() == Logger::ERROR);
_stepperMotor->setLogLevel(Logger::WARNING);
BOOST_CHECK(_stepperMotor->getLogLevel() == Logger::WARNING);
_stepperMotor->setLogLevel(Logger::INFO);
BOOST_CHECK(_stepperMotor->getLogLevel() == Logger::INFO);
_stepperMotor->setLogLevel(Logger::DETAIL);
BOOST_CHECK(_stepperMotor->getLogLevel() == Logger::DETAIL);
_stepperMotor->setLogLevel(Logger::FULL_DETAIL);
BOOST_CHECK(_stepperMotor->getLogLevel() == Logger::FULL_DETAIL);
_stepperMotor->setLogLevel(Logger::NO_LOGGING);
}
void StepperMotorTest::testCalibration() {
BOOST_CHECK(_stepperMotor-><API key>() == <API key>::M_NOT_CALIBRATED);
_stepperMotor->calibrateMotor();
BOOST_CHECK(_stepperMotor-><API key>() == <API key>::<API key>);
}
void StepperMotorTest::testSetPositionAs() {
<API key>->setTargetPosition(0);
<API key>->setActualPosition(0);
_stepperMotor->setAutostart(false);
_stepperMotor->setMaxPositionLimit(5000);
_stepperMotor->setMinPositionLimit(-5000);
_stepperMotor->setEnabled(true);
_stepperMotor-><API key>(5000);
BOOST_CHECK(_stepperMotor->getCurrentPosition() == 5000);
BOOST_CHECK(_stepperMotor-><API key>() == 50000);
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getActualPosition());
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getTargetPosition());
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_OK);
BOOST_CHECK(_stepperMotor-><API key>() == 100000);
BOOST_CHECK(_stepperMotor-><API key>() == 0);
_stepperMotor->setEnabled(false);
_stepperMotor-><API key>(-2000);
BOOST_CHECK(_stepperMotor->getCurrentPosition() == -200);
BOOST_CHECK(_stepperMotor-><API key>() == -2000);
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getActualPosition());
BOOST_CHECK(_stepperMotor-><API key>() == <API key>->getTargetPosition());
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_DISABLED);
BOOST_CHECK(_stepperMotor-><API key>() == 48000);
BOOST_CHECK(_stepperMotor-><API key>() == -52000);
}
void StepperMotorTest::testSetGetSpeed() {
_stepperMotor->setUserSpeedLimit(100);
BOOST_CHECK_CLOSE(_stepperMotor->getUserSpeedLimit(), 100., 1e-6);
}
void StepperMotorTest::testMoveToPosition() {
<API key>-><API key>();
//!!!! CHANGE THIS FOR LINEAR STEPER MOTOR TESTS
<API key>-><API key>(false);
<API key>-><API key>(false);
_stepperMotor->setAutostart(false);
_stepperMotor->setEnabled(true);
// set motor in error state - configuration error end test routine
auto currentPosition = _stepperMotor-><API key>();
_stepperMotor->setMaxPositionLimit(50);
_stepperMotor->setMinPositionLimit(100);
_stepperMotor-><API key>(true);
BOOST_CHECK(_stepperMotor->getStatusAndError().status == <API key>::M_ERROR);
BOOST_CHECK(
_stepperMotor->getStatusAndError().error == <API key>::<API key>);
auto statusAndError = _stepperMotor->moveToPosition(0);
BOOST_CHECK(statusAndError.status == <API key>::M_ERROR);
BOOST_CHECK(statusAndError.error == <API key>::<API key>);
BOOST_CHECK(<API key>->getTargetPosition() == currentPosition);
_stepperMotor-><API key>(false);
currentPosition = _stepperMotor-><API key>();
_stepperMotor-><API key>(currentPosition - 100);
_stepperMotor-><API key>(currentPosition - 200);
_stepperMotor-><API key>(true);
boost::thread workerThread1_1(&StepperMotorTest::thread, this, 1);
statusAndError = _stepperMotor->moveToPosition(currentPosition + 100);
workerThread1_1.join();
BOOST_CHECK(_stepperMotor-><API key>() == _stepperMotor-><API key>());
BOOST_CHECK(statusAndError.status == <API key>::<API key>);
BOOST_CHECK(statusAndError.error == <API key>::M_NO_ERROR);
BOOST_CHECK(<API key>->getTargetPosition() == currentPosition - 100);
currentPosition = _stepperMotor-><API key>();
boost::thread workerThread1_2(&StepperMotorTest::thread, this, 1);
statusAndError = _stepperMotor->moveToPosition(currentPosition - 600);
workerThread1_2.join();
BOOST_CHECK(_stepperMotor-><API key>() == _stepperMotor-><API key>());
BOOST_CHECK(statusAndError.status == <API key>::<API key>);
BOOST_CHECK(statusAndError.error == <API key>::M_NO_ERROR);
BOOST_CHECK(<API key>->getTargetPosition() == _stepperMotor-><API key>());
_stepperMotor-><API key>(false);
// test stop blocking function
boost::thread workedThread2(&StepperMotorTest::thread, this, 2);
int targerPosition = <API key>->getActualPosition() + 3000;
statusAndError = _stepperMotor-><API key>(targerPosition);
BOOST_CHECK(statusAndError.status == <API key>::M_OK);
BOOST_CHECK(statusAndError.error == <API key>::M_NO_ERROR);
BOOST_CHECK(_stepperMotor-><API key>() != targerPosition);
workedThread2.join();
// test when we will succesfully finish movement
targerPosition = <API key>->getActualPosition() + 9901;
boost::thread workedThread3_1(&StepperMotorTest::thread, this, 1);
statusAndError = _stepperMotor-><API key>(targerPosition);
BOOST_CHECK(statusAndError.status == <API key>::M_OK);
BOOST_CHECK(statusAndError.error == <API key>::M_NO_ERROR);
BOOST_CHECK(_stepperMotor-><API key>() == targerPosition);
workedThread3_1.join();
// test when we will succesfully finish movement but with autostart ON
_stepperMotor->setAutostart(true);
targerPosition = <API key>->getActualPosition() + 3000;
boost::thread workedThread3_2(&StepperMotorTest::thread, this, 1);
statusAndError = _stepperMotor-><API key>(targerPosition);
BOOST_CHECK(statusAndError.status == <API key>::M_OK);
BOOST_CHECK(statusAndError.error == <API key>::M_NO_ERROR);
BOOST_CHECK(_stepperMotor-><API key>() == targerPosition);
_stepperMotor->setAutostart(false);
workedThread3_2.join();
}
void StepperMotorTest::thread(int testCase) {
if(testCase == 1) {
// do not proceed till the parent thread has asked the moter to move
if(_stepperMotor->isMoving() == false) {
usleep(50000);
}
// simulate the movement
<API key>->moveTowardsTarget(1);
}
if(testCase == 2) {
// do not proceed till the parent thread has asked the moter to move
if(_stepperMotor->isMoving() == false) {
usleep(10000);
}
// simulate the movement
<API key>->moveTowardsTarget(0.4);
_stepperMotor->stop();
<API key>->moveTowardsTarget(1);
}
}
void StepperMotorTest::testUnitConverter() {
<API key>(_stepperMotor-><API key>(_testUnitConveter));
BOOST_CHECK(_stepperMotor-><API key>(10) == 100);
BOOST_CHECK(_stepperMotor-><API key>(-10) == -100);
BOOST_CHECK(_stepperMotor-><API key>(10.5) == 105);
BOOST_CHECK(_stepperMotor-><API key>(-10.5) == -105);
BOOST_CHECK(_stepperMotor-><API key>(100) == 10);
BOOST_CHECK(_stepperMotor-><API key>(-100) == -10);
BOOST_CHECK(_stepperMotor-><API key>(105) == 10.5);
BOOST_CHECK(_stepperMotor-><API key>(-105) == -10.5);
_testUnitConveter.reset();
BOOST_CHECK_THROW(_stepperMotor-><API key>(_testUnitConveter), <API key>);
_stepperMotor-><API key>();
BOOST_CHECK(_stepperMotor-><API key>(10) == 10);
BOOST_CHECK(_stepperMotor-><API key>(-10) == -10);
BOOST_CHECK(_stepperMotor-><API key>(10.5) == 10);
BOOST_CHECK(_stepperMotor-><API key>(-10.5) == -10);
BOOST_CHECK(_stepperMotor-><API key>(100) == 100);
BOOST_CHECK(_stepperMotor-><API key>(-100) == -100);
BOOST_CHECK(_stepperMotor-><API key>(105) == 105);
BOOST_CHECK(_stepperMotor-><API key>(-105) == -105);
}
void StepperMotorTest::<API key>() {
_testUnitConveter.reset(new TestUnitConveter);
<API key>(_stepperMotor-><API key>(_testUnitConveter));
<API key>-><API key>();
_stepperMotor->setAutostart(false);
_stepperMotor->setEnabled(true);
_stepperMotor->setTargetPosition(765);
_stepperMotor->start();
<API key>->moveTowardsTarget(1);
BOOST_CHECK(_stepperMotor->getCurrentPosition() == 765);
BOOST_CHECK(_stepperMotor-><API key>() == 7650);
_stepperMotor->setTargetPosition(-500);
_stepperMotor->start();
<API key>->moveTowardsTarget(1);
BOOST_CHECK(_stepperMotor->getCurrentPosition() == -500);
BOOST_CHECK(_stepperMotor-><API key>() == -5000);
}
void StepperMotorTest::<API key>() {
// setup
auto dmapFile = mtca4u::getDMapFilePath();
mtca4u::setDMapFilePath("./dummies.dmap");
auto dummyModeStatus = <API key>::instance().getDummyMode();
<API key>::instance().setDummyMode(false);
mtca4u::StepperMotor motor("<API key>", "MD22_0", 0, "<API key>.xml");
// Expected max speed capability in this case:[from
// <API key>.xml]
// Vmax = 1398 (0x576)
// fclk = 32000000
// pulse_div = 6
// <API key> = Vmax * fclk/((2^pulse_div) * 2048
auto <API key> = (1398.0 * 32000000.0) / (exp2(6) * 2048 * 32);
// <API key> = Vmin * fclk/((2^pulse_div) * 2048
auto <API key> = (1.0 * 32000000.0) / // VMin = 1 (1.0)
(exp2(6) * 2048 * 32);
// verify <API key>
BOOST_CHECK(motor.<API key>() == <API key>);
// set speed > MaxAllowedSpeed
BOOST_CHECK(motor.setUserSpeedLimit(<API key>) == <API key>);
BOOST_CHECK(motor.getUserSpeedLimit() == <API key>);
BOOST_CHECK(motor.setUserSpeedLimit(<API key> + 10) == <API key>);
BOOST_CHECK(motor.getUserSpeedLimit() == <API key>);
// set speed < MinAllowedSpeed
BOOST_CHECK(motor.setUserSpeedLimit(<API key>) == <API key>);
BOOST_CHECK(motor.getUserSpeedLimit() == <API key>);
BOOST_CHECK(motor.setUserSpeedLimit(<API key> - 10) == <API key>);
BOOST_CHECK(motor.getUserSpeedLimit() == <API key>);
BOOST_CHECK(motor.setUserSpeedLimit(-100) == <API key>);
BOOST_CHECK(motor.getUserSpeedLimit() == <API key>);
// set speed in valid range [Vmin, Vmax]
// speed = 8000 microsteps per second -> results in Vmax = 1048.576
// Vmax 1048.576 floors to 1048 => which gives returned/actual set speed as
// 7995.6054... microsteps per second
auto expectedSetSpeed = (1048.0 * 32000000.0) / (exp2(6) * 2048 * 32);
BOOST_CHECK(motor.setUserSpeedLimit(8000) == expectedSetSpeed);
BOOST_CHECK(motor.getUserSpeedLimit() == expectedSetSpeed);
// Verify that Vmax is 1048 in the internal register (which is the
// VMax corresponding to expectedSetSpeed)
auto md22_instance = boost::<API key><DFMC_MD22Dummy>(
BackendFactory::getInstance().createBackend("<API key>"));
BOOST_ASSERT(md22_instance != NULL);
TMC429OutputWord vMaxRegister = <API key>(md22_instance);
BOOST_CHECK(vMaxRegister.getDATA() == 1048);
// teardown
<API key>::instance().setDummyMode(dummyModeStatus);
mtca4u::setDMapFilePath(dmapFile);
}
void StepperMotorTest::testSetGetCurrent() {
auto dmapFile = mtca4u::getDMapFilePath();
mtca4u::setDMapFilePath("./dummies.dmap");
auto dummyModeStatus = <API key>::instance().getDummyMode();
<API key>::instance().setDummyMode(false);
mtca4u::StepperMotor motor("<API key>", "MD22_0", 0, "<API key>.xml");
// The motor has been configured for a maximum current of .24 Amps, with 1.8A
// being the maximum the driver ic can provide. This translates to a current
// scale according to the formula:
// (.24 * 32)/1.8 - 1 == 3.266
// the 32 in the above formula comes from the 32 current scale levels for the
// tmc260.
// The tmc260 current scale register takes a whole number. So floor(3.266)
// goes into the current scale register. Because of this we get an effective
// current limit of:
// 1.8 * (3 + 1)/32 == .225 A
auto <API key> = 1.8 * (4.0) / 32.0;
auto safeCurrentLimit = motor.getSafeCurrentLimit();
BOOST_CHECK(safeCurrentLimit == <API key>);
// set Current to Beyond the safe limit
BOOST_CHECK(motor.setUserCurrentLimit(safeCurrentLimit + 10) == safeCurrentLimit);
BOOST_CHECK(motor.getUserCurrentLimit() == safeCurrentLimit);
BOOST_CHECK(motor.setUserCurrentLimit(safeCurrentLimit) == safeCurrentLimit);
BOOST_CHECK(motor.getUserCurrentLimit() == safeCurrentLimit);
// set a current below minimum value.
// Minimum value of current (when current scale is 0):
// 1.8 * (0 + 1)/32 == .05625A
auto minimumCurrent = 1.8 * 1.0 / 32.0;
BOOST_CHECK(motor.setUserCurrentLimit(0) == minimumCurrent);
BOOST_CHECK(motor.getUserCurrentLimit() == minimumCurrent);
BOOST_CHECK(motor.setUserCurrentLimit(-10) == minimumCurrent);
BOOST_CHECK(motor.getUserCurrentLimit() == minimumCurrent);
// Current in a valid range: 0 - .24A
// I = .2A
// CS = (.20 * 32)/1.8 - 1 = floor(2.556) = 2
// For CS 2: Expected current = (1.8 * (2 + 1))/32 = .16875A
auto expectedCurrent = (1.8 * (2 + 1)) / 32.0;
BOOST_CHECK(motor.setUserCurrentLimit(.2) == expectedCurrent);
BOOST_CHECK(motor.getUserCurrentLimit() == expectedCurrent);
// Verify that CS is 2 in the internal register ()
auto md22_instance = boost::<API key><DFMC_MD22Dummy>(
BackendFactory::getInstance().createBackend("<API key>"));
BOOST_ASSERT(md22_instance != NULL);
<API key> stallGuard = <API key>(md22_instance);
BOOST_CHECK(stallGuard.getCurrentScale() == 2);
// teardown
<API key>::instance().setDummyMode(dummyModeStatus);
mtca4u::setDMapFilePath(dmapFile);
}
/*
void <API key>::testGetID(){
BOOST_CHECK( <API key>.getID() == THE_ID );
}
void <API key>::testIsSetEnabled(){
// motor should be disabled now
BOOST_CHECK( <API key>.isEnabled() == false );
// just a small test that the motor does not move
// move to somewhere way beyond the end swith. The current position should go
there.
BOOST_CHECK( <API key>.getDecoderPosition() == 10000 );
BOOST_CHECK( <API key>.getActualPosition() == 0 );
BOOST_CHECK( <API key>.getTargetPosition() == 0 );
<API key>.setTargetPosition(2000000);
// motor must not be moving
BOOST_CHECK( <API key>.getActualVelocity() == 0 );
<API key>.moveTowardsTarget(1);
// real position has not changed, target positon reached
BOOST_CHECK( <API key>.getDecoderPosition() == 10000 );
BOOST_CHECK( <API key>.getActualPosition() == 2000000 );
// reset the positons and enable the motor. All other tests are done with
motor
// activated.
<API key>.setTargetPosition(0);
<API key>.setActualPosition(0);
<API key>.setEnabled();
// check that on/of works as expected
BOOST_CHECK( <API key>.isEnabled() );
<API key>.setEnabled(false);
BOOST_CHECK( <API key>.isEnabled() == false );
<API key>.setEnabled();
}
void <API key>::<API key>(){
// upon initialisation all positions must be 0
BOOST_CHECK( <API key>.getTargetPosition() == 0);
BOOST_CHECK( <API key>.<API key>() );
<API key>.setTargetPosition(1234);
BOOST_CHECK( <API key>.<API key>() == false );
BOOST_CHECK( <API key>.getTargetPosition() == 1234);
// set it back to 0 to simplify further tests
<API key>.setTargetPosition(0);
BOOST_CHECK( <API key>.<API key>() );
}
void <API key>::<API key>(){
// upon initialisation all positions must be 0
BOOST_CHECK( <API key>.getActualPosition() == 0);
<API key>.setActualPosition(1000);
BOOST_CHECK( <API key>.getActualPosition() == 1000);
}
void <API key>::<API key>(){
// we strongly depent on the order of the execution here. actual position is
1000,
// while the target position is 0, to we expect a negative velocity
BOOST_CHECK( <API key>.getActualVelocity() == -25 );
<API key>.setActualPosition(0);
BOOST_CHECK( <API key>.getActualVelocity() == 0 );
<API key>.setActualPosition(-1000);
BOOST_CHECK( <API key>.getActualVelocity() == 25 );
// whitebox test: as the decision in getActualVelocity() directly depends on
// the private isMoving, this is the ideal case to test it.
// move to the positive end switch. Although the target positon is not reached
the
// motor must not move any more
<API key>.setActualPosition(0);
<API key>.setTargetPosition(200000);
BOOST_CHECK( <API key>.getActualVelocity() == 25 );
<API key>.moveTowardsTarget(1);
BOOST_CHECK( <API key>.getActualVelocity() == 0 );
<API key>.setTargetPosition(-200000);
BOOST_CHECK( <API key>.getActualVelocity() == -25 );
<API key>.moveTowardsTarget(1);
BOOST_CHECK( <API key>.getActualVelocity() == 0 );
BOOST_CHECK_THROW(<API key>.setActualVelocity(0),
<API key>);
}
void <API key>::<API key>(){
BOOST_CHECK( <API key>.<API key>() == 0 );
BOOST_CHECK_THROW(<API key>.<API key>(0),
<API key>);
}
void <API key>::<API key>(){
// Set the actual position to something positive. The micro step count is
// positive and identical to the actual count.
// Does this make sense? Check the data sheet.
<API key>.setActualPosition(5000);
BOOST_CHECK( <API key>.getMicroStepCount() == 5000 );
BOOST_CHECK_THROW(<API key>.setMicroStepCount(0),
<API key>);
}
void <API key>::testGetStatus(){
BOOST_CHECK_THROW(<API key>.getStatus(), <API key>);
}
void <API key>::<API key>(){
BOOST_CHECK(<API key>.<API key>() ==
MotorControler::DecoderReadoutMode::HEIDENHAIN);
BOOST_CHECK_THROW(<API key>.<API key>(MotorControler::DecoderReadoutMode::INCREMENTAL),
<API key>);
}
void <API key>::<API key>(){
// we are still at the negative end switch
BOOST_CHECK( <API key>.getDecoderPosition() == 0 );
// actual position is 5000, move into the absolute positive range
<API key>.setTargetPosition(17000); // 12000 steps
<API key>.moveTowardsTarget(1);
BOOST_CHECK( <API key>.getDecoderPosition() == 12000 );
}
void <API key>::<API key>(){
<API key> <API key> =
<API key>.<API key>();
BOOST_CHECK(<API key>.<API key>());
BOOST_CHECK(<API key>.<API key>());
BOOST_CHECK(<API key>.<API key>() == false);
BOOST_CHECK(<API key>.<API key>() == false);
BOOST_CHECK(<API key>.<API key>() == 0 );
// move to the positive end switch and recheck
<API key>.setTargetPosition(
<API key>.getActualPosition()
+ 2000000);
<API key>.moveTowardsTarget(1);
<API key> = <API key>.<API key>();
BOOST_CHECK(<API key>.<API key>());
BOOST_CHECK(<API key>.<API key>());
BOOST_CHECK(<API key>.<API key>() );
BOOST_CHECK(<API key>.<API key>() == false);
BOOST_CHECK(<API key>.<API key>() == 1 );
// deactivate the positive end switch. Although it is still active in
hardware,
// this should not be reported
<API key>.<API key>(false);
<API key> = <API key>.<API key>();
BOOST_CHECK(<API key>.<API key>() == false);
BOOST_CHECK(<API key>.<API key>());
BOOST_CHECK(<API key>.<API key>() == false );
BOOST_CHECK(<API key>.<API key>() == false);
BOOST_CHECK(<API key>.<API key>() == 0 );
// reenable the switch and to the same for the negative switch
<API key>.<API key>(true);
<API key>.setTargetPosition(
<API key>.getActualPosition()
- 2000000);
<API key>.moveTowardsTarget(1);
<API key> = <API key>.<API key>();
BOOST_CHECK(<API key>.<API key>());
BOOST_CHECK(<API key>.<API key>());
BOOST_CHECK(<API key>.<API key>() == false);
BOOST_CHECK(<API key>.<API key>() );
BOOST_CHECK(<API key>.<API key>() == 1 );
// deactivate the positive end switch. Although it is still active in
hardware,
// this should not be reported
<API key>.<API key>(false);
<API key> = <API key>.<API key>();
BOOST_CHECK(<API key>.<API key>() );
BOOST_CHECK(<API key>.<API key>() == false );
BOOST_CHECK(<API key>.<API key>() == false );
BOOST_CHECK(<API key>.<API key>() == false);
BOOST_CHECK(<API key>.<API key>() == 0 );
// reenable the switch and to the same for the negative switch
<API key>.<API key>(true);
}
void <API key>::<API key>(){
// ok, we are at the negative end switch. reset target and actual position to
0
// for a clean test environment.
<API key>.setActualPosition(0);
<API key>.setTargetPosition(0);
// move to a target position in the range in multiple steps
<API key>.setTargetPosition(4000);
BOOST_CHECK( <API key>.getActualPosition() == 0 );
BOOST_CHECK( <API key>.getTargetPosition() == 4000 );
BOOST_CHECK( <API key>.getDecoderPosition() == 0 );
<API key>.moveTowardsTarget(0.25);
BOOST_CHECK( <API key>.getActualPosition() == 1000 );
BOOST_CHECK( <API key>.getTargetPosition() == 4000 );
BOOST_CHECK( <API key>.getDecoderPosition() == 1000 );
<API key>.moveTowardsTarget(0.5);
BOOST_CHECK( <API key>.getActualPosition() == 2500 );
BOOST_CHECK( <API key>.getTargetPosition() == 4000 );
BOOST_CHECK( <API key>.getDecoderPosition() == 2500 );
// moving backwards works differently, this does nothing
<API key>.moveTowardsTarget(-0.25);
BOOST_CHECK( <API key>.getActualPosition() == 2500 );
BOOST_CHECK( <API key>.getTargetPosition() == 4000 );
BOOST_CHECK( <API key>.getDecoderPosition() == 2500 );
// moving further than the target position also does not work
<API key>.moveTowardsTarget(2);
BOOST_CHECK( <API key>.getActualPosition() == 4000 );
BOOST_CHECK( <API key>.getTargetPosition() == 4000 );
BOOST_CHECK( <API key>.getDecoderPosition() == 4000 );
// ok, let's recalibrate and do the stuff backwards
<API key>.setActualPosition(0);
<API key>.setTargetPosition(-400); // we intentionally do not move
all the
// way back to the end switch
BOOST_CHECK( <API key>.getActualPosition() == 0 );
BOOST_CHECK( <API key>.getTargetPosition() == -400 );
BOOST_CHECK( <API key>.getDecoderPosition() == 4000 );
// this moves backwards because the target position is smaller than the actual
one
<API key>.moveTowardsTarget(0.25);
BOOST_CHECK( <API key>.getActualPosition() == -100 );
BOOST_CHECK( <API key>.getTargetPosition() == -400 );
BOOST_CHECK( <API key>.getDecoderPosition() == 3900 );
<API key>.moveTowardsTarget(0.5);
BOOST_CHECK( <API key>.getActualPosition() == -250 );
BOOST_CHECK( <API key>.getTargetPosition() == -400 );
BOOST_CHECK( <API key>.getDecoderPosition() == 3750 );
// moving backwards works differently, this does nothing
<API key>.moveTowardsTarget(-0.25);
BOOST_CHECK( <API key>.getActualPosition() == -250 );
BOOST_CHECK( <API key>.getTargetPosition() == -400 );
BOOST_CHECK( <API key>.getDecoderPosition() == 3750 );
// moving further than the target position also does not work
<API key>.moveTowardsTarget(2);
BOOST_CHECK( <API key>.getActualPosition() == -400 );
BOOST_CHECK( <API key>.getTargetPosition() == -400 );
BOOST_CHECK( <API key>.getDecoderPosition() == 3600 );
// now check that the end switches are handled correctly
// move to the middle and recalibrate for easier readability
<API key>.setTargetPosition(6000);
<API key>.moveTowardsTarget(1);
<API key>.setActualPosition(0);
<API key>.setTargetPosition(0);
BOOST_CHECK( <API key>.getActualPosition() == 0 );
BOOST_CHECK( <API key>.getTargetPosition() == 0 );
BOOST_CHECK( <API key>.getDecoderPosition() == 10000 );
// set a target position outside the end switches and see what happes
<API key>.setTargetPosition(11000);
// only move half the way, should be fine
<API key>.moveTowardsTarget(0.5);
BOOST_CHECK( <API key>.getActualPosition() == 5500 );
BOOST_CHECK( <API key>.getTargetPosition() == 11000 );
BOOST_CHECK( <API key>.getDecoderPosition() == 15500 );
// move the rest, it should stop at the end switch and not be moving any more
<API key>.moveTowardsTarget(1);
BOOST_CHECK( <API key>.getActualPosition() == 10000 );
BOOST_CHECK( <API key>.getTargetPosition() == 11000 );
BOOST_CHECK( <API key>.getDecoderPosition() == 20000 );
BOOST_CHECK( <API key>.getActualVelocity() == 0 );
BOOST_CHECK(<API key>.<API key>().<API key>()
);
// Move back, deactivate the end switch and try again
// (Don't try this at home. It will break your hardware!)
<API key>.setTargetPosition(5500);
<API key>.moveTowardsTarget(1);
BOOST_CHECK( <API key>.getActualPosition() == 5500 );
BOOST_CHECK( <API key>.getTargetPosition() == 5500 );
BOOST_CHECK( <API key>.getDecoderPosition() == 15500 );
<API key>.<API key>(false);
<API key>.setTargetPosition(11000);
<API key>.moveTowardsTarget(1);
BOOST_CHECK( <API key>.getActualPosition() == 11000 );
BOOST_CHECK( <API key>.getTargetPosition() == 11000 );
BOOST_CHECK( <API key>.getDecoderPosition() == 21000 );
// now the same for the negative end switch
// set a target position outside the end switches and see what happes
<API key>.setTargetPosition(-11000);
// only move half the way, should be fine
<API key>.moveTowardsTarget(0.5);
BOOST_CHECK( <API key>.getActualPosition() == 0 );
BOOST_CHECK( <API key>.getTargetPosition() == -11000 );
BOOST_CHECK( <API key>.getDecoderPosition() == 10000 );
// move the rest, it should stop at the end switch and not be moving any more
<API key>.moveTowardsTarget(1);
BOOST_CHECK( <API key>.getActualPosition() == -10000 );
BOOST_CHECK( <API key>.getTargetPosition() == -11000 );
BOOST_CHECK( <API key>.getDecoderPosition() == 0 );
BOOST_CHECK( <API key>.getActualVelocity() == 0 );
BOOST_CHECK(<API key>.<API key>().<API key>()
);
// Move back, deactivate the end switch and try again
// (Don't try this at home. It will break your hardware!)
<API key>.setTargetPosition(-5500);
<API key>.moveTowardsTarget(1);
BOOST_CHECK( <API key>.getActualPosition() == -5500 );
BOOST_CHECK( <API key>.getTargetPosition() == -5500 );
BOOST_CHECK( <API key>.getDecoderPosition() == 4500 );
<API key>.<API key>(false);
<API key>.setTargetPosition(-11000);
<API key>.moveTowardsTarget(1);
BOOST_CHECK( <API key>.getActualPosition() == -11000 );
BOOST_CHECK( <API key>.getTargetPosition() == -11000 );
// the decoder delivers a huge value because it is unsigned. We broke the
hardware
// anyway ;-) Negative positons are not possible.
BOOST_CHECK( <API key>.getDecoderPosition()
== static_cast<unsigned int>(-1000) );
}
*/
TMC429OutputWord <API key>(boost::shared_ptr<DFMC_MD22Dummy>& dfmc_md22) {
TMC429InputWord readVmaxRegister;
readVmaxRegister.setSMDA(0);
readVmaxRegister.setIDX_JDX(tmc429::<API key>);
readVmaxRegister.setRW(tmc429::RW_READ);
return TMC429OutputWord(dfmc_md22->readTMC429Register(readVmaxRegister.getDataWord()));
}
<API key> <API key>(boost::shared_ptr<DFMC_MD22Dummy>& dfmc_md2) {
auto motorId = 0;
return <API key>(
dfmc_md2->readTMC260Register(motorId, DFMC_MD22Dummy::TMC260Register::<API key>));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.