text:
package com.opengamma.financial.analytics.model.credit.isdanew;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.lang.ArrayUtils;
import org.threeten.bp.Period;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;

import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.credit.BuySellProtection;
import com.opengamma.analytics.financial.credit.creditdefaultswap.StandardCDSQuotingConvention;
import com.opengamma.analytics.financial.credit.isdastandardmodel.AnalyticCDSPricer;
import com.opengamma.analytics.financial.credit.isdastandardmodel.CDSAnalytic;
import com.opengamma.analytics.financial.credit.isdastandardmodel.CDSQuoteConvention;
import com.opengamma.analytics.financial.credit.isdastandardmodel.FiniteDifferenceSpreadSensitivityCalculator;
import com.opengamma.analytics.financial.credit.isdastandardmodel.IMMDateLogic;
import com.opengamma.analytics.financial.credit.isdastandardmodel.ISDACompliantCreditCurve;
import com.opengamma.analytics.financial.credit.isdastandardmodel.ISDACompliantYieldCurve;
import com.opengamma.analytics.financial.credit.isdastandardmodel.MarketQuoteConverter;
import com.opengamma.analytics.financial.credit.isdastandardmodel.ParSpread;
import com.opengamma.analytics.financial.credit.isdastandardmodel.PointsUpFront;
import com.opengamma.analytics.financial.credit.isdastandardmodel.QuotedSpread;
import com.opengamma.analytics.financial.model.BumpType;
import com.opengamma.analytics.math.curve.NodalTenorDoubleCurve;
import com.opengamma.core.AbstractSourceWithExternalBundle;
import com.opengamma.core.change.ChangeManager;
import com.opengamma.core.change.DummyChangeManager;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.core.region.Region;
import com.opengamma.core.region.RegionSource;
import com.opengamma.core.value.MarketDataRequirementNames;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.function.AbstractFunction.NonCompiledInvoker;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.OpenGammaCompilationContext;
import com.opengamma.financial.analytics.TenorLabelledMatrix1D;
import com.opengamma.financial.analytics.model.cds.ISDAFunctionConstants;
import com.opengamma.financial.analytics.model.credit.CreditSecurityToRecoveryRateVisitor;
import com.opengamma.financial.analytics.model.credit.SpreadCurveFunctions;
import com.opengamma.financial.credit.CdsRecoveryRateIdentifier;
import com.opengamma.financial.security.FinancialSecurityTypes;
import com.opengamma.financial.security.cds.CreditDefaultSwapSecurity;
import com.opengamma.financial.security.cds.LegacyVanillaCDSSecurity;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.id.ObjectId;
import com.opengamma.id.UniqueId;
import com.opengamma.id.VersionCorrection;
import com.opengamma.master.region.ManageableRegion;
import com.opengamma.util.async.AsynchronousExecution;
import com.opengamma.util.credit.CreditCurveIdentifier;
import com.opengamma.util.i18n.Country;
import com.opengamma.util.money.Currency;
import com.opengamma.util.time.Tenor;

//TODO Check bucketed cs01 in desired outputs before calcing as expensive

/**
 * Abstract class for cds functions that require ISDA and spread curves.
 */
public class ISDACompliantCDSFunction extends NonCompiledInvoker {

  private final String[] _valueRequirements = new String[] { ValueRequirementNames.ACCRUED_DAYS, ValueRequirementNames.ACCRUED_PREMIUM,
                ValueRequirementNames.POINTS_UPFRONT, ValueRequirementNames.CLEAN_PRESENT_VALUE, ValueRequirementNames.DIRTY_PRESENT_VALUE,
                ValueRequirementNames.CLEAN_PRICE,
                ValueRequirementNames.QUOTED_SPREAD, ValueRequirementNames.UPFRONT_AMOUNT, ValueRequirementNames.BUCKETED_CS01,
                ValueRequirementNames.PARALLEL_CS01,
                ValueRequirementNames.PRINCIPAL };
  public static final double ONE_BPS = 1e-4; // fractional 1 BPS
  private HolidaySource _holidaySource; // OpenGammaCompilationContext.getHolidaySource(context);
  private RegionSource _regionSource;
  private static final MarketQuoteConverter POINTS_UP_FRONT_CONVERTER = new MarketQuoteConverter();
  protected static final AnalyticCDSPricer PRICER = new AnalyticCDSPricer();
  public static final FiniteDifferenceSpreadSensitivityCalculator CALCULATOR = new FiniteDifferenceSpreadSensitivityCalculator();

  @Override
  public void init(final FunctionCompilationContext context) {
    // using hardcoded region and calendar for now
    _holidaySource = OpenGammaCompilationContext.getHolidaySource(context);
    _regionSource = new TestRegionSource(getTestRegion()); // OpenGammaCompilationContext.getRegionSource(context);
    // _converter = new CreditDefaultSwapSecurityConverterDeprecated(holidaySource, regionSource);
  }

