text:
package util

import "time"

// OptionalUInt8 returns a pointer to a value
func OptionalUInt8(value uint8) *uint8 {
	return &value
}

// OptionalUInt16 returns a pointer to a value
func OptionalUInt16(value uint16) *uint16 {
	return &value
}

// OptionalUInt returns a pointer to a value
func OptionalUInt(value uint) *uint {
	return &value
}

// OptionalUInt64 returns a pointer to a value
func OptionalUInt64(value uint64) *uint64 {
	return &value
}

// OptionalInt16 returns a pointer to a value
func OptionalInt16(value int16) *int16 {
	return &value
}

// OptionalInt returns a pointer to a value
func OptionalInt(value int) *int {
	return &value
}

// OptionalInt32 returns a pointer to a value
func OptionalInt32(value int32) *int32 {
	return &value
}

// OptionalInt64 returns a pointer to a value
func OptionalInt64(value int64) *int64 {
	return &value
}

// OptionalFloat32 returns a pointer to a value
func OptionalFloat32(value float32) *float32 {
	return &value
}

// OptionalFloat64 returns a pointer to a value
func OptionalFloat64(value float64) *float64 {
	return &value
}

// OptionalString returns a pointer to a value
func OptionalString(value string) *string {
	return &value
}

// OptionalBool returns a pointer to a value
func OptionalBool(value bool) *bool {
	return &value
}

// OptionalTime returns a pointer to a value
func OptionalTime(value time.Time) *time.Time {
	return &value
}

