_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3400
|
ForwardRateAgreement.getRate
|
train
|
public double getRate(AnalyticModel model) {
if(model==null) {
throw new IllegalArgumentException("model==null");
}
ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);
if(forwardCurve==null) {
throw new IllegalArgumentException("No forward curve of name '" + forwardCurveName + "' found in given model:\n" + model.toString());
}
double fixingDate = schedule.getFixing(0);
return forwardCurve.getForward(model,fixingDate);
}
|
java
|
{
"resource": ""
}
|
q3401
|
AbstractLIBORCovarianceModelParametric.getParameter
|
train
|
public RandomVariable[] getParameter() {
double[] parameterAsDouble = this.getParameterAsDouble();
RandomVariable[] parameter = new RandomVariable[parameterAsDouble.length];
for(int i=0; i<parameter.length; i++) {
parameter[i] = new Scalar(parameterAsDouble[i]);
}
return parameter;
}
|
java
|
{
"resource": ""
}
|
q3402
|
DiscountCurveInterpolation.createDiscountCurveFromMonteCarloLiborModel
|
train
|
public static DiscountCurveInterface createDiscountCurveFromMonteCarloLiborModel(String forwardCurveName, LIBORModelMonteCarloSimulationModel model, double startTime) throws CalculationException{
// Check if the LMM uses a discount curve which is created from a forward curve
if(model.getModel().getDiscountCurve()==null || model.getModel().getDiscountCurve().getName().toLowerCase().contains("DiscountCurveFromForwardCurve".toLowerCase())){
return new DiscountCurveFromForwardCurve(ForwardCurveInterpolation.createForwardCurveFromMonteCarloLiborModel(forwardCurveName, model, startTime));
}
else {
// i.e. forward curve of Libor Model not OIS. In this case return the OIS curve.
// Only at startTime 0!
return (DiscountCurveInterface) model.getModel().getDiscountCurve();
}
}
|
java
|
{
"resource": ""
}
|
q3403
|
BusinessdayCalendarExcludingTARGETHolidays.isEasterSunday
|
train
|
public static boolean isEasterSunday(LocalDate date) {
int y = date.getYear();
int a = y % 19;
int b = y / 100;
int c = y % 100;
int d = b / 4;
int e = b % 4;
int f = (b + 8) / 25;
int g = (b - f + 1) / 3;
int h = (19 * a + b - d - g + 15) % 30;
int i = c / 4;
int k = c % 4;
int l = (32 + 2 * e + 2 * i - h - k) % 7;
int m = (a + 11 * h + 22 * l) / 451;
int easterSundayMonth = (h + l - 7 * m + 114) / 31;
int easterSundayDay = ((h + l - 7 * m + 114) % 31) + 1;
int month = date.getMonthValue();
int day = date.getDayOfMonth();
return (easterSundayMonth == month) && (easterSundayDay == day);
}
|
java
|
{
"resource": ""
}
|
q3404
|
FloatingpointDate.getDateFromFloatingPointDate
|
train
|
public static LocalDateTime getDateFromFloatingPointDate(LocalDateTime referenceDate, double floatingPointDate) {
if(referenceDate == null) {
return null;
}
Duration duration = Duration.ofSeconds(Math.round(floatingPointDate * SECONDS_PER_DAY));
return referenceDate.plus(duration);
}
|
java
|
{
"resource": ""
}
|
q3405
|
FloatingpointDate.getFloatingPointDateFromDate
|
train
|
public static double getFloatingPointDateFromDate(LocalDateTime referenceDate, LocalDateTime date) {
Duration duration = Duration.between(referenceDate, date);
return ((double)duration.getSeconds()) / SECONDS_PER_DAY;
}
|
java
|
{
"resource": ""
}
|
q3406
|
FloatingpointDate.getDateFromFloatingPointDate
|
train
|
public static LocalDate getDateFromFloatingPointDate(LocalDate referenceDate, double floatingPointDate) {
if(referenceDate == null) {
return null;
}
return referenceDate.plusDays((int)Math.round(floatingPointDate*365.0));
}
|
java
|
{
"resource": ""
}
|
q3407
|
PoissonDistribution.inverseCumulativeDistribution
|
train
|
public double inverseCumulativeDistribution(double x) {
double p = Math.exp(-lambda);
double dp = p;
int k = 0;
while(x > p) {
k++;
dp *= lambda / k;
p += dp;
}
return k;
}
|
java
|
{
"resource": ""
}
|
q3408
|
CurveInterpolation.addPoint
|
train
|
protected void addPoint(double time, RandomVariable value, boolean isParameter) {
synchronized (rationalFunctionInterpolationLazyInitLock) {
if(interpolationEntity == InterpolationEntity.LOG_OF_VALUE_PER_TIME && time == 0) {
boolean containsOne = false; int index=0;
for(int i = 0; i< value.size(); i++){if(value.get(i)==1.0) {containsOne = true; index=i; break;}}
if(containsOne && isParameter == false) {
return;
} else {
throw new IllegalArgumentException("The interpolation method LOG_OF_VALUE_PER_TIME does not allow to add a value at time = 0 other than 1.0 (received 1 at index" + index + ").");
}
}
RandomVariable interpolationEntityValue = interpolationEntityFromValue(value, time);
int index = getTimeIndex(time);
if(index >= 0) {
if(points.get(index).value == interpolationEntityValue) {
return; // Already in list
} else if(isParameter) {
return;
} else {
throw new RuntimeException("Trying to add a value for a time for which another value already exists.");
}
}
else {
// Insert the new point, retain ordering.
Point point = new Point(time, interpolationEntityValue, isParameter);
points.add(-index-1, point);
if(isParameter) {
// Add this point also to the list of parameters
int parameterIndex = getParameterIndex(time);
if(parameterIndex >= 0) {
new RuntimeException("CurveFromInterpolationPoints inconsistent.");
}
pointsBeingParameters.add(-parameterIndex-1, point);
}
}
rationalFunctionInterpolation = null;
curveCacheReference = null;
}
}
|
java
|
{
"resource": ""
}
|
q3409
|
SchedulePrototype.getOffsetCodeFromSchedule
|
train
|
public static String getOffsetCodeFromSchedule(Schedule schedule) {
double doubleLength = 0;
for(int i = 0; i < schedule.getNumberOfPeriods(); i ++) {
doubleLength += schedule.getPeriodLength(i);
}
doubleLength /= schedule.getNumberOfPeriods();
doubleLength *= 12;
int periodLength = (int) Math.round(doubleLength);
String offsetCode = periodLength + "M";
return offsetCode;
}
|
java
|
{
"resource": ""
}
|
q3410
|
SchedulePrototype.getOffsetCodeFromCurveName
|
train
|
public static String getOffsetCodeFromCurveName(String curveName) {
if(curveName == null || curveName.length() == 0) {
return null;
}
String[] splits = curveName.split("(?<=\\D)(?=\\d)");
String offsetCode = splits[splits.length-1];
if(!Character.isDigit(offsetCode.charAt(0))) {
return null;
}
offsetCode = offsetCode.split("(?<=[A-Za-z])(?=.)", 2)[0];
offsetCode = offsetCode.replaceAll( "[\\W_]", "" );
return offsetCode;
}
|
java
|
{
"resource": ""
}
|
q3411
|
SchedulePrototype.generateScheduleDescriptor
|
train
|
public ScheduleDescriptor generateScheduleDescriptor(LocalDate startDate, LocalDate endDate) {
return new ScheduleDescriptor(startDate, endDate, getFrequency(), getDaycountConvention(), getShortPeriodConvention(), getDateRollConvention(),
getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());
}
|
java
|
{
"resource": ""
}
|
q3412
|
SchedulePrototype.generateSchedule
|
train
|
public Schedule generateSchedule(LocalDate referenceDate, LocalDate startDate, LocalDate endDate) {
return ScheduleGenerator.createScheduleFromConventions(referenceDate, startDate, endDate, getFrequency(), getDaycountConvention(),
getShortPeriodConvention(), getDateRollConvention(), getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), isUseEndOfMonth());
}
|
java
|
{
"resource": ""
}
|
q3413
|
ScheduleGenerator.createScheduleFromConventions
|
train
|
@Deprecated
public static ScheduleInterface createScheduleFromConventions(
LocalDate referenceDate,
LocalDate startDate,
String frequency,
double maturity,
String daycountConvention,
String shortPeriodConvention
)
{
return createScheduleFromConventions(
referenceDate,
startDate,
frequency,
maturity,
daycountConvention,
shortPeriodConvention,
"UNADJUSTED",
new BusinessdayCalendarAny(),
0, 0);
}
|
java
|
{
"resource": ""
}
|
q3414
|
CalibratedCurves.getCalibrationProductForSymbol
|
train
|
public AnalyticProductInterface getCalibrationProductForSymbol(String symbol) {
/*
* The internal data structure is not optimal here (a map would make more sense here),
* if the user does not require access to the products, we would allow non-unique symbols.
* Hence we store both in two side by side vectors.
*/
for(int i=0; i<calibrationProductsSymbols.size(); i++) {
String calibrationProductSymbol = calibrationProductsSymbols.get(i);
if(calibrationProductSymbol.equals(symbol)) {
return calibrationProducts.get(i);
}
}
return null;
}
|
java
|
{
"resource": ""
}
|
q3415
|
BermudanDigitalOption.getValue
|
train
|
@Override
public RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException {
if(exerciseMethod == ExerciseMethod.UPPER_BOUND_METHOD) {
// Find optimal lambda
GoldenSectionSearch optimizer = new GoldenSectionSearch(-1.0, 1.0);
while(!optimizer.isDone()) {
double lambda = optimizer.getNextPoint();
double value = this.getValues(evaluationTime, model, lambda).getAverage();
optimizer.setValue(value);
}
return getValues(evaluationTime, model, optimizer.getBestPoint());
}
else {
return getValues(evaluationTime, model, 0.0);
}
}
|
java
|
{
"resource": ""
}
|
q3416
|
HazardCurve.createHazardCurveFromSurvivalProbabilities
|
train
|
public static HazardCurve createHazardCurveFromSurvivalProbabilities(String name, double[] times, double[] givenSurvivalProbabilities){
HazardCurve survivalProbabilities = new HazardCurve(name);
for(int timeIndex=0; timeIndex<times.length;timeIndex++) {
survivalProbabilities.addSurvivalProbability(times[timeIndex], givenSurvivalProbabilities[timeIndex], times[timeIndex] > 0);
}
return survivalProbabilities;
}
|
java
|
{
"resource": ""
}
|
q3417
|
SwaptionDataLattice.convertLattice
|
train
|
public SwaptionDataLattice convertLattice(QuotingConvention targetConvention, double displacement, AnalyticModel model) {
if(displacement != 0 && targetConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) {
throw new IllegalArgumentException("SwaptionDataLattice only supports displacement, when using QuotingCOnvention.PAYERVOLATILITYLOGNORMAL.");
}
//Reverse sign of moneyness, if switching between payer and receiver convention.
int reverse = ((targetConvention == QuotingConvention.RECEIVERPRICE) ^ (quotingConvention == QuotingConvention.RECEIVERPRICE)) ? -1 : 1;
List<Integer> maturities = new ArrayList<>();
List<Integer> tenors = new ArrayList<>();
List<Integer> moneynesss = new ArrayList<>();
List<Double> values = new ArrayList<>();
for(DataKey key : entryMap.keySet()) {
maturities.add(key.maturity);
tenors.add(key.tenor);
moneynesss.add(key.moneyness * reverse);
values.add(getValue(key.maturity, key.tenor, key.moneyness, targetConvention, displacement, model));
}
return new SwaptionDataLattice(referenceDate, targetConvention, displacement,
forwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule,
maturities.stream().mapToInt(Integer::intValue).toArray(),
tenors.stream().mapToInt(Integer::intValue).toArray(),
moneynesss.stream().mapToInt(Integer::intValue).toArray(),
values.stream().mapToDouble(Double::doubleValue).toArray());
}
|
java
|
{
"resource": ""
}
|
q3418
|
SwaptionDataLattice.append
|
train
|
public SwaptionDataLattice append(SwaptionDataLattice other, AnalyticModel model) {
SwaptionDataLattice combined = new SwaptionDataLattice(referenceDate, quotingConvention, displacement,
forwardCurveName, discountCurveName, floatMetaSchedule, fixMetaSchedule);
combined.entryMap.putAll(entryMap);
if(quotingConvention == other.quotingConvention && displacement == other.displacement) {
combined.entryMap.putAll(other.entryMap);
} else {
SwaptionDataLattice converted = other.convertLattice(quotingConvention, displacement, model);
combined.entryMap.putAll(converted.entryMap);
}
return combined;
}
|
java
|
{
"resource": ""
}
|
q3419
|
SwaptionDataLattice.getMoneynessAsOffsets
|
train
|
public double[] getMoneynessAsOffsets() {
DoubleStream moneyness = getGridNodesPerMoneyness().keySet().stream().mapToDouble(Integer::doubleValue);
if(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {
moneyness = moneyness.map(new DoubleUnaryOperator() {
@Override
public double applyAsDouble(double x) {
return x * 0.01;
}
});
} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {
moneyness = moneyness.map(new DoubleUnaryOperator() {
@Override
public double applyAsDouble(double x) {
return - x * 0.0001;
}
});
} else {
moneyness = moneyness.map(new DoubleUnaryOperator() {
@Override
public double applyAsDouble(double x) {
return x * 0.0001;
}
});
}
return moneyness.toArray();
}
|
java
|
{
"resource": ""
}
|
q3420
|
SwaptionDataLattice.getMaturities
|
train
|
public double[] getMaturities(double moneyness) {
int[] maturitiesInMonths = getMaturities(convertMoneyness(moneyness));
double[] maturities = new double[maturitiesInMonths.length];
for(int index = 0; index < maturities.length; index++) {
maturities[index] = convertMaturity(maturitiesInMonths[index]);
}
return maturities;
}
|
java
|
{
"resource": ""
}
|
q3421
|
SwaptionDataLattice.getTenors
|
train
|
public int[] getTenors() {
Set<Integer> setTenors = new HashSet<>();
for(int moneyness : getGridNodesPerMoneyness().keySet()) {
setTenors.addAll(Arrays.asList((IntStream.of(keyMap.get(moneyness)[1]).boxed().toArray(Integer[]::new))));
}
return setTenors.stream().sorted().mapToInt(Integer::intValue).toArray();
}
|
java
|
{
"resource": ""
}
|
q3422
|
SwaptionDataLattice.getTenors
|
train
|
public int[] getTenors(int moneynessBP, int maturityInMonths) {
try {
List<Integer> ret = new ArrayList<>();
for(int tenor : getGridNodesPerMoneyness().get(moneynessBP)[1]) {
if(containsEntryFor(maturityInMonths, tenor, moneynessBP)) {
ret.add(tenor);
}
}
return ret.stream().mapToInt(Integer::intValue).toArray();
} catch (NullPointerException e) {
return new int[0];
}
}
|
java
|
{
"resource": ""
}
|
q3423
|
SwaptionDataLattice.getTenors
|
train
|
public double[] getTenors(double moneyness, double maturity) {
int maturityInMonths = (int) Math.round(maturity * 12);
int[] tenorsInMonths = getTenors(convertMoneyness(moneyness), maturityInMonths);
double[] tenors = new double[tenorsInMonths.length];
for(int index = 0; index < tenors.length; index++) {
tenors[index] = convertTenor(maturityInMonths, tenorsInMonths[index]);
}
return tenors;
}
|
java
|
{
"resource": ""
}
|
q3424
|
SwaptionDataLattice.convertMoneyness
|
train
|
private int convertMoneyness(double moneyness) {
if(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {
return (int) Math.round(moneyness * 100);
} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {
return - (int) Math.round(moneyness * 10000);
} else {
return (int) Math.round(moneyness * 10000);
}
}
|
java
|
{
"resource": ""
}
|
q3425
|
SwaptionDataLattice.convertMaturity
|
train
|
private double convertMaturity(int maturityInMonths) {
Schedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, 12);
return schedule.getFixing(0);
}
|
java
|
{
"resource": ""
}
|
q3426
|
SwaptionDataLattice.convertTenor
|
train
|
private double convertTenor(int maturityInMonths, int tenorInMonths) {
Schedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, tenorInMonths);
return schedule.getPayment(schedule.getNumberOfPeriods()-1);
}
|
java
|
{
"resource": ""
}
|
q3427
|
SwaptionDataLattice.containsEntryFor
|
train
|
public boolean containsEntryFor(int maturityInMonths, int tenorInMonths, int moneynessBP) {
return entryMap.containsKey(new DataKey(maturityInMonths, tenorInMonths, moneynessBP));
}
|
java
|
{
"resource": ""
}
|
q3428
|
SwaptionDataLattice.convertToConvention
|
train
|
private double convertToConvention(double value, DataKey key, QuotingConvention toConvention, double toDisplacement,
QuotingConvention fromConvention, double fromDisplacement, AnalyticModel model) {
if(toConvention == fromConvention) {
if(toConvention != QuotingConvention.PAYERVOLATILITYLOGNORMAL) {
return value;
} else {
if(toDisplacement == fromDisplacement) {
return value;
} else {
return convertToConvention(convertToConvention(value, key, QuotingConvention.PAYERPRICE, 0, fromConvention, fromDisplacement, model),
key, toConvention, toDisplacement, QuotingConvention.PAYERPRICE, 0, model);
}
}
}
Schedule floatSchedule = floatMetaSchedule.generateSchedule(getReferenceDate(), key.maturity, key.tenor);
Schedule fixSchedule = fixMetaSchedule.generateSchedule(getReferenceDate(), key.maturity, key.tenor);
double forward = Swap.getForwardSwapRate(fixSchedule, floatSchedule, model.getForwardCurve(forwardCurveName), model);
double optionMaturity = floatSchedule.getFixing(0);
double offset = key.moneyness /10000.0;
double optionStrike = forward + (quotingConvention == QuotingConvention.RECEIVERPRICE ? -offset : offset);
double payoffUnit = SwapAnnuity.getSwapAnnuity(fixSchedule.getFixing(0), fixSchedule, model.getDiscountCurve(discountCurveName), model);
if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.PAYERVOLATILITYLOGNORMAL)) {
return AnalyticFormulas.blackScholesGeneralizedOptionValue(forward + fromDisplacement, value, optionMaturity, optionStrike + fromDisplacement, payoffUnit);
}
else if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.PAYERVOLATILITYNORMAL)) {
return AnalyticFormulas.bachelierOptionValue(forward, value, optionMaturity, optionStrike, payoffUnit);
}
else if(toConvention.equals(QuotingConvention.PAYERPRICE) && fromConvention.equals(QuotingConvention.RECEIVERPRICE)) {
return value + (forward - optionStrike) * payoffUnit;
}
else if(toConvention.equals(QuotingConvention.PAYERVOLATILITYLOGNORMAL) && fromConvention.equals(QuotingConvention.PAYERPRICE)) {
return AnalyticFormulas.blackScholesOptionImpliedVolatility(forward + toDisplacement, optionMaturity, optionStrike + toDisplacement, payoffUnit, value);
}
else if(toConvention.equals(QuotingConvention.PAYERVOLATILITYNORMAL) && fromConvention.equals(QuotingConvention.PAYERPRICE)) {
return AnalyticFormulas.bachelierOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, value);
}
else if(toConvention.equals(QuotingConvention.RECEIVERPRICE) && fromConvention.equals(QuotingConvention.PAYERPRICE)) {
return value - (forward - optionStrike) * payoffUnit;
}
else {
return convertToConvention(convertToConvention(value, key, QuotingConvention.PAYERPRICE, 0, fromConvention, fromDisplacement, model),
key, toConvention, toDisplacement, QuotingConvention.PAYERPRICE, 0, model);
}
}
|
java
|
{
"resource": ""
}
|
q3429
|
Bond.getCouponPayment
|
train
|
public double getCouponPayment(int periodIndex, AnalyticModel model) {
ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);
if(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {
throw new IllegalArgumentException("No forward curve with name '" + forwardCurveName + "' was found in the model:\n" + model.toString());
}
double periodLength = schedule.getPeriodLength(periodIndex);
double couponPayment=fixedCoupon ;
if(forwardCurve != null ) {
couponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex));
}
return couponPayment*periodLength;
}
|
java
|
{
"resource": ""
}
|
q3430
|
Bond.getValueWithGivenSpreadOverCurve
|
train
|
public double getValueWithGivenSpreadOverCurve(double evaluationTime,Curve referenceCurve, double spread, AnalyticModel model) {
double value=0;
for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods();periodIndex++) {
double paymentDate = schedule.getPayment(periodIndex);
value+= paymentDate>evaluationTime ? getCouponPayment(periodIndex,model)*Math.exp(-spread*paymentDate)*referenceCurve.getValue(paymentDate): 0.0;
}
double paymentDate = schedule.getPayment(schedule.getNumberOfPeriods()-1);
return paymentDate>evaluationTime ? value+Math.exp(-spread*paymentDate)*referenceCurve.getValue(paymentDate):0.0;
}
|
java
|
{
"resource": ""
}
|
q3431
|
Bond.getValueWithGivenYield
|
train
|
public double getValueWithGivenYield(double evaluationTime, double rate, AnalyticModel model) {
DiscountCurve referenceCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors("referenceCurve", new double[] {0.0, 1.0}, new double[] {1.0, 1.0});
return getValueWithGivenSpreadOverCurve(evaluationTime, referenceCurve, rate, model);
}
|
java
|
{
"resource": ""
}
|
q3432
|
Bond.getSpread
|
train
|
public double getSpread(double bondPrice, Curve referenceCurve, AnalyticModel model) {
GoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);
while(search.getAccuracy() > 1E-11 && !search.isDone()) {
double x = search.getNextPoint();
double fx=getValueWithGivenSpreadOverCurve(0.0,referenceCurve,x,model);
double y = (bondPrice-fx)*(bondPrice-fx);
search.setValue(y);
}
return search.getBestPoint();
}
|
java
|
{
"resource": ""
}
|
q3433
|
Bond.getYield
|
train
|
public double getYield(double bondPrice, AnalyticModel model) {
GoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);
while(search.getAccuracy() > 1E-11 && !search.isDone()) {
double x = search.getNextPoint();
double fx=getValueWithGivenYield(0.0,x,model);
double y = (bondPrice-fx)*(bondPrice-fx);
search.setValue(y);
}
return search.getBestPoint();
}
|
java
|
{
"resource": ""
}
|
q3434
|
Bond.getAccruedInterest
|
train
|
public double getAccruedInterest(LocalDate date, AnalyticModel model) {
int periodIndex=schedule.getPeriodIndex(date);
Period period=schedule.getPeriod(periodIndex);
DayCountConvention dcc= schedule.getDaycountconvention();
double accruedInterest=getCouponPayment(periodIndex,model)*(dcc.getDaycountFraction(period.getPeriodStart(), date))/schedule.getPeriodLength(periodIndex);
return accruedInterest;
}
|
java
|
{
"resource": ""
}
|
q3435
|
Bond.getAccruedInterest
|
train
|
public double getAccruedInterest(double time, AnalyticModel model) {
LocalDate date= FloatingpointDate.getDateFromFloatingPointDate(schedule.getReferenceDate(), time);
return getAccruedInterest(date, model);
}
|
java
|
{
"resource": ""
}
|
q3436
|
AnalyticFormulas.blackScholesOptionTheta
|
train
|
public static double blackScholesOptionTheta(
double initialStockValue,
double riskFreeRate,
double volatility,
double optionMaturity,
double optionStrike)
{
if(optionStrike <= 0.0 || optionMaturity <= 0.0)
{
// The Black-Scholes model does not consider it being an option
return 0.0;
}
else
{
// Calculate theta
double dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));
double dMinus = dPlus - volatility * Math.sqrt(optionMaturity);
double theta = volatility * Math.exp(-0.5*dPlus*dPlus) / Math.sqrt(2.0 * Math.PI) / Math.sqrt(optionMaturity) / 2 * initialStockValue + riskFreeRate * optionStrike * Math.exp(-riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);
return theta;
}
}
|
java
|
{
"resource": ""
}
|
q3437
|
AbstractMonteCarloProduct.getValues
|
train
|
public Map<String, Object> getValues(double evaluationTime, MonteCarloSimulationInterface model) throws CalculationException
{
RandomVariableInterface values = getValue(evaluationTime, model);
if(values == null) {
return null;
}
// Sum up values on path
double value = values.getAverage();
double error = values.getStandardError();
Map<String, Object> results = new HashMap<String, Object>();
results.put("value", value);
results.put("error", error);
return results;
}
|
java
|
{
"resource": ""
}
|
q3438
|
RationalFunctionInterpolation.getValue
|
train
|
public double getValue(double x)
{
synchronized(interpolatingRationalFunctionsLazyInitLock) {
if(interpolatingRationalFunctions == null) {
doCreateRationalFunctions();
}
}
// Get interpolating rational function for the given point x
int pointIndex = java.util.Arrays.binarySearch(points, x);
if(pointIndex >= 0) {
return values[pointIndex];
}
int intervallIndex = -pointIndex-2;
// Check for extrapolation
if(intervallIndex < 0) {
// Extrapolation
if(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) {
return values[0];
} else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) {
return values[0]+(values[1]-values[0])/(points[1]-points[0])*(x-points[0]);
} else {
intervallIndex = 0;
}
}
else if(intervallIndex > points.length-2) {
// Extrapolation
if(this.extrapolationMethod == ExtrapolationMethod.CONSTANT) {
return values[points.length-1];
} else if(this.extrapolationMethod == ExtrapolationMethod.LINEAR) {
return values[points.length-1]+(values[points.length-2]-values[points.length-1])/(points[points.length-2]-points[points.length-1])*(x-points[points.length-1]);
} else {
intervallIndex = points.length-2;
}
}
RationalFunction rationalFunction = interpolatingRationalFunctions[intervallIndex];
// Calculate interpolating value
return rationalFunction.getValue(x-points[intervallIndex]);
}
|
java
|
{
"resource": ""
}
|
q3439
|
RandomVariableUniqueVariable.getGradient
|
train
|
public RandomVariable[] getGradient(){
// for now let us take the case for output-dimension equal to one!
int numberOfVariables = getNumberOfVariablesInList();
int numberOfCalculationSteps = factory.getNumberOfEntriesInList();
RandomVariable[] omega_hat = new RandomVariable[numberOfCalculationSteps];
// first entry gets initialized
omega_hat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);
/*
* TODO: Find way that calculations form here on are not 'recorded' by the factory
* IDEA: Let the calculation below run on {@link RandomVariableFromDoubleArray}, ie cast everything down!
* */
for(int functionIndex = numberOfCalculationSteps - 2; functionIndex > 0; functionIndex--){
// apply chain rule
omega_hat[functionIndex] = new RandomVariableFromDoubleArray(0.0);
/*TODO: save all D_{i,j}*\omega_j in vector and sum up later */
for(RandomVariableUniqueVariable parent:parentsVariables){
int variableIndex = parent.getVariableID();
omega_hat[functionIndex] = omega_hat[functionIndex].add(getPartialDerivative(functionIndex, variableIndex).mult(omega_hat[variableIndex]));
}
}
/* Due to the fact that we can still introduce 'new' true variables on the fly they are NOT the last couple of indices!
* Thus save the indices of the true variables and recover them after finalizing all the calculations
* IDEA: quit calculation after minimal true variable index is reached */
RandomVariable[] gradient = new RandomVariable[numberOfVariables];
/* TODO: sort array in correct manner! */
int[] indicesOfVariables = getIDsOfVariablesInList();
for(int i = 0; i < numberOfVariables; i++){
gradient[i] = omega_hat[numberOfCalculationSteps - numberOfVariables + indicesOfVariables[i]];
}
return gradient;
}
|
java
|
{
"resource": ""
}
|
q3440
|
AbstractVolatilitySurfaceParametric.getCloneCalibrated
|
train
|
public AbstractVolatilitySurfaceParametric getCloneCalibrated(final AnalyticModel calibrationModel, final Vector<AnalyticProduct> calibrationProducts, final List<Double> calibrationTargetValues, Map<String,Object> calibrationParameters, final ParameterTransformation parameterTransformation, OptimizerFactory optimizerFactory) throws SolverException {
if(calibrationParameters == null) {
calibrationParameters = new HashMap<>();
}
Integer maxIterationsParameter = (Integer)calibrationParameters.get("maxIterations");
Double accuracyParameter = (Double)calibrationParameters.get("accuracy");
Double evaluationTimeParameter = (Double)calibrationParameters.get("evaluationTime");
// @TODO currently ignored, we use the setting form the OptimizerFactory
int maxIterations = maxIterationsParameter != null ? maxIterationsParameter.intValue() : 600;
double accuracy = accuracyParameter != null ? accuracyParameter.doubleValue() : 1E-8;
double evaluationTime = evaluationTimeParameter != null ? evaluationTimeParameter.doubleValue() : 0.0;
AnalyticModel model = calibrationModel.addVolatilitySurfaces(this);
Solver solver = new Solver(model, calibrationProducts, calibrationTargetValues, parameterTransformation, evaluationTime, optimizerFactory);
Set<ParameterObject> objectsToCalibrate = new HashSet<>();
objectsToCalibrate.add(this);
AnalyticModel modelCalibrated = solver.getCalibratedModel(objectsToCalibrate);
// Diagnostic output
if (logger.isLoggable(Level.FINE)) {
double lastAccuracy = solver.getAccuracy();
int lastIterations = solver.getIterations();
logger.fine("The solver achieved an accuracy of " + lastAccuracy + " in " + lastIterations + ".");
}
return (AbstractVolatilitySurfaceParametric)modelCalibrated.getVolatilitySurface(this.getName());
}
|
java
|
{
"resource": ""
}
|
q3441
|
SeasonalCurve.computeSeasonalAdjustments
|
train
|
public static double[] computeSeasonalAdjustments(double[] realizedCPIValues, int lastMonth, int numberOfYearsToAverage) {
/*
* Cacluate average log returns
*/
double[] averageLogReturn = new double[12];
Arrays.fill(averageLogReturn, 0.0);
for(int arrayIndex = 0; arrayIndex < 12*numberOfYearsToAverage; arrayIndex++){
int month = (((((lastMonth-1 - arrayIndex) % 12) + 12) % 12));
double logReturn = Math.log(realizedCPIValues[realizedCPIValues.length - 1 - arrayIndex] / realizedCPIValues[realizedCPIValues.length - 2 - arrayIndex]);
averageLogReturn[month] += logReturn/numberOfYearsToAverage;
}
/*
* Normalize
*/
double sum = 0.0;
for(int index = 0; index < averageLogReturn.length; index++){
sum += averageLogReturn[index];
}
double averageSeasonal = sum / averageLogReturn.length;
double[] seasonalAdjustments = new double[averageLogReturn.length];
for(int index = 0; index < seasonalAdjustments.length; index++){
seasonalAdjustments[index] = averageLogReturn[index] - averageSeasonal;
}
// Annualize seasonal adjustments
for(int index = 0; index < seasonalAdjustments.length; index++){
seasonalAdjustments[index] = seasonalAdjustments[index] * 12;
}
return seasonalAdjustments;
}
|
java
|
{
"resource": ""
}
|
q3442
|
ProductFactoryCascade.addFactoryBefore
|
train
|
public ProductFactoryCascade<T> addFactoryBefore(ProductFactory<? extends T> factory) {
ArrayList<ProductFactory<? extends T>> factories = new ArrayList<ProductFactory<? extends T>>(this.factories.size()+1);
factories.addAll(this.factories);
factories.add(0, factory);
return new ProductFactoryCascade<>(factories);
}
|
java
|
{
"resource": ""
}
|
q3443
|
ForwardRateVolatilitySurfaceCurvature.getValues
|
train
|
public RandomVariable getValues(double evaluationTime, LIBORMarketModel model) {
if(evaluationTime > 0) {
throw new RuntimeException("Forward start evaluation currently not supported.");
}
// Fetch the covariance model of the model
LIBORCovarianceModel covarianceModel = model.getCovarianceModel();
// We sum over all forward rates
int numberOfComponents = covarianceModel.getLiborPeriodDiscretization().getNumberOfTimeSteps();
// Accumulator
RandomVariable integratedLIBORCurvature = new RandomVariableFromDoubleArray(0.0);
for(int componentIndex = 0; componentIndex < numberOfComponents; componentIndex++) {
// Integrate from 0 up to the fixing of the rate
double timeEnd = covarianceModel.getLiborPeriodDiscretization().getTime(componentIndex);
int timeEndIndex = covarianceModel.getTimeDiscretization().getTimeIndex(timeEnd);
// If timeEnd is not in the time discretization we get timeEndIndex = -insertionPoint-1. In that case, we use the index prior to the insertionPoint
if(timeEndIndex < 0) {
timeEndIndex = -timeEndIndex - 2;
}
// Sum squared second derivative of the variance for all components at this time step
RandomVariable integratedLIBORCurvatureCurrentRate = new RandomVariableFromDoubleArray(0.0);
for(int timeIndex = 0; timeIndex < timeEndIndex-2; timeIndex++) {
double timeStep1 = covarianceModel.getTimeDiscretization().getTimeStep(timeIndex);
double timeStep2 = covarianceModel.getTimeDiscretization().getTimeStep(timeIndex+1);
RandomVariable covarianceLeft = covarianceModel.getCovariance(timeIndex+0, componentIndex, componentIndex, null);
RandomVariable covarianceCenter = covarianceModel.getCovariance(timeIndex+1, componentIndex, componentIndex, null);
RandomVariable covarianceRight = covarianceModel.getCovariance(timeIndex+2, componentIndex, componentIndex, null);
// Calculate second derivative
RandomVariable curvatureSquared = covarianceRight.sub(covarianceCenter.mult(2.0)).add(covarianceLeft);
curvatureSquared = curvatureSquared.div(timeStep1 * timeStep2);
// Take square
curvatureSquared = curvatureSquared.squared();
// Integrate over time
integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.add(curvatureSquared.mult(timeStep1));
}
// Empty intervall - skip
if(timeEnd == 0) {
continue;
}
// Average over time
integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.div(timeEnd);
// Take square root
integratedLIBORCurvatureCurrentRate = integratedLIBORCurvatureCurrentRate.sqrt();
// Take max over all forward rates
integratedLIBORCurvature = integratedLIBORCurvature.add(integratedLIBORCurvatureCurrentRate);
}
integratedLIBORCurvature = integratedLIBORCurvature.div(numberOfComponents);
return integratedLIBORCurvature.sub(tolerance).floor(0.0);
}
|
java
|
{
"resource": ""
}
|
q3444
|
AbstractLIBORCovarianceModel.getFactorLoading
|
train
|
public RandomVariableInterface[] getFactorLoading(double time, double component, RandomVariableInterface[] realizationAtTimeIndex) {
int componentIndex = liborPeriodDiscretization.getTimeIndex(component);
if(componentIndex < 0) {
componentIndex = -componentIndex - 2;
}
return getFactorLoading(time, componentIndex, realizationAtTimeIndex);
}
|
java
|
{
"resource": ""
}
|
q3445
|
BermudanSwaptionFromSwapSchedules.getValueUnderlyingNumeraireRelative
|
train
|
private RandomVariable getValueUnderlyingNumeraireRelative(LIBORModelMonteCarloSimulationModel model, Schedule legSchedule, boolean paysFloat, double swaprate, double notional) throws CalculationException {
RandomVariable value = model.getRandomVariableForConstant(0.0);
for(int periodIndex = legSchedule.getNumberOfPeriods() - 1; periodIndex >= 0; periodIndex--) {
double fixingTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getFixing());
double paymentTime = FloatingpointDate.getFloatingPointDateFromDate(model.getReferenceDate().toLocalDate(), legSchedule.getPeriod(periodIndex).getPayment());
double periodLength = legSchedule.getPeriodLength(periodIndex);
RandomVariable numeraireAtPayment = model.getNumeraire(paymentTime);
RandomVariable monteCarloProbabilitiesAtPayment = model.getMonteCarloWeights(paymentTime);
if(swaprate != 0.0) {
RandomVariable periodCashFlowFix = model.getRandomVariableForConstant(swaprate * periodLength * notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);
value = value.add(periodCashFlowFix);
}
if(paysFloat) {
RandomVariable libor = model.getLIBOR(fixingTime, fixingTime, paymentTime);
RandomVariable periodCashFlowFloat = libor.mult(periodLength).mult(notional).div(numeraireAtPayment).mult(monteCarloProbabilitiesAtPayment);
value = value.add(periodCashFlowFloat);
}
}
return value;
}
|
java
|
{
"resource": ""
}
|
q3446
|
BermudanSwaptionFromSwapSchedules.getConditionalExpectationEstimator
|
train
|
public ConditionalExpectationEstimator getConditionalExpectationEstimator(double exerciseTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException {
RandomVariable[] regressionBasisFunctions = regressionBasisFunctionProvider.getBasisFunctions(exerciseTime, model);
return conditionalExpectationRegressionFactory.getConditionalExpectationEstimator(regressionBasisFunctions, regressionBasisFunctions);
}
|
java
|
{
"resource": ""
}
|
q3447
|
LIBORMarketModelStandard.getNumeraire
|
train
|
@Override
public RandomVariable getNumeraire(double time) throws CalculationException {
int timeIndex = getLiborPeriodIndex(time);
if(timeIndex < 0) {
// Interpolation of Numeraire: linear interpolation of the reciprocal.
int lowerIndex = -timeIndex -1;
int upperIndex = -timeIndex;
double alpha = (time-getLiborPeriod(lowerIndex)) / (getLiborPeriod(upperIndex) - getLiborPeriod(lowerIndex));
return getNumeraire(getLiborPeriod(upperIndex)).invert().mult(alpha).add(getNumeraire(getLiborPeriod(lowerIndex)).invert().mult(1.0-alpha)).invert();
}
// Calculate the numeraire, when time is part of liborPeriodDiscretization
// Get the start of the product
int firstLiborIndex = getLiborPeriodIndex(time);
if(firstLiborIndex < 0) {
throw new CalculationException("Simulation time discretization not part of forward rate tenor discretization.");
}
// Get the end of the product
int lastLiborIndex = liborPeriodDiscretization.getNumberOfTimeSteps()-1;
if(measure == Measure.SPOT) {
// Spot measure
firstLiborIndex = 0;
lastLiborIndex = getLiborPeriodIndex(time)-1;
}
/*
* Calculation of the numeraire
*/
// Initialize to 1.0
RandomVariable numeraire = new RandomVariableFromDoubleArray(time, 1.0);
// The product
for(int liborIndex = firstLiborIndex; liborIndex<=lastLiborIndex; liborIndex++) {
RandomVariable libor = getLIBOR(getTimeIndex(Math.min(time,liborPeriodDiscretization.getTime(liborIndex))), liborIndex);
double periodLength = liborPeriodDiscretization.getTimeStep(liborIndex);
if(measure == Measure.SPOT) {
numeraire = numeraire.accrue(libor, periodLength);
}
else {
numeraire = numeraire.discount(libor, periodLength);
}
}
/*
* Adjust for discounting
*/
if(discountCurve != null) {
DiscountCurve discountcountCurveFromForwardPerformance = new DiscountCurveFromForwardCurve(forwardRateCurve);
double deterministicNumeraireAdjustment = discountcountCurveFromForwardPerformance.getDiscountFactor(time) / discountCurve.getDiscountFactor(time);
numeraire = numeraire.mult(deterministicNumeraireAdjustment);
}
return numeraire;
}
|
java
|
{
"resource": ""
}
|
q3448
|
FDMThetaMethod.u_neg_inf
|
train
|
private double u_neg_inf(double x, double tau) {
return f(boundaryCondition.getValueAtLowerBoundary(model, f_t(tau), f_s(x)), x, tau);
}
|
java
|
{
"resource": ""
}
|
q3449
|
LinearRegression.getRegressionCoefficients
|
train
|
public double[] getRegressionCoefficients(RandomVariable value) {
if(basisFunctions.length == 0) {
return new double[] { };
}
else if(basisFunctions.length == 1) {
/*
* Regression with one basis function is just a projection on that vector. <b,x>/<b,b>
*/
return new double[] { value.mult(basisFunctions[0]).getAverage() / basisFunctions[0].squared().getAverage() };
}
else if(basisFunctions.length == 2) {
/*
* Regression with two basis functions can be solved explicitly if determinant != 0 (otherwise we will fallback to SVD)
*/
double a = basisFunctions[0].squared().getAverage();
double b = basisFunctions[0].mult(basisFunctions[1]).average().squared().doubleValue();
double c = b;
double d = basisFunctions[1].squared().getAverage();
double determinant = (a * d - b * c);
if(determinant != 0) {
double x = value.mult(basisFunctions[0]).getAverage();
double y = value.mult(basisFunctions[1]).getAverage();
double alpha0 = (d * x - b * y) / determinant;
double alpha1 = (a * y - c * x) / determinant;
return new double[] { alpha0, alpha1 };
}
}
/*
* General case
*/
// Build regression matrix
double[][] BTB = new double[basisFunctions.length][basisFunctions.length];
for(int i=0; i<basisFunctions.length; i++) {
for(int j=0; j<=i; j++) {
double covariance = basisFunctions[i].mult(basisFunctions[j]).getAverage();
BTB[i][j] = covariance;
BTB[j][i] = covariance;
}
}
double[] BTX = new double[basisFunctions.length];
for(int i=0; i<basisFunctions.length; i++) {
double covariance = basisFunctions[i].mult(value).getAverage();
BTX[i] = covariance;
}
return LinearAlgebra.solveLinearEquationLeastSquare(BTB, BTX);
}
|
java
|
{
"resource": ""
}
|
q3450
|
FPMLParser.getSwapProductDescriptor
|
train
|
private ProductDescriptor getSwapProductDescriptor(Element trade) {
InterestRateSwapLegProductDescriptor legReceiver = null;
InterestRateSwapLegProductDescriptor legPayer = null;
NodeList legs = trade.getElementsByTagName("swapStream");
for(int legIndex = 0; legIndex < legs.getLength(); legIndex++) {
Element leg = (Element) legs.item(legIndex);
boolean isPayer = leg.getElementsByTagName("payerPartyReference").item(0).getAttributes().getNamedItem("href").getNodeValue().equals(homePartyId);
if(isPayer) {
legPayer = getSwapLegProductDescriptor(leg);
} else {
legReceiver = getSwapLegProductDescriptor(leg);
}
}
return new InterestRateSwapProductDescriptor(legReceiver, legPayer);
}
|
java
|
{
"resource": ""
}
|
q3451
|
Library.getVersionString
|
train
|
public static String getVersionString() {
String versionString = "UNKNOWN";
Properties propeties = getProperites();
if(propeties != null) {
versionString = propeties.getProperty("finmath-lib.version");
}
return versionString;
}
|
java
|
{
"resource": ""
}
|
q3452
|
Library.getBuildString
|
train
|
public static String getBuildString() {
String versionString = "UNKNOWN";
Properties propeties = getProperites();
if(propeties != null) {
versionString = propeties.getProperty("finmath-lib.build");
}
return versionString;
}
|
java
|
{
"resource": ""
}
|
q3453
|
DiscountCurve.createDiscountCurveFromDiscountFactors
|
train
|
public static DiscountCurve createDiscountCurveFromDiscountFactors(String name, double[] times, double[] givenDiscountFactors) {
DiscountCurve discountFactors = new DiscountCurve(name);
for(int timeIndex=0; timeIndex<times.length;timeIndex++) {
discountFactors.addDiscountFactor(times[timeIndex], givenDiscountFactors[timeIndex], times[timeIndex] > 0);
}
return discountFactors;
}
|
java
|
{
"resource": ""
}
|
q3454
|
EuropeanOptionSmile.getDescriptors
|
train
|
public Map<Double, SingleAssetEuropeanOptionProductDescriptor> getDescriptors(LocalDate referenceDate){
int numberOfStrikes = strikes.length;
HashMap<Double, SingleAssetEuropeanOptionProductDescriptor> descriptors = new HashMap<Double, SingleAssetEuropeanOptionProductDescriptor>();
LocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity);
for(int i = 0; i< numberOfStrikes; i++) {
descriptors.put(strikes[i], new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[i]));
}
return descriptors;
}
|
java
|
{
"resource": ""
}
|
q3455
|
EuropeanOptionSmile.getDescriptor
|
train
|
public SingleAssetEuropeanOptionProductDescriptor getDescriptor(LocalDate referenceDate, int index) throws ArrayIndexOutOfBoundsException{
LocalDate maturityDate = FloatingpointDate.getDateFromFloatingPointDate(referenceDate, maturity);
if(index >= strikes.length) {
throw new ArrayIndexOutOfBoundsException("Strike index out of bounds");
}else {
return new SingleAssetEuropeanOptionProductDescriptor(underlyingName, maturityDate, strikes[index]);
}
}
|
java
|
{
"resource": ""
}
|
q3456
|
AbstractCurve.getValues
|
train
|
public RandomVariable[] getValues(double[] times) {
RandomVariable[] values = new RandomVariable[times.length];
for(int i=0; i<times.length; i++) {
values[i] = getValue(null, times[i]);
}
return values;
}
|
java
|
{
"resource": ""
}
|
q3457
|
DayCountConventionFactory.getDaycount
|
train
|
public static double getDaycount(LocalDate startDate, LocalDate endDate, String convention) {
DayCountConventionInterface daycountConvention = getDayCountConvention(convention);
return daycountConvention.getDaycount(startDate, endDate);
}
|
java
|
{
"resource": ""
}
|
q3458
|
CMSOption.getValue
|
train
|
public double getValue(ForwardCurve forwardCurve, double swaprateVolatility) {
double[] swapTenor = new double[fixingDates.length+1];
System.arraycopy(fixingDates, 0, swapTenor, 0, fixingDates.length);
swapTenor[swapTenor.length-1] = paymentDates[paymentDates.length-1];
TimeDiscretization fixTenor = new TimeDiscretizationFromArray(swapTenor);
TimeDiscretization floatTenor = new TimeDiscretizationFromArray(swapTenor);
double forwardSwapRate = Swap.getForwardSwapRate(fixTenor, floatTenor, forwardCurve);
double swapAnnuity = SwapAnnuity.getSwapAnnuity(fixTenor, forwardCurve);
double payoffUnit = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor[0], swapTenor[1]), forwardCurve) / (swapTenor[1] - swapTenor[0]);
return AnalyticFormulas.huntKennedyCMSOptionValue(forwardSwapRate, swaprateVolatility, swapAnnuity, exerciseDate, swapTenor[swapTenor.length-1]-swapTenor[0], payoffUnit, strike) * (swapTenor[1] - swapTenor[0]);
}
|
java
|
{
"resource": ""
}
|
q3459
|
DiscountCurveNelsonSiegelSvensson.getDiscountFactor
|
train
|
@Override
public double getDiscountFactor(AnalyticModelInterface model, double maturity)
{
// Change time scale
maturity *= timeScaling;
double beta1 = parameter[0];
double beta2 = parameter[1];
double beta3 = parameter[2];
double beta4 = parameter[3];
double tau1 = parameter[4];
double tau2 = parameter[5];
double x1 = tau1 > 0 ? FastMath.exp(-maturity/tau1) : 0.0;
double x2 = tau2 > 0 ? FastMath.exp(-maturity/tau2) : 0.0;
double y1 = tau1 > 0 ? (maturity > 0.0 ? (1.0-x1)/maturity*tau1 : 1.0) : 0.0;
double y2 = tau2 > 0 ? (maturity > 0.0 ? (1.0-x2)/maturity*tau2 : 1.0) : 0.0;
double zeroRate = beta1 + beta2 * y1 + beta3 * (y1-x1) + beta4 * (y2-x2);
return Math.exp(- zeroRate * maturity);
}
|
java
|
{
"resource": ""
}
|
q3460
|
ScheduleGenerator.createScheduleFromConventions
|
train
|
@Deprecated
public static Schedule createScheduleFromConventions(
LocalDate referenceDate,
LocalDate startDate,
String frequency,
double maturity,
String daycountConvention,
String shortPeriodConvention,
String dateRollConvention,
BusinessdayCalendar businessdayCalendar,
int fixingOffsetDays,
int paymentOffsetDays
)
{
LocalDate maturityDate = createDateFromDateAndOffset(startDate, maturity);
return createScheduleFromConventions(
referenceDate,
startDate,
maturityDate,
Frequency.valueOf(frequency.toUpperCase()),
DaycountConvention.getEnum(daycountConvention),
ShortPeriodConvention.valueOf(shortPeriodConvention.toUpperCase()),
DateRollConvention.getEnum(dateRollConvention),
businessdayCalendar,
fixingOffsetDays,
paymentOffsetDays
);
}
|
java
|
{
"resource": ""
}
|
q3461
|
CurveEstimation.getRegressionCurve
|
train
|
public Curve getRegressionCurve(){
// @TODO Add threadsafe lazy init.
if(regressionCurve !=null) {
return regressionCurve;
}
DoubleMatrix a = solveEquationSystem();
double[] curvePoints=new double[partition.getLength()];
curvePoints[0]=a.get(0);
for(int i=1;i<curvePoints.length;i++) {
curvePoints[i]=curvePoints[i-1]+a.get(i)*(partition.getIntervalLength(i-1));
}
return new CurveInterpolation(
"RegressionCurve",
referenceDate,
CurveInterpolation.InterpolationMethod.LINEAR,
CurveInterpolation.ExtrapolationMethod.CONSTANT,
CurveInterpolation.InterpolationEntity.VALUE,
partition.getPoints(),
curvePoints);
}
|
java
|
{
"resource": ""
}
|
q3462
|
Cap.getValueAsPrice
|
train
|
public double getValueAsPrice(double evaluationTime, AnalyticModel model) {
ForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);
DiscountCurve discountCurve = model.getDiscountCurve(discountCurveName);
DiscountCurve discountCurveForForward = null;
if(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {
// User might like to get forward from discount curve.
discountCurveForForward = model.getDiscountCurve(forwardCurveName);
if(discountCurveForForward == null) {
// User specified a name for the forward curve, but no curve was found.
throw new IllegalArgumentException("No curve of the name " + forwardCurveName + " was found in the model.");
}
}
double value = 0.0;
for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {
double fixingDate = schedule.getFixing(periodIndex);
double paymentDate = schedule.getPayment(periodIndex);
double periodLength = schedule.getPeriodLength(periodIndex);
/*
* We do not count empty periods.
* Since empty periods are an indication for a ill-specified product,
* it might be reasonable to throw an illegal argument exception instead.
*/
if(periodLength == 0) {
continue;
}
double forward = 0.0;
if(forwardCurve != null) {
forward += forwardCurve.getForward(model, fixingDate, paymentDate-fixingDate);
}
else if(discountCurveForForward != null) {
/*
* Classical single curve case: using a discount curve as a forward curve.
* This is only implemented for demonstration purposes (an exception would also be appropriate :-)
*/
if(fixingDate != paymentDate) {
forward += (discountCurveForForward.getDiscountFactor(fixingDate) / discountCurveForForward.getDiscountFactor(paymentDate) - 1.0) / (paymentDate-fixingDate);
}
}
double discountFactor = paymentDate > evaluationTime ? discountCurve.getDiscountFactor(model, paymentDate) : 0.0;
double payoffUnit = discountFactor * periodLength;
double effektiveStrike = strike;
if(isStrikeMoneyness) {
effektiveStrike += getATMForward(model, true);
}
VolatilitySurface volatilitySurface = model.getVolatilitySurface(volatiltiySufaceName);
if(volatilitySurface == null) {
throw new IllegalArgumentException("Volatility surface not found in model: " + volatiltiySufaceName);
}
if(volatilitySurface.getQuotingConvention() == QuotingConvention.VOLATILITYLOGNORMAL) {
double volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYLOGNORMAL);
value += AnalyticFormulas.blackScholesGeneralizedOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);
}
else {
// Default to normal volatility as quoting convention
double volatility = volatilitySurface.getValue(model, fixingDate, effektiveStrike, VolatilitySurface.QuotingConvention.VOLATILITYNORMAL);
value += AnalyticFormulas.bachelierOptionValue(forward, volatility, fixingDate, effektiveStrike, payoffUnit);
}
}
return value / discountCurve.getDiscountFactor(model, evaluationTime);
}
|
java
|
{
"resource": ""
}
|
q3463
|
LevenbergMarquardt.setDerivatives
|
train
|
public void setDerivatives(double[] parameters, double[][] derivatives) throws SolverException {
// Calculate new derivatives. Note that this method is called only with
// parameters = parameterCurrent, so we may use valueCurrent.
Vector<Future<double[]>> valueFutures = new Vector<Future<double[]>>(parameterCurrent.length);
for (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {
final double[] parametersNew = parameters.clone();
final double[] derivative = derivatives[parameterIndex];
final int workerParameterIndex = parameterIndex;
Callable<double[]> worker = new Callable<double[]>() {
public double[] call() {
double parameterFiniteDifference;
if(parameterSteps != null) {
parameterFiniteDifference = parameterSteps[workerParameterIndex];
}
else {
/*
* Try to adaptively set a parameter shift. Note that in some
* applications it may be important to set parameterSteps.
* appropriately.
*/
parameterFiniteDifference = (Math.abs(parametersNew[workerParameterIndex]) + 1) * 1E-8;
}
// Shift parameter value
parametersNew[workerParameterIndex] += parameterFiniteDifference;
// Calculate derivative as (valueUpShift - valueCurrent) / parameterFiniteDifference
try {
setValues(parametersNew, derivative);
} catch (Exception e) {
// We signal an exception to calculate the derivative as NaN
Arrays.fill(derivative, Double.NaN);
}
for (int valueIndex = 0; valueIndex < valueCurrent.length; valueIndex++) {
derivative[valueIndex] -= valueCurrent[valueIndex];
derivative[valueIndex] /= parameterFiniteDifference;
if(Double.isNaN(derivative[valueIndex])) {
derivative[valueIndex] = 0.0;
}
}
return derivative;
}
};
if(executor != null) {
Future<double[]> valueFuture = executor.submit(worker);
valueFutures.add(parameterIndex, valueFuture);
}
else {
FutureTask<double[]> valueFutureTask = new FutureTask<double[]>(worker);
valueFutureTask.run();
valueFutures.add(parameterIndex, valueFutureTask);
}
}
for (int parameterIndex = 0; parameterIndex < parameterCurrent.length; parameterIndex++) {
try {
derivatives[parameterIndex] = valueFutures.get(parameterIndex).get();
}
catch (InterruptedException e) {
throw new SolverException(e);
} catch (ExecutionException e) {
throw new SolverException(e);
}
}
}
|
java
|
{
"resource": ""
}
|
q3464
|
TasklaunchrequestTransformProcessorConfiguration.parseParams
|
train
|
private List<String> parseParams(String param) {
Assert.hasText(param, "param must not be empty nor null");
List<String> paramsToUse = new ArrayList<>();
Matcher regexMatcher = DEPLOYMENT_PARAMS_PATTERN.matcher(param);
int start = 0;
while (regexMatcher.find()) {
String p = removeQuoting(param.substring(start, regexMatcher.start()).trim());
if (StringUtils.hasText(p)) {
paramsToUse.add(p);
}
start = regexMatcher.start();
}
if (param != null && param.length() > 0) {
String p = removeQuoting(param.substring(start, param.length()).trim());
if (StringUtils.hasText(p)) {
paramsToUse.add(p);
}
}
return paramsToUse;
}
|
java
|
{
"resource": ""
}
|
q3465
|
SqlUtils.load
|
train
|
public static String load(LoadConfiguration config, String prefix) {
if (config.getMode() == Mode.INSERT) {
return loadInsert(config, prefix);
}
else if (config.getMode() == Mode.UPDATE) {
return loadUpdate(config, prefix);
}
throw new IllegalArgumentException("Unsupported mode " + config.getMode());
}
|
java
|
{
"resource": ""
}
|
q3466
|
TriggertaskSourceConfiguration.parseProperties
|
train
|
public static Map<String, String> parseProperties(String s) {
Map<String, String> properties = new HashMap<String, String>();
if (!StringUtils.isEmpty(s)) {
Matcher matcher = PROPERTIES_PATTERN.matcher(s);
int start = 0;
while (matcher.find()) {
addKeyValuePairAsProperty(s.substring(start, matcher.start()), properties);
start = matcher.start() + 1;
}
addKeyValuePairAsProperty(s.substring(start), properties);
}
return properties;
}
|
java
|
{
"resource": ""
}
|
q3467
|
GpfdistServer.start
|
train
|
public synchronized HttpServer<Buffer, Buffer> start() throws Exception {
if (server == null) {
server = createProtocolListener();
}
return server;
}
|
java
|
{
"resource": ""
}
|
q3468
|
ReadableTableFactoryBean.setSegmentReject
|
train
|
public void setSegmentReject(String reject) {
if (!StringUtils.hasText(reject)) {
return;
}
Integer parsedLimit = null;
try {
parsedLimit = Integer.parseInt(reject);
segmentRejectType = SegmentRejectType.ROWS;
} catch (NumberFormatException e) {
}
if (parsedLimit == null && reject.contains("%")) {
try {
parsedLimit = Integer.parseInt(reject.replace("%", "").trim());
segmentRejectType = SegmentRejectType.PERCENT;
} catch (NumberFormatException e) {
}
}
segmentRejectLimit = parsedLimit;
}
|
java
|
{
"resource": ""
}
|
q3469
|
AbstractTwitterInboundChannelAdapter.setReadTimeout
|
train
|
public void setReadTimeout(int millis) {
// Hack to get round Spring's dynamic loading of http client stuff
ClientHttpRequestFactory f = getRequestFactory();
if (f instanceof SimpleClientHttpRequestFactory) {
((SimpleClientHttpRequestFactory) f).setReadTimeout(millis);
}
else {
((HttpComponentsClientHttpRequestFactory) f).setReadTimeout(millis);
}
}
|
java
|
{
"resource": ""
}
|
q3470
|
AbstractTwitterInboundChannelAdapter.setConnectTimeout
|
train
|
public void setConnectTimeout(int millis) {
ClientHttpRequestFactory f = getRequestFactory();
if (f instanceof SimpleClientHttpRequestFactory) {
((SimpleClientHttpRequestFactory) f).setConnectTimeout(millis);
}
else {
((HttpComponentsClientHttpRequestFactory) f).setConnectTimeout(millis);
}
}
|
java
|
{
"resource": ""
}
|
q3471
|
WebsocketSinkServerHandler.handleTextWebSocketFrameInternal
|
train
|
private void handleTextWebSocketFrameInternal(TextWebSocketFrame frame, ChannelHandlerContext ctx) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("%s received %s", ctx.channel(), frame.text()));
}
addTraceForFrame(frame, "text");
ctx.channel().write(new TextWebSocketFrame("Echo: " + frame.text()));
}
|
java
|
{
"resource": ""
}
|
q3472
|
WebsocketSinkServerHandler.addTraceForFrame
|
train
|
private void addTraceForFrame(WebSocketFrame frame, String type) {
Map<String, Object> trace = new LinkedHashMap<>();
trace.put("type", type);
trace.put("direction", "in");
if (frame instanceof TextWebSocketFrame) {
trace.put("payload", ((TextWebSocketFrame) frame).text());
}
if (traceEnabled) {
websocketTraceRepository.add(trace);
}
}
|
java
|
{
"resource": ""
}
|
q3473
|
MailSourceConfiguration.getFlowBuilder
|
train
|
@SuppressWarnings({ "rawtypes", "unchecked" })
private IntegrationFlowBuilder getFlowBuilder() {
IntegrationFlowBuilder flowBuilder;
URLName urlName = this.properties.getUrl();
if (this.properties.isIdleImap()) {
flowBuilder = getIdleImapFlow(urlName);
}
else {
MailInboundChannelAdapterSpec adapterSpec;
switch (urlName.getProtocol().toUpperCase()) {
case "IMAP":
case "IMAPS":
adapterSpec = getImapFlowBuilder(urlName);
break;
case "POP3":
case "POP3S":
adapterSpec = getPop3FlowBuilder(urlName);
break;
default:
throw new IllegalArgumentException(
"Unsupported mail protocol: " + urlName.getProtocol());
}
flowBuilder = IntegrationFlows.from(
adapterSpec.javaMailProperties(getJavaMailProperties(urlName))
.selectorExpression(this.properties.getExpression())
.shouldDeleteMessages(this.properties.isDelete()),
new Consumer<SourcePollingChannelAdapterSpec>() {
@Override
public void accept(
SourcePollingChannelAdapterSpec sourcePollingChannelAdapterSpec) {
sourcePollingChannelAdapterSpec.poller(MailSourceConfiguration.this.defaultPoller);
}
});
}
return flowBuilder;
}
|
java
|
{
"resource": ""
}
|
q3474
|
MailSourceConfiguration.getIdleImapFlow
|
train
|
private IntegrationFlowBuilder getIdleImapFlow(URLName urlName) {
return IntegrationFlows.from(Mail.imapIdleAdapter(urlName.toString())
.shouldDeleteMessages(this.properties.isDelete())
.javaMailProperties(getJavaMailProperties(urlName))
.selectorExpression(this.properties.getExpression())
.shouldMarkMessagesAsRead(this.properties.isMarkAsRead()));
}
|
java
|
{
"resource": ""
}
|
q3475
|
MailSourceConfiguration.getImapFlowBuilder
|
train
|
@SuppressWarnings("rawtypes")
private MailInboundChannelAdapterSpec getImapFlowBuilder(URLName urlName) {
return Mail.imapInboundAdapter(urlName.toString())
.shouldMarkMessagesAsRead(this.properties.isMarkAsRead());
}
|
java
|
{
"resource": ""
}
|
q3476
|
CanvasSignInController.postDeclineView
|
train
|
protected View postDeclineView() {
return new TopLevelWindowRedirect() {
@Override
protected String getRedirectUrl(Map<String, ?> model) {
return postDeclineUrl;
}
};
}
|
java
|
{
"resource": ""
}
|
q3477
|
SignedRequestDecoder.decodeSignedRequest
|
train
|
@SuppressWarnings("unchecked")
public Map<String, ?> decodeSignedRequest(String signedRequest) throws SignedRequestException {
return decodeSignedRequest(signedRequest, Map.class);
}
|
java
|
{
"resource": ""
}
|
q3478
|
SignedRequestDecoder.decodeSignedRequest
|
train
|
public <T> T decodeSignedRequest(String signedRequest, Class<T> type) throws SignedRequestException {
String[] split = signedRequest.split("\\.");
String encodedSignature = split[0];
String payload = split[1];
String decoded = base64DecodeToString(payload);
byte[] signature = base64DecodeToBytes(encodedSignature);
try {
T data = objectMapper.readValue(decoded, type);
String algorithm = objectMapper.readTree(decoded).get("algorithm").textValue();
if (algorithm == null || !algorithm.equals("HMAC-SHA256")) {
throw new SignedRequestException("Unknown encryption algorithm: " + algorithm);
}
byte[] expectedSignature = encrypt(payload, secret);
if (!Arrays.equals(expectedSignature, signature)) {
throw new SignedRequestException("Invalid signature.");
}
return data;
} catch (IOException e) {
throw new SignedRequestException("Error parsing payload.", e);
}
}
|
java
|
{
"resource": ""
}
|
q3479
|
FqlResult.getString
|
train
|
public String getString(String fieldName) {
return hasValue(fieldName) ? String.valueOf(resultMap.get(fieldName)) : null;
}
|
java
|
{
"resource": ""
}
|
q3480
|
FqlResult.getInteger
|
train
|
public Integer getInteger(String fieldName) {
try {
return hasValue(fieldName) ? Integer.valueOf(String.valueOf(resultMap.get(fieldName))) : null;
} catch (NumberFormatException e) {
throw new FqlException("Field '" + fieldName +"' is not a number.", e);
}
}
|
java
|
{
"resource": ""
}
|
q3481
|
FqlResult.getLong
|
train
|
public Long getLong(String fieldName) {
try {
return hasValue(fieldName) ? Long.valueOf(String.valueOf(resultMap.get(fieldName))) : null;
} catch (NumberFormatException e) {
throw new FqlException("Field '" + fieldName +"' is not a number.", e);
}
}
|
java
|
{
"resource": ""
}
|
q3482
|
FqlResult.getFloat
|
train
|
public Float getFloat(String fieldName) {
try {
return hasValue(fieldName) ? Float.valueOf(String.valueOf(resultMap.get(fieldName))) : null;
} catch (NumberFormatException e) {
throw new FqlException("Field '" + fieldName +"' is not a number.", e);
}
}
|
java
|
{
"resource": ""
}
|
q3483
|
FqlResult.getBoolean
|
train
|
public Boolean getBoolean(String fieldName) {
return hasValue(fieldName) ? Boolean.valueOf(String.valueOf(resultMap.get(fieldName))) : null;
}
|
java
|
{
"resource": ""
}
|
q3484
|
FqlResult.getTime
|
train
|
public Date getTime(String fieldName) {
try {
if (hasValue(fieldName)) {
return new Date(Long.valueOf(String.valueOf(resultMap.get(fieldName))) * 1000);
} else {
return null;
}
} catch (NumberFormatException e) {
throw new FqlException("Field '" + fieldName +"' is not a time.", e);
}
}
|
java
|
{
"resource": ""
}
|
q3485
|
FqlResult.hasValue
|
train
|
public boolean hasValue(String fieldName) {
return resultMap.containsKey(fieldName) && resultMap.get(fieldName) != null;
}
|
java
|
{
"resource": ""
}
|
q3486
|
FacebookTemplate.fetchObject
|
train
|
public <T> T fetchObject(String objectId, Class<T> type) {
URI uri = URIBuilder.fromUri(getBaseGraphApiUrl() + objectId).build();
return getRestTemplate().getForObject(uri, type);
}
|
java
|
{
"resource": ""
}
|
q3487
|
RealTimeUpdateController.verifySubscription
|
train
|
@RequestMapping(value="/{subscription}", method=GET, params="hub.mode=subscribe")
public @ResponseBody String verifySubscription(
@PathVariable("subscription") String subscription,
@RequestParam("hub.challenge") String challenge,
@RequestParam("hub.verify_token") String verifyToken) {
logger.debug("Received subscription verification request for '" + subscription + "'.");
return tokens.containsKey(subscription) && tokens.get(subscription).equals(verifyToken) ? challenge : "";
}
|
java
|
{
"resource": ""
}
|
q3488
|
FacebookErrorHandler.handleFacebookError
|
train
|
void handleFacebookError(HttpStatus statusCode, FacebookError error) {
if (error != null && error.getCode() != null) {
int code = error.getCode();
if (code == UNKNOWN) {
throw new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);
} else if (code == SERVICE) {
throw new ServerException(FACEBOOK_PROVIDER_ID, error.getMessage());
} else if (code == TOO_MANY_CALLS || code == USER_TOO_MANY_CALLS || code == EDIT_FEED_TOO_MANY_USER_CALLS || code == EDIT_FEED_TOO_MANY_USER_ACTION_CALLS) {
throw new RateLimitExceededException(FACEBOOK_PROVIDER_ID);
} else if (code == PERMISSION_DENIED || isUserPermissionError(code)) {
throw new InsufficientPermissionException(FACEBOOK_PROVIDER_ID);
} else if (code == PARAM_SESSION_KEY || code == PARAM_SIGNATURE) {
throw new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());
} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == null) {
throw new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());
} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == 463) {
throw new ExpiredAuthorizationException(FACEBOOK_PROVIDER_ID);
} else if (code == PARAM_ACCESS_TOKEN) {
throw new RevokedAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());
} else if (code == MESG_DUPLICATE) {
throw new DuplicateStatusException(FACEBOOK_PROVIDER_ID, error.getMessage());
} else if (code == DATA_OBJECT_NOT_FOUND || code == PATH_UNKNOWN) {
throw new ResourceNotFoundException(FACEBOOK_PROVIDER_ID, error.getMessage());
} else {
throw new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);
}
}
}
|
java
|
{
"resource": ""
}
|
q3489
|
NavigationDrawerFragment.showGlobalContextActionBar
|
train
|
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(R.string.app_name);
}
|
java
|
{
"resource": ""
}
|
q3490
|
UrlsInterface.getGroup
|
train
|
public String getGroup(String groupId) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_GET_GROUP);
parameters.put("group_id", groupId);
Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element payload = response.getPayload();
return payload.getAttribute("url");
}
|
java
|
{
"resource": ""
}
|
q3491
|
UrlsInterface.getUserProfile
|
train
|
public String getUserProfile(String userId) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_GET_USER_PROFILE);
parameters.put("user_id", userId);
Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element payload = response.getPayload();
return payload.getAttribute("url");
}
|
java
|
{
"resource": ""
}
|
q3492
|
UrlsInterface.lookupGroup
|
train
|
public Group lookupGroup(String url) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_LOOKUP_GROUP);
parameters.put("url", url);
Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Group group = new Group();
Element payload = response.getPayload();
Element groupnameElement = (Element) payload.getElementsByTagName("groupname").item(0);
group.setId(payload.getAttribute("id"));
group.setName(((Text) groupnameElement.getFirstChild()).getData());
return group;
}
|
java
|
{
"resource": ""
}
|
q3493
|
UrlsInterface.lookupUser
|
train
|
public String lookupUser(String url) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_LOOKUP_USER);
parameters.put("url", url);
Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element payload = response.getPayload();
Element groupnameElement = (Element) payload.getElementsByTagName("username").item(0);
return ((Text) groupnameElement.getFirstChild()).getData();
}
|
java
|
{
"resource": ""
}
|
q3494
|
UrlsInterface.lookupGallery
|
train
|
public Gallery lookupGallery(String galleryId) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_LOOKUP_GALLERY);
parameters.put("url", galleryId);
Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element galleryElement = response.getPayload();
Gallery gallery = new Gallery();
gallery.setId(galleryElement.getAttribute("id"));
gallery.setUrl(galleryElement.getAttribute("url"));
User owner = new User();
owner.setId(galleryElement.getAttribute("owner"));
gallery.setOwner(owner);
gallery.setCreateDate(galleryElement.getAttribute("date_create"));
gallery.setUpdateDate(galleryElement.getAttribute("date_update"));
gallery.setPrimaryPhotoId(galleryElement.getAttribute("primary_photo_id"));
gallery.setPrimaryPhotoServer(galleryElement.getAttribute("primary_photo_server"));
gallery.setVideoCount(galleryElement.getAttribute("count_videos"));
gallery.setPhotoCount(galleryElement.getAttribute("count_photos"));
gallery.setPrimaryPhotoFarm(galleryElement.getAttribute("farm"));
gallery.setPrimaryPhotoSecret(galleryElement.getAttribute("secret"));
gallery.setTitle(XMLUtilities.getChildValue(galleryElement, "title"));
gallery.setDesc(XMLUtilities.getChildValue(galleryElement, "description"));
return gallery;
}
|
java
|
{
"resource": ""
}
|
q3495
|
FavoritesInterface.add
|
train
|
public void add(String photoId) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_ADD);
parameters.put("photo_id", photoId);
Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
|
java
|
{
"resource": ""
}
|
q3496
|
FavoritesInterface.getContext
|
train
|
public PhotoContext getContext(String photoId, String userId) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_GET_CONTEXT);
parameters.put("photo_id", photoId);
parameters.put("user_id", userId);
Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Collection<Element> payload = response.getPayloadCollection();
PhotoContext photoContext = new PhotoContext();
for (Element element : payload) {
String elementName = element.getTagName();
if (elementName.equals("prevphoto")) {
Photo photo = new Photo();
photo.setId(element.getAttribute("id"));
photoContext.setPreviousPhoto(photo);
} else if (elementName.equals("nextphoto")) {
Photo photo = new Photo();
photo.setId(element.getAttribute("id"));
photoContext.setNextPhoto(photo);
} else {
if (logger.isInfoEnabled()) {
logger.info("unsupported element name: " + elementName);
}
}
}
return photoContext;
}
|
java
|
{
"resource": ""
}
|
q3497
|
PeopleInterface.editCoords
|
train
|
public void editCoords(String photoId, String userId, Rectangle bounds) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_EDIT_COORDS);
parameters.put("photo_id", photoId);
parameters.put("user_id", userId);
parameters.put("person_x", bounds.x);
parameters.put("person_y", bounds.y);
parameters.put("person_w", bounds.width);
parameters.put("person_h", bounds.height);
Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
|
java
|
{
"resource": ""
}
|
q3498
|
Flickr.getAuthInterface
|
train
|
@Override
public AuthInterface getAuthInterface() {
if (authInterface == null) {
authInterface = new AuthInterface(apiKey, sharedSecret, transport);
}
return authInterface;
}
|
java
|
{
"resource": ""
}
|
q3499
|
Flickr.getActivityInterface
|
train
|
@Override
public ActivityInterface getActivityInterface() {
if (activityInterface == null) {
activityInterface = new ActivityInterface(apiKey, sharedSecret, transport);
}
return activityInterface;
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.