  @Override
  public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target,
      final Set<ValueRequirement> desiredValues)
      throws AsynchronousExecution {
    final ZonedDateTime now = ZonedDateTime.now(executionContext.getValuationClock());
    final ValueRequirement requirement = desiredValues.iterator().next();
    final ValueProperties properties = requirement.getConstraints().copy().get();

    final LegacyVanillaCDSSecurity security = (LegacyVanillaCDSSecurity) target.getSecurity();
    // LegacyVanillaCreditDefaultSwapDefinition cds = _converter.visitLegacyVanillaCDSSecurity(security);
    final ValueRequirement desiredValue = desiredValues.iterator().next(); // all same constraints

    final String quoteConventionString = desiredValue.getConstraint(ISDAFunctionConstants.CDS_QUOTE_CONVENTION);
    final StandardCDSQuotingConvention quoteConvention = StandardCDSQuotingConvention.parse(quoteConventionString);

    final CdsRecoveryRateIdentifier recoveryRateIdentifier = security.accept(new CreditSecurityToRecoveryRateVisitor(
        executionContext.getSecuritySource()));
    final Object recoveryRateObject = inputs.getValue(new ValueRequirement("PX_LAST",
        ComputationTargetType.PRIMITIVE,
        recoveryRateIdentifier.getExternalId()));
    if (recoveryRateObject == null) {
      throw new OpenGammaRuntimeException("Could not get recovery rate");
      // LOGGER.warn("Could not get recovery rate, defaulting to 0.4: " + recoveryRateIdentifier);
      // recoveryRateObject = 0.4;
    }
    final double recoveryRate = (Double) recoveryRateObject;

    // get the isda curve
    final Object isdaObject = inputs.getValue(ValueRequirementNames.YIELD_CURVE);
    if (isdaObject == null) {
      throw new OpenGammaRuntimeException("Couldn't get isda curve");
    }
    final ISDACompliantYieldCurve yieldCurve = (ISDACompliantYieldCurve) isdaObject;

    // spreads
    final NodalTenorDoubleCurve spreadObject = (NodalTenorDoubleCurve) inputs.getValue(ValueRequirementNames.BUCKETED_SPREADS);
    if (spreadObject == null) {
      throw new OpenGammaRuntimeException("Unable to get spreads");
    }
    final double[] spreads = ArrayUtils.toPrimitive(spreadObject.getYData());
    // final String pillarString = IMMDateGenerator.isIMMDate(security.getMaturityDate()) ? requirement.getConstraint(ISDAFunctionConstants.ISDA_BUCKET_TENORS)
    // : ISDACompliantCreditCurveFunction.NON_IMM_PILLAR_TENORS;
    final ZonedDateTime[] bucketDates = SpreadCurveFunctions.getPillarDates(now, spreadObject.getXData());
    final CDSQuoteConvention[] quotes = SpreadCurveFunctions.getQuotes(security.getMaturityDate(), spreads, security.getParSpread(), quoteConvention, false);

    // spreads
    final NodalTenorDoubleCurve pillarObject = (NodalTenorDoubleCurve) inputs.getValue(ValueRequirementNames.PILLAR_SPREADS);
    if (pillarObject == null) {
      throw new OpenGammaRuntimeException("Unable to get pillars");
    }

    // CDS analytics for credit curve (possible performance improvement if earlier result obtained)
    // final LegacyVanillaCreditDefaultSwapDefinition curveCDS = cds.withStartDate(now);
    // security.setStartDate(now); // needed for curve instruments
    final CDSAnalytic[] bucketCDSs = new CDSAnalytic[bucketDates.length];
    for (int i = 0; i < bucketCDSs.length; i++) {
      // security.setMaturityDate(bucketDates[i]);
      final CDSAnalyticVisitor visitor = new CDSAnalyticVisitor(now.toLocalDate(), _holidaySource, _regionSource, security.getStartDate().toLocalDate(),
          bucketDates[i].toLocalDate(), recoveryRate);
      bucketCDSs[i] = security.accept(visitor);
    }

    final ZonedDateTime[] pillarDates = SpreadCurveFunctions.getPillarDates(now, pillarObject.getXData());
    final CDSAnalytic[] pillarCDSs = new CDSAnalytic[pillarDates.length];
    for (int i = 0; i < pillarCDSs.length; i++) {
      // security.setMaturityDate(bucketDates[i]);
      final CDSAnalyticVisitor visitor = new CDSAnalyticVisitor(now.toLocalDate(), _holidaySource, _regionSource, security.getStartDate().toLocalDate(),
          pillarDates[i].toLocalDate(), recoveryRate);
      pillarCDSs[i] = security.accept(visitor);
    }

    final ISDACompliantCreditCurve creditCurve = (ISDACompliantCreditCurve) inputs.getValue(ValueRequirementNames.HAZARD_RATE_CURVE);
    if (creditCurve == null) {
      throw new OpenGammaRuntimeException("Couldnt get credit curve");
    }

    // final CDSAnalytic analytic = CDSAnalyticConverter.create(cds, now.toLocalDate());
    final CDSAnalyticVisitor visitor = new CDSAnalyticVisitor(now.toLocalDate(), _holidaySource, _regionSource, recoveryRate);
    final CDSAnalytic analytic = security.accept(visitor);
    final BuySellProtection buySellProtection = security.isBuy() ? BuySellProtection.BUY : BuySellProtection.SELL;
    // final String term = new Tenor(Period.between(security.getStartDate().toLocalDate(), security.getMaturityDate().toLocalDate())).getPeriod().toString();
    // final Double cdsQuoteDouble = (Double) inputs.getValue(new ValueRequirement(MarketDataRequirementNames.MARKET_VALUE,
    // ComputationTargetType.PRIMITIVE, ExternalId.of("Tenor", term)));
    final Double cdsQuoteDouble = (Double) inputs.getValue(MarketDataRequirementNames.MARKET_VALUE);
    if (cdsQuoteDouble == null) {
      throw new OpenGammaRuntimeException("Couldn't get spread for " + security);
    }
    final CDSQuoteConvention quote = SpreadCurveFunctions.getQuotes(security.getMaturityDate(), new double[] { cdsQuoteDouble }, security.getParSpread(),
        quoteConvention, true)[0];

    final boolean isNonIMMFAndFromPUF = !IMMDateLogic.isIMMDate(security.getMaturityDate().toLocalDate()) && quote instanceof PointsUpFront;
    final boolean isNonIMMAndFromSpread = !IMMDateLogic.isIMMDate(security.getMaturityDate().toLocalDate())
        && (quote instanceof QuotedSpread || quote instanceof ParSpread);
    final int buySellPremiumFactor = security.isBuy() ? -1 : 1;

    final double notional = security.getNotional().getAmount();
    final double coupon = security.getParSpread() * ONE_BPS;
    final PointsUpFront puf = getPointsUpfront(quote, buySellProtection, yieldCurve, analytic, creditCurve);
    final double accruedPremiumPrim = isNonIMMAndFromSpread || isNonIMMFAndFromPUF ? 0 : analytic.getAccruedPremium(coupon);
    // final double accruedPremium = isNonIMMAndFromSpread || isNonIMMFAndFromPUF ? 0 : analytic.getAccruedPremium(coupon) * notional * buySellPremiumFactor;
    final double accruedPremium = isNonIMMAndFromSpread || isNonIMMFAndFromPUF ? 0 : accruedPremiumPrim * notional * buySellPremiumFactor;
    final int accruedDays = isNonIMMAndFromSpread || isNonIMMFAndFromPUF ? 0 : analytic.getAccruedDays();
    final double quotedSpread = getQuotedSpread(quote, puf, buySellProtection, yieldCurve, analytic).getQuotedSpread();
    final double upfrontAmount = isNonIMMAndFromSpread ? 0 : getUpfrontAmount(analytic, puf, notional, accruedPremiumPrim, buySellProtection);
    final double cleanPV = puf.getPointsUpFront() * notional;
    final double principal = isNonIMMAndFromSpread ? 0 : cleanPV;
    final double cleanPrice = getCleanPrice(puf);
    final TenorLabelledMatrix1D bucketedCS01 = getBucketedCS01(analytic, bucketCDSs, spreadObject.getXData(), quote, notional, yieldCurve, creditCurve);
    final double parallelCS01 = getParallelCS01(quote, analytic, yieldCurve, notional, pillarCDSs, ArrayUtils.toPrimitive(pillarObject.getYData()));

    final Set<ComputedValue> results = Sets.newHashSetWithExpectedSize(_valueRequirements.length);
    results.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.ACCRUED_PREMIUM, target.toSpecification(), properties), accruedPremium));
    results.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.ACCRUED_DAYS, target.toSpecification(), properties), accruedDays));
    results.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.QUOTED_SPREAD, target.toSpecification(), properties), quotedSpread / ONE_BPS));
    results.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.UPFRONT_AMOUNT, target.toSpecification(), properties), upfrontAmount));
    results.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.DIRTY_PRESENT_VALUE, target.toSpecification(), properties), upfrontAmount));
    results.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CLEAN_PRESENT_VALUE, target.toSpecification(), properties), cleanPV));
    results.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.PRINCIPAL, target.toSpecification(), properties), principal));
    results.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.CLEAN_PRICE, target.toSpecification(), properties), cleanPrice));
    results.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.BUCKETED_CS01, target.toSpecification(), properties), bucketedCS01));
    results.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.PARALLEL_CS01, target.toSpecification(), properties), parallelCS01));
    results.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.POINTS_UPFRONT, target.toSpecification(), properties), puf.getPointsUpFront()));
    return results;
  }

  @Override
  public ComputationTargetType getTargetType() {
    return FinancialSecurityTypes.LEGACY_VANILLA_CDS_SECURITY;
  }

  @Override
  public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
    final Set<ValueSpecification> specs = new HashSet<>();
    final ValueProperties properties = createValueProperties()
        .withAny(ISDAFunctionConstants.ISDA_CURVE_OFFSET)
        .withAny(ISDAFunctionConstants.ISDA_CURVE_DATE)
        .with(ISDAFunctionConstants.ISDA_IMPLEMENTATION, ISDAFunctionConstants.ISDA_IMPLEMENTATION_NEW)
        .withAny(ISDAFunctionConstants.CDS_QUOTE_CONVENTION)
        .withAny(ISDAFunctionConstants.ISDA_BUCKET_TENORS)
        .with(ValuePropertyNames.CURVE_CALCULATION_METHOD, ISDAFunctionConstants.ISDA_METHOD_NAME)
        .get();
    for (final String value : _valueRequirements) {
      specs.add(new ValueSpecification(value, target.toSpecification(), properties));
    }
    return specs;
  }

  @Override
  public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
    final LegacyVanillaCDSSecurity cds = (LegacyVanillaCDSSecurity) target.getSecurity();
    final Currency ccy = cds.getNotional().getCurrency();
    final CreditCurveIdentifier isdaIdentifier = getISDACurveIdentifier(cds);
    final CreditCurveIdentifier spreadIdentifier = getSpreadCurveIdentifier(cds);

    final String isdaOffset = desiredValue.getConstraint(ISDAFunctionConstants.ISDA_CURVE_OFFSET);
    if (isdaOffset == null) {
      return null;
    }

    final String isdaCurveDate = desiredValue.getConstraint(ISDAFunctionConstants.ISDA_CURVE_DATE);
    if (isdaCurveDate == null) {
      return null;
    }

    final String isdaCurveMethod = desiredValue.getConstraint(ISDAFunctionConstants.ISDA_IMPLEMENTATION);
    if (isdaCurveMethod == null) {
      return null;
    }

    // isda curve
    final ValueProperties isdaProperties = ValueProperties.builder()
        .with(ValuePropertyNames.CURVE, isdaIdentifier.toString())
        .with(ValuePropertyNames.CURVE_CALCULATION_METHOD, ISDAFunctionConstants.ISDA_METHOD_NAME)
        .with(ISDAFunctionConstants.ISDA_CURVE_OFFSET, isdaOffset)
        .with(ISDAFunctionConstants.ISDA_CURVE_DATE, isdaCurveDate)
        .with(ISDAFunctionConstants.ISDA_IMPLEMENTATION, isdaCurveMethod)
        .get();
    final ValueRequirement isdaRequirment = new ValueRequirement(ValueRequirementNames.YIELD_CURVE, ComputationTargetType.CURRENCY, ccy.getUniqueId(),
        isdaProperties);

    final String quoteConvention = desiredValue.getConstraint(ISDAFunctionConstants.CDS_QUOTE_CONVENTION);
    if (quoteConvention == null) {
      return null;
    }

    final String bucketTenors = desiredValue.getConstraint(ISDAFunctionConstants.ISDA_BUCKET_TENORS);
    if (bucketTenors == null) {
      return null;
    }

    // market spreads
    final ValueProperties spreadProperties = ValueProperties.builder()
        .with(ISDAFunctionConstants.CDS_QUOTE_CONVENTION, quoteConvention)
        .with(ValuePropertyNames.CURVE_CALCULATION_METHOD, ISDAFunctionConstants.ISDA_METHOD_NAME)
        .with(ISDAFunctionConstants.ISDA_CURVE_OFFSET, isdaOffset)
        .with(ISDAFunctionConstants.ISDA_CURVE_DATE, isdaCurveDate)
        .with(ISDAFunctionConstants.ISDA_IMPLEMENTATION, isdaCurveMethod)
        .with(ISDAFunctionConstants.ISDA_BUCKET_TENORS, bucketTenors)
        .get();
    final ValueRequirement spreadRequirment = new ValueRequirement(ValueRequirementNames.BUCKETED_SPREADS, target.toSpecification(), spreadProperties);
    final ValueRequirement pillarRequirment = new ValueRequirement(ValueRequirementNames.PILLAR_SPREADS, target.toSpecification(), spreadProperties);
    final ValueRequirement creditCurveRequirement = new ValueRequirement(ValueRequirementNames.HAZARD_RATE_CURVE, target.toSpecification(), spreadProperties);

    // get individual spread for this cds (ignore business day adjustment on either)
    final Period period = Period.between(cds.getStartDate().toLocalDate().withDayOfMonth(20), cds.getMaturityDate().toLocalDate().withDayOfMonth(20));
    final ValueRequirement cdsSpreadRequirement = new ValueRequirement(MarketDataRequirementNames.MARKET_VALUE, ComputationTargetType.PRIMITIVE,
        ExternalId.of("Tenor", period.toString()));

    final CdsRecoveryRateIdentifier recoveryRateIdentifier = cds.accept(new CreditSecurityToRecoveryRateVisitor(context.getSecuritySource()));
    final ValueRequirement recoveryRateRequirement = new ValueRequirement("PX_LAST", ComputationTargetType.PRIMITIVE, recoveryRateIdentifier.getExternalId());

    return Sets.newHashSet(isdaRequirment, spreadRequirment, cdsSpreadRequirement, creditCurveRequirement, pillarRequirment, recoveryRateRequirement);
  }

  @Override
  public boolean canHandleMissingInputs() {
    return true;
  }

  @Override
  public boolean canHandleMissingRequirements() {
    return true;
  }

  public static CreditCurveIdentifier getSpreadCurveIdentifier(final CreditDefaultSwapSecurity cds) {
    return getCreditCurveIdentifier(cds, "");
  }

  public static CreditCurveIdentifier getISDACurveIdentifier(final CreditDefaultSwapSecurity cds) {
    return getCreditCurveIdentifier(cds, "ISDA_");
  }

  /**
   * Get the CreditCurveIdentifier with name appended
   *
   * @param security
   */
  private static CreditCurveIdentifier getCreditCurveIdentifier(final CreditDefaultSwapSecurity security, final String name) {
    final CreditCurveIdentifier curveIdentifier = CreditCurveIdentifier.of(name + security.getReferenceEntity().getValue(),
        security.getNotional().getCurrency(), security.getDebtSeniority().toString(), security.getRestructuringClause().toString());
    return curveIdentifier;
  }

  public PointsUpFront getPointsUpfront(final CDSQuoteConvention quote, final BuySellProtection buySellProtection, final ISDACompliantYieldCurve yieldCurve,
      final CDSAnalytic analytic, final ISDACompliantCreditCurve creditCurve) {
    double puf = 0.0;
    if (quote instanceof PointsUpFront) {
      return (PointsUpFront) quote;
    } else if (quote instanceof QuotedSpread) {
      puf = POINTS_UP_FRONT_CONVERTER.quotedSpreadToPUF(analytic,
          quote.getCoupon(),
          yieldCurve,
          ((QuotedSpread) quote).getQuotedSpread());
    } else if (quote instanceof ParSpread) {
      puf = PRICER.pv(analytic, yieldCurve, creditCurve, ((ParSpread) quote).getCoupon());
    } else {
      throw new OpenGammaRuntimeException("Unknown quote type " + quote);
    }
    // SELL protection reverses directions of legs
    puf = buySellProtection == BuySellProtection.SELL ? -puf : puf;
    return new PointsUpFront(quote.getCoupon(), puf);
  }

  public static QuotedSpread getQuotedSpread(final CDSQuoteConvention quote, final PointsUpFront puf, final BuySellProtection buySellProtection,
      final ISDACompliantYieldCurve yieldCurve, final CDSAnalytic analytic) {
    double quotedSpread;
    if (quote instanceof QuotedSpread) {
      return (QuotedSpread) quote;
    }
    quotedSpread = POINTS_UP_FRONT_CONVERTER.pufToQuotedSpread(analytic, puf.getCoupon(), yieldCurve, puf.getPointsUpFront());
    // SELL protection reverses directions of legs
    quotedSpread = buySellProtection == BuySellProtection.SELL ? -quotedSpread : quotedSpread;
    return new QuotedSpread(quote.getCoupon(), quotedSpread);
  }

  public double getUpfrontAmount(final CDSAnalytic analytic, final PointsUpFront puf, final double notional, final double accPremiumPrim,
      final BuySellProtection buySellProtection) {
    // upfront amount is defined as dirty PV
    final double cash = (puf.getPointsUpFront() - accPremiumPrim) * notional;
    // SELL protection reverses directions of legs
    return buySellProtection == BuySellProtection.SELL ? -cash : cash;
  }

  public double getCleanPrice(final PointsUpFront puf) {
    return 100.0 * (1 - puf.getPointsUpFront());
  }

  public TenorLabelledMatrix1D getBucketedCS01(final CDSAnalytic analytic, final CDSAnalytic[] buckets, final Tenor[] tenors, final CDSQuoteConvention quote,
      final double notional, final ISDACompliantYieldCurve yieldCurve, final ISDACompliantCreditCurve creditCurve) {
    // TODO: Check quote.getCoupon() is spread value for IMM & 0.01 (or 0.05) for non IMM
    double[] cs01Values;
    if (quote instanceof ParSpread) {
      cs01Values = CALCULATOR.bucketedCS01FromCreditCurve(analytic, quote.getCoupon(), buckets, yieldCurve, creditCurve, ONE_BPS);
    } else if (quote instanceof PointsUpFront) {
      cs01Values = CALCULATOR.bucketedCS01FromPUF(analytic, (PointsUpFront) quote, yieldCurve, buckets, ONE_BPS);
    } else {
      cs01Values = CALCULATOR.bucketedCS01FromCreditCurve(analytic, quote.getCoupon()/* coupon * ONE_BPS */, buckets, yieldCurve, creditCurve, ONE_BPS);
    }
    for (int i = 0; i < cs01Values.length; i++) {
      cs01Values[i] *= notional * ONE_BPS;
    }
    return new TenorLabelledMatrix1D(tenors, cs01Values);
  }

  public double getParallelCS01(final CDSQuoteConvention quote, final CDSAnalytic analytic, final ISDACompliantYieldCurve yieldCurve, final double notional,
      final CDSAnalytic[] pillars, final double[] pillarSpreads) {
    double cs01;
    if (quote instanceof ParSpread) {
      cs01 = CALCULATOR.parallelCS01FromParSpreads(analytic,
          quote.getCoupon(), // ParSpread
          yieldCurve,
          pillars,
          pillarSpreads,
          ONE_BPS,
          BumpType.ADDITIVE);
    } else {
      cs01 = CALCULATOR.parallelCS01(analytic, quote, yieldCurve, ONE_BPS);
    }
    return Double.valueOf(cs01 * notional * ONE_BPS);
  }

  public static ManageableRegion getTestRegion() {
    final ManageableRegion region = new ManageableRegion();
    region.setUniqueId(UniqueId.parse("Dummy~region"));
    region.setName("United States");
    region.setCurrency(Currency.USD);
    region.setCountry(Country.US);
    region.setTimeZone(ZoneId.of("America/New_York"));
    region.setExternalIdBundle(ExternalIdBundle.of(ExternalId.parse("dummy~region")));
    return region;
  }

  /** test region. */
  public final class TestRegionSource extends AbstractSourceWithExternalBundle<Region> implements RegionSource {

    private final AtomicLong _count = new AtomicLong(0);
    private final Region _testRegion;

    private TestRegionSource(final Region testRegion) {
      _testRegion = testRegion;
    }

    private TestRegionSource() {
      _testRegion = getTestRegion();
    }

    @Override
    public Collection<Region> get(final ExternalIdBundle bundle, final VersionCorrection versionCorrection) {
      _count.getAndIncrement();
      Collection<Region> result = Collections.emptyList();
      if (_testRegion.getExternalIdBundle().equals(bundle) && versionCorrection.equals(VersionCorrection.LATEST)) {
        result = Collections.singleton((Region) getTestRegion());
      }
      return result;
    }

    @Override
    public Region get(final ObjectId objectId, final VersionCorrection versionCorrection) {
      _count.getAndIncrement();
      Region result = null;
      if (_testRegion.getUniqueId().getObjectId().equals(objectId) && versionCorrection.equals(VersionCorrection.LATEST)) {
        result = _testRegion;
      }
      return result;
    }

    @Override
    public Region get(final UniqueId uniqueId) {
      _count.getAndIncrement();
      Region result = null;
      if (_testRegion.getUniqueId().equals(uniqueId)) {
        result = _testRegion;
      }
      return result;
    }

    @Override
    public Region getHighestLevelRegion(final ExternalIdBundle bundle) {
      _count.getAndIncrement();
      Region result = null;
      if (_testRegion.getExternalIdBundle().equals(bundle)) {
        result = _testRegion;
      }
      return result;
    }

    @Override
    public Region getHighestLevelRegion(final ExternalId externalId) {
      _count.getAndIncrement();
      Region result = null;
      if (_testRegion.getExternalIdBundle().contains(externalId)) {
        result = _testRegion;
      }
      return result;
    }

    /**
     * Gets the count.
     *
     * @return the count
     */
    public AtomicLong getCount() {
      return _count;
    }

    @Override
    public ChangeManager changeManager() {
      return DummyChangeManager.INSTANCE;
    }

  }
}