// OptionalDuration returns a pointer to a value
func OptionalDuration(value time.Duration) *time.Duration {
	return &value
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef ERROR_FUNCTIONS_H
#define ERROR_FUNCTIONS_H

void errMsg(const char *format, ...);

#ifdef __GNUC__
/* This macro stops 'gcc -Wall' complainting that "control reaches end of
   non-void function" if we use the following functions to terminate main()
   or some other non-void function. */
#define NORETURN __attribute__((__noreturn__))
#else
#define NORETURN
#endif

void errExit(const char *format, ...) NORETURN;

void err_exit(const char *format, ...) NORETURN;

void errExitEN(int errnum, const char *format, ...) NORETURN;

void fatal(const char *format, ...) NORETURN;

void usageErr(const char *format, ...) NORETURN;

void cmdLineErr(const char *format, ...) NORETURN;

#endif


text:
rburgstaler.github.io
=====================


text:
$(document).ready(function () {
    "use strict";

    var fn = {

        // Launch Functions
        Launch: function () {
            window.app = {};
			fn.App();
			fn.Gui();
        },

		Gui: function() {
			// init gui in a clear state
			window.app.gui = PiMillGui();
			window.app.gui.init();

		},

		App: function() {

			window.app.socket = PiMillClient();
			window.app.socket.connect();

		}

	};

    $(document).ready(function () {
        fn.Launch();
    });

});


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Xunit.Performance;

namespace System.Runtime.Tests
{
    public class Perf_UInt32
    {
        [Benchmark]
        public void ToString_()
        {
            uint testint = new uint();
            foreach (var iteration in Benchmark.Iterations)
                using (iteration.StartMeasurement())
                    for (int i = 0; i < 10000; i++)
                    {
                        testint.ToString(); testint.ToString(); testint.ToString();
                        testint.ToString(); testint.ToString(); testint.ToString();
                        testint.ToString(); testint.ToString(); testint.ToString();
                    }
        }
    }
}


text:
package com.opengamma.strata.pricer.swap;

import java.time.LocalDate;
import java.util.Optional;
import java.util.function.BiFunction;

import com.google.common.collect.ImmutableList;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.currency.CurrencyAmount;
import com.opengamma.strata.basics.currency.MultiCurrencyAmount;
import com.opengamma.strata.basics.value.ValueDerivatives;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.collect.array.DoubleArray;
import com.opengamma.strata.market.amount.CashFlow;
import com.opengamma.strata.market.amount.CashFlows;
import com.opengamma.strata.market.explain.ExplainKey;
import com.opengamma.strata.market.explain.ExplainMap;
import com.opengamma.strata.market.explain.ExplainMapBuilder;
import com.opengamma.strata.market.sensitivity.PointSensitivityBuilder;
import com.opengamma.strata.pricer.rate.RatesProvider;
import com.opengamma.strata.product.swap.KnownAmountSwapPaymentPeriod;
import com.opengamma.strata.product.swap.RatePaymentPeriod;
import com.opengamma.strata.product.swap.ResolvedSwapLeg;
import com.opengamma.strata.product.swap.SwapPaymentEvent;
import com.opengamma.strata.product.swap.SwapPaymentPeriod;

/**
 * Pricer for for rate swap legs.
 *

 * This function provides the ability to price a {@link ResolvedSwapLeg}.
 * The product is priced by pricing each period and event.
 */
public class DiscountingSwapLegPricer {

  /**
   * Default implementation.
   */
  public static final DiscountingSwapLegPricer DEFAULT = new DiscountingSwapLegPricer(
      SwapPaymentPeriodPricer.standard(),
      SwapPaymentEventPricer.standard());

  /**
   * Pricer for {@link SwapPaymentPeriod}.
   */
  private final SwapPaymentPeriodPricer<SwapPaymentPeriod> paymentPeriodPricer;
  /**
   * Pricer for {@link SwapPaymentEvent}.
   */
  private final SwapPaymentEventPricer<SwapPaymentEvent> paymentEventPricer;

  /* Small parameter below which the cash annuity formula is modified. */
  private static final double MIN_YIELD = 1.0E-4;

  /**
   * Creates an instance.
   *
   * @param paymentPeriodPricer  the pricer for {@link SwapPaymentPeriod}
   * @param paymentEventPricer  the pricer for {@link SwapPaymentEvent}
   */
  public DiscountingSwapLegPricer(
      SwapPaymentPeriodPricer<SwapPaymentPeriod> paymentPeriodPricer,
      SwapPaymentEventPricer<SwapPaymentEvent> paymentEventPricer) {
    this.paymentPeriodPricer = ArgChecker.notNull(paymentPeriodPricer, "paymentPeriodPricer");
    this.paymentEventPricer = ArgChecker.notNull(paymentEventPricer, "paymentEventPricer");
  }

  //-------------------------------------------------------------------------
  /**
   * Gets the underlying leg pricer.
   *
   * @return the leg pricer
   */
  public SwapPaymentPeriodPricer<SwapPaymentPeriod> getPeriodPricer() {
    return paymentPeriodPricer;
  }

  /**
   * Gets the underlying leg pricer.
   *
   * @return the leg pricer
   */
  public SwapPaymentEventPricer<SwapPaymentEvent> getEventPricer() {
    return paymentEventPricer;
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the present value of the swap leg, converted to the specified currency.
   *

   * The present value of the leg is the value on the valuation date.
   * This is the discounted forecast value.
   * The result is converted to the specified currency.
   *
   * @param leg  the leg
   * @param currency  the currency to convert to
   * @param provider  the rates provider
   * @return the present value of the swap leg in the specified currency
   */
  public CurrencyAmount presentValue(ResolvedSwapLeg leg, Currency currency, RatesProvider provider) {
    double pv = presentValueInternal(leg, provider);
    return CurrencyAmount.of(currency, (pv * provider.fxRate(leg.getCurrency(), currency)));
  }

  /**
   * Calculates the present value of the swap leg.
   *

   * The present value of the leg is the value on the valuation date.
   * This is the discounted forecast value.
   * The result is returned using the payment currency of the leg.
   *
   * @param leg  the leg
   * @param provider  the rates provider
   * @return the present value of the swap leg
   */
  public CurrencyAmount presentValue(ResolvedSwapLeg leg, RatesProvider provider) {
    return CurrencyAmount.of(leg.getCurrency(), presentValueInternal(leg, provider));
  }

  // calculates the present value in the currency of the swap leg
  double presentValueInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    return presentValuePeriodsInternal(leg, provider) + presentValueEventsInternal(leg, provider);
  }

  /**
   * Calculates the forecast value of the swap leg.
   *

   * The forecast value of the leg is the value on the valuation date without present value discounting.
   * The result is returned using the payment currency of the leg.
   *
   * @param leg  the leg
   * @param provider  the rates provider
   * @return the forecast value of the swap leg
   */
  public CurrencyAmount forecastValue(ResolvedSwapLeg leg, RatesProvider provider) {
    return CurrencyAmount.of(leg.getCurrency(), forecastValueInternal(leg, provider));
  }

  // calculates the present value in the currency of the swap leg
  double forecastValueInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    return forecastValuePeriodsInternal(leg, provider) + forecastValueEventsInternal(leg, provider);
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the accrued interest since the last payment.
   *

   * This determines the payment period applicable at the valuation date and calculates
   * the accrued interest since the last payment.
   * The result is returned using the payment currency of the leg.
   *
   * @param leg  the leg
   * @param provider  the rates provider
   * @return the accrued interest of the swap leg
   */
  public CurrencyAmount accruedInterest(ResolvedSwapLeg leg, RatesProvider provider) {
    Optional<SwapPaymentPeriod> period = leg.findPaymentPeriod(provider.getValuationDate());
    if (period.isPresent()) {
      double accruedInterest = paymentPeriodPricer.accruedInterest(period.get(), provider);
      return CurrencyAmount.of(leg.getCurrency(), accruedInterest);
    }
    return CurrencyAmount.zero(leg.getCurrency());
  }

  //-------------------------------------------------------------------------
  /**
   * Computes the Present Value of a Basis Point for a swap leg.
   *

   * The Present Value of a Basis Point is the value of the leg when the rate is equal to 1.
   * A better name would be "Present Value of 1".
   * The quantity is also known as "physical annuity" or "level".
   *

   * Each period must not have FX reset or compounding.
   * They must not be of type {@link KnownAmountSwapPaymentPeriod}.
   *
   * @param leg  the swap leg
   * @param provider  the rates provider
   * @return the Present Value of a Basis Point
   */
  public double pvbp(ResolvedSwapLeg leg, RatesProvider provider) {
    double pvbpLeg = 0d;
    for (SwapPaymentPeriod period : leg.getPaymentPeriods()) {
      pvbpLeg += paymentPeriodPricer.pvbp(period, provider);
    }
    return pvbpLeg;
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the coupon equivalent of a swap leg.
   *

   * The coupon equivalent is the common fixed coupon for all the periods which would
   * result in the same present value of the leg.
   *

   * This is used in particular for swaption pricing with a model on the swap rate.
   *
   * @param leg  the swap leg
   * @param provider  the rates provider
   * @param pvbp  the present value of a basis point
   * @return the fixed coupon equivalent
   */
  public double couponEquivalent(ResolvedSwapLeg leg, RatesProvider provider, double pvbp) {
    return presentValuePeriodsInternal(leg, provider) / pvbp;
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the present value sensitivity of the swap leg.
   *

   * The present value sensitivity of the leg is the sensitivity of the present value to
   * the underlying curves.
   *
   * @param leg  the leg
   * @param provider  the rates provider
   * @return the present value curve sensitivity of the swap leg
   */
  public PointSensitivityBuilder presentValueSensitivity(ResolvedSwapLeg leg, RatesProvider provider) {
    return legValueSensitivity(
        leg,
        provider,
        paymentPeriodPricer::presentValueSensitivity,
        paymentEventPricer::presentValueSensitivity);
  }

  /**
   * Calculates the forecast value sensitivity of the swap leg.
   *

   * The forecast value sensitivity of the leg is the sensitivity of the forecast value to
   * the underlying curves.
   *
   * @param leg  the leg
   * @param provider  the rates provider
   * @return the forecast value curve sensitivity of the swap leg
   */
  public PointSensitivityBuilder forecastValueSensitivity(ResolvedSwapLeg leg, RatesProvider provider) {
    return legValueSensitivity(
        leg,
        provider,
        paymentPeriodPricer::forecastValueSensitivity,
        paymentEventPricer::forecastValueSensitivity);
  }

  // calculate present or forecast value sensitivity for a leg
  private PointSensitivityBuilder legValueSensitivity(
      ResolvedSwapLeg leg,
      RatesProvider provider,
      BiFunction<SwapPaymentPeriod, RatesProvider, PointSensitivityBuilder> periodFn,
      BiFunction<SwapPaymentEvent, RatesProvider, PointSensitivityBuilder> eventFn) {

    PointSensitivityBuilder builder = PointSensitivityBuilder.none();
    for (SwapPaymentPeriod period : leg.getPaymentPeriods()) {
      if (!period.getPaymentDate().isBefore(provider.getValuationDate())) {
        builder = builder.combinedWith(periodFn.apply(period, provider));
      }
    }
    for (SwapPaymentEvent event : leg.getPaymentEvents()) {
      if (!event.getPaymentDate().isBefore(provider.getValuationDate())) {
        builder = builder.combinedWith(eventFn.apply(event, provider));
      }
    }
    return builder;
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the Present Value of a Basis Point curve sensitivity for a fixed swap leg.
   *

   * The Present Value of a Basis Point is the value of the leg when the rate is equal to 1.
   * A better name would be "Present Value of 1".
   * The quantity is also known as "physical annuity" or "level".
   *

   * Each period must not have FX reset or compounding.
   * They must not be of type {@link KnownAmountSwapPaymentPeriod}.
   *
   * @param fixedLeg  the swap fixed leg
   * @param provider  the rates provider
   * @return the Present Value of a Basis Point sensitivity to the curves
   */
  public PointSensitivityBuilder pvbpSensitivity(ResolvedSwapLeg fixedLeg, RatesProvider provider) {
    PointSensitivityBuilder builder = PointSensitivityBuilder.none();
    for (SwapPaymentPeriod period : fixedLeg.getPaymentPeriods()) {
      builder = builder.combinedWith(paymentPeriodPricer.pvbpSensitivity(period, provider));
    }
    return builder;
  }

  //-------------------------------------------------------------------------
  /**
   * Computes the conventional cash annuity from a swap leg.
   *

   * The computation is relevant only for standard swaps with constant notional and regular payments.
   * The swap leg must be a fixed leg. However, this is not checked internally.
   *
   * @param fixedLeg  the fixed leg of the swap
   * @param yield  the yield
   * @return the cash annuity
   */
  public double annuityCash(ResolvedSwapLeg fixedLeg, double yield) {
    int nbFixedPeriod = fixedLeg.getPaymentPeriods().size();
    SwapPaymentPeriod paymentPeriod = fixedLeg.getPaymentPeriods().get(0);
    ArgChecker.isTrue(paymentPeriod instanceof RatePaymentPeriod, "payment period should be RatePaymentPeriod");
    RatePaymentPeriod ratePaymentPeriod = (RatePaymentPeriod) paymentPeriod;
    int nbFixedPaymentYear = (int) Math.round(1d /
        ratePaymentPeriod.getDayCount().yearFraction(ratePaymentPeriod.getStartDate(), ratePaymentPeriod.getEndDate()));
    double notional = Math.abs(ratePaymentPeriod.getNotional());
    double annuityCash = notional * annuityCash(nbFixedPaymentYear, nbFixedPeriod, yield);
    return annuityCash;
  }

  /**
   * Computes the conventional cash annuity for a given yield.
   *
   * @param nbPaymentsPerYear  the number of payment per year
   * @param nbPeriods  the total number of periods
   * @param yield  the yield
   * @return the cash annuity
   */
  public double annuityCash(int nbPaymentsPerYear, int nbPeriods, double yield) {
    double tau = 1d / nbPaymentsPerYear;
    if (Math.abs(yield) > MIN_YIELD) {
      return (1d - Math.pow(1d + yield * tau, -nbPeriods)) / yield;
    }
    double annuity = 0.0d;
    double periodFactor = 1.0d / (1.0d + yield * tau);
    double multiPeriodFactor = periodFactor;
    for (int i = 0; i < nbPeriods; i++) {
      annuity += multiPeriodFactor;
      multiPeriodFactor *= periodFactor;
    }
    annuity *= tau;
    return annuity;
  }

  /**
   * Computes the conventional cash annuity for a given yield and its first derivative with respect to the yield.
   *
   * @param nbPaymentsPerYear  the number of payment per year
   * @param nbPeriods  the total number of periods
   * @param yield  the yield
   * @return the cash annuity and its first derivative
   */
  public ValueDerivatives annuityCash1(int nbPaymentsPerYear, int nbPeriods, double yield) {
    double tau = 1d / nbPaymentsPerYear;
    if (Math.abs(yield) > MIN_YIELD) {
      double yieldPerPeriod = yield * tau;
      double dfEnd = Math.pow(1d + yieldPerPeriod, -nbPeriods);
      double annuity = (1d - dfEnd) / yield;
      double derivative = -annuity / yield;
      derivative += tau * nbPeriods * dfEnd / ((1d + yieldPerPeriod) * yield);
      return ValueDerivatives.of(annuity, DoubleArray.of(derivative));
    }
    double annuity = 0.0d;
    double derivative = 0.0d;
    double periodFactor = 1.0d / (1.0d + yield * tau);
    double multiPeriodFactor = periodFactor;
    for (int i = 0; i < nbPeriods; i++) {
      annuity += multiPeriodFactor;
      multiPeriodFactor *= periodFactor;
      derivative += -(i + 1) * multiPeriodFactor;
    }
    annuity *= tau;
    derivative *= tau * tau;
    return ValueDerivatives.of(annuity, DoubleArray.of(derivative));
  }

  /**
   * Computes the conventional cash annuity for a given yield and its first two derivatives with respect to the yield.
   *
   * @param nbPaymentsPerYear  the number of payment per year
   * @param nbPeriods  the total number of periods
   * @param yield  the yield
   * @return the cash annuity and its first two derivatives
   */
  public ValueDerivatives annuityCash2(int nbPaymentsPerYear, int nbPeriods, double yield) {
    double tau = 1d / nbPaymentsPerYear;
    if (Math.abs(yield) > MIN_YIELD) {
      double yieldPerPeriod = yield * tau;
      double dfEnd = Math.pow(1d + yieldPerPeriod, -nbPeriods);
      double annuity = (1d - dfEnd) / yield;
      double derivative1 = -annuity / yield;
      derivative1 += tau * nbPeriods * dfEnd / ((1d + yieldPerPeriod) * yield);
      double derivative2 = -2 * derivative1 / yield;
      derivative2 -= tau * tau * nbPeriods * (nbPeriods + 1) * dfEnd / ((1d + yieldPerPeriod) * (1d + yieldPerPeriod) * yield);
      return ValueDerivatives.of(annuity, DoubleArray.of(derivative1, derivative2));
    }
    double annuity = 0.0d;
    double derivative1 = 0.0d;
    double derivative2 = 0.0d;
    double periodFactor = 1.0d / (1.0d + yield * tau);
    double multiPeriodFactor = periodFactor;
    for (int i = 0; i < nbPeriods; i++) {
      annuity += multiPeriodFactor;
      multiPeriodFactor *= periodFactor;
      derivative1 += -(i + 1) * multiPeriodFactor;
      derivative2 += (i + 1) * (i + 2) * multiPeriodFactor * periodFactor;
    }
    annuity *= tau;
    derivative1 *= tau * tau;
    derivative2 *= tau * tau * tau;
    return ValueDerivatives.of(annuity, DoubleArray.of(derivative1, derivative2));
  }

  /**
   * Computes the conventional cash annuity for a given yield and its first three derivatives with respect to the yield.
   *
   * @param nbPaymentsPerYear  the number of payment per year
   * @param nbPeriods  the total number of periods
   * @param yield  the yield
   * @return the cash annuity and its first three derivatives
   */
  public ValueDerivatives annuityCash3(int nbPaymentsPerYear, int nbPeriods, double yield) {
    double tau = 1d / nbPaymentsPerYear;
    if (Math.abs(yield) > MIN_YIELD) {
      double yieldPerPeriod = yield * tau;
      double dfEnd = Math.pow(1d + yieldPerPeriod, -nbPeriods);
      double annuity = (1d - dfEnd) / yield;
      double derivative1 = -annuity / yield;
      derivative1 += tau * nbPeriods * dfEnd / ((1d + yieldPerPeriod) * yield);
      double derivative2 = -2 * derivative1 / yield;
      derivative2 -= tau * tau * nbPeriods * (nbPeriods + 1) * dfEnd / ((1d + yieldPerPeriod) * (1d + yieldPerPeriod) * yield);
      double derivative3 = -6.0d * annuity / (yield * yield * yield);
      derivative3 += 6.0d * tau * nbPeriods / (yield * yield * yield) * dfEnd / (1d + yieldPerPeriod);
      derivative3 += 3.0d * tau * tau * nbPeriods * (nbPeriods + 1) * dfEnd /
          ((1d + yieldPerPeriod) * (1d + yieldPerPeriod) * yield * yield);
      derivative3 += tau * tau * tau * nbPeriods * (nbPeriods + 1) * (nbPeriods + 2) * dfEnd /
          ((1d + yieldPerPeriod) * (1d + yieldPerPeriod) * (1d + yieldPerPeriod) * yield);
      return ValueDerivatives.of(annuity, DoubleArray.of(derivative1, derivative2, derivative3));
    }
    double annuity = 0.0d;
    double derivative1 = 0.0d;
    double derivative2 = 0.0d;
    double derivative3 = 0.0d;
    double periodFactor = 1.0d / (1.0d + yield * tau);
    double multiPeriodFactor = periodFactor;
    for (int i = 0; i < nbPeriods; i++) {
      annuity += multiPeriodFactor;
      multiPeriodFactor *= periodFactor;
      derivative1 += -(i + 1) * multiPeriodFactor;
      derivative2 += (i + 1) * (i + 2) * multiPeriodFactor * periodFactor;
      derivative3 += -(i + 1) * (i + 2) * (i + 3) * multiPeriodFactor * periodFactor * periodFactor;
    }
    annuity *= tau;
    derivative1 *= tau * tau;
    derivative2 *= tau * tau * tau;
    derivative3 *= tau * tau * tau * tau;
    return ValueDerivatives.of(annuity, DoubleArray.of(derivative1, derivative2, derivative3));
  }

  /**
   * Computes the derivative of the conventional cash annuity with respect to the yield from a swap leg.
   *

   * The computation is relevant only for standard swaps with constant notional and regular payments.
   * The swap leg must be a fixed leg. However, this is not checked internally.
   *
   * @param fixedLeg  the fixed leg of the swap
   * @param yield  the yield
   * @return the cash annuity
   */
  public ValueDerivatives annuityCashDerivative(ResolvedSwapLeg fixedLeg, double yield) {
    int nbFixedPeriod = fixedLeg.getPaymentPeriods().size();
    SwapPaymentPeriod paymentPeriod = fixedLeg.getPaymentPeriods().get(0);
    ArgChecker.isTrue(paymentPeriod instanceof RatePaymentPeriod, "payment period should be RatePaymentPeriod");
    RatePaymentPeriod ratePaymentPeriod = (RatePaymentPeriod) paymentPeriod;
    int nbFixedPaymentYear = (int) Math.round(1d /
        ratePaymentPeriod.getDayCount().yearFraction(ratePaymentPeriod.getStartDate(), ratePaymentPeriod.getEndDate()));
    double notional = Math.abs(ratePaymentPeriod.getNotional());
    ValueDerivatives annuityUnit = annuityCash1(nbFixedPaymentYear, nbFixedPeriod, yield);
    return ValueDerivatives.of(annuityUnit.getValue() * notional, annuityUnit.getDerivatives().multipliedBy(notional));
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the future cash flows of the swap leg.
   *

   * Each expected cash flow is added to the result.
   * This is based on {@link #forecastValue(ResolvedSwapLeg, RatesProvider)}.
   *
   * @param leg  the swap leg for which the cash flows should be computed
   * @param provider  the rates provider
   * @return the cash flows
   */
  public CashFlows cashFlows(ResolvedSwapLeg leg, RatesProvider provider) {
    CashFlows cashFlowPeriods = cashFlowPeriodsInternal(leg, provider);
    CashFlows cashFlowEvents = cashFlowEventsInternal(leg, provider);
    return cashFlowPeriods.combinedWith(cashFlowEvents);
  }

  //-------------------------------------------------------------------------
  // calculates the forecast value of the events composing the leg in the currency of the swap leg
  double forecastValueEventsInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    double total = 0d;
    for (SwapPaymentEvent event : leg.getPaymentEvents()) {
      if (!event.getPaymentDate().isBefore(provider.getValuationDate())) {
        total += paymentEventPricer.forecastValue(event, provider);
      }
    }
    return total;
  }

  // calculates the forecast value of the periods composing the leg in the currency of the swap leg
  double forecastValuePeriodsInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    double total = 0d;
    for (SwapPaymentPeriod period : leg.getPaymentPeriods()) {
      if (!period.getPaymentDate().isBefore(provider.getValuationDate())) {
        total += paymentPeriodPricer.forecastValue(period, provider);
      }
    }
    return total;
  }

  // calculates the present value of the events composing the leg in the currency of the swap leg
  double presentValueEventsInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    double total = 0d;
    for (SwapPaymentEvent event : leg.getPaymentEvents()) {
      if (!event.getPaymentDate().isBefore(provider.getValuationDate())) {
        total += paymentEventPricer.presentValue(event, provider);
      }
    }
    return total;
  }

  // calculates the present value of the periods composing the leg in the currency of the swap leg
  double presentValuePeriodsInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    double total = 0d;
    for (SwapPaymentPeriod period : leg.getPaymentPeriods()) {
      if (!period.getPaymentDate().isBefore(provider.getValuationDate())) {
        total += paymentPeriodPricer.presentValue(period, provider);
      }
    }
    return total;
  }

  // calculates the present value curve sensitivity of the events composing the leg in the currency of the swap leg
  PointSensitivityBuilder presentValueSensitivityEventsInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    PointSensitivityBuilder builder = PointSensitivityBuilder.none();
    for (SwapPaymentEvent event : leg.getPaymentEvents()) {
      if (!event.getPaymentDate().isBefore(provider.getValuationDate())) {
        builder = builder.combinedWith(paymentEventPricer.presentValueSensitivity(event, provider));
      }
    }
    return builder;
  }

  // calculates the present value curve sensitivity of the periods composing the leg in the currency of the swap leg
  PointSensitivityBuilder presentValueSensitivityPeriodsInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    PointSensitivityBuilder builder = PointSensitivityBuilder.none();
    for (SwapPaymentPeriod period : leg.getPaymentPeriods()) {
      if (!period.getPaymentDate().isBefore(provider.getValuationDate())) {
        builder = builder.combinedWith(paymentPeriodPricer.presentValueSensitivity(period, provider));
      }
    }
    return builder;
  }

  //-------------------------------------------------------------------------
  // calculates the cash flow of the periods composing the leg in the currency of the swap leg
  CashFlows cashFlowPeriodsInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    ImmutableList.Builder<CashFlow> builder = ImmutableList.builder();
    for (SwapPaymentPeriod period : leg.getPaymentPeriods()) {
      if (!period.getPaymentDate().isBefore(provider.getValuationDate())) {
        double forecastValue = paymentPeriodPricer.forecastValue(period, provider);
        if (forecastValue != 0d) {
          Currency currency = period.getCurrency();
          LocalDate paymentDate = period.getPaymentDate();
          double discountFactor = provider.discountFactor(currency, paymentDate);
          CashFlow singleCashFlow = CashFlow.ofForecastValue(paymentDate, currency, forecastValue, discountFactor);
          builder.add(singleCashFlow);
        }
      }
    }
    return CashFlows.of(builder.build());
  }

  // calculates the cash flow of the events composing the leg in the currency of the swap leg
  CashFlows cashFlowEventsInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    ImmutableList.Builder<CashFlow> builder = ImmutableList.builder();
    for (SwapPaymentEvent event : leg.getPaymentEvents()) {
      if (!event.getPaymentDate().isBefore(provider.getValuationDate())) {
        double forecastValue = paymentEventPricer.forecastValue(event, provider);
        if (forecastValue != 0d) {
          Currency currency = event.getCurrency();
          LocalDate paymentDate = event.getPaymentDate();
          double discountFactor = provider.discountFactor(currency, paymentDate);
          CashFlow singleCashFlow = CashFlow.ofForecastValue(paymentDate, currency, forecastValue, discountFactor);
          builder.add(singleCashFlow);
        }
      }
    }
    return CashFlows.of(builder.build());
  }

  //-------------------------------------------------------------------------
  /**
   * Explain present value builder used to build large explain map from the individual legs.
   *
   * @param leg  the swap log
   * @param provider  the rates provider
   * @param builder  the explain map builder which will be populated but the leg
   */
  void explainPresentValueInternal(ResolvedSwapLeg leg, RatesProvider provider, ExplainMapBuilder builder) {
    builder.put(ExplainKey.ENTRY_TYPE, "Leg");
    builder.put(ExplainKey.PAY_RECEIVE, leg.getPayReceive());
    builder.put(ExplainKey.LEG_TYPE, leg.getType().toString());
    for (SwapPaymentPeriod period : leg.getPaymentPeriods()) {
      builder.addListEntry(
          ExplainKey.PAYMENT_PERIODS, child -> paymentPeriodPricer.explainPresentValue(period, provider, child));
    }
    for (SwapPaymentEvent event : leg.getPaymentEvents()) {
      builder.addListEntry(
          ExplainKey.PAYMENT_EVENTS, child -> paymentEventPricer.explainPresentValue(event, provider, child));
    }
    builder.put(ExplainKey.FORECAST_VALUE, forecastValue(leg, provider));
    builder.put(ExplainKey.PRESENT_VALUE, presentValue(leg, provider));
  }

  /**
   * Explain present value for a swap leg.
   *
   * @param leg  the swap log
   * @param provider  the rates provider
   * @return the explain PV map
   */
  public ExplainMap explainPresentValue(ResolvedSwapLeg leg, RatesProvider provider) {
    ExplainMapBuilder builder = ExplainMap.builder();
    explainPresentValueInternal(leg, provider, builder);
    return builder.build();
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the currency exposure of the swap leg.
   *
   * @param leg  the leg
   * @param provider  the rates provider
   * @return the currency exposure of the swap leg
   */
  public MultiCurrencyAmount currencyExposure(ResolvedSwapLeg leg, RatesProvider provider) {
    return currencyExposurePeriodsInternal(leg, provider).plus(currencyExposureEventsInternal(leg, provider));
  }

  private MultiCurrencyAmount currencyExposurePeriodsInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    MultiCurrencyAmount total = MultiCurrencyAmount.empty();
    for (SwapPaymentPeriod period : leg.getPaymentPeriods()) {
      if (!period.getPaymentDate().isBefore(provider.getValuationDate())) {
        total = total.plus(paymentPeriodPricer.currencyExposure(period, provider));
      }
    }
    return total;
  }

  private MultiCurrencyAmount currencyExposureEventsInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    MultiCurrencyAmount total = MultiCurrencyAmount.empty();
    for (SwapPaymentEvent event : leg.getPaymentEvents()) {
      if (!event.getPaymentDate().isBefore(provider.getValuationDate())) {
        total = total.plus(paymentEventPricer.currencyExposure(event, provider));
      }
    }
    return total;
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the current cash of the swap leg.
   *
   * @param leg  the leg
   * @param provider  the rates provider
   * @return the current cash of the swap leg
   */
  public CurrencyAmount currentCash(ResolvedSwapLeg leg, RatesProvider provider) {
    return CurrencyAmount.of(leg.getCurrency(),
        currentCashPeriodsInternal(leg, provider) + (currentCashEventsInternal(leg, provider)));
  }

  private double currentCashPeriodsInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    double total = 0d;
    for (SwapPaymentPeriod period : leg.getPaymentPeriods()) {
      if (!period.getPaymentDate().isBefore(provider.getValuationDate())) {
        total += paymentPeriodPricer.currentCash(period, provider);
      }
    }
    return total;
  }

  private double currentCashEventsInternal(ResolvedSwapLeg leg, RatesProvider provider) {
    double total = 0d;
    for (SwapPaymentEvent event : leg.getPaymentEvents()) {
      if (!event.getPaymentDate().isBefore(provider.getValuationDate())) {
        total += paymentEventPricer.currentCash(event, provider);
      }
    }
    return total;
  }
}


text:
Order: 20
Title: Overview
Description: Overview how to implement support for a pull request system.
---
Pull Request Systems need to implement the [IPullRequestSystem] interface.
For simplyfing implementation there exists an abstract [PullRequestSystem] base class from which concrete implementation can be inherited.

[IPullRequestSystem]: ../../../api/Cake.Prca.PullRequests/IPullRequestSystem
[PullRequestSystem]: ../../../api/Cake.Prca.PullRequests/PullRequestSystem


text:
package com.google.gwt.sample.dynatablerf.spring.config;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 * Defines the DataSource. You might want to replace the Driverbased Datasource
 * with J2EE lookup depending on your situation.
 * @author Gerbrand van Dieijen <gerbrand@vandieijen.nl>
 *
 */
@Configuration
@PropertySource("classpath:application.properties")
public class DataSourceConfig {
	private static final Logger LOG = LoggerFactory.getLogger(DataSourceConfig.class);

	@Autowired
	Environment env;

	@Bean
	@Autowired
	public DataSource dataSource() throws Exception {
		DriverManagerDataSource ds = new DriverManagerDataSource();
    	ds.setDriverClassName(env.getProperty("jdbc.driver"));
        LOG.info("Creating datasource for {}",env.getProperty("jdbc.url"));
        ds.setUrl(env.getProperty("jdbc.url"));
        ds.setUsername(env.getProperty("jdbc.username"));
        ds.setPassword(env.getProperty("jdbc.password"));
        return ds;
	}
}