text:
""" Imports TreeNodes"""
from tree.tree import TreeNode

class AvlTree(object):
    """
    An avl tree.
    """

    def __init__(self):
        # Root node of the tree.
        self.node = None
        self.height = -1
        self.balance = 0

    def insert(self, key):
        """
        Insert new key into node
        """
        # Create new node
        node = TreeNode(key)
        if not self.node:
            self.node = node
            self.node.left = AvlTree()
            self.node.right = AvlTree()
        elif key < self.node.val:
            self.node.left.insert(key)
        elif key > self.node.val:
            self.node.right.insert(key)
        self.re_balance()

    def re_balance(self):
        """
        Re balance tree. After inserting or deleting a node,
        """
        self.update_heights(recursive=False)
        self.update_balances(False)

        while self.balance < -1 or self.balance > 1:
            if self.balance > 1:
                if self.node.left.balance < 0:
                    self.node.left.rotate_left()
                    self.update_heights()
                    self.update_balances()
                self.rotate_right()
                self.update_heights()
                self.update_balances()

            if self.balance < -1:
                if self.node.right.balance > 0:
                    self.node.right.rotate_right()
                    self.update_heights()
                    self.update_balances()
                self.rotate_left()
                self.update_heights()
                self.update_balances()

    def update_heights(self, recursive=True):
        """
        Update tree height
        """
        if self.node:
            if recursive:
                if self.node.left:
                    self.node.left.update_heights()
                if self.node.right:
                    self.node.right.update_heights()

            self.height = 1 + max(self.node.left.height,
                                  self.node.right.height)
        else:
            self.height = -1

    def update_balances(self, recursive=True):
        """
        Calculate tree balance factor

        """
        if self.node:
            if recursive:
                if self.node.left:
                    self.node.left.update_balances()
                if self.node.right:
                    self.node.right.update_balances()

            self.balance = self.node.left.height - self.node.right.height
        else:
            self.balance = 0

    def rotate_right(self):
        """
        Right rotation
        """
        new_root = self.node.left.node
        new_left_sub = new_root.right.node
        old_root = self.node

        self.node = new_root
        old_root.left.node = new_left_sub
        new_root.right.node = old_root

    def rotate_left(self):
        """
        Left rotation
        """
        new_root = self.node.right.node
        new_left_sub = new_root.left.node
        old_root = self.node

        self.node = new_root
        old_root.right.node = new_left_sub
        new_root.left.node = old_root

    def in_order_traverse(self):
        """
        In-order traversal of the tree
        """
        result = []

        if not self.node:
            return result

        result.extend(self.node.left.in_order_traverse())
        result.append(self.node.key)
        result.extend(self.node.right.in_order_traverse())
        return result

redpajama_set_name: RedPajamaGithub


text:
class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.belongs_to :multimedia
      t.integer :parent_id
      t.string :text

      t.timestamps
    end
  end
end


text:
using namespace Tiny;

CauseUserIdCause::CauseUserIdCause()
{
	_class = std::string();
	shortDescription = std::string();
	userId = std::string();
	userName = std::string();
}

CauseUserIdCause::CauseUserIdCause(std::string jsonString)
{
	this->fromJson(jsonString);
}

CauseUserIdCause::~CauseUserIdCause()
{

}

void
CauseUserIdCause::fromJson(std::string jsonObj)
{
    bourne::json object = bourne::json::parse(jsonObj);

    const char *_classKey = "_class";

    if(object.has_key(_classKey))
    {
        bourne::json value = object[_classKey];

        jsonToValue(&_class, value, "std::string");

    }

    const char *shortDescriptionKey = "shortDescription";

    if(object.has_key(shortDescriptionKey))
    {
        bourne::json value = object[shortDescriptionKey];

        jsonToValue(&shortDescription, value, "std::string");

    }

    const char *userIdKey = "userId";

    if(object.has_key(userIdKey))
    {
        bourne::json value = object[userIdKey];

        jsonToValue(&userId, value, "std::string");

    }

    const char *userNameKey = "userName";

    if(object.has_key(userNameKey))
    {
        bourne::json value = object[userNameKey];

        jsonToValue(&userName, value, "std::string");

    }

}

bourne::json
CauseUserIdCause::toJson()
{
    bourne::json object = bourne::json::object();

    object["_class"] = getClass();

    object["shortDescription"] = getShortDescription();

    object["userId"] = getUserId();

    object["userName"] = getUserName();

    return object;

}

std::string
CauseUserIdCause::getClass()
{
	return _class;
}

void
CauseUserIdCause::setClass(std::string  _class)
{
	this->_class = _class;
}

std::string
CauseUserIdCause::getShortDescription()
{
	return shortDescription;
}

void
CauseUserIdCause::setShortDescription(std::string  shortDescription)
{
	this->shortDescription = shortDescription;
}

std::string
CauseUserIdCause::getUserId()
{
	return userId;
}

void
CauseUserIdCause::setUserId(std::string  userId)
{
	this->userId = userId;
}

std::string
CauseUserIdCause::getUserName()
{
	return userName;
}

void
CauseUserIdCause::setUserName(std::string  userName)
{
	this->userName = userName;
}


text:
<?php

namespace luya\web;

use luya\base\Widget;
use luya\Exception;
use luya\helpers\FileHelper;
use luya\helpers\StringHelper;
use luya\traits\CacheableTrait;
use Yii;

/**
 * Svg "inserter"
 *
 * This Widget will insert the contents of a given SVG file at the widgets position
 * or create an svg>use element for a given file + symbol.
 *
 * Inline the SVG contents:
 *
 * ```php
 *  <?= Svg::widget([
 *     'folder' => "@webroot/images/svg",
 *     'file' => 'logos/logo.svg',
 *     'cssClass' => 'additional-class-for-css'
 * ]); ?>
 * ```
 *
 * SVG > Use implementation:
 *
 * ```php
 * <?= Svg::widget([
 *     'symbolMode' => true,
 *     'symbolName' => 'example'
 *     'file' => 'images/svg-sprite.svg',
 *     'cssClass' => 'additional-class-for-css'
 * ]); ?>
 * ```
 *
 * @property string $folder The base folder path. Default is "@webroot/svg"
 *
 * @author Marc Stampfli <marc@zephir.ch>
 * @since 1.0.0
 */
class Svg extends Widget
{
    use CacheableTrait;

    /**
     * @var bool If symbolMode is true the widget will create a svg > use
     * @since 1.0.12
     */
    public $symbolMode;

    /**
     * @var string The name of the symbol that will be referenced
     * @since 1.0.12
     */
    public $symbolName;

    /**
     * @var string Relative path to the SVG file based on $folder
     */
    public $file;

    /**
     * @var string Additional css class to add to the SVG element, use only if the SVG itself has no class
     */
    public $cssClass;

    /**
     * @var string The base folder path. Default is "@webroot/svg"
     */
    private $_folder;

    /**
     * Setter method for $folder.
     *
     * @param string $folder Set folder for the given string (parsed trough Yii::getAlias())
     */
    public function setFolder($folder)
    {
        $this->_folder = Yii::getAlias($folder);
    }

    /**
     * Getter method for $folder.
     *
     * @return string Returns the folder string, if none is set it will return the default value "@webroot/svg"
     */
    public function getFolder()
    {
        if ($this->_folder === null) {
            $this->_folder = Yii::getAlias("@webroot/svg");
        }

        return rtrim($this->_folder, DIRECTORY_SEPARATOR);
    }