text:
go environment/flag variable management.

Priority:
- flag > environment > default

```go
package main

import "github.com/jklaw90/env"

func main() {

    config := env.NewConfig(env.OptionPanicOnMissing, env.OptionLogOn). // define options here
		AddEnv("KEY", "value", "description here").
		AddEnv("DEBUG", "true", "some bool for xyz").
		AddEnv("OVER", "9000", "some int").
		AddFlagEnv("FLAG_CASE", "flagcase", "special", "special env name") // will use flag if specified

    env := env.New(config)

    // examples
	println(env.Get("KEY"))       // "value" unless environment var defined for KEY
	println(env.GetBool("DEBUG")) // true unless environment var defined for DEBUG
	println(env.GetInt("OVER"))   // 9000 unless environment var defined for OVER
	println(env.Get("FLAG_CASE")) // "special" unless environment var defined for FLAG_CASE or flagcase flag was set
    println(env.Get("SLKDFJKLSDFJ")) // Logs missing variable name if option set

    // for global use if needed...
	println(env.Get("KEY")) // "value"
}
```


text:
#pragma once
#include <aws/appstream/AppStream_EXPORTS.h>
#include <aws/appstream/model/CertificateBasedAuthStatus.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace AppStream
{
namespace Model
{

  /**
   *
The certificate-based authentication properties used to authenticate SAML 2.0
   * Identity Provider (IdP) user identities to Active Directory domain-joined
   * streaming instances. Fallback is turned on by default when certificate-based
   * authentication is Enabled . Fallback allows users to log in using their
   * AD domain password if certificate-based authentication is unsuccessful, or to
   * unlock a desktop lock screen. Enabled_no_directory_login_fallback enables
   * certificate-based authentication, but does not allow users to log in using their
   * AD domain password. Users will be disconnected to re-authenticate using
   * certificates.

See Also:
   AWS
   * API Reference

   */
  class AWS_APPSTREAM_API CertificateBasedAuthProperties
  {
  public:
    CertificateBasedAuthProperties();
    CertificateBasedAuthProperties(Aws::Utils::Json::JsonView jsonValue);
    CertificateBasedAuthProperties& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The status of the certificate-based authentication properties.

     */
    inline const CertificateBasedAuthStatus& GetStatus() const{ return m_status; }

    /**
     *
The status of the certificate-based authentication properties.

     */
    inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }

    /**
     *
The status of the certificate-based authentication properties.

     */
    inline void SetStatus(const CertificateBasedAuthStatus& value) { m_statusHasBeenSet = true; m_status = value; }

    /**
     *
The status of the certificate-based authentication properties.

     */
    inline void SetStatus(CertificateBasedAuthStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }

    /**
     *
The status of the certificate-based authentication properties.

     */
    inline CertificateBasedAuthProperties& WithStatus(const CertificateBasedAuthStatus& value) { SetStatus(value); return *this;}

    /**
     *
The status of the certificate-based authentication properties.

     */
    inline CertificateBasedAuthProperties& WithStatus(CertificateBasedAuthStatus&& value) { SetStatus(std::move(value)); return *this;}

    /**
     *
The ARN of the AWS Certificate Manager Private CA resource.

     */
    inline const Aws::String& GetCertificateAuthorityArn() const{ return m_certificateAuthorityArn; }

    /**
     *
The ARN of the AWS Certificate Manager Private CA resource.

     */
    inline bool CertificateAuthorityArnHasBeenSet() const { return m_certificateAuthorityArnHasBeenSet; }

    /**
     *
The ARN of the AWS Certificate Manager Private CA resource.

     */
    inline void SetCertificateAuthorityArn(const Aws::String& value) { m_certificateAuthorityArnHasBeenSet = true; m_certificateAuthorityArn = value; }

    /**
     *
The ARN of the AWS Certificate Manager Private CA resource.

     */
    inline void SetCertificateAuthorityArn(Aws::String&& value) { m_certificateAuthorityArnHasBeenSet = true; m_certificateAuthorityArn = std::move(value); }

    /**
     *
The ARN of the AWS Certificate Manager Private CA resource.

     */
    inline void SetCertificateAuthorityArn(const char* value) { m_certificateAuthorityArnHasBeenSet = true; m_certificateAuthorityArn.assign(value); }

    /**
     *
The ARN of the AWS Certificate Manager Private CA resource.

     */
    inline CertificateBasedAuthProperties& WithCertificateAuthorityArn(const Aws::String& value) { SetCertificateAuthorityArn(value); return *this;}

    /**
     *
The ARN of the AWS Certificate Manager Private CA resource.

     */
    inline CertificateBasedAuthProperties& WithCertificateAuthorityArn(Aws::String&& value) { SetCertificateAuthorityArn(std::move(value)); return *this;}

    /**
     *
The ARN of the AWS Certificate Manager Private CA resource.

     */
    inline CertificateBasedAuthProperties& WithCertificateAuthorityArn(const char* value) { SetCertificateAuthorityArn(value); return *this;}

  private:

    CertificateBasedAuthStatus m_status;
    bool m_statusHasBeenSet = false;

    Aws::String m_certificateAuthorityArn;
    bool m_certificateAuthorityArnHasBeenSet = false;
  };

} // namespace Model
} // namespace AppStream
} // namespace Aws


text:
<?php
/**
 * Register General section, settings and controls for Theme Customizer
 *
 */

// Add Theme Colors section to Customizer
add_action( 'customize_register', 'leeway_customize_register_general_settings' );

function leeway_customize_register_general_settings( $wp_customize ) {

	// Add Section for Theme Options
	$wp_customize->add_section( 'leeway_section_general', array(
        'title'    => esc_html__( 'General Settings', 'leeway' ),
        'priority' => 10,
		'panel' => 'leeway_options_panel'
		)
	);

	// Add Settings and Controls for Layout
	$wp_customize->add_setting( 'leeway_theme_options[layout]', array(
        'default'           => 'right-sidebar',
		'type'           	=> 'option',
        'transport'         => 'refresh',
        'sanitize_callback' => 'leeway_sanitize_layout'
		)
	);
    $wp_customize->add_control( 'leeway_control_layout', array(
        'label'    => esc_html__( 'Theme Layout', 'leeway' ),
        'section'  => 'leeway_section_general',
        'settings' => 'leeway_theme_options[layout]',
        'type'     => 'radio',
		'priority' => 1,
        'choices'  => array(
            'left-sidebar' => esc_html__( 'Left Sidebar', 'leeway' ),
            'right-sidebar' => esc_html__( 'Right Sidebar', 'leeway' )
			)
		)
	);

	// Add Default Fonts Header
	$wp_customize->add_setting( 'leeway_theme_options[default_fonts]', array(
        'default'           => '',
		'type'           	=> 'option',
        'transport'         => 'refresh',
        'sanitize_callback' => 'esc_attr'
        )
    );
    $wp_customize->add_control( new Leeway_Customize_Header_Control(
        $wp_customize, 'leeway_control_default_fonts', array(
            'label' => esc_html__( 'Default Fonts', 'leeway' ),
            'section' => 'leeway_section_general',
            'settings' => 'leeway_theme_options[default_fonts]',
            'priority' => 2
            )
        )
    );

	// Add Settings and Controls for Deactivate Google Font setting
	$wp_customize->add_setting( 'leeway_theme_options[deactivate_google_fonts]', array(
        'default'           => false,
		'type'           	=> 'option',
        'transport'         => 'refresh',
        'sanitize_callback' => 'leeway_sanitize_checkbox'
		)
	);
    $wp_customize->add_control( 'leeway_control_deactivate_google_fonts', array(
        'label'    => esc_html__( 'Deactivate Google Fonts in case your language is not compatible.', 'leeway' ),
        'section'  => 'leeway_section_general',
        'settings' => 'leeway_theme_options[deactivate_google_fonts]',
        'type'     => 'checkbox',
		'priority' => 3
		)
	);

}


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

import * as headerActions from '../actions/header';

/**
 * @description High Order Component for set Header
 * @param {XML} WrappedComponent
 * @param text
 * @return {XML} return react component
 * @constructor
 */
const SetTextHOC = (WrappedComponent, text) => {
  /**
   * @description propTypes for SetText component
   * @type {{setText: (*)}}
   */
  const propTypes = {
    setText: PropTypes.func.isRequired,
  };
  /**
   * @class SetText
   * @extends React.Component
   * @description Render component
   */
  class SetText extends Component {

    componentDidMount() {
      this.props.setText(text);
    }

    /**
     * @description render
     * @return {Object} JSX HTML Content
     */
    render() {
      const { setText,dispatch, ...props } = this.props;
      return <WrappedComponent {...props} />;
    }
  }

  SetText.propTypes = propTypes;

  const mapDispatchToProps = dispatch => ({
    setText: (settedText) => {
      dispatch(headerActions.setText(settedText));
    },
  });

  return connect(null, mapDispatchToProps)(SetText);
};

export default SetTextHOC;


text:
package org.bricket.plugin.user_picture.service;

import java.util.List;

import org.bricket.plugin.user.domain.User;
import org.bricket.plugin.user_picture.domain.UserPicture;
import org.bricket.service.BricketDomainService;

/**
 * @author Ingo Renner
 * @author Henning Teek
 *
 */
public interface UserPictureService extends BricketDomainService<UserPicture> {
    UserPicture saveUserPicture(UserPicture userPicture);

    void deleteUserPicture(UserPicture userPicture);

    UserPicture loadUserPicture(Long id);

    List<UserPicture> loadAllUserPicture();

    List<UserPicture> loadUserPictureByUser(User user, int from, int count, String sortProperty, boolean sortAsc);

    int getCountByUser(User user);
}


text:
package grpcx

import (
	"context"
	"errors"
	"fmt"

	"google.golang.org/grpc/metadata"
)

const idKey = "id"

// ReadWorkerID reads the worker ID from an incoming gRPC request context.
func ReadWorkerID(ctx context.Context) (string, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return "", errors.New("failed to read metadata from context")
	}
	id, ok := md[idKey]
	if !ok || len(id) < 1 {
		return "", fmt.Errorf("failed to find worker id in metadata %v", md)
	}
	if len(id) > 1 {
		return "", fmt.Errorf("multiple worker ids in metadata: %v", id)
	}
	return id[0], nil
}

// WriteWorkerID write the worker ID to an outgoing gRPC request context. It
// merges the information with any existing gRPC metadata.
func WriteWorkerID(ctx context.Context, id string) context.Context {
	md := metadata.New(map[string]string{
		idKey: id,
	})
	if old, ok := metadata.FromOutgoingContext(ctx); ok {
		md = metadata.Join(md, old)
	}
	return metadata.NewOutgoingContext(ctx, md)
}


text:
//
//  UIAlertController+TCAdditions.h
//  ThunderCats
//
//  Copyright (c) 2015 Metova Inc.
//
//  MIT License
//
//  Permission is hereby granted, free of charge, to any person obtaining
//  a copy of this software and associated documentation files (the
//  "Software"), to deal in the Software without restriction, including
//  without limitation the rights to use, copy, modify, merge, publish,
//  distribute, sublicense, and/or sell copies of the Software, and to
//  permit persons to whom the Software is furnished to do so, subject to
//  the following conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
//  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
//  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#import <UIKit/UIKit.h>
#import "TCNullabilityMacros.h"

@interface UIAlertController (TCAdditions)

/**
 *  A block definition for the cancelAction on the UIAlertController+TCAdditions methods.
 */
typedef void (^ TCCancelAction)(UIAlertAction * __tc_nonnull);

/**
 *  This is a convenient method that returns an alert controller with the title, "Not Implemented", and message, "This feature is not yet implemented."
 */
+ (instancetype __tc_nonnull)tc_notImplementedAlert;

/**
 *  Creates a UIAlertController standard (popup) alert with a cancel button
 *
 *  @param title             The title of the alert
 *  @param message           The message displayed on the alert
 *  @param cancelButtonTitle The text displayed on the cancel button
 *  @param cancelAction      A completion block which will be executed when the user taps cancel which has one UIAlertAction as a parameter. If the value is nil the alert will be dismissed upon tapping the cancel button.
 *
 *  @return A UIAlertController
 */
+ (instancetype __tc_nonnull)tc_alertWithTitle:(NSString * __tc_nonnull)title
                                       message:(NSString * __tc_nonnull)message
                             cancelButtonTitle:(NSString * __tc_nonnull)cancelButtonTitle
                                  cancelAction:(TCCancelAction __tc_nullable)cancelAction;

/**
 *  Creates a UIAlertController which uses an action sheet
 *
 *  @param title             The title of the alert
 *  @param message           The message displayed on the alert
 *  @param cancelButtonTitle The text displayed on the cancel button
 *  @param cancelAction      A completion block which will be executed when the user taps cancel which has one UIAlertAction as a parameter. If the value is nil the alert will be dismissed upon tapping the cancel button.
 *
 *  @return A UIAlertController
 */
+ (instancetype __tc_nonnull)tc_alertWithActionSheet:(NSString * __tc_nonnull)title
                                             message:(NSString * __tc_nonnull)message
                                   cancelButtonTitle:(NSString * __tc_nonnull)cancelButtonTitle
                                        cancelAction:(TCCancelAction __tc_nullable)cancelAction;

/**
 *  Creates a UIAlertController which uses an action sheet for choosing from Camera Roll or Taking a Photo. Checks which source is available and only displays the available sources. Must instantiate and pass in an image picker with delegate already set.
 *
 *  @param imagePicker              The image picker to be used
 *  @param presentingViewController The view controller presenting the image picker
 *
 *  @return A UIAlertController
 */
+ (instancetype __tc_nonnull)tc_imagePickerActionSheet:(UIImagePickerController * __tc_nonnull)imagePicker
                                    presentingViewController:(UIViewController * __tc_nonnull)presentingViewController;

@end


text:
module Matrix

  # Public: A Class to represent the weight of a road between two connected cities.
  class Road
    include Comparable

    attr_reader :cities, :weight

    # Public: Initialize a new Matrix::Network::Road.
    #
    # city_a - The first Matrix::City.
    # city_b - The second Matrix::City.
    # weight - The weight of the road.
    def initialize(city_a, city_b, weight)
      raise ArgumentError unless city_a && city_b && weight.is_a?(Numeric)
      @cities = [city_a, city_b]
      @weight = weight
    end

    def <=>(other)
      weight <=> other.weight
    end

    def eql?(other)
      other.kind_of?(Road) && cities.sort == other.cities.sort
    end
  end
end


text:
package com.b2international.snowowl.snomed.reasoner;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

import com.b2international.index.Index;
import com.b2international.snowowl.core.RepositoryManager;
import com.b2international.snowowl.core.config.SnowOwlConfiguration;
import com.b2international.snowowl.core.plugin.Component;
import com.b2international.snowowl.core.repository.TerminologyRepositoryConfigurer;
import com.b2international.snowowl.core.setup.Environment;
import com.b2international.snowowl.core.setup.Plugin;
import com.b2international.snowowl.snomed.common.SnomedTerminologyComponentConstants;
import com.b2international.snowowl.snomed.datastore.config.SnomedCoreConfiguration;
import com.b2international.snowowl.snomed.reasoner.classification.ClassificationTracker;
import com.b2international.snowowl.snomed.reasoner.index.*;
import com.google.common.collect.ImmutableList;

/**
 * @since 7.0
 */
@Component
public final class SnomedReasonerPlugin extends Plugin implements TerminologyRepositoryConfigurer {

	@Override
	public void run(final SnowOwlConfiguration configuration, final Environment env) throws Exception {
		if (env.isServer()) {
			final Index repositoryIndex = env.service(RepositoryManager.class).get(getToolingId()).service(Index.class);
			final SnomedCoreConfiguration snomedConfig = configuration.getModuleConfig(SnomedCoreConfiguration.class);
			final int maximumReasonerRuns = snomedConfig.getMaxReasonerRuns();
			final long cleanUpInterval = TimeUnit.MINUTES.toMillis(5L); // TODO: make this configurable
			final ClassificationTracker classificationTracker = new ClassificationTracker(repositoryIndex, maximumReasonerRuns, cleanUpInterval);

			env.services().registerService(ClassificationTracker.class, classificationTracker);
		}
	}

	@Override
	public Collection<Class<?>> getAdditionalMappings() {
		return ImmutableList.<Class<?>>of(
			ClassificationTaskDocument.class,
			EquivalentConceptSetDocument.class,
			ConceptChangeDocument.class,
			DescriptionChangeDocument.class,
			RelationshipChangeDocument.class,
			ConcreteDomainChangeDocument.class
		);
	}

	@Override
	public String getToolingId() {
		return SnomedTerminologyComponentConstants.TOOLING_ID;
	}

}


text:
import { defineMessages } from 'react-intl'

// use pattern [reducer]_message

/* eslint-disable max-len */
export default defineMessages({
  lnurl_auth_error: 'Unable to authenticate with {service}: {reason}',
  lnurl_auth_success: 'Successfully authenticated with {service}',
  lnurl_channel_started: 'Incoming channel requested. Please wait…',
  lnurl_channel_error: 'Unable to request incoming channel from {service}: {reason}',
  lnurl_channel_success: 'Channel request from {service} accepted',
  lnurl_withdraw_started: 'Withdrawal requested. Please wait…',
  lnurl_withdraw_error: 'Unable to process withdrawal request from {service}: {reason}',
  lnurl_withdraw_success: 'Withdrawal request from {service} complete',
})


text:
package org.ripple.bouncycastle.jcajce.provider.symmetric;

import org.ripple.bouncycastle.crypto.CipherKeyGenerator;
import org.ripple.bouncycastle.crypto.engines.XTEAEngine;
import org.ripple.bouncycastle.jcajce.provider.config.ConfigurableProvider;
import org.ripple.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher;
import org.ripple.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator;
import org.ripple.bouncycastle.jcajce.provider.symmetric.util.IvAlgorithmParameters;
import org.ripple.bouncycastle.jcajce.provider.util.AlgorithmProvider;

public final class XTEA
{
    private XTEA()
    {
    }

    public static class ECB
        extends BaseBlockCipher
    {
        public ECB()
        {
            super(new XTEAEngine());
        }
    }

    public static class KeyGen
        extends BaseKeyGenerator
    {
        public KeyGen()
        {
            super("XTEA", 128, new CipherKeyGenerator());
        }
    }

    public static class AlgParams
        extends IvAlgorithmParameters
    {
        protected String engineToString()
        {
            return "XTEA IV";
        }
    }

    public static class Mappings
        extends AlgorithmProvider
    {
        private static final String PREFIX = XTEA.class.getName();

        public Mappings()
        {
        }

        public void configure(ConfigurableProvider provider)
        {

            provider.addAlgorithm("Cipher.XTEA", PREFIX + "$ECB");
            provider.addAlgorithm("KeyGenerator.XTEA", PREFIX + "$KeyGen");
            provider.addAlgorithm("AlgorithmParameters.XTEA", PREFIX + "$AlgParams");

        }
    }
}


text:
package org.ovirt.engine.ui.uicommonweb.models.storage;

import java.util.ArrayList;

import org.ovirt.engine.core.common.action.ImportVmTemplateParameters;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.Cluster;
import org.ovirt.engine.core.common.businessentities.Quota;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.uicommonweb.models.vms.ImportEntityData;
import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback;

public class RegisterTemplateModel extends RegisterEntityModel<VmTemplate> {

    protected void onSave() {
        ArrayList<VdcActionParametersBase> parameters = new ArrayList<>();
        for (ImportEntityData<VmTemplate> entityData : getEntities().getItems()) {
            VmTemplate vmTemplate = entityData.getEntity();
            Cluster cluster = entityData.getCluster().getSelectedItem();

            ImportVmTemplateParameters params = new ImportVmTemplateParameters();
            params.setContainerId(vmTemplate.getId());
            params.setStorageDomainId(getStorageDomainId());
            params.setImagesExistOnTargetStorageDomain(true);
            params.setClusterId(cluster != null ? cluster.getId() : null);

            if (isQuotaEnabled()) {
                Quota quota = entityData.getClusterQuota().getSelectedItem();
                params.setQuotaId(quota != null ? quota.getId() : null);
                params.setDiskTemplateMap(vmTemplate.getDiskTemplateMap());
                updateDiskQuotas(new ArrayList<Disk>(params.getDiskTemplateMap().values()));
            }

            parameters.add(params);
        }

        startProgress();
        Frontend.getInstance().runMultipleAction(VdcActionType.ImportVmTemplateFromConfiguration, parameters, new IFrontendMultipleActionAsyncCallback() {
            @Override
            public void executed(FrontendMultipleActionAsyncResult result) {
                stopProgress();
                cancel();
            }
        }, this);
    }

}


text:
import os
PROJECT_DIR = os.path.dirname(__file__)

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

CACHE_BACKEND = 'locmem:///'

MANAGERS = ADMINS

DATABASE_ENGINE = 'mysql'#'postgresql_psycopg2'       # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'cms'           # Or path to database file if using sqlite3.
DATABASE_USER = 'cms'           # Not used with sqlite3.
DATABASE_PASSWORD = 'cms'       # Not used with sqlite3.
DATABASE_HOST = ''     # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = ''              # Set to empty string for default. Not used with sqlite3.

# Test database settings
TEST_DATABASE_CHARSET = "utf8"
TEST_DATABASE_COLLATION = "utf8_general_ci"