    /**
     * @inheritdoc
     */
    public function run()
    {
        // Cache generated code
        return $this->getOrSetHasCache(['svg', $this->folder, $this->file, $this->cssClass, $this->symbolName], function () {
            // Check if file ends with .svg, if not add the extension
            $svgFile = StringHelper::endsWith($this->file, '.svg') ? $this->file : $this->file . '.svg';

            if ($this->symbolMode) {
                $svgPath = Yii::$app->view->publicHtml . '/' . $svgFile;

                return '<svg class="symbol symbol--' . $this->symbolName . '' . ($this->cssClass ? ' ' . $this->cssClass : '') . '"><use class="symbol__use" xlink:href="' . $svgPath . '#' . $this->symbolName . '" /></svg>';
            } else {
                // Build the full svg file path
                $svgPath = $this->folder . DIRECTORY_SEPARATOR . $svgFile;

                // Get the svg contents
                $content = FileHelper::getFileContent($svgPath);

                // If a cssClass string is given, add it to the <svg> tag
                if ($this->cssClass && is_string($this->cssClass)) {
                    $content = preg_replace('/<svg/', '<svg class="' . $this->cssClass . '"', $content);
                }

                if ($content) {
                    return $content;
                }
            }

            throw new Exception('Unable to access SVG File: ' . $svgPath);
        });
    }
}


text:
import os
from os.path import join

from sklearn._build_utils import get_blas_info

def configuration(parent_package='', top_path=None):
    import numpy
    from numpy.distutils.misc_util import Configuration

    config = Configuration('utils', parent_package, top_path)
    config.add_subpackage('sparsetools')

    cblas_libs, blas_info = get_blas_info()
    cblas_compile_args = blas_info.pop('extra_compile_args', [])
    cblas_includes = [join('..', 'src', 'cblas'),
                      numpy.get_include(),
                      blas_info.pop('include_dirs', [])]

    libraries = []
    if os.name == 'posix':
        libraries.append('m')
        cblas_libs.append('m')

    config.add_extension('sparsefuncs_fast', sources=['sparsefuncs_fast.c'],
                         libraries=libraries)

    config.add_extension('arrayfuncs',
                         sources=['arrayfuncs.c'],
                         depends=[join('src', 'cholesky_delete.h')],
                         libraries=cblas_libs,
                         include_dirs=cblas_includes,
                         extra_compile_args=cblas_compile_args,
                         **blas_info
                         )

    config.add_extension(
        'murmurhash',
        sources=['murmurhash.c', join('src', 'MurmurHash3.cpp')],
        include_dirs=['src'])

    config.add_extension('lgamma',
                         sources=['lgamma.c', join('src', 'gamma.c')],
                         include_dirs=['src'],
                         libraries=libraries)

    config.add_extension('graph_shortest_path',
                         sources=['graph_shortest_path.c'],
                         include_dirs=[numpy.get_include()])

    config.add_extension('fast_dict',
                         sources=['fast_dict.cpp'],
                         language="c++",
                         include_dirs=[numpy.get_include()],
                         libraries=libraries)

    config.add_extension('seq_dataset',
                         sources=['seq_dataset.c'],
                         include_dirs=[numpy.get_include()])

    config.add_extension('weight_vector',
                         sources=['weight_vector.c'],
                         include_dirs=cblas_includes,
                         libraries=cblas_libs,
                         **blas_info)

    config.add_extension("_random",
                         sources=["_random.c"],
                         include_dirs=[numpy.get_include()],
                         libraries=libraries)

    config.add_extension("_logistic_sigmoid",
                         sources=["_logistic_sigmoid.c"],
                         include_dirs=[numpy.get_include()],
                         libraries=libraries)

    config.add_subpackage('tests')

    return config

if __name__ == '__main__':
    from numpy.distutils.core import setup
    setup(**configuration(top_path='').todict())


text:
labels:
- 'Stage-Alpha'
summary: 'XEP-0355 (Namespace Delegation) implementation'
...

Introduction
============

Namespace Delegation is an extension which allows server to delegate
some features handling to an entity/component. Typical use case is an
external PEP service, but it can be used more generally when your
prefered server lack one internal feature and you found an external
component which can do it.

Details
=======