DATABASE_SUPPORTS_TRANSACTIONS = True

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be avilable on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# Absolute path to the directory that holds media.
MEDIA_ROOT = os.path.join(PROJECT_DIR, '../cms/media/')
#ADMIN_MEDIA_ROOT = os.path.join(PROJECT_DIR, '../admin_media/')
MEDIA_URL = '/media/'

ADMIN_MEDIA_PREFIX = '/media/admin/'

FIXTURE_DIRS = [os.path.join(PROJECT_DIR, 'fixtures')]

# Make this unique, and don't share it with anybody.
SECRET_KEY = '*xq7m@)*f2awoj!spa0(jibsrz9%c0d=e(g)v*!17y(vx0ue_3'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
#     'django.template.loaders.eggs.load_template_source',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.auth",
    "django.core.context_processors.i18n",
    "django.core.context_processors.debug",
    "django.core.context_processors.request",
    "django.core.context_processors.media",
    "cms.context_processors.media",
)

INTERNAL_IPS = ('127.0.0.1',)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.doc.XViewMiddleware',

    #'django.contrib.csrf.middleware.CsrfMiddleware',
    'cms.middleware.user.CurrentUserMiddleware',
    'cms.middleware.page.CurrentPageMiddleware',
    'cms.middleware.multilingual.MultilingualURLMiddleware',
    'cms.middleware.toolbar.ToolbarMiddleware',
    #'debug_toolbar.middleware.DebugToolbarMiddleware',

)

ROOT_URLCONF = 'example.urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_DIR, 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.admin',
    'django.contrib.sites',
    #'tagging',

    'cms',
    'publisher',

    'cms.plugins.text',
    'cms.plugins.picture',
    'cms.plugins.file',
    'cms.plugins.flash',
    'cms.plugins.link',
    'cms.plugins.snippet',
    'cms.plugins.googlemap',
    'cms.plugins.teaser',
    'cms.plugins.video',
    'cms.plugins.twitter',
    'cms.plugins.inherit',
    'mptt',
    'reversion',
    'example.categories',
    #'debug_toolbar',
    'south',
    # sample application
    'example.sampleapp',
    #'test_utils',
    #'store',
)

gettext = lambda s: s

LANGUAGE_CODE = "en"

LANGUAGES = (
    ('fr', gettext('French')),
    ('de', gettext('German')),
    ('en', gettext('English')),
    ('pt-br', gettext("Brazil")),
)

CMS_LANGUAGE_CONF = {
    'de':['fr', 'en'],
    'en':['fr', 'de'],
}

APPEND_SLASH = True

CMS_TEMPLATES = (
    ('index.html', gettext('default')),
    ('nice.html', gettext('nice one')),
    ('cool.html', gettext('cool one')),
    ('long-folder-long/long-template-name.html', gettext('long')),
)

CMS_APPLICATIONS_URLS = (
    ('sampleapp.urls', 'Sample application'),
    ('sampleapp.urlstwo', 'Second sample application'),
)

CMS_PLACEHOLDER_CONF = {
    'right-column': {
        "plugins": ('FilePlugin', 'FlashPlugin', 'LinkPlugin', 'PicturePlugin', 'TextPlugin', 'SnippetPlugin'),
        "extra_context": {"theme":"16_16"},
        "name":gettext("right column")
    },

    'body': {
        "extra_context": {"theme":"16_5"},
        "name":gettext("body"),
    },
    'fancy-content': {
        "plugins": ('TextPlugin', 'LinkPlugin'),
        "extra_context": {"theme":"16_11"},
        "name":gettext("fancy content custom name"),
        "limits": {
            "global": 3,
            "TextPlugin": 1,
        },
    },
}

CMS_NAVIGATION_EXTENDERS = (('example.categories.navigation.get_nodes', 'Categories'),
                            ('example.sampleapp.menu_extender.get_nodes', 'SampleApp Menu'),)

CMS_SOFTROOT = True
CMS_MODERATOR = True
CMS_PERMISSION = True
CMS_REDIRECTS = True
CMS_SEO_FIELDS = True
CMS_FLAT_URLS = False
CMS_MENU_TITLE_OVERWRITE = True
CMS_HIDE_UNTRANSLATED = False
CMS_URL_OVERWRITE = True

try:
    from local_settings import *
except ImportError:
    pass

"""wt ?
try:
    import coverage
    TEST_RUNNER='cms.tests.test_runner_with_coverage'
    COVERAGE_MODULES = [
        'cms',
        'cms.admin',
        'cms.admin.change_list',
        'cms.admin.forms',
        'cms.admin.models',
        'cms.admin.permissionadmin',
        'cms.admin.useradmin',
        'cms.admin.utils',
        'cms.admin.views',
        'cms.admin.widgets',
        'cms.admin.dialog',
        'cms.admin.dialog.forms',
        'cms.admin.dialog.utils',
        'cms.admin.dialog.views',
        'cms.cache',
        'cms.cache.permissions',
        'cms.cache.signals',
        'cms.conf.global_settings',
        'cms.conf.patch',
        'cms.management.commands.publisher_publish',
        'cms.middleware.multilingual',
        'cms.middleware.page',
        'cms.middleware.user',
        'cms.migrations',
        'cms.models',
        'cms.models.managers',
        'cms.models.moderatormodels',
        'cms.models.pagemodel',
        'cms.models.permissionmodels',
        'cms.models.pluginmodel',
        'cms.models.query',
        'cms.models.signals',
        'cms.models.titlemodels',
        'cms.sitemaps.cms_sitemap',
        'cms.templatetags.cms_admin',
        'cms.templatetags.cms_tags',
        'cms.templatetags.js',
        'cms.templatetags.mlurl',
        'cms.utils',
        'cms.utils.admin',
        'cms.utils.helpers',
        'cms.utils.i18n',
        'cms.utils.mail',
        'cms.utils.moderator',
        'cms.utils.navigation',
        'cms.utils.page',
        'cms.utils.permissions',
        'cms.utils.urlutils',
        'cms.appresolver',
        'cms.context_processors',
        'cms.plugin_base',
        'cms.plugin_pool',
        'cms.signals',
        'cms.urls',
        'cms.views',
        'publisher',
        'publisher.base',
        'publisher.errors',
        'publisher.manager',
        'publisher.models',
        'publisher.mptt_support',
        'publisher.options',
        'publisher.query',
        ]
except:
    pass
"""


text:
namespace Central.SrcSrv
{
    using Central.Util;

    using System.Collections.Generic;
    using System.Diagnostics;

    /// <summary>
    /// The source store helpers.
    /// </summary>
    public class SourceStoreHelpers
    {
        public static List<string> GetSourceFilesFromPdb(string pdbFile)
        {
            var sourceFiles = new List<string>();

            var process = new Process
                              {
                                  StartInfo =
                                      {
                                          UseShellExecute = false,
                                          FileName = WinSdkToolResolver.GetPath(WinSdkTool.SrcTool),
                                          Arguments = CreateSrcToolCommandLine(pdbFile),
                                          RedirectStandardOutput = true
                                      }
                              };
            // process.StartInfo.CreateNoWindow = true;
            process.Start();
            while (true)
            {
                var sourceFileReference = process.StandardOutput.ReadLine();
                if (sourceFileReference == null)
                {
                    break;
                }

                sourceFiles.Add(sourceFileReference);
            }

            process.WaitForExit();

            return sourceFiles;
        }

        private static string CreateSrcToolCommandLine(string pdbFile)
        {
            var commandLine = new List<string>();

            commandLine.Add("-r");
            commandLine.Add(string.Format("\"{0}\"", pdbFile));

            return string.Join(" ", commandLine.ToArray());
        }

        public static List<string> AddStreamToPdb(string pdbFile, string srcsrvIniFile)
        {
            var sourceFiles = new List<string>();

            var process = new Process();
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.FileName = WinSdkToolResolver.GetPath(WinSdkTool.PdbStr);
            process.StartInfo.Arguments = CreatePdbstrCommandLine(pdbFile, srcsrvIniFile);
            // process.StartInfo.CreateNoWindow = true;
            process.Start();
            process.WaitForExit();

            return sourceFiles;
        }

        private static string CreatePdbstrCommandLine(string pdbFile, string srcsrvIniFile)
        {
            var commandLine = new List<string>();

            commandLine.Add("-w");
            commandLine.Add(string.Format("\"-p:{0}\"", pdbFile));
            commandLine.Add(string.Format("\"-i:{0}\"", srcsrvIniFile));
            commandLine.Add("-s:srcsrv");

            return string.Join(" ", commandLine.ToArray());
        }
    }
}


text:
import component from './component';
require('semantic-ui-css/semantic.css');
import './main.css';

document.body.appendChild(component());


text:
package eu.dnetlib.iis.wf.citationmatching;

import com.google.common.collect.Lists;
import eu.dnetlib.iis.citationmatching.schemas.ReferenceMetadata;
import eu.dnetlib.iis.wf.citationmatching.converter.ReferenceMetadataToMatchableConverter;
import org.apache.commons.lang3.StringUtils;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import pl.edu.icm.coansys.citations.data.MatchableEntity;
import scala.Option;
import scala.Tuple2;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;

import static org.mockito.Mockito.*;

/**
 * @author madryk
 */
@ExtendWith(MockitoExtension.class)
public class ReferenceMetadataInputConverterTest {

    private ReferenceMetadataInputConverter referenceMetadataInputConverter = new ReferenceMetadataInputConverter();

    @Mock
    private ReferenceMetadataToMatchableConverter converter;

    @Mock
    private JavaPairRDD<String, ReferenceMetadata> inputCitations;

    @Mock
    private JavaPairRDD<String, MatchableEntity> convertedCitations;

    @Captor
    private ArgumentCaptor<PairFlatMapFunction<Tuple2<String, ReferenceMetadata>, String, MatchableEntity>> convertCitationFunction;

    @BeforeEach
    public void setup() {
        referenceMetadataInputConverter.setConverter(converter);
    }

    //------------------------ TESTS --------------------------

    @Test
    public void convertCitations() throws Exception {

        // given
        doReturn(convertedCitations).when(inputCitations).flatMapToPair(any());

        // execute

        JavaPairRDD<String, MatchableEntity> retConvertedCitations = referenceMetadataInputConverter.convertCitations(inputCitations);

        // assert

        assertSame(retConvertedCitations, convertedCitations);

        verify(inputCitations).flatMapToPair(convertCitationFunction.capture());
        assertConvertCitationFunction(convertCitationFunction.getValue());
        assertConvertCitationFunction_TOO_LONG_RAW_TEXT(convertCitationFunction.getValue());

    }

    //------------------------ PRIVATE --------------------------

    private void assertConvertCitationFunction(PairFlatMapFunction<Tuple2<String, ReferenceMetadata>, String, MatchableEntity> function) throws Exception {
        ReferenceMetadata referenceMetadata = mock(ReferenceMetadata.class);
        MatchableEntity matchableEntity = mock(MatchableEntity.class);

        when(converter.convertToMatchableEntity("cit_id_3", referenceMetadata)).thenReturn(matchableEntity);
        doReturn(Option.apply("some raw text")).when(matchableEntity).rawText();

        Iterable<Tuple2<String, MatchableEntity>> retConverted = function.call(new Tuple2<>("cit_id_3", referenceMetadata));

        List<Tuple2<String, MatchableEntity>> retConvertedList = Lists.newArrayList(retConverted);
        assertEquals(1, retConvertedList.size());
        assertSame(retConvertedList.get(0)._2, matchableEntity);
        assertEquals("cit_id_3", retConvertedList.get(0)._1);

    }

    private void assertConvertCitationFunction_TOO_LONG_RAW_TEXT(PairFlatMapFunction<Tuple2<String, ReferenceMetadata>, String, MatchableEntity> function) throws Exception {
        ReferenceMetadata referenceMetadata = mock(ReferenceMetadata.class);
        MatchableEntity matchableEntity = mock(MatchableEntity.class);

        when(converter.convertToMatchableEntity("cit_id_3", referenceMetadata)).thenReturn(matchableEntity);
        doReturn(Option.apply(StringUtils.repeat('a', 10001))).when(matchableEntity).rawText();

        Iterable<Tuple2<String, MatchableEntity>> retConverted = function.call(new Tuple2<>("cit_id_3", referenceMetadata));

        List<Tuple2<String, MatchableEntity>> retConvertedList = Lists.newArrayList(retConverted);
        assertEquals(0, retConvertedList.size());

    }
}


text:
using SFA.DAS.CookieService;
using SFA.DAS.EmployerAccounts.Interfaces;
using SFA.DAS.EmployerAccounts.Services;
using SFA.DAS.EmployerAccounts.Web.Logging;
using SFA.DAS.NLog.Logger;
using StructureMap;
using System.Web;
using SFA.DAS.Authorization.Context;
using SFA.DAS.EmployerAccounts.Web.Authorization;
using SFA.DAS.Authorization.Handlers;
using SFA.DAS.EmployerAccounts.Web.Orchestrators;

namespace SFA.DAS.EmployerAccounts.Web.DependencyResolution
{
    public class DefaultRegistry : Registry
    {
        public DefaultRegistry()
        {
            Scan(s =>
            {
                s.AssembliesFromApplicationBaseDirectory(a => a.GetName().Name.StartsWith("SFA.DAS") && !a.GetName().Name.StartsWith("SFA.DAS.Authorization"));
                s.RegisterConcreteTypesAgainstTheFirstInterface();
                s.With(new ControllerConvention());
            });

            For<ILoggingContext>().Use(c => HttpContext.Current == null ? null : new LoggingContext(new HttpContextWrapper(HttpContext.Current)));
            For<HttpContextBase>().Use(() => new HttpContextWrapper(HttpContext.Current));
            For(typeof(ICookieService<>)).Use(typeof(HttpCookieService<>));
            For(typeof(ICookieStorageService<>)).Use(typeof(CookieStorageService<>));

            var authorizationContextProvider = For<IAuthorizationContextProvider>().Use<AuthorizationContextProvider>();
            For<IAuthorizationContextProvider>().Use<ImpersonationAuthorizationContext>()
           .Ctor<IAuthorizationContextProvider>().Is(authorizationContextProvider);
            For<IDefaultAuthorizationHandler>().Use<Authorization.DefaultAuthorizationHandler>();

            For<EmployerTeamOrchestrator>().DecorateAllWith<EmployerTeamOrchestratorWithCallToAction>();
        }
    }

}