You can have all the details by reading the
[XEP-0355](http://xmpp.org/extensions/xep-0355.html). Only the admin
mode is implemented so far.

Usage
=====

To use the module, like usual add **"delegation"** to your
modules\_enabled. Note that if you use it with a local component, you
also need to activate the module in your component section:

    modules_enabled = {
            [...]

            "delegation";
    }

    [...]

    Component "youcomponent.yourdomain.tld"
        component_secret = "yourpassword"
        modules_enabled = {"delegation"}

then specify delegated namespaces **in your host section** like that:

    VirtualHost "yourdomain.tld"

        delegations = {
            ["urn:xmpp:mam:0"] = {
                filtering = {"node"};
                jid = "pubsub.yourdomain.tld";
            },
            ["http://jabber.org/protocol/pubsub"] = {
                jid = "pubsub.yourdomain.tld";
            },
        }

Here all MAM requests with a "node" attribute (i.e. all MAM pubsub
request) will be delegated to pubsub.yourdomain.tld. Similarly, all
pubsub request to the host (i.e. the PEP requests) will be delegated to
pubsub.yourdomain.tld.

**/! Be extra careful when you give a delegation to an entity/component,
it's a powerful access, only do it if you absoly trust the
component/entity, and you know where the software is coming from**

Configuration
=============

The configuration is done with a table which map delegated namespace to
namespace data. Namespace data MUST have a **jid** (in the form **jid =
"delegated@domain.tld"**) and MAY have an additional **filtering**
array. If filtering is present, request with attributes in the array
will be delegated, other will be treated normally (i.e. by Prosody).

If your are not a developper, the delegated namespace(s)/attribute(s)
are most probably specified with the external component/entity you want
to use.

Compatibility
=============

If you use it with Prosody 0.9 and a component, you need to patch
core/mod\_component.lua to fire a new signal. To do it, copy the
following patch in a, for example, /tmp/component.patch file:

    diff --git a/plugins/mod_component.lua b/plugins/mod_component.lua
    --- a/plugins/mod_component.lua
    +++ b/plugins/mod_component.lua
    @@ -85,6 +85,7 @@
                    session.type = "component";
                    module:log("info", "External component successfully authenticated");
                    session.send(st.stanza("handshake"));
    +               module:fire_event("component-authenticated", { session = session });

                    return true;
            end

Then, at the root of prosody, enter:

`patch -p1 < /tmp/component.patch`

  ----- ----------------------------------------------------
  0.10  Works
  0.9   Need a patched core/mod\_component.lua (see above)
  ----- ----------------------------------------------------

Note
====

This module is often used with mod\_privilege (c.f. XEP for more
details)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Thinktecture.IdentityServer.Core.Configuration;
using Thinktecture.IdentityServer.Core.Services;
using Thinktecture.IdentityServer.Core.Services.InMemory;

namespace IdentitySTS.Config
{
    class Factory
    {
        public static IdentityServerServiceFactory Configure(string connString)
        {
            var factory = new IdentityServerServiceFactory();

            factory.UserService =
                new Registration<IUserService>(resolver => AspNetIdentityUserServiceFactory.Factory(connString));

            var scopeStore = new InMemoryScopeStore(Scopes.Get());
            factory.ScopeStore = new Registration<IScopeStore>(resolver => scopeStore);

            var clientStore = new InMemoryClientStore(Clients.Get());
            factory.ClientStore = new Registration<IClientStore>(resolver => clientStore);

            return factory;
        }
    }
}


text:
[Original Demo](http://gnuplot.sourceforge.net/demo_4.6/transparent.html)

### 1

```ruby
# # Example of transparent fill areas
# # Ethan A Merritt - Aug 2006
# # NB:
# #    Not all terminal types support transparency
# #    Assumes UTF-8 support for plot titles
# #
# set style fill solid 1.0 noborder
# set style function filledcurves y1=0
# set clip two
#
# Gauss(x,mu,sigma) = 1./(sigma*sqrt(2*pi)) * exp( -(x-mu)**2 / (2*sigma**2) )
# d1(x) = Gauss(x, 0.5, 0.5)
# d2(x) = Gauss(x,  2.,  1.)
# d3(x) = Gauss(x, -1.,  2.)
#
# set xrange [-5:5]
# set yrange [0:1]
#
# unset colorbox
#
# set key title "Gaussian Distribution"
# set key top left Left reverse samplen 1
#
# #set obj 1 rect from graph 0,0 to graph 1,1
# #set obj 1 rect back fs solid 0.25 fc lt 4
#
# set title "Solid filled curves"
# plot d1(x) fs solid 1.0 lc rgb "forest-green" title "μ =  0.5 σ = 0.5", \
#      d2(x) lc rgb "gold" title "μ =  2.0 σ = 1.0", \
#      d3(x) lc rgb "red" title "μ = -1.0 σ = 2.0"

Numo.gnuplot do
  set :style, fill_solid:1.0, noborder:true
  set :style, function:'filledcurves y1=0'
  set clip:"two"
  run "Gauss(x,mu,sigma) = 1./(sigma*sqrt(2*pi)) * exp( -(x-mu)**2 / (2*sigma**2) )"
  run "d1(x) = Gauss(x, 0.5, 0.5)"
  run "d2(x) = Gauss(x, 2., 1.)"
  run "d3(x) = Gauss(x, -1., 2.)"
  set xrange:-5..5
  set yrange:0..1
  unset :colorbox
  set :key, title:"Gaussian Distribution"
  set :key, :top, :left, :Left, :reverse, samplen:1
  set title:"Solid filled curves"
  plot ["d1(x)", fs_solid:1.0, lc_rgb:"forest-green", title:"μ =  0.5 σ = 0.5"],
    ["d2(x)", lc_rgb:"gold", title:"μ =  2.0 σ = 1.0"],
    ["d3(x)", lc_rgb:"red", title:"μ = -1.0 σ = 2.0"]
end
```
![904transparent/001](https://raw.githubusercontent.com/ruby-numo/numo-gnuplot-demo/master/gnuplot/md/904transparent/image/001.png)

### 2

```ruby
# set style fill transparent solid 0.5 noborder
# set title "Transparent filled curves"
# replot

Numo.gnuplot do
  set :style, fill:"transparent", solid:0.5, noborder:true
  set title:"Transparent filled curves"
  replot
end
```
![904transparent/002](https://raw.githubusercontent.com/ruby-numo/numo-gnuplot-demo/master/gnuplot/md/904transparent/image/002.png)

### 3

```ruby
# set style fill pattern 4 bo
# set title "Pattern-filled curves"
# replot

Numo.gnuplot do
  set :style, :fill, pattern:4, bo:true
  set title:"Pattern-filled curves"
  replot
end
```
![904transparent/003](https://raw.githubusercontent.com/ruby-numo/numo-gnuplot-demo/master/gnuplot/md/904transparent/image/003.png)

### 4

```ruby
# set style fill transparent pattern 4 bo
# set title "Transparent pattern-filled curves"
# replot

Numo.gnuplot do
  set :style, fill:"transparent", pattern:4, bo:true
  set title:"Transparent pattern-filled curves"
  replot
end
```
![904transparent/004](https://raw.githubusercontent.com/ruby-numo/numo-gnuplot-demo/master/gnuplot/md/904transparent/image/004.png)


text:
package edu.stanford.bmir.styledstring.attributes;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.text.AttributedCharacterIterator;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.when;

/**
 * Matthew Horridge
 * Stanford Center for Biomedical Informatics Research
 * 07/12/14
 */
@RunWith(MockitoJUnitRunner.class)
public class FontSizeAttribute_TestCase {

    public static final int FONT_SIZE = 50;

    private FontSizeAttribute fontSizeAttribute;

    private FontSizeAttribute otherFontSizeAttribute;

    @Before
    public void setUp() throws Exception {
        fontSizeAttribute = new FontSizeAttribute(FONT_SIZE);
        otherFontSizeAttribute = new FontSizeAttribute(FONT_SIZE);
    }

    @Test
    public void shouldBeEqualToSelf() {
        assertThat(fontSizeAttribute, is(equalTo(fontSizeAttribute)));
    }

    @Test
    public void shouldNotBeEqualToNull() {
        assertThat(fontSizeAttribute, is(not(equalTo(null))));
    }

    @Test
    public void shouldBeEqualToOther() {
        assertThat(fontSizeAttribute, is(equalTo(otherFontSizeAttribute)));
    }

    @Test
    public void shouldHaveSameHashCodeAsOther() {
        assertThat(fontSizeAttribute.hashCode(), is(otherFontSizeAttribute.hashCode()));
    }

    @Test
    public void shouldGenerateToString() {
        assertThat(fontSizeAttribute.toString(), startsWith("FontSizeAttribute"));
    }

    @Test
    public void shouldReturnCorrectCssPropertyName() {
        assertThat(fontSizeAttribute.getCssPropertyName(), is("font-size"));
    }

    @Test
    public void shouldReturnCorrectCssPropertyValue() {
        assertThat(fontSizeAttribute.getCssPropertyValue(), is("50pt"));
    }

    @Test
    public void shouldReturnCorrectAttributedStringAttribute() {
        AttributedCharacterIterator.Attribute expected = TextAttribute.SIZE;
        assertThat(fontSizeAttribute.getAttributedStringAttribute(), is(expected));
    }

    @Test
    public void shouldReturnCorrectAttributedStringValue() {
        assertThat(fontSizeAttribute.getAttributedStringValue(), is((Object) FONT_SIZE));
    }

    @Test
    public void shouldReturnCorrectStyledDocumentStyleAttribute() {
        assertThat(fontSizeAttribute.getStyledDocumentStyleAttribute(), is(StyleConstants.Size));
    }

    @Test
    public void shouldReturnCorrectStyledDocumentAttributeValue() {
        assertThat(fontSizeAttribute.getStyledDocumentStyleAttributeValue(), is((Object) FONT_SIZE));
    }
}


text:
\documentclass[10pt]{article}
\usepackage{fancyhdr}
\usepackage[utf8]{inputenc}
\usepackage[spanish]{babel}
\usepackage{anysize}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage[export]{adjustbox}
\marginsize{2cm}{2cm}{2cm}{2cm}
\pagestyle{fancy}

%\sloppy
\lhead{Lineamientos}
\chead{}
\rhead{Lenguajes de Programación}
\lfoot{}
\cfoot{\thepage}
\rfoot{}
%\setlength{\headrulewidth}{0.4pt}
%\setlength{\footrulewidth}{0.4pt}
\usepackage{array}
\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}b{#1}}
\begin{document}
\begin{center}
  \begin{tabular}[h]{c C{10cm} c}
    \includegraphics[scale=.2]{cover.png} &
    \textbf{{\Large Lenguajes de \newline Programación}}
    \newline \textbf{Profesor}: Karla Ramírez Pulido
    \newline \textbf{Ayudante de Teoría}: Héctor Enrique Gómez Morales
    \newline \textbf{Ayudante le Laboratorio}: Héctor Enrique Gómez Morales
    \newline Inicio de semestre: 10 de agosto de 2015
    \newline Fin de semestre: 27 de noviembre de 2015 &
    \includegraphics[scale=.4]{cover2.png}
  \end{tabular}
\end{center}

\begin{itemize}
\item \textbf{Acerca del Curso}

  \begin{itemize}
  \item  Nombre de la materia: Lenguajes de Programación.
  \item Tipo de materia: Obligatoria de 5to. semestre en Ciencias de
    la Computación.
  \item Clave: 1536.
  \item Grupo: 7050.
  \item Salón: P-211.
  \item Laboratorio: Laboratorio de Ciencias de la Computación 3.
  \item Horario de Clase: Lunes, Martes y Viernes de 11:00 a 12:00 hrs.
  \item Horario de Ayudantía: Miércoles y Jueves de 11:00 a 12:00 hrs.
  \item Horario de Laboratorio: Miércoles de 16:00 a 18:00 hrs.
  \end{itemize}

\item \textbf{Lenguaje de Programación}

  El principal lenguaje de programación que se usará será Racket (un
  descendiente de Scheme), aunque habrán prácticas en que tendrán
  que utilizar otro lenguaje. Para las prácticas en Racket se utilizará el
  intérprete del PLT (también conocido como DrRacket) versión 6.2. El dialecto que se
  usará en el curso (a menos que se especifique uno diferente para alguna práctica)
  será PLAI.

\item \textbf{Evaluación - Teoría}

  La evaluación de la parte teórica sera por medio de tareas que constaran de un conjunto de preguntas, las cuales deberán responder correctamente.

  La forma de entrega de las tareas debe ser:
  \begin{itemize}
  \item En un documento en formato PDF, preferentemente usando \LaTeX.
  \item La tarea debe tener el siguiente formato para su nombre:
\begin{verbatim}
  <Apellido Paterno>_<Apellido Materno>_<Nombres>_TareaN.pdf
\end{verbatim}
\item Este documento debe estar en linea en un repositorio en Github,
  dentro de un directorio llamado Tareas.\footnote{Github y el uso de git se dará a conocer en clase de ayudantía.}
  \end{itemize}

  \textbf{No} se aceptaran tareas hechas a mano.

  \pagebreak

\item \textbf{Forma de Evaluación}

  La forma de evaluar a cada alumno está dada por los rubros:
  exámenes, prácticas y teoría.

  \begin{itemize}
  \item Exámenes: 40\%
  \item Prácticas: 30\%
  \item Tareas: 30\%
  \end{itemize}

  Las siguientes son restricciones generales sobre proceso de calificación y entrega de prácticas, reportes, evaluaciones y exámenes:

  \begin{itemize}
  \item No habrá reposición de exámenes, reportes, evaluaciones, ni prácticas.
  \item No habrá examen final.
  \item La fecha y forma de entrega de las prácticas y parte teórica será \textbf{estricta e inapelable}, esto es, no habrá prórrogas.
  \item Los exámenes serán evaluados individualmente; las prácticas, los reportes escritos y las evaluaciones presenciales serán por equipos de 2 personas mínimo a 3 personas máximo.
  \item Cualquier reporte que incluya traducciones automáticas (o carentes de sentido) tendrá calificación de 0 automáticamente.
  \item Para tener derecho a presentar cada examen en el curso se deberán haber entregado todas y cada uno de los reportes previos al mismo.
  \end{itemize}

  Las siguientes reglas  no se pueden cambiar bajo ninguna circunstancia. Incurrir en el incumplimiento de alguna de ellas implica obtener automáticamente una calificación final de 5:
  \begin{itemize}
  \item Está estrictamente prohibido cometer plagio. El plagio implica reproducir (o traducir de manera literal) íntegra o parcialmente tareas, prácticas, publicaciones, anotaciones, etc. sin señalar de forma precisa a su autor original e indicar el documento o lugar en el que se encontró.
  \item Es necesario cumplir al menos con el 80\% de asistencia incluyendo las ayudantías.
  \end{itemize}

  Las calificaciones finales serán definitivas. El único caso en el que se podrá obtener NP será el no haber entregado ninguna tarea, práctica o examen.

\item \textbf{Lista de Correo}

  La lista de correo del curso es: \textbf{lenguajes@googlegroups.com} donde se
  podrán discutir las dudas de prácticas y temas relacionados
  con el curso entre otras cosas.

  \begin{itemize}
  \item Correo del Profesor: \textbf{karla@ciencias.unam.mx}
  \item Correo del Ayudante: \textbf{hectoregm@gmail.com}
  \end{itemize}

\item \textbf{Página del Curso}

  Por medio de la página del curso será posible ver información relacionada
  con el mismo, de tal suerte que no habrá complicación para descargar las
  prácticas y tareas que se hayan encargado durante el semestre. A su
  vez, se publicará información relacionada con calificaciones,
  lineamientos, el uso del taller y noticias mencionadas en
  clase. La página estará disponible en: \\
  \url{http://valhalla.fciencias.unam.mx/lenguajes}

\end{itemize}
\end{document}


text:
/*
 * Tesla REST API - Tests for the Vehicles API
 */
package com.servebeer.please.tesla_client;

import com.servebeer.please.tesla_client.generated.handler.ApiException;
import com.servebeer.please.tesla_client.generated.model.AlterVehicleStateResponse;
import com.servebeer.please.tesla_client.generated.model.ChargeStateResponseResponse;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;

/**
 * API tests for VehiclesApi - un-@Ignore the tests you want to run
 */
public class TeslaCommunicatorIT {

    private static TeslaCommunicator teslaCommunicator = null;

    /**
     * run once for the class before any tests are executed
     */
    @BeforeClass
    public static void beforeClass() throws ApiException {
        teslaCommunicator = new TeslaCommunicator(TestDefaults.TEST_USER_EMAIL_ADDRESS, TestDefaults.TEST_USER_PASSWORD);
    }

    @Test
    public void getChargerPowerTest() throws Exception {
        System.out.println("getChargerPower: " + teslaCommunicator.getChargerPower());
    }

    @Test
    public void isConnectedTest() throws Exception {
        System.out.println("isConnected: " + teslaCommunicator.isConnected());
    }

    /**
     * WARNING - if the current limit is not one of the minimum, standard or maximum limits, executing this test
     * will reset the current limit to the standard limit.
     */
    @Test
    public void setChargeLimitToMinimumTest() throws Exception {

        // figure out what the current limit is set to
        ChargeStateResponseResponse getStateResponse = teslaCommunicator.getChargeState().getResponse();
        int originalLimit = getStateResponse.getChargeLimitSoc();
        int minLimit = getStateResponse.getChargeLimitSocMin();
        int maxLimit = getStateResponse.getChargeLimitSocMax();

        // if the original limit is already the minimum limit, set the limit to the maximum limit first
        if (originalLimit == minLimit) {
            teslaCommunicator.setChargeLimitToMaximum();

            // check to see if that worked okay.
            assertEquals("Whoops - problems setting up the test", maxLimit, (int) teslaCommunicator.getChargeState().getResponse().getChargeLimitSoc());
        }

        // this is the actual test - set the charge limit to the minimum value
        AlterVehicleStateResponse setLimitResponse = teslaCommunicator.setChargeLimitToMinimum();
        String reason = (setLimitResponse.getResponse() != null && setLimitResponse.getResponse().getReason() != null) ? setLimitResponse.getResponse().getReason() : "Reason found in response";

        // test the response
        int currentLimit = teslaCommunicator.getChargeState().getResponse().getChargeLimitSoc();
        assertEquals("Charge limit was not successfully set to minimum", minLimit, currentLimit);

        // reset the limit if necessary
        if (originalLimit != currentLimit) {
            // setting directly to standard doesn't always work, so set to max first
            teslaCommunicator.setChargeLimitToMaximum();
            if (originalLimit != maxLimit) {
                teslaCommunicator.setChargeLimitToStandard();
            }
        }

    }

    @Test
    public void setChargeLimitToStandardTest() throws Exception {

        // figure out what the current limit is set to
        ChargeStateResponseResponse getStateResponse = teslaCommunicator.getChargeState().getResponse();
        int originalLimit = getStateResponse.getChargeLimitSoc();
        int minLimit = getStateResponse.getChargeLimitSocMin();
        int stdLimit = getStateResponse.getChargeLimitSocStd();
        int maxLimit = getStateResponse.getChargeLimitSocMax();

        // if the original limit is already the maximum limit, set the limit to the maximum limit first
        if (originalLimit == stdLimit) {
            teslaCommunicator.setChargeLimitToMaximum();

            // check to see if that worked okay.
            assertEquals("Whoops - problems setting up the test", maxLimit, (int) teslaCommunicator.getChargeState().getResponse().getChargeLimitSoc());
        }

        // this is the actual test - set the charge limit to the standard value
        AlterVehicleStateResponse setLimitResponse = teslaCommunicator.setChargeLimitToStandard();
        String reason = (setLimitResponse.getResponse() != null && setLimitResponse.getResponse().getReason() != null) ? setLimitResponse.getResponse().getReason() : "Reason found in response";

        // test the response
        int currentLimit = teslaCommunicator.getChargeState().getResponse().getChargeLimitSoc();
        assertEquals("Charge limit was not successfully set to standard", stdLimit, currentLimit);

        // reset the limit if necessary
        if (originalLimit == maxLimit) {
            teslaCommunicator.setChargeLimitToMaximum();
        } else if (originalLimit == minLimit) {
            teslaCommunicator.setChargeLimitToMinimum();
        }

    }

    @Test
    public void setChargeLimitToMaximumTest() throws Exception {

        // figure out what the current limit is set to
        ChargeStateResponseResponse getStateResponse = teslaCommunicator.getChargeState().getResponse();
        int originalLimit = getStateResponse.getChargeLimitSoc();
        int minLimit = getStateResponse.getChargeLimitSocMin();
        int maxLimit = getStateResponse.getChargeLimitSocMax();

        // if the original limit is already the maximum limit, set the limit to the minimum limit first
        if (originalLimit == maxLimit) {
            teslaCommunicator.setChargeLimitToMinimum();

            // check to see if that worked okay.
            assertEquals("Whoops - problems setting up the test", minLimit, (int) teslaCommunicator.getChargeState().getResponse().getChargeLimitSoc());
        }

        // this is the actual test - set the charge limit to the maximum value
        AlterVehicleStateResponse setLimitResponse = teslaCommunicator.setChargeLimitToMaximum();
        String reason = (setLimitResponse.getResponse() != null && setLimitResponse.getResponse().getReason() != null) ? setLimitResponse.getResponse().getReason() : "Reason found in response";

        // test the response
        int currentLimit = teslaCommunicator.getChargeState().getResponse().getChargeLimitSoc();
        assertEquals("Charge limit was not successfully set to maximum", maxLimit, currentLimit);

        // reset the limit if necessary
        if (originalLimit != currentLimit) {
            // setting directly to standard doesn't always work, so set to min first
            if (originalLimit == minLimit) {
                teslaCommunicator.setChargeLimitToMinimum();
            } else {
                teslaCommunicator.setChargeLimitToStandard();
            }
        }

    }

    // this one is always failing. I don't know why,  do YOU ??
    @Ignore
    @Test
    public void setValetTest() throws Exception {
        AlterVehicleStateResponse response = teslaCommunicator.setValetMode(true, 1234);

        String reason = (response.getResponse() != null && response.getResponse().getReason() != null) ? response.getResponse().getReason() : "Reason found in response";
        assertTrue("Error - server reason: " + reason, response.getResponse().getResult());
    }

    @Ignore
    @Test
    public void startChargingTest() throws Exception {
        AlterVehicleStateResponse response = teslaCommunicator.startCharging();

        String reason = (response.getResponse() != null && response.getResponse().getReason() != null) ? response.getResponse().getReason() : "Reason found in response";
        assertTrue("Error - server reason: " + reason, response.getResponse().getResult());
    }

    @Ignore
    @Test
    public void stopChargingTest() throws Exception {
        AlterVehicleStateResponse response = teslaCommunicator.stopCharging();

        String reason = (response.getResponse() != null && response.getResponse().getReason() != null) ? response.getResponse().getReason() : "Reason found in response";
        assertTrue("Error - server reason: " + reason, response.getResponse().getResult());
    }

    @Ignore
    @Test
    public void wakeVehicleTest() throws Exception {
        AlterVehicleStateResponse response = teslaCommunicator.wakeVehicle();

        String reason = (response.getResponse() != null && response.getResponse().getReason() != null) ? response.getResponse().getReason() : "Reason found in response";
        assertTrue("Error - server reason: " + reason, response.getResponse().getResult());
    }
}


text:
layout: post
title:  "jQuery/Ajax Rails Project v2"
date:   2017-08-23 01:47:09 +0000
---

The goal of this project was to update my existing rails portfolio project, [Chill Flix](https://github.com/lucketta/chill-flix-rails-portfolio-project), to include jQuery and Ajax requests to update the DOM without a page refresh.

Feel free to read my last blog post to get a more in-depth explanation of the initial project, [here](http://areannaluckett.org/2017/07/08/activerecord_query_in_rails_portfolio_project/). In short, I wanted to create a webapp that allows users to keep track of their favorite TV shows.

The requirements for this project were to:
* Include a show resource rendered using jQuery and an Active Model Serialization JSON backend.
* Include an index resource rendered using jQuery and an Active Model Serialization JSON backend.
* Include at least one has_many relationship in information rendered via JSON and appended to the DOM.
* Use your Rails API and a form to create a resource and render the response without a page refresh.
* Translate JSON responses into JS Model Objects.
* At least one of the JS Model Objects must have at least one method added by your code to the prototype.

I definitely had a lot of fun with this project, especially at the end, when I was all finished, and realized this is how web pages are built. How exciting! To have gone from not knowing how the internet works, to being able to create my own dynamic web app has been an awesome journey.

Like everyone else in the coding world, however, I did run into a particulary challenging bug:

Each TV show page allows a user to submit a review and their username. My job was to code this functionality by appending a JSON object using content from the form to the DOM without a page refresh.

First, I created the form. I then used Javascript to create a listener for the form submit and used a Jquery.post call to load data from the server. After serializing the data and pushing that data to the post request, I was finding that I was getting back the HTML of the whole page instead of the JSON object.

For those of you who have run into that problem, here is a quick tip:

![](http://imgur.com/bupmwen.png)

This is the low level call using Ajax that will allow you to set a datatype to JSON and that will render a JSON object, instead of receiving HTML. From there, I was able to create a new record in my model and append that object to the DOM.

With just one more major project to go before I finish the curriculum, I am super excited to learn what React and Redux have in store for me.


text:
@implementation DeviceDetection

+ (uint) detectDevice {
    NSString *model= [[UIDevice currentDevice] model];
    struct utsname u;
	uname(&u);

    if (!strcmp(u.machine, "iPhone1,1")) {
		return MODEL_IPHONE;
	} else if (!strcmp(u.machine, "iPhone1,2")){
		return MODEL_IPHONE_3G;
	} else if (!strcmp(u.machine, "iPhone2,1")){
		return MODEL_IPHONE_3GS;
	} else if (!strcmp(u.machine, "iPhone3,1")){
		return MODEL_IPHONE_4;
	} else if (!strcmp(u.machine, "iPod1,1")){
		return MODEL_IPOD_TOUCH_GEN1;
	} else if (!strcmp(u.machine, "iPod2,1")){
		return MODEL_IPOD_TOUCH_GEN2;
	} else if (!strcmp(u.machine, "iPod3,1")){
		return MODEL_IPOD_TOUCH_GEN3;
	} else if (!strcmp(u.machine, "iPad1,1")){
		return MODEL_IPAD;
	} else if (!strcmp(u.machine, "i386")){
		//NSString *iPhoneSimulator = @"iPhone Simulator";
		NSString *iPadSimulator = @"iPad Simulator";
		if([model compare:iPadSimulator] == NSOrderedSame)
			return MODEL_IPAD_SIMULATOR;
		else
			return MODEL_IPHONE_SIMULATOR;
	}
	else {
		return MODEL_UNKNOWN;
	}
}

+ (NSString *) returnDeviceName:(BOOL)ignoreSimulator {
    NSString *returnValue = @"Unknown";

    switch ([DeviceDetection detectDevice])
	{
        case MODEL_IPHONE_SIMULATOR:
			returnValue = @"iPhone Simulator";
			break;
		case MODEL_IPOD_TOUCH_GEN1:
			returnValue = @"iPod Touch";
			break;
		case MODEL_IPOD_TOUCH_GEN2:
			returnValue = @"iPod Touch";
			break;
		case MODEL_IPOD_TOUCH_GEN3:
			returnValue = @"iPod Touch";
			break;
		case MODEL_IPHONE:
			returnValue = @"iPhone";
			break;
		case MODEL_IPHONE_3G:
			returnValue = @"iPhone 3G";
			break;
		case MODEL_IPHONE_3GS:
			returnValue = @"iPhone 3GS";
			break;
		case MODEL_IPHONE_4:
			returnValue = @"iPhone 4";
			break;

		case MODEL_IPAD:
			returnValue = @"iPad";
			break;
		default:
			break;
	}

	return returnValue;
}

@end


text:
namespace Llvm.NET.Instructions
{
    public class DebugInfoIntrinsic
        : Intrinsic
    {
        internal DebugInfoIntrinsic( LLVMValueRef valueRef )
            : base( ValidateConversion( valueRef, NativeMethods.IsADbgInfoIntrinsic ) )
        {
        }
    }
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/write_fj"
        android:title="上传附件"/>

</menu>


text:
package com.amazonaws.services.servicecatalog.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeProductViewResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The summary metadata about the specified product.
     *

     */
    private ProductViewSummary productViewSummary;
    /**
     *

     * A list of provisioning artifact objects for the specified product. The ProvisioningArtifacts
     * represent the ways in which the specified product can be provisioned.
     *

     */
    private java.util.List<ProvisioningArtifact> provisioningArtifacts;

    /**
     *

     * The summary metadata about the specified product.
     *

     *
     * @param productViewSummary
     *        The summary metadata about the specified product.
     */

    public void setProductViewSummary(ProductViewSummary productViewSummary) {
        this.productViewSummary = productViewSummary;
    }

    /**
     *

     * The summary metadata about the specified product.
     *

     *
     * @return The summary metadata about the specified product.
     */

    public ProductViewSummary getProductViewSummary() {
        return this.productViewSummary;
    }

    /**
     *

     * The summary metadata about the specified product.
     *

     *
     * @param productViewSummary
     *        The summary metadata about the specified product.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeProductViewResult withProductViewSummary(ProductViewSummary productViewSummary) {
        setProductViewSummary(productViewSummary);
        return this;
    }

    /**
     *

     * A list of provisioning artifact objects for the specified product. The ProvisioningArtifacts
     * represent the ways in which the specified product can be provisioned.
     *

     *
     * @return A list of provisioning artifact objects for the specified product. The ProvisioningArtifacts
     *         represent the ways in which the specified product can be provisioned.
     */

    public java.util.List<ProvisioningArtifact> getProvisioningArtifacts() {
        return provisioningArtifacts;
    }

    /**
     *

     * A list of provisioning artifact objects for the specified product. The ProvisioningArtifacts
     * represent the ways in which the specified product can be provisioned.
     *

     *
     * @param provisioningArtifacts
     *        A list of provisioning artifact objects for the specified product. The ProvisioningArtifacts
     *        represent the ways in which the specified product can be provisioned.
     */

    public void setProvisioningArtifacts(java.util.Collection<ProvisioningArtifact> provisioningArtifacts) {
        if (provisioningArtifacts == null) {
            this.provisioningArtifacts = null;
            return;
        }

        this.provisioningArtifacts = new java.util.ArrayList<ProvisioningArtifact>(provisioningArtifacts);
    }

    /**
     *

     * A list of provisioning artifact objects for the specified product. The ProvisioningArtifacts
     * represent the ways in which the specified product can be provisioned.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setProvisioningArtifacts(java.util.Collection)} or
     * {@link #withProvisioningArtifacts(java.util.Collection)} if you want to override the existing values.
     *

     *
     * @param provisioningArtifacts
     *        A list of provisioning artifact objects for the specified product. The ProvisioningArtifacts
     *        represent the ways in which the specified product can be provisioned.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeProductViewResult withProvisioningArtifacts(ProvisioningArtifact... provisioningArtifacts) {
        if (this.provisioningArtifacts == null) {
            setProvisioningArtifacts(new java.util.ArrayList<ProvisioningArtifact>(provisioningArtifacts.length));
        }
        for (ProvisioningArtifact ele : provisioningArtifacts) {
            this.provisioningArtifacts.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of provisioning artifact objects for the specified product. The ProvisioningArtifacts
     * represent the ways in which the specified product can be provisioned.
     *

     *
     * @param provisioningArtifacts
     *        A list of provisioning artifact objects for the specified product. The ProvisioningArtifacts
     *        represent the ways in which the specified product can be provisioned.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeProductViewResult withProvisioningArtifacts(java.util.Collection<ProvisioningArtifact> provisioningArtifacts) {
        setProvisioningArtifacts(provisioningArtifacts);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getProductViewSummary() != null)
            sb.append("ProductViewSummary: ").append(getProductViewSummary()).append(",");
        if (getProvisioningArtifacts() != null)
            sb.append("ProvisioningArtifacts: ").append(getProvisioningArtifacts());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeProductViewResult == false)
            return false;
        DescribeProductViewResult other = (DescribeProductViewResult) obj;
        if (other.getProductViewSummary() == null ^ this.getProductViewSummary() == null)
            return false;
        if (other.getProductViewSummary() != null && other.getProductViewSummary().equals(this.getProductViewSummary()) == false)
            return false;
        if (other.getProvisioningArtifacts() == null ^ this.getProvisioningArtifacts() == null)
            return false;
        if (other.getProvisioningArtifacts() != null && other.getProvisioningArtifacts().equals(this.getProvisioningArtifacts()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getProductViewSummary() == null) ? 0 : getProductViewSummary().hashCode());
        hashCode = prime * hashCode + ((getProvisioningArtifacts() == null) ? 0 : getProvisioningArtifacts().hashCode());
        return hashCode;
    }

    @Override
    public DescribeProductViewResult clone() {
        try {
            return (DescribeProductViewResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="management.orderService">

    <insert id="insertBatch" parameterType="java.util.List" useGeneratedKeys="false">
        insert into
        airdevice.order_service
        (
            os_id, order_id, service_id, block_flag, create_time
        )
        values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.osId}, #{item.orderId}, #{item.serviceId}, #{item.blockFlag}, #{item.createAt})
        </foreach>
    </insert>

    <insert id="insert" parameterType="model.order.OrderService">
        insert into airdevice.order_service
    </insert>
</mapper>


text:
Add callbacks to requests in flight to avoid async duplication

## USAGE

```javascript
var inflight = require('inflight')

// some request that does some stuff
function req(key, callback) {
  // key is any random string.  like a url or filename or whatever.
  //
  // will return either a falsey value, indicating that the
  // request for this key is already in flight, or a new callback
  // which when called will call all callbacks passed to inflightk
  // with the same key
  callback = inflight(key, callback)

  // If we got a falsey value back, then there's already a req going
  if (!callback) return

  // this is where you'd fetch the url or whatever
  // callback is also once()-ified, so it can safely be assigned
  // to multiple events etc.  First call wins.
  setTimeout(function() {
    callback(null, key)
  }, 100)
}

// only assigns a single setTimeout
// when it dings, all cbs get called
req('foo', cb1)
req('foo', cb2)
req('foo', cb3)
req('foo', cb4)
```


text:
@interface PersonalPageViewController : UIViewController
{
    NSString *usernameStr;
}
-(void)passData:(NSString*)argu;
@property (strong, nonatomic) NSString *cellUserName;
@end


text:
layout: page
title: Dougherty Family Reunion
date: 2016-05-24
author: Stephen Sandoval
tags: weekly links, java
status: published
summary: In magna massa, tempor eget tortor ac, vulputate vulputate nibh.
banner: images/banner/office-01.jpg
booking:
  startDate: 05/03/2017
  endDate: 05/06/2017
  ctyhocn: JAXDWHX
  groupCode: DFR
published: true
---
Nam molestie euismod tellus. Fusce efficitur in orci nec sodales. Nulla non iaculis enim. Cras augue est, sodales viverra lorem id, scelerisque tincidunt tortor. Nullam condimentum quam a eros bibendum, ac vestibulum libero mattis. Suspendisse euismod posuere felis. Nam consectetur tincidunt nisi. Quisque et turpis posuere, vestibulum sem pellentesque, congue mi.

1 Vestibulum venenatis diam at semper consequat
1 Phasellus convallis augue at lorem elementum tempus non eu mauris.

Curabitur ultrices justo a diam fermentum condimentum at et arcu. Nullam fringilla aliquam tortor, sit amet consequat lacus gravida eget. Etiam tempus neque mi, at dictum enim blandit quis. Curabitur euismod, est ut venenatis porttitor, orci ligula gravida dui, non rutrum sapien dui eget metus. Fusce ultricies nulla eu elit semper gravida. Quisque eget hendrerit tortor. Fusce eu sapien ac elit posuere tincidunt. Donec imperdiet vestibulum tellus quis malesuada.
Etiam volutpat nisl a libero elementum pellentesque. Phasellus ultricies lacus commodo, volutpat ipsum at, pulvinar quam. Donec pellentesque nisi in placerat congue. Etiam in sem vel mi porta eleifend. Vivamus augue nisi, aliquet in turpis efficitur, semper malesuada enim. Nulla nec tortor varius, consequat velit a, aliquam urna. Donec maximus semper gravida. Maecenas ornare condimentum nibh, eu suscipit libero interdum ornare. Phasellus eget sapien lacus. Vestibulum commodo orci ac ultrices pretium. Sed sem lacus, pulvinar eu sapien sed, consequat sodales purus. Curabitur id placerat mauris.


text:
class HairGeneratorObject : public ObjectData
{
	INSTANCEOF(HairGeneratorObject, ObjectData)

public:
	virtual Bool Init(GeListNode* node);
	virtual void Free(GeListNode* node);

	virtual Bool Message(GeListNode* node, Int32 type, void* data);
	virtual DRAWRESULT Draw(BaseObject* op, DRAWPASS drawpass, BaseDraw* bd, BaseDrawHelp* bh);
	virtual BaseObject* GetVirtualObjects(BaseObject* op, HierarchyHelp* hh);

	virtual Bool AddToExecution(BaseObject* op, PriorityList* list);
	virtual EXECUTIONRESULT Execute(BaseObject* op, BaseDocument* doc, BaseThread* bt, Int32 priority, EXECUTIONFLAGS flags);

	static NodeData* Alloc() { return NewObjClear(HairGeneratorObject); }
};

//////////////////////////////////////////////////////////////////////////

Bool HairGeneratorObject::Init(GeListNode* node)
{
	BaseContainer* bc = ((BaseList2D*)node)->GetDataInstance();

	bc->SetInt32(HAIR_GEN_COUNT, 5000);
	bc->SetInt32(HAIR_GEN_SEGMENTS, 6);
	bc->SetFloat(HAIR_GEN_LENGTH, 15);
	bc->SetFloat(HAIR_GEN_LENGTH_VAR, 5);
	bc->SetFloat(HAIR_GEN_NOISE, 0.2);
	bc->SetBool(HAIR_GEN_GENERATE, false);

	return true;
}

void HairGeneratorObject::Free(GeListNode* node)
{
}

Bool HairGeneratorObject::Message(GeListNode* node, Int32 type, void* data)
{
	return SUPER::Message(node, type, data);
}

DRAWRESULT HairGeneratorObject::Draw(BaseObject* op, DRAWPASS drawpass, BaseDraw* bd, BaseDrawHelp* bh)
{
	return DRAWRESULT_SKIP;
}

Bool HairGeneratorObject::AddToExecution(BaseObject* op, PriorityList* list)
{
	list->Add(op, EXECUTIONPRIORITY_GENERATOR, EXECUTIONFLAGS_0);
	return true;
}

static void RunExecute(BaseObject* op, BaseDocument* doc)
{
	while (op)
	{
		if (op->IsInstanceOf(Ohair))
			((HairObject*)op)->Update(doc);
		RunExecute(op->GetDown(), doc);
		op = op->GetNext();
	}
}

EXECUTIONRESULT HairGeneratorObject::Execute(BaseObject* op, BaseDocument* doc, BaseThread* bt, Int32 priority, EXECUTIONFLAGS flags)
{
	RunExecute(op->GetCache(), doc);
	return EXECUTIONRESULT_OK;
}

BaseObject* HairGeneratorObject::GetVirtualObjects(BaseObject* pObject, HierarchyHelp* hh)
{
	Bool				bDirty = pObject->CheckCache(hh);
	HairObject* main = nullptr;
	HairGuides* guides = nullptr;
	Vector*			pnts = nullptr;

	if (!bDirty)
		bDirty = pObject->IsDirty(DIRTYFLAGS_DATA | DIRTYFLAGS_MATRIX);
	if (!bDirty)
		return pObject->GetCache(hh);

	//BaseContainer *bc=pObject->GetDataInstance();

	main = HairObject::Alloc();
	if (!main)
		goto error;

	main->Lock(hh->GetDocument(), hh->GetThread(), false, 0);

	guides = HairGuides::Alloc(1000, 8);
	if (!guides)
		goto error;

	main->SetGuides(guides, false);
	//guides->SetMg(mg);

	pnts = guides->GetPoints();

	Int32 i, l;

	for (i = 0; i < 1000; i++)
	{
		for (l = 0; l <= 8; l++)
		{
			pnts[i * 9 + l] = Vector(i, l * 20.0, 0.0);
		}
	}

	main->Unlock();

	if (!pObject->CopyTagsTo(main, true, false, false, nullptr))
		goto error;

	main->Update(hh->GetDocument());

	return main;

error:

	HairObject::Free(main);

	return BaseObject::Alloc(Onull);
}

//////////////////////////////////////////////////////////////////////////

#define ID_HAIR_GENERATOR_EXAMPLE 1020787

Bool RegisterGeneratorObject()
{
	return RegisterObjectPlugin(ID_HAIR_GENERATOR_EXAMPLE, GeLoadString(IDS_HAIR_GENERATOR_EXAMPLE), OBJECT_CALL_ADDEXECUTION | OBJECT_GENERATOR | OBJECT_INPUT, HairGeneratorObject::Alloc, "Ohairsdkgen", AutoBitmap("hairgen.tif"), 0);
}


text:
I am ZnPercentEncoder.
I implement RFC 3986 percent encoding and decoding.

All characters that are not part of a safe set are encoded using a percent (%) followed by a two digit hexadecimal number of a byte value. Non-ASCII characters are first encoded, normally using UTF-8.

My #encode: and #decode: messages work from String to String.

My decoder additionally will accept + as an encoding for a space.

See also http://en.wikipedia.org/wiki/Percent-encoding

Part of Zinc HTTP Components


text:
using webm::Element;

namespace {

class ElementTest : public testing::Test {};

TEST_F(ElementTest, Construction) {
  Element<int> value_initialized;
  EXPECT_EQ(false, value_initialized.is_present());
  EXPECT_EQ(0, value_initialized.value());

  Element<int> absent_custom_default(1);
  EXPECT_EQ(false, absent_custom_default.is_present());
  EXPECT_EQ(1, absent_custom_default.value());

  Element<int> present(2, true);
  EXPECT_EQ(true, present.is_present());
  EXPECT_EQ(2, present.value());
}

TEST_F(ElementTest, Assignment) {
  Element<int> e;

  e.Set(42, true);
  EXPECT_EQ(true, e.is_present());
  EXPECT_EQ(42, e.value());

  *e.mutable_value() = 0;
  EXPECT_EQ(true, e.is_present());
  EXPECT_EQ(0, e.value());
}

}  // namespace


text:
Imports System.Data.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Data.SqlClient
Imports Telerik.Web.UI
Public Class EmailLog
    Inherits System.Web.UI.Page
    'Dim rgEmailDataReader As SqlDataReader
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Response.Cache.SetCacheability(HttpCacheability.NoCache)

        'login check
        Dim loginchk = New clsLoginCheck()

        'Only Admins
        If Not User.IsInRole("Admin") And Not User.IsInRole("Contractor Admin") Then
            Response.Redirect("../Blank.aspx")
        End If

        If Not IsPostBack Then

            Dim intVersion As Integer = 0
            txtSelectEmailSentDate.Text = System.DateTime.Now.ToShortDateString()
            lblddlDaysVal.Text = ddlDays.SelectedValue
            lblSelectEmailSentDateVal.Text = txtSelectEmailSentDate.Text

        End If
    End Sub

    Private Sub sqlDatasource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles sqlDatasource1.Selecting
        e.Command.Parameters("@EndDate").Value = CDate(lblSelectEmailSentDateVal.Text).AddDays(lblddlDaysVal.Text)
        e.Command.Parameters("@StartDate").Value = CDate(lblSelectEmailSentDateVal.Text).AddDays(-CInt(lblddlDaysVal.Text))
    End Sub

    Private Sub btn508_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn508.Click
        If btn508.Text = "Keyboard Accessible View" Then
            btn508.Text = "Interactive View"
        Else
            btn508.Text = "Keyboard Accessible View"
        End If
        pnl508.Visible = Not pnl508.Visible
        rgEmail.ShowGroupPanel = Not rgEmail.ShowGroupPanel
        rgEmail.AllowFilteringByColumn = Not rgEmail.AllowFilteringByColumn
        rgEmail.MasterTableView.GroupByExpressions.Clear()
        rgEmail.MasterTableView.FilterExpression = ""
        rgEmail.Rebind()
    End Sub

    Private Sub btnGroupBy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGroupBy.Click
        Dim expression As GridGroupByExpression = New GridGroupByExpression
        Dim gridGroupByField As GridGroupByField = New GridGroupByField
        If ddlGroup.SelectedIndex < 1 Then
            rgEmail.MasterTableView.GroupByExpressions.Clear()
        Else
            If rgEmail.MasterTableView.GroupByExpressions.Count > 0 Then
                rgEmail.MasterTableView.GroupByExpressions.Clear()
            End If
            'SelectFields values (appear in header)
            gridGroupByField = New GridGroupByField
            gridGroupByField.FieldName = ddlGroup.SelectedValue
            gridGroupByField.HeaderText = ddlGroup.SelectedItem.Text
            gridGroupByField.FieldAlias = ddlGroup.SelectedValue

            gridGroupByField.HeaderValueSeparator = " for current group: "
            gridGroupByField.FormatString = "<strong>{0}</strong>"

            expression.SelectFields.Insert(0, gridGroupByField)
            expression.GroupByFields.Insert(0, gridGroupByField)

            rgEmail.MasterTableView.GroupByExpressions.Insert(0, expression)
        End If
        rgEmail.Rebind()
    End Sub

    Private Sub btnFilter_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFilter.Click
        If ddlFilter.SelectedIndex < 1 Then
            rgEmail.MasterTableView.FilterExpression = ""
            'clear all filter expressions also
        Else
            If ddlFilter.SelectedValue = "SentDate" Then
                Dim dtStartFilter As System.DateTime
                Dim dtEndFilter As System.DateTime
                Try
                    dtStartFilter = CDate(txtFilter.Text + " 00:00:00.0000000")
                    dtEndFilter = CDate(txtFilter.Text + " 23:59:59.9999999")
                    rgEmail.MasterTableView.FilterExpression = "([" & ddlFilter.SelectedValue & "] >= '" & dtStartFilter & "' AND [" & ddlFilter.SelectedValue & "] <= '" & dtEndFilter & "') "
                Catch ex As Exception
                    rgEmail.MasterTableView.FilterExpression = "([" & ddlFilter.SelectedValue & "] = " & txtFilter.Text & ") "
                End Try
            Else
                rgEmail.MasterTableView.FilterExpression = "([" & ddlFilter.SelectedValue & "] LIKE '%" & txtFilter.Text & "%') "
            End If
        End If
        rgEmail.MasterTableView.Rebind()
    End Sub

    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit.Click
        lblddlDaysVal.Text = ddlDays.SelectedValue
        lblSelectEmailSentDateVal.Text = txtSelectEmailSentDate.Text
        rgEmail.MasterTableView.CurrentPageIndex = 0
        rgEmail.MasterTableView.Rebind()
    End Sub

    Protected Sub Export_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ExportButton.Click
        ConfigureExport()

        If (Not IgnoreCheckBox.Checked) Then
            rgEmail.Rebind()
        End If
        rgEmail.ExportSettings.OpenInNewWindow = True
        rgEmail.MasterTableView.Caption = Now.ToString
        rgEmail.MasterTableView.ExportToExcel()
    End Sub

    Public Sub ConfigureExport()
        rgEmail.ExportSettings.ExportOnlyData = True
        rgEmail.ExportSettings.IgnorePaging = IgnoreCheckBox.Checked
    End Sub

    Private Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        rgEmail.MasterTableView.FilterExpression = ""
        rgEmail.Rebind()
    End Sub
End Class


text:
<?php
session_start();
header('Access-Control-Allow-Origin: *');

class login {

	function __construct()
    {

    }
    public  function login() {

         	$username = isset($_POST["username"]) ? $_POST["username"]: false;
			$password = isset($_POST["password"]) ? $_POST["password"] : false;

			if(!($username || $password)){
				$this->echo_fail("Missing parameters");
				return;
			}

			$data = array(
				"username" => $username,
				"password" => $password
			);

			$result = $this->curl_post("http://reliefboard.com/ph/login_controller/test_login_endpoint.php",
			$data);

			if($result['status'] == "ok"){

				$_SESSION['username'] = $result['result']['username'];
				$this->echo_ok($result['result']);
			}

    }

    public function logout(){
    	session_unset();
		session_destroy();
		$this->echo_ok("Sucessfully logged out");
    }

    public function echo_ok($message){
    	$data = array('status' =>  'ok', "result" => $message );
    	echo json_encode($data);
    }

    public function echo_fail($error){
    	$data = array('status' =>  'fail', "message" => $error );
    	echo json_encode($data);
    }

    public function curl_post($endpoint, $params){
    	$ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $endpoint);
	    curl_setopt($ch, CURLOPT_POST, 1);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

	    $response = curl_exec($ch);
	    curl_close($ch);
	    return json_decode($response, TRUE);
    }
}

?>


text:
Digests archive

No records were found

{{digest.title}}

{{digest.publishedDate | date:'yyyy-MM-dd'}}

                    {{showDetails && 'Hide' || 'Show more'}}

                            chevron_left

{{currentPage}} of {{totalPages}} page(-s)

                            chevron_right


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/LibraryUpdater.iml" filepath="$PROJECT_DIR$/LibraryUpdater.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/libraryupdater/libraryupdater.iml" filepath="$PROJECT_DIR$/libraryupdater/libraryupdater.iml" />
    </modules>
  </component>
</project>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Monogr. Uredin. (Lipsiae) 1(3): 442 (1903)

#### Original name
Puccinia depauperans P. Syd. & Syd., 1903

### Remarks
null


text:
ARG REPO=mcr.microsoft.com/dotnet/aspnet
FROM $REPO:5.0-alpine3.12-amd64

ENV \
    # Unset ASPNETCORE_URLS from aspnet base image
    ASPNETCORE_URLS= \
    DOTNET_SDK_VERSION=5.0.101 \
    # Disable the invariant mode (set in base image)
    DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false \
    # Enable correct mode for dotnet watch (only mode supported in a container)
    DOTNET_USE_POLLING_FILE_WATCHER=true \
    # Skip extraction of XML docs - generally not useful within an image/container - helps performance
    NUGET_XMLDOC_MODE=skip \
    # PowerShell telemetry for docker image usage
    POWERSHELL_DISTRIBUTION_CHANNEL=PSDocker-DotnetSDK-Alpine-3.12

RUN apk add --no-cache \
    curl \
    icu-libs \
    git

# Install .NET SDK
RUN wget -O dotnet.tar.gz https://dotnetcli.azureedge.net/dotnet/Sdk/$DOTNET_SDK_VERSION/dotnet-sdk-$DOTNET_SDK_VERSION-linux-musl-x64.tar.gz \
    && dotnet_sha512='e874661647b530c58e78dad4fc0537739a30c460e31678547e9dc186858c5119730d4e7a6b529bf96655ff11e8fabcecec9eb24b5faf5348fe20b8c7f3080c3a' \
    && echo "$dotnet_sha512  dotnet.tar.gz" | sha512sum -c - \
    && mkdir -p /usr/share/dotnet \
    && tar -C /usr/share/dotnet -oxzf dotnet.tar.gz ./packs ./sdk ./templates ./LICENSE.txt ./ThirdPartyNotices.txt \
    && rm dotnet.tar.gz \
    # Trigger first run experience by running arbitrary cmd
    && dotnet help

# Install PowerShell global tool
RUN powershell_version=7.2.0-preview.1 \
    && wget -O PowerShell.Linux.Alpine.$powershell_version.nupkg https://pwshtool.blob.core.windows.net/tool/$powershell_version/PowerShell.Linux.Alpine.$powershell_version.nupkg \
    && powershell_sha512='4b82a8567915c2d327f2c70f13017dcf35d8de9079e16a51897e512828e2e37dd0a925d06c61c11751c9bec940eea382f9ad07d96cbed78a39876862b2c17e48' \
    && echo "$powershell_sha512  PowerShell.Linux.Alpine.$powershell_version.nupkg" | sha512sum -c - \
    && mkdir -p /usr/share/powershell \
    && dotnet tool install --add-source / --tool-path /usr/share/powershell --version $powershell_version PowerShell.Linux.Alpine \
    && dotnet nuget locals all --clear \
    && rm PowerShell.Linux.Alpine.$powershell_version.nupkg \
    && chmod 755 /usr/share/powershell/pwsh \
    && ln -s /usr/share/powershell/pwsh /usr/bin/pwsh \
    # To reduce image size, remove the copy nupkg that nuget keeps.
    && find /usr/share/powershell -print | grep -i '.*[.]nupkg$' | xargs rm \
    # Add ncurses-terminfo-base to resolve psreadline dependency
    && apk add --no-cache ncurses-terminfo-base


text:
require 'cgi'
require 'net/http'
require 'json'
require 'pp'
require './constants'

# Is this point within the configured bbox of an OTP instance?
def has_otp_config(lat, lon)
  # Disabling OTP for the time being. Not ready for prime time.
  return false

  match = OTP_MAPPING.select {|m| lon >= m["bbox"]["min_lon"] && lon <= m["bbox"]["max_lon"] &&
                                  lat >= m["bbox"]["min_lat"] && lat <= m["bbox"]["max_lat"] }
  !match.empty?
end

# Get the base url for the OTP instance for this point
def get_otp_url(lat, lon)
  match = OTP_MAPPING.select {|m| lon >= m["bbox"]["min_lon"] && lon <= m["bbox"]["max_lon"] &&
                                  lat >= m["bbox"]["min_lat"] && lat <= m["bbox"]["max_lat"] }
  match.first["url"] if !match.empty?
end

# Get the important data from OTP
def get_info_from_otp(params)
  base_url=get_otp_url(params[:origin][0], params[:origin][1])

  # Do we have a url?
  if (!base_url.nil?)

    # Params to pas to OTP
    query_params = "plan?" + {
      "arriveBy" => "false",
      "date" => params[:date] || Date.today.strftime("%m/%d/%Y"),
      "time" => params[:time] || Time.now.strftime("%I:%M %p"),
      "mode" => "TRANSIT,WALK",
      "optimize" => "QUICK",
      "maxWalkDistance" => "1260",
      "toPlace" => params[:origin].join(","),
      "fromPlace" => params[:destination].join(",")
    }.map {|k,v| "#{k}=#{CGI.escape(v)}"}*"&"

    uri = URI.parse(base_url+query_params)
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Get.new(uri.request_uri)
    # Be sure to ask for JSON
    request.initialize_http_header({"Accept" => "application/json"})

    # puts "calling url #{uri}"
    res = JSON.parse(http.request(request).body)

    # TODO: make this more elegant when the fare data is better understood
    begin
      cost = res["plan"]["itineraries"].first["fare"]["fare"]["regular"]["cents"].fdiv(100)
    rescue Exception => e
      cost = nil
    end

    {
      :walk_duration => res["plan"]["itineraries"].first["walkTime"],
      :transit_duration => res["plan"]["itineraries"].first["transitTime"],
      :wait_duration => res["plan"]["itineraries"].first["waitingTime"],
      :duration => res["plan"]["itineraries"].first["duration"].fdiv(1000),
      :cost => cost
    }
  end
end