text:
<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Line_Suit extends ORM {
    protected  $_table_name = 'line_suit';

	public function deleteClear()
	{
	   if($this->id)
       {
           DB::delete('line_suit_price')->where("suitid={$this->id}")->execute();
           $this->delete();
       }

	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
              android:background="@android:color/holo_orange_dark"
              android:gravity="center"
    >

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textSize="30sp"
       android:textColor="@android:color/white"
       android:text="StackCardsView"
       />

</LinearLayout>


text:
package it.uspread.android.activity.stats;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import java.util.List;

import it.uspread.android.R;
import it.uspread.android.activity.USpreadItFragment;
import it.uspread.android.data.UserRanking;
import it.uspread.android.task.Task;
import it.uspread.android.task.TaskListUsersRanking;

/**
 * Activité
 *

 *
Page des scores

 *

 *
 * @author Lone Décosterd,
 */
public class HallOfFameFragmentActivity extends USpreadItFragment {

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.activity_scores, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loadingUsersRanking();
    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().setTitle(getResources().getString(R.string.activity_scores));
    }

    /**
     * Chargement du classement.
     */
    private void loadingUsersRanking() {
        new TaskListUsersRanking().execute();
    }

    @Override
    public void onReceiveTaskResultUpdateUI(final Task.TaskResult taskResult) {
        if (taskResult.success) {
            if (taskResult.resultCode == TaskListUsersRanking.RESULT_CODE) {
                final List<UserRanking> listUserRanking = (List<UserRanking>) taskResult.resultData;
                final UsersAdapter listAdapter = new UsersAdapter(getActivity(), listUserRanking);
                ((ListView) getActivity().findViewById(R.id.listUsers)).setAdapter(listAdapter);
            }
        }
    }
}


text:
package io.jenkins.blueocean.blueocean_bitbucket_pipeline.server;

import com.cloudbees.jenkins.plugins.bitbucket.endpoints.AbstractBitbucketEndpoint;
import com.cloudbees.jenkins.plugins.bitbucket.endpoints.BitbucketEndpointConfiguration;
import io.jenkins.blueocean.blueocean_bitbucket_pipeline.Messages;
import io.jenkins.blueocean.commons.DigestUtils;
import io.jenkins.blueocean.commons.ServiceException;
import io.jenkins.blueocean.rest.Reachable;
import io.jenkins.blueocean.rest.hal.Link;
import io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpoint;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebMethod;
import org.kohsuke.stapler.verb.DELETE;
import org.kohsuke.stapler.verb.GET;

import javax.servlet.http.HttpServletResponse;

/**
 * @author Vivek Pandey
 */
public class BitbucketServerEndpoint extends ScmServerEndpoint {
    private final String id;
    private final Link self;
    private final String apiUrl;
    private final String name;

    public BitbucketServerEndpoint(AbstractBitbucketEndpoint endpoint, Reachable parent) {
        this.id = DigestUtils.sha256Hex(endpoint.getServerUrl());
        this.apiUrl = endpoint.getServerUrl();
        this.name = StringUtils.isBlank(endpoint.getDisplayName()) ?  endpoint.getServerUrl() : endpoint.getDisplayName();
        this.self = parent.getLink().rel(id);
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getApiUrl() {
        return apiUrl;
    }

    @Override
    public Link getLink() {
        return self;
    }

    /**
     * Validates this server endpoint. Checks availability and version requirement.
     * @return If valid HttpStatus 200, if unsupported version then 428 and if unreachable then 400 error code is returned.
     */
    @GET
    @WebMethod(name="validate")
    public HttpResponse validate(){
        String version = BitbucketServerApi.getVersion(apiUrl);
        if(!BitbucketServerApi.isSupportedVersion(version)){
            throw new ServiceException.PreconditionRequired(
                    Messages.bbserver_version_validation_error(
                            version, BitbucketServerApi.MINIMUM_SUPPORTED_VERSION));
        }
        return ( req, rsp, node ) -> rsp.setStatus( 200);
    }

    @WebMethod(name="") @DELETE
    public void doDelete(StaplerResponse resp) {
        final BitbucketEndpointConfiguration config = BitbucketEndpointConfiguration.get();
        config.removeEndpoint(getApiUrl());
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}


text:
package glkit

type Window interface {
	SetTitle(title string)
}

/*
Create a new window with the specified width and height.
*/
func CreateWindow(width, height int) (Window, error) {
	return PlatformCreateWindow(width, height)
}

var PlatformCreateWindow = func(width, height int) (Window, error) {
	panic("no Atitlan foundation backend imported")
}


text:
import { Component, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
import { BLE } from '@ionic-native/ble';
import { Trackees } from '../../providers/providers';
import { AlertController } from 'ionic-angular';

declare var google;

@Component({
  templateUrl: 'trackee-add.html',
})
export class TrackeeAddPage {
  id: string;
  name: string;
  type: string;
  nearMeNotifSetting: string;
  showMap: Boolean = true;
  firstIdHit: Boolean = false;
  @ViewChild('map') map;
  constructor(private nav: NavController, private ble: BLE, private trackees: Trackees, public alert: AlertController) {}

  initJSMaps(mapEle) {
    let map = new google.maps.Map(mapEle, {
      center: { lat: -6.2416331, lng: 106.7945741 },
      zoom: 15,
      mapTypeControl: false,
      streetViewControl: false,
      fullscreenControl: false
    });

    map.setOptions({ minZoom: 11, maxZoom: 20 });

    var bounds = {
      north: -6.2416331 + 0.005,
      south: -6.2416331 - 0.005,
      east: 106.7945741 + 0.005,
      west: 106.7945741 - 0.005
    };

    // Define a rectangle and set its editable property to true.
    var rectangle = new google.maps.Rectangle({
      bounds: bounds,
      editable: true
    });
    rectangle.setMap(map);
  }

  ionViewDidLoad() {
    let mapEle = this.map.nativeElement;

    if (!mapEle) {
      console.error('Unable to initialize map, no map element with #map view reference.');
      return;
    }

    // Disable this switch if you'd like to only use JS maps, as the APIs
    // are slightly different between the two. However, this makes it easy
    // to use native maps while running in Cordova, and JS maps on the web.
    // if (this.platform.is('cordova') === true) {
    //   this.initNativeMaps(mapEle);
    // } else {
    //   this.initJSMaps(mapEle);
    // }
    this.initJSMaps(mapEle);
  }

  scanBLE() {
    this.firstIdHit = true;
    const onDeviceFound = (device) => {
      if (this.firstIdHit) {
        this.id = device.id;
        this.firstIdHit = false;
      }
    }
    const onError = (err) => {
      console.log('Error while scanning:', err);
    }
    this.ble.startScan([]).subscribe(onDeviceFound, onError);
  }

  saveTrackee() {
    const payload = {
      boundingBoxNotifSetting: {
        enabled: false,
        // enabled: true,
        // northeast: {
        //   latitude: -6.240446,
        //   longitude: 106.790652
        // },
        // southwest: {
        //   latitude: -6.241364,
        //   longitude: 106.791425
        // }
      },
      category: this.type,
      id: this.id,
      name: this.name,
      nearMeNotifSetting: parseInt(this.nearMeNotifSetting || "0")
    };
    this.trackees.existById(this.id, (res) => {
      if (res) {
        let alert = this.alert.create({
          title: 'Already registered!',
          subTitle: 'Your scanned device already registered!',
          buttons: ['OK']
        });
        alert.present();
      } else {
        this.trackees.store(payload, () => {
           this.nav.pop();
        });
      }
    });
  }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cmd3/cmd3.h"
#include "linenoise/linenoise.h"

static int sys_info(int argc, const char **argv, char *buf, size_t buf_size)
{
	int bytes_writen;

	bytes_writen = snprintf(buf, buf_size, "Info: argc=%d, arg[0]=%s""\n", argc, argv[0]);

	return bytes_writen;
}

static void register_commands()
{
    new_cmdtree_create("info", "System Information", sys_info, CMDTREE_NO_PARENT);
}

static void completion(const char *buf, linenoiseCompletions *lc)
{
//    if (buf[0] == 'h') {
//        linenoiseAddCompletion(lc,"hello");
//        linenoiseAddCompletion(lc,"hello there");
//    }
}

int main(int argc, char **argv)
{
    char *line;
    char *prgname = argv[0];
    char report_buf[256];

    register_commands();

    if(argc > 1)
    {
        argc--;
        argv++;
        if (!strcmp(*argv,"-c"))
        {
            argc--;
            argv++;

        	const char *arg_vdata[CMD_TREE_MAX_DEPTH];
        	const char **arg_vec = arg_vdata;
        	int   arg_count = 0;
        	cmdtree_stov(*argv, &arg_count, arg_vec);

            report_buf[0] = '\0';
            cmdtree_exec(arg_count, arg_vec, report_buf, sizeof(report_buf));
            printf("\r%s", report_buf);
        }
        else
        {
            fprintf(stderr, "Usage: %s [-c \"command\"]\n", prgname);
            exit(1);
        }
    }

    /* Set the completion callback. This will be called every time the
     * user uses the <tab> key. */
    linenoiseSetCompletionCallback(completion);

    /* Load history from file. The history file is just a plain text file
     * where entries are separated by newlines. */
    linenoiseHistoryLoad("history.txt"); /* Load the history at startup */

    /*
     * The typed string is returned as a malloc() allocated string by
     * linenoise, so the user needs to free() it. */
    while((line = linenoise("\r" "console> ")) != NULL)
    {
    	printf("\r");
        if (line[0] != '\0' && line[0] != '/')
        {
            linenoiseHistoryAdd(line); /* Add to the history. */

        	/*
        	 * Split the cmd string using white space delimiters, ending up with an argv/argc format.
        	 */
        	const char *arg_vdata[CMD_TREE_MAX_DEPTH];
        	const char **arg_vec = arg_vdata;
        	int   arg_count = 0;
        	cmdtree_stov(line, &arg_count, arg_vec);

        	report_buf[0] = '\0';
        	cmdtree_exec(arg_count, arg_vec, report_buf, sizeof(report_buf));
            printf("%s\r\n", report_buf);

            linenoiseHistorySave("history.txt"); /* Save the history on disk. */
        }
        else if (!strncmp(line,"/q",2))
        {
        	printf("Exit console.\r\n");
        	free(line);
        	exit(0);
        }
        else if (line[0] == '/')
        {
            printf("Unreconized command: %s\n", line);
        }
        free(line);
    }
    return 0;
}


text:
from __future__ import unicode_literals, print_function
import unittest
import compilebot as cb

"""
Integration test cases for the compile function. Tests require ideone login
credentials.

Run the following command from the parent directory in order to run only
this test module: python -m unittest tests.integration.compiler
"""

cb.USER_AGENT = "compilebot integration tests run by {}".format(cb.R_USERNAME)
cb.LOG_FILE = "tests.log"

def test_suite():
    cases = [
        TestCompile
    ]
    alltests = [
        unittest.TestLoader().loadTestsFromTestCase(case) for case in cases
    ]
    return unittest.TestSuite(alltests)

@unittest.skipIf(cb.CONFIG['tests']['integration']['compiler']['skip'],
                 "Test config option set to skip")
class TestCompile(unittest.TestCase):

    def test_compile(self):
        expected_details = {
            'cmpinfo': '',
            'error': 'OK',
            'input': "Hello World",
            'langId': 116,
            'langName': "Python 3",
            'output': "Hello World\n",
            'public': True,
            'result': 15,
            'signal': 0,
            'source': "x = input()\nprint(x)",
            'status': 0,
            'stderr': "",
        }
        source = "x = input()\nprint(x)"
        lang = "python 3"
        stdin = "Hello World"
        details = cb.compile(source, lang, stdin)
        self.assertTrue(details['link'])
        self.assertDictContainsSubset(expected_details, details)

if __name__ == "__main__":
    unittest.main(exit=False)


text:
package hu.akarnokd.rxjava2.basetypes;

import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;

import org.reactivestreams.*;

import io.reactivex.exceptions.*;
import io.reactivex.functions.*;
import io.reactivex.internal.functions.ObjectHelper;
import io.reactivex.internal.subscriptions.*;
import io.reactivex.plugins.RxJavaPlugins;

/**
 * Use a resource while the actual Solo is running.
 * @param <T> the element type of the supplied Solo
 * @param <R> the resource type
 */
final class SoloUsing<T, R> extends Solo<T> {

    final Callable<R> resourceSupplier;

    final Function<? super R, ? extends Solo<T>> sourceSupplier;

    final Consumer<? super R> disposer;

    final boolean eager;

    SoloUsing(Callable<R> resourceSupplier, Function<? super R, ? extends Solo<T>> sourceSupplier,
            Consumer<? super R> disposer, boolean eager) {
        this.resourceSupplier = resourceSupplier;
        this.sourceSupplier = sourceSupplier;
        this.disposer = disposer;
        this.eager = eager;
    }

    @Override
    protected void subscribeActual(Subscriber<? super T> s) {
        R resource;

        try {
            resource = resourceSupplier.call();
        } catch (Throwable ex) {
            Exceptions.throwIfFatal(ex);
            EmptySubscription.error(ex, s);
            return;
        }

        Solo<T> np;

        try {
            np = ObjectHelper.requireNonNull(sourceSupplier.apply(resource), "The sourceSupplier returned a null Nono");
        } catch (Throwable ex) {
            Exceptions.throwIfFatal(ex);
            if (eager) {
                try {
                    disposer.accept(resource);
                } catch (Throwable exc) {
                    Exceptions.throwIfFatal(exc);
                    ex = new CompositeException(ex, exc);
                }

                EmptySubscription.error(ex, s);
            } else {
                EmptySubscription.error(ex, s);
                try {
                    disposer.accept(resource);
                } catch (Throwable exc) {
                    Exceptions.throwIfFatal(exc);
                    RxJavaPlugins.onError(exc);
                }
            }
            return;
        }

        np.subscribe(new UsingSubscriber<T, R>(s, resource, disposer, eager));
    }

    static final class UsingSubscriber<T, R> extends DeferredScalarSubscription<T>
    implements Subscriber<T> {

        private static final long serialVersionUID = 5500674592438910341L;

        final Consumer<? super R> disposer;

        final boolean eager;

        final AtomicBoolean once;

        Subscription upstream;

        R resource;

        UsingSubscriber(Subscriber<? super T> downstream, R resource, Consumer<? super R> disposer, boolean eager) {
            super(downstream);
            this.resource = resource;
            this.disposer = disposer;
            this.eager = eager;
            this.once = new AtomicBoolean();
        }

        @Override
        public void cancel() {
            if (once.compareAndSet(false, true)) {
                disposeFinally();
            }
        }

        void disposeFinally() {
            try {
                disposer.accept(resource);
            } catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                RxJavaPlugins.onError(ex);
            }
        }

        @Override
        public void onSubscribe(Subscription s) {
            if (SubscriptionHelper.validate(this.upstream, s)) {
                this.upstream = s;

                downstream.onSubscribe(this);

                s.request(Long.MAX_VALUE);
            }
        }

        @Override
        public void onNext(T t) {
            value = t;
        }

        @Override
        public void onError(Throwable t) {
            if (eager) {
                if (once.compareAndSet(false, true)) {
                    try {
                        disposer.accept(resource);
                    } catch (Throwable ex) {
                        Exceptions.throwIfFatal(ex);
                        t = new CompositeException(t, ex);
                    }
                }
            }

            downstream.onError(t);

            if (!eager) {
                if (once.compareAndSet(false, true)) {
                    disposeFinally();
                }
            }
        }

        @Override
        public void onComplete() {
            if (eager) {
                if (once.compareAndSet(false, true)) {
                    try {
                        disposer.accept(resource);
                    } catch (Throwable ex) {
                        Exceptions.throwIfFatal(ex);
                        downstream.onError(ex);
                        return;
                    }
                }
            }

            T v = value;
            if (v == null) {
                downstream.onComplete();
            } else {
                complete(v);
            }

            if (!eager) {
                if (once.compareAndSet(false, true)) {
                    disposeFinally();
                }
            }
        }
    }
}


text:
module AuthTogether
  VERSION = "0.0.1.alpha"
end


text:
from ._policy_client import PolicyClient
__all__ = ['PolicyClient']


text:
package ua.ikonovalov.professions;

/**
 * Created by Strong on 10.09.18.
 */
public class Student {
    private String name;
    private int course;

    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return this.name;
    }
    public int getCourse() {
        return this.course;
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Llama By Varun Gaur</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

    <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet">

    <link href="css/creative.min.css" rel="stylesheet">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Home

                        About

                        Facts

						Motivation

                        Fans

                        Contact

Save the Drama
For the Llama

Hello and Welcome Dear Llama Lovers!!!
Wanna know more about the Majestic Llamas?

                Find Out More

The Great Llamas

Llamas are native to South America and are domesticated as pack animals to move large amounts of goods over the rough terrain of the Andes. There is so much to know about these awesome animals.

                    Let's Get Started!

                                    Know More About

                                    Llama's Origins

                                    Know More About

                                    Llama's Home

                                    Know More About

                                    Llama's Food

                                    Know More About

                                    Llama's Strengths

                                    Know More About

                                    Llama Babies

                                    Know More About

                                    Other Fun Facts

Motivation and my Interests

					I am crazy for how things look. I feel extracting data is vital but transforming the extracted data into more meaningful information and presenting it in an understandable format is far more critical.

As it is eminent from my resume, I have been professionally working on Front-end Screens development from last 8 years now. It was just my interest which landed me in a team of experts in this field. I have worked in a team (Front-end Reviewer team for Finacle 10.3.x Release) which reviews front-end specific code changes and constantly tries to come up with front-end specific technical amendments to improve a banking user's experience.

Currently I am doing research work with Dr. Paolo Papotti, where we are trying to come up with a Console (Rule Miner) for Data Scientists where they can discover Horn Rules and execute those rules on some positive and negative examples. A user might not be able to understand the rules extracted by the algorithm as it is full of mathematical jargons,  hence we are trying to enhance system capabilities to present extracted Rules in a more English-like statements to improve readability of Complex rules. Presenting data in an efficient and elegant way is of utmost importance. We are using different technologies for doing these tasks like jQuery, Ajax calls, Bootstrap, HTML5 etc

Reason behind the Way it is !!

This website is designed using some of the Latest Technologies like Bootstrap, jQuery and HTML5.
					HTML5 provides many advantages such as Inbuilt Support for Multimedia Components, Access to Geo Location, Client Side Storage using Web SQL database and application cache, among many others.
					Bootstrap makes this website 100% responsive and highly flexible.

Know More About the Biggest Llama Lover

Varun's Website

Varun's LinkedIn

Varun's Github

Varun's Facebook

Get My Resume Here

                Resume

Connect With Me

Call me or send an email and I will get in touch with you asap.

408-480-2742

varungaur.jp@gmail.com