text:
package org.drip.analytics.curve;

/*
 * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 */

/*!
 * Copyright (C) 2013 Lakshmi Krishnamurthy
 * Copyright (C) 2012 Lakshmi Krishnamurthy
 * Copyright (C) 2011 Lakshmi Krishnamurthy
 *
 * This file is part of CreditAnalytics, a free-software/open-source library for fixed income analysts and
 * 		developers - http://www.credit-trader.org
 *
 * CreditAnalytics is a free, full featured, fixed income credit analytics library, developed with a special
 * 		focus towards the needs of the bonds and credit products community.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *   	you may not use this file except in compliance with the License.
 *
 *  You may obtain a copy of the License at
 *  	http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  	distributed under the License is distributed on an "AS IS" BASIS,
 *  	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 *  See the License for the specific language governing permissions and
 *  	limitations under the License.
 */

/**
 * This class contains the constant hazard rate based credit curve holder object. It exports the
 *  following functionality:
 *  - Calculate survival probability / survival probability Jacobian
 *  - Calculate recovery / recovery Jacobian
 *  - Calculate hazard rate / hazard rate Jacobian
 *  - Construct tweaked curve instances (parallel/tenor/custom tweaks)
 *  - Optionally provide the calibration instruments and quotes used to build the curve.
 *
 * @author Lakshmi Krishnamurthy
 */

public class ConstantForwardHazard extends org.drip.analytics.definition.CreditCurve {
	private static final int NUM_DF_QUADRATURES = 5;

	private java.lang.String _strName = "";
	private double[] _adblCalibQuote = null;
	private double[] _adblHazardDate = null;
	private double[] _adblHazardRate = null;
	private double[] _adblRecoveryDate = null;
	private double[] _adblRecoveryRate = null;
	private double _dblStartDate = java.lang.Double.NaN;
	private java.lang.String[] _astrCalibMeasure = null;
	private double _dblSpecificDefaultDate = java.lang.Double.NaN;
	private org.drip.param.valuation.ValuationParams _valParam = null;
	private org.drip.param.valuation.QuotingParams _quotingParams = null;
	private org.drip.product.definition.CalibratableComponent[] _aCalibInst = null;
	private org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> _mapQuote = null;
	private org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.String> _mapMeasure = null;
	private java.util.Map<org.drip.analytics.date.JulianDate,
		org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double>> _mmFixing = null;

	private boolean _bFlat = false;
	private org.drip.param.pricer.PricerParams _pricerParam = null;
	private org.drip.analytics.definition.DiscountCurve _dc = null;
	private org.drip.analytics.definition.DiscountCurve _dcTSY = null;
	private org.drip.analytics.definition.DiscountCurve _dcEDSF = null;

	private org.drip.analytics.definition.CreditCurve createFromBaseNTP (
		final org.drip.param.definition.NodeTweakParams ntp)
	{
		double[] adblHazardBumped = org.drip.analytics.support.AnalyticsHelper.BumpNTPNode
			(_adblHazardRate, ntp);

		if (null == adblHazardBumped || _adblHazardRate.length != adblHazardBumped.length) return null;

		try {
			return new ConstantForwardHazard (_dblStartDate, _strName, adblHazardBumped, _adblHazardDate,
				_adblRecoveryRate, _adblRecoveryDate, _dblSpecificDefaultDate);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * Creates a credit curve from hazard rate and recovery rate term structures
	 *
	 * @param dblStart Curve Epoch date
	 * @param strName Credit Curve Name
	 * @param adblHazardRate Matched array of hazard rates
	 * @param adblHazardDate Matched array of hazard dates
	 * @param adblRecoveryRate Matched array of recovery rates
	 * @param adblRecoveryDate Matched array of recovery dates
	 * @param dblSpecificDefaultDate (Optional) Specific Default Date
	 *
	 * @throws java.lang.Exception Thrown if inputs are invalid
	 */

	public ConstantForwardHazard (
		final double dblStart,
		final java.lang.String strName,
		final double adblHazardRate[],
		final double adblHazardDate[],
		final double[] adblRecoveryRate,
		final double[] adblRecoveryDate,
		final double dblSpecificDefaultDate)
		throws java.lang.Exception
	{
		if (null == adblHazardRate || 0 == adblHazardRate.length || null == adblHazardDate || 0 ==
			adblHazardDate.length || adblHazardRate.length != adblHazardDate.length || null ==
				adblRecoveryRate || 0 == adblRecoveryRate.length || null == adblRecoveryDate || 0 ==
					adblRecoveryDate.length || adblRecoveryRate.length != adblRecoveryDate.length ||
						!org.drip.math.common.NumberUtil.IsValid (dblStart))
			throw new java.lang.Exception ("Invalid Credit curve init params!");

		_dblStartDate = dblStart;
		_dblSpecificDefaultDate = dblSpecificDefaultDate;
		_adblHazardRate = new double[adblHazardRate.length];
		_adblRecoveryRate = new double[adblRecoveryRate.length];
		_adblHazardDate = new double[adblHazardDate.length];
		_adblRecoveryDate = new double[adblRecoveryDate.length];

		for (int i = 0; i < adblHazardRate.length; ++i)
			_adblHazardRate[i] = adblHazardRate[i];

		for (int i = 0; i < _adblHazardDate.length; ++i)
			_adblHazardDate[i] = adblHazardDate[i];

		for (int i = 0; i < adblRecoveryRate.length; ++i)
			_adblRecoveryRate[i] = adblRecoveryRate[i];

		for (int i = 0; i < adblRecoveryDate.length; ++i)
			_adblRecoveryDate[i] = adblRecoveryDate[i];
	}

	/**
	 * CreditCurve de-serialization from input byte array
	 *
	 * @param ab Byte Array
	 *
	 * @throws java.lang.Exception Thrown if CreditCurve cannot be properly de-serialized
	 */

	public ConstantForwardHazard (
		final byte[] ab)
		throws java.lang.Exception
	{
		if (null == ab || 0 == ab.length)
			throw new java.lang.Exception ("CreditCurve de-serializer: Invalid input Byte array");

		java.lang.String strRawString = new java.lang.String (ab);

		if (null == strRawString || strRawString.isEmpty())
			throw new java.lang.Exception ("CreditCurve de-serializer: Empty state");

		java.lang.String strSerializedCreditCurve = strRawString.substring (0, strRawString.indexOf
			(getObjectTrailer()));

		if (null == strSerializedCreditCurve || strSerializedCreditCurve.isEmpty())
			throw new java.lang.Exception ("CreditCurve de-serializer: Cannot locate state");

		java.lang.String[] astrField = org.drip.math.common.StringUtil.Split (strSerializedCreditCurve,
			getFieldDelimiter());

		if (null == astrField || 6 > astrField.length)
			throw new java.lang.Exception ("CreditCurve de-serializer: Invalid reqd field set");

		// double dblVersion = new java.lang.Double (astrField[0]);

		if (null == astrField[1] || astrField[1].isEmpty())
			throw new java.lang.Exception ("CreditCurve de-serializer: Cannot locate curve name");

		if (org.drip.service.stream.Serializer.NULL_SER_STRING.equalsIgnoreCase (_strName = astrField[1]))
			_strName = "";

		if (null == astrField[2] || astrField[2].isEmpty() ||
			org.drip.service.stream.Serializer.NULL_SER_STRING.equalsIgnoreCase (astrField[2]))
			throw new java.lang.Exception ("CreditCurve de-serializer: Cannot locate start date");

		_dblStartDate = new java.lang.Double (astrField[2]);

		java.util.List<java.lang.Double> lsdblHazardDate = new java.util.ArrayList<java.lang.Double>();

		java.util.List<java.lang.Double> lsdblHazardRate = new java.util.ArrayList<java.lang.Double>();

		if (null == astrField[3] || astrField[3].isEmpty() ||
			org.drip.service.stream.Serializer.NULL_SER_STRING.equalsIgnoreCase (astrField[3]))
			throw new java.lang.Exception ("CreditCurve de-serializer: Cannot decode hazard state");

		if (!org.drip.math.common.StringUtil.KeyValueListFromStringArray (lsdblHazardDate, lsdblHazardRate,
			astrField[3], getCollectionRecordDelimiter(), getCollectionKeyValueDelimiter()))
			throw new java.lang.Exception ("CreditCurve de-serializer: Cannot decode hazard state");

		if (0 == lsdblHazardDate.size() || 0 == lsdblHazardRate.size() || lsdblHazardDate.size() !=
			lsdblHazardRate.size())
			throw new java.lang.Exception ("CreditCurve de-serializer: Cannot decode hazard state");

		_adblHazardDate = new double[lsdblHazardDate.size()];

		_adblHazardRate = new double[lsdblHazardRate.size()];

		for (int i = 0; i < _adblHazardRate.length; ++i) {
			_adblHazardDate[i] = lsdblHazardDate.get (i);

			_adblHazardRate[i] = lsdblHazardRate.get (i);
		}

		java.util.List<java.lang.Double> lsdblRecoveryDate = new java.util.ArrayList<java.lang.Double>();

		java.util.List<java.lang.Double> lsdblRecoveryRate = new java.util.ArrayList<java.lang.Double>();

		if (null == astrField[4] || astrField[4].isEmpty() ||
			org.drip.service.stream.Serializer.NULL_SER_STRING.equalsIgnoreCase (astrField[4]))
			throw new java.lang.Exception ("CreditCurve de-serializer: Cannot decode recovery state");

		if (!org.drip.math.common.StringUtil.KeyValueListFromStringArray (lsdblRecoveryDate,
			lsdblRecoveryRate, astrField[4], getCollectionRecordDelimiter(),
				getCollectionKeyValueDelimiter()))
			throw new java.lang.Exception ("CreditCurve de-serializer: Cannot decode recovery state");

		if (0 == lsdblRecoveryDate.size() || 0 == lsdblRecoveryRate.size() || lsdblRecoveryDate.size() !=
			lsdblRecoveryRate.size())
			throw new java.lang.Exception ("CreditCurve de-serializer: Cannot decode recovery state");

		_adblRecoveryDate = new double[lsdblRecoveryDate.size()];

		_adblRecoveryRate = new double[lsdblRecoveryRate.size()];

		for (int i = 0; i < _adblRecoveryRate.length; ++i) {
			_adblRecoveryDate[i] = lsdblRecoveryDate.get (i);

			_adblRecoveryRate[i] = lsdblRecoveryRate.get (i);
		}

		_dblSpecificDefaultDate = new java.lang.Double (astrField[5]);
	}

	@Override public boolean initializeCalibrationRun (
		final double dblLeftSlope)
	{
		return true;
	}

	@Override public int numCalibNodes()
	{
		return _adblHazardDate.length;
	}

	@Override public org.drip.analytics.date.JulianDate getStartDate()
	{
		try {
			return new org.drip.analytics.date.JulianDate (_dblStartDate);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override public void setInstrCalibInputs (
		final org.drip.param.valuation.ValuationParams valParam,
		final boolean bFlat,
		final org.drip.analytics.definition.DiscountCurve dc,
		final org.drip.analytics.definition.DiscountCurve dcTSY,
		final org.drip.analytics.definition.DiscountCurve dcEDSF,
		final org.drip.param.pricer.PricerParams pricerParam,
		final org.drip.product.definition.CalibratableComponent[] aCalibInst,
		final double[] adblCalibQuote,
		final java.lang.String[] astrCalibMeasure,
		final java.util.Map<org.drip.analytics.date.JulianDate,
			org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double>> mmFixing,
		final org.drip.param.valuation.QuotingParams quotingParams)
	{
		_dc = dc;
		_bFlat = bFlat;
		_dcTSY = dcTSY;
		_dcEDSF = dcEDSF;
		_valParam = valParam;
		_mmFixing = mmFixing;
		_aCalibInst = aCalibInst;
		_pricerParam = pricerParam;
		_quotingParams = quotingParams;
		_adblCalibQuote = adblCalibQuote;
		_astrCalibMeasure = astrCalibMeasure;

		_mapQuote = new org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double>();

		_mapMeasure = new org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.String>();

		for (int i = 0; i < aCalibInst.length; ++i) {
			_mapMeasure.put (_aCalibInst[i].getPrimaryCode(), astrCalibMeasure[i]);

			_mapQuote.put (_aCalibInst[i].getPrimaryCode(), adblCalibQuote[i]);

			java.lang.String[] astrSecCode = _aCalibInst[i].getSecondaryCode();

			if (null != astrSecCode) {
				for (int j = 0; j < astrSecCode.length; ++j)
					_mapQuote.put (astrSecCode[j], adblCalibQuote[i]);
			}
		}
	}

	@Override public org.drip.product.definition.CalibratableComponent[] getCalibComponents()
	{
		return _aCalibInst;
	}

	@Override public double[] getCompQuotes()
	{
		return _adblCalibQuote;
	}

	@Override public java.lang.String[] getCompMeasures()
	{
		return _astrCalibMeasure;
	}

	@Override public org.drip.analytics.date.JulianDate getNodeDate (
		final int iNode)
	{
		if (iNode >= _adblHazardDate.length) return null;

		try {
			return new org.drip.analytics.date.JulianDate (_adblHazardDate[iNode]);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override public double getQuote (
		final java.lang.String strInstr)
		throws java.lang.Exception
	{
		if (null == _mapQuote || 0 == _mapQuote.size() || null == strInstr || strInstr.isEmpty() ||
			!_mapQuote.containsKey (strInstr))
			throw new java.lang.Exception ("Cannot get " + strInstr);

		return _mapQuote.get (strInstr);
	}

	@Override public ConstantForwardHazard createParallelHazardShiftedCurve (
		final double dblShift)
	{
		if (!org.drip.math.common.NumberUtil.IsValid (dblShift)) return null;

		double[] adblHazard = new double[_adblHazardRate.length];

		for (int i = 0; i < _adblHazardRate.length; ++i)
			adblHazard[i] = _adblHazardRate[i] + dblShift;

		try {
			return new ConstantForwardHazard (_dblStartDate, _strName, adblHazard, _adblHazardDate,
				_adblRecoveryRate, _adblRecoveryDate, _dblSpecificDefaultDate);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override public ConstantForwardHazard createParallelShiftedCurve (
		final double dblShift)
	{
		if (!org.drip.math.common.NumberUtil.IsValid (dblShift)) return null;

		if (null == _valParam || null == _aCalibInst || 0 == _aCalibInst.length || null == _adblCalibQuote ||
			0 == _adblCalibQuote.length || null == _astrCalibMeasure || 0 == _astrCalibMeasure.length ||
				_astrCalibMeasure.length != _adblCalibQuote.length || _adblCalibQuote.length !=
					_aCalibInst.length)
			return createParallelHazardShiftedCurve (dblShift);

		ConstantForwardHazard cc = null;
		double[] adblCalibQuote = new double[_adblCalibQuote.length];

		org.drip.analytics.calibration.CurveCalibrator calibrator = new
			org.drip.analytics.calibration.CurveCalibrator();

		try {
			cc = new ConstantForwardHazard (_dblStartDate, _strName, _adblHazardRate, _adblHazardDate,
				_adblRecoveryRate, _adblRecoveryDate, _dblSpecificDefaultDate);
		} catch (java.lang.Exception e) {
			e.printStackTrace();

			return null;
		}

		for (int i = 0; i < _adblCalibQuote.length; ++i) {
			try {
				calibrator.bootstrapHazardRate (cc, _aCalibInst[i], i, _valParam, _dc, _dcTSY, _dcEDSF,
					_pricerParam, _astrCalibMeasure[i], adblCalibQuote[i] = _adblCalibQuote[i] + dblShift,
						_mmFixing, _quotingParams, _bFlat);
			} catch (java.lang.Exception e) {
				e.printStackTrace();

				return null;
			}
		}

		cc.setInstrCalibInputs (_valParam, _bFlat, _dc, _dcTSY, _dcEDSF, _pricerParam, _aCalibInst,
			adblCalibQuote, _astrCalibMeasure, _mmFixing, _quotingParams);

		return cc;
	}

	@Override public org.drip.analytics.definition.CreditCurve createFlatCurve (
		final double dblFlatNodeValue,
		final boolean bSingleNode,
		final double dblRecovery)
	{
		if (!org.drip.math.common.NumberUtil.IsValid (dblFlatNodeValue) || 0. >= dblFlatNodeValue || null ==
			_valParam || null == _aCalibInst || 0 == _aCalibInst.length || null == _adblCalibQuote || 0 ==
				_adblCalibQuote.length || null == _astrCalibMeasure || 0 == _astrCalibMeasure.length ||
					_astrCalibMeasure.length != _adblCalibQuote.length || _adblCalibQuote.length !=
						_aCalibInst.length)
			return null;

		org.drip.analytics.definition.CreditCurve cc = null;

		org.drip.analytics.calibration.CurveCalibrator calibrator = new
			org.drip.analytics.calibration.CurveCalibrator();

		try {
			if (bSingleNode)
				cc = org.drip.analytics.creator.CreditCurveBuilder.FromHazardNode (_dblStartDate, _strName,
					_adblHazardRate[0], _adblHazardDate[0], !org.drip.math.common.NumberUtil.IsValid
						(dblRecovery) ? _adblRecoveryRate[0] : dblRecovery);
			else
				cc = new ConstantForwardHazard (_dblStartDate, _strName, _adblHazardRate, _adblHazardDate,
					_adblRecoveryRate, _adblRecoveryDate, _dblSpecificDefaultDate);
		} catch (java.lang.Exception e) {
			e.printStackTrace();

			return null;
		}

		for (int i = 0; i < _adblCalibQuote.length; ++i) {
			try {
				calibrator.bootstrapHazardRate (cc, _aCalibInst[i], i, _valParam, _dc, _dcTSY, _dcEDSF,
					_pricerParam, _astrCalibMeasure[i], dblFlatNodeValue, _mmFixing, _quotingParams, true);
			} catch (java.lang.Exception e) {
				e.printStackTrace();

				return null;
			}
		}

		if (bSingleNode)
			cc.setInstrCalibInputs (_valParam, true, _dc, _dcTSY, _dcEDSF, _pricerParam, new
				org.drip.product.definition.CalibratableComponent[] {_aCalibInst[0]}, new double[]
					{dblFlatNodeValue}, _astrCalibMeasure, _mmFixing, _quotingParams);
		else {
			double[] adblCalibValue = new double[_adblCalibQuote.length];

			for (int i = 0; i < _adblCalibQuote.length; ++i)
				adblCalibValue[i] = dblFlatNodeValue;

			cc.setInstrCalibInputs (_valParam, true, _dc, _dcTSY, _dcEDSF, _pricerParam, _aCalibInst,
				adblCalibValue, _astrCalibMeasure, _mmFixing, _quotingParams);
		}

		return cc;
	}

	@Override public java.lang.String getName()
	{
		return _strName;
	}

	@Override public boolean setNodeValue (
		final int iNodeIndex,
		final double dblValue)
	{
		if (!org.drip.math.common.NumberUtil.IsValid (dblValue) || iNodeIndex > _adblHazardRate.length)
			return false;

		for (int i = iNodeIndex; i < _adblHazardRate.length; ++i)
			_adblHazardRate[i] = dblValue;

		return true;
	}

	@Override public boolean bumpNodeValue (
		final int iNodeIndex,
		final double dblValue)
	{
		if (!org.drip.math.common.NumberUtil.IsValid (dblValue) || iNodeIndex > _adblHazardRate.length)
			return false;

		for (int i = iNodeIndex; i < _adblHazardRate.length; ++i)
			_adblHazardRate[i] += dblValue;

		return true;
	}

	@Override public boolean setFlatValue (
		final double dblValue)
	{
		if (!org.drip.math.common.NumberUtil.IsValid (dblValue)) return false;

		for (int i = 0; i < _adblHazardRate.length; ++i)
			_adblHazardRate[i] = dblValue;

		return true;
	}

	@Override  public org.drip.analytics.definition.CreditCurve createTweakedCurve (
		final org.drip.param.definition.NodeTweakParams ntp)
	{
		if (null == ntp) return null;

		if (!(ntp instanceof org.drip.param.definition.CreditNodeTweakParams))
			return createFromBaseNTP (ntp);

		org.drip.param.definition.CreditNodeTweakParams cntp =
			(org.drip.param.definition.CreditNodeTweakParams) ntp;

		if (org.drip.param.definition.CreditNodeTweakParams.CREDIT_TWEAK_NODE_PARAM_RECOVERY.equalsIgnoreCase
			(cntp._strTweakParamType)) {
			double[] adblRecoveryRateBumped = null;

			if (null == (adblRecoveryRateBumped = org.drip.analytics.support.AnalyticsHelper.BumpNTPNode
				(_adblRecoveryRate, cntp)) || adblRecoveryRateBumped.length != _adblRecoveryRate.length)
				return null;

			try {
				return new ConstantForwardHazard (_dblStartDate, _strName, _adblHazardRate, _adblHazardDate,
					adblRecoveryRateBumped, _adblRecoveryDate, _dblSpecificDefaultDate);
			} catch (java.lang.Exception e) {
				e.printStackTrace();
			}
		} else if
			(org.drip.param.definition.CreditNodeTweakParams.CREDIT_TWEAK_NODE_PARAM_QUOTE.equalsIgnoreCase
				(cntp._strTweakParamType)) {
			if (org.drip.param.definition.CreditNodeTweakParams.CREDIT_TWEAK_NODE_MEASURE_HAZARD.equalsIgnoreCase
				(cntp._strTweakMeasureType)) {
				double[] adblHazardBumped = null;

				if (null == (adblHazardBumped = org.drip.analytics.support.AnalyticsHelper.BumpNTPNode
					(_adblHazardRate, cntp)) || adblHazardBumped.length != _adblHazardRate.length)
					return null;

				try {
					return new ConstantForwardHazard (_dblStartDate, _strName, adblHazardBumped,
						_adblHazardDate, _adblRecoveryRate, _adblRecoveryDate, _dblSpecificDefaultDate);
				} catch (java.lang.Exception e) {
					e.printStackTrace();
				}
			} else if
				(org.drip.param.definition.CreditNodeTweakParams.CREDIT_TWEAK_NODE_MEASURE_QUOTE.equalsIgnoreCase
					(cntp._strTweakMeasureType)) {
				double[] adblQuoteBumped = null;

				if (null == (adblQuoteBumped = org.drip.analytics.support.AnalyticsHelper.BumpNTPNode
					(_adblHazardRate, cntp)) || adblQuoteBumped.length != _adblHazardRate.length)
					return null;

				org.drip.analytics.definition.CreditCurve cc = null;

				org.drip.analytics.calibration.CurveCalibrator calibrator = new
					org.drip.analytics.calibration.CurveCalibrator();

				try {
					if (cntp._bSingleNodeCalib)
						cc = org.drip.analytics.creator.CreditCurveBuilder.FromHazardNode (_dblStartDate,
							_strName, _adblHazardRate[0], _adblHazardDate[0], _adblRecoveryRate[0]);
					else
						cc = new ConstantForwardHazard (_dblStartDate, _strName, _adblHazardRate,
							_adblHazardDate, _adblRecoveryRate, _adblRecoveryDate, _dblSpecificDefaultDate);
				} catch (java.lang.Exception e) {
					e.printStackTrace();

					return null;
				}

				for (int i = 0; i < adblQuoteBumped.length; ++i) {
					try {
						calibrator.bootstrapHazardRate (cc, _aCalibInst[i], i, _valParam, _dc, _dcTSY,
							_dcEDSF, _pricerParam, _astrCalibMeasure[i], adblQuoteBumped[i], _mmFixing,
								_quotingParams, _bFlat);
					} catch (java.lang.Exception e) {
						e.printStackTrace();

						return null;
					}
				}

				cc.setInstrCalibInputs (_valParam, _bFlat, _dc, _dcTSY, _dcEDSF, _pricerParam, _aCalibInst,
					adblQuoteBumped, _astrCalibMeasure, _mmFixing, _quotingParams);

				return cc;
			}
		}

		return null;
	}

	@Override public boolean setSpecificDefault (
		final double dblSpecificDefaultDate)
	{
		_dblSpecificDefaultDate = dblSpecificDefaultDate;
		return true;
	}

	@Override public boolean unsetSpecificDefault()
	{
		_dblSpecificDefaultDate = java.lang.Double.NaN;
		return true;
	}

	@Override public double getSurvival (
		final double dblDate)
		throws java.lang.Exception
	{
		if (!org.drip.math.common.NumberUtil.IsValid (dblDate))
			throw new java.lang.Exception ("No surv for NaN date");

		if (dblDate <= _dblStartDate) return 1.;

		if (org.drip.math.common.NumberUtil.IsValid (_dblSpecificDefaultDate) && dblDate >=
			_dblSpecificDefaultDate)
			return 0.;

		int i = 0;
		double dblExpArg = 0.;
		double dblStartDate = _dblStartDate;

		while (i < _adblHazardRate.length && dblDate > _adblHazardDate[i]) {
			dblExpArg -= _adblHazardRate[i] * (_adblHazardDate[i] - dblStartDate);
			dblStartDate = _adblHazardDate[i++];
		}

		if (i >= _adblHazardRate.length) i = _adblHazardRate.length - 1;

		dblExpArg -= _adblHazardRate[i] * (dblDate - dblStartDate);

		return java.lang.Math.exp (dblExpArg / 365.25);
	}

	@Override public double getSurvival (
		final org.drip.analytics.date.JulianDate dt)
		throws java.lang.Exception
	{
		if (null == dt) throw new java.lang.Exception ("No surv for null date");

		return getSurvival (dt.getJulian());
	}

	@Override public double getSurvival (
		final java.lang.String strTenor)
		throws java.lang.Exception
	{
		if (null == strTenor || strTenor.isEmpty())
			throw new java.lang.Exception ("CC.getSurvival got bad tenor");

		return getSurvival (new org.drip.analytics.date.JulianDate (_dblStartDate).addTenor (strTenor));
	}

	@Override public double getEffectiveSurvival (
		final double dblDate1,
		final double dblDate2)
		throws java.lang.Exception
	{
		if (dblDate1 == dblDate2) return getSurvival (dblDate1);

		int iNumQuadratures = 0;
		double dblEffectiveSurvival = 0.;
		double dblQuadratureWidth = (dblDate2 - dblDate1) / NUM_DF_QUADRATURES;

		for (double dblDate = dblDate1; dblDate <= dblDate2; dblDate += dblQuadratureWidth) {
			++iNumQuadratures;

			dblEffectiveSurvival += (getSurvival (dblDate) + getSurvival (dblDate + dblQuadratureWidth));
		}

		return dblEffectiveSurvival / (2. * iNumQuadratures);
	}

	@Override public double getEffectiveSurvival (
		final org.drip.analytics.date.JulianDate dt1,
		final org.drip.analytics.date.JulianDate dt2)
		throws java.lang.Exception
	{
		if (null == dt1 || null == dt2) throw new java.lang.Exception ("No surv for null date");

		return getEffectiveSurvival (dt1.getJulian(), dt2.getJulian());
	}

	@Override public double getEffectiveSurvival (
		final java.lang.String strTenor1,
		final java.lang.String strTenor2)
		throws java.lang.Exception
	{
		if (null == strTenor1 || strTenor1.isEmpty() || null == strTenor2 || strTenor2.isEmpty())
			throw new java.lang.Exception ("CC.getEffectiveSurvival got bad tenor");

		return getEffectiveSurvival (new org.drip.analytics.date.JulianDate (_dblStartDate).addTenor
			(strTenor1), new org.drip.analytics.date.JulianDate (_dblStartDate).addTenor (strTenor2));
	}

	@Override public double calcHazard (
		final org.drip.analytics.date.JulianDate dt1,
		final org.drip.analytics.date.JulianDate dt2)
		throws java.lang.Exception
	{
		if (null == dt1 || null == dt2) throw new java.lang.Exception ("No hazard for null dates");

		if (dt1.getJulian() < _dblStartDate || dt2.getJulian() < _dblStartDate) return 0.;

		return 365.25 / (dt2.getJulian() - dt1.getJulian()) * java.lang.Math.log (getSurvival (dt1) /
			getSurvival (dt2));
	}

	@Override public double calcHazard (
		final org.drip.analytics.date.JulianDate dt)
		throws java.lang.Exception
	{
		return calcHazard (dt, new org.drip.analytics.date.JulianDate (_dblStartDate));
	}

	@Override public double calcHazard (
		final java.lang.String strTenor)
		throws java.lang.Exception
	{
		if (null == strTenor || strTenor.isEmpty())
			throw new java.lang.Exception ("CC.calcHazard got bad tenor");

		return calcHazard (new org.drip.analytics.date.JulianDate (_dblStartDate).addTenor (strTenor));
	}

	@Override public double getRecovery (
		final double dblDate)
		throws java.lang.Exception
	{
		if (!org.drip.math.common.NumberUtil.IsValid (dblDate))
			throw new java.lang.Exception ("No rec for NaN date");

		for (int i = 0; i < _adblRecoveryDate.length; ++i) {
			if (dblDate < _adblRecoveryDate[i]) return _adblRecoveryRate[i];
		}

		return _adblRecoveryRate[_adblRecoveryDate.length - 1];
	}

	@Override public double getRecovery (
		final org.drip.analytics.date.JulianDate dt)
		throws java.lang.Exception
	{
		if (null == dt) throw new java.lang.Exception ("No rec for null date");

		return getRecovery (dt.getJulian());
	}

	@Override public double getRecovery (
		final java.lang.String strTenor)
		throws java.lang.Exception
	{
		if (null == strTenor || strTenor.isEmpty())
			throw new java.lang.Exception ("CC.getRecovery got bad tenor");

		return getRecovery (new org.drip.analytics.date.JulianDate (_dblStartDate).addTenor (strTenor));
	}

	@Override public double getEffectiveRecovery (
		final double dblDate1,
		final double dblDate2)
		throws java.lang.Exception
	{
		if (dblDate1 == dblDate2) return getRecovery (dblDate1);

		int iNumQuadratures = 0;
		double dblEffectiveRecovery = 0.;
		double dblQuadratureWidth = (dblDate2 - dblDate1) / NUM_DF_QUADRATURES;

		for (double dblDate = dblDate1; dblDate <= dblDate2; dblDate += dblQuadratureWidth) {
			++iNumQuadratures;

			dblEffectiveRecovery += (getRecovery (dblDate) + getRecovery (dblDate + dblQuadratureWidth));
		}

		return dblEffectiveRecovery / (2. * iNumQuadratures);
	}

	@Override public double getEffectiveRecovery (
		final org.drip.analytics.date.JulianDate dt1,
		final org.drip.analytics.date.JulianDate dt2)
		throws java.lang.Exception
	{
		if (null == dt1 || null == dt2) throw new java.lang.Exception ("No rec for null date");

		return getEffectiveRecovery (dt1.getJulian(), dt2.getJulian());
	}

	@Override public double getEffectiveRecovery (
		final java.lang.String strTenor1,
		final java.lang.String strTenor2)
		throws java.lang.Exception
	{
		if (null == strTenor1 || strTenor1.isEmpty() || null == strTenor2 || strTenor2.isEmpty())
			throw new java.lang.Exception ("CC.getEffectiveRecovery got bad tenor");

		return getEffectiveRecovery (new org.drip.analytics.date.JulianDate (_dblStartDate).addTenor
			(strTenor1), new org.drip.analytics.date.JulianDate (_dblStartDate).addTenor (strTenor2));
	}

	@Override public byte[] serialize()
	{
		java.lang.StringBuffer sb = new java.lang.StringBuffer();

		java.lang.String strNameSer = _strName;

		if (null == strNameSer || strNameSer.isEmpty())
			strNameSer = org.drip.service.stream.Serializer.NULL_SER_STRING;

		sb.append (org.drip.service.stream.Serializer.VERSION + getFieldDelimiter() + strNameSer +
			getFieldDelimiter() + _dblStartDate + getFieldDelimiter());

		for (int i = 0; i < _adblHazardDate.length; ++i) {
			if (0 != i) sb.append (getCollectionRecordDelimiter());

			sb.append (_adblHazardDate[i] + getCollectionKeyValueDelimiter() + _adblHazardRate[i]);
		}

		sb.append (getFieldDelimiter());

		for (int i = 0; i < _adblRecoveryDate.length; ++i) {
			if (0 != i) sb.append (getCollectionRecordDelimiter());

			sb.append (_adblRecoveryDate[i] + getCollectionKeyValueDelimiter() + _adblRecoveryRate[i]);
		}

		sb.append (getFieldDelimiter() + _dblSpecificDefaultDate);

		return sb.append (getObjectTrailer()).toString().getBytes();
	}

	@Override public org.drip.service.stream.Serializer deserialize (
		final byte[] ab) {
		try {
			return new ConstantForwardHazard (ab);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override public java.lang.String displayString()
	{
		try {
			java.lang.StringBuffer sb = new java.lang.StringBuffer();

			for (int i = 0; i < _adblHazardRate.length; ++i) {
				if (0 != i) sb.append (" | ");

				sb.append (new org.drip.analytics.date.JulianDate (_adblHazardDate[i]) + "=" +
					_adblHazardRate[i]);
			}

			return sb.toString();
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override public boolean buildInterpolator()
	{
		return false;
	}

	public static void main (
		final java.lang.String[] astrArgs)
		throws java.lang.Exception
	{
		double dblStart = org.drip.analytics.date.JulianDate.Today().getJulian();

		double[] adblHazardDate = new double[3];
		double[] adblHazardRate = new double[3];
		double[] adblRecoveryDate = new double[3];
		double[] adblRecoveryRate = new double[3];

		for (int i = 0; i < 3; ++i) {
			adblHazardDate[i] = dblStart + 365. * (i + 1);
			adblHazardRate[i] = 0.01 * (i + 1);
			adblRecoveryDate[i] = dblStart + 365. * (i + 1);
			adblRecoveryRate[i] = 0.40;
		}

		ConstantForwardHazard cc = new ConstantForwardHazard (dblStart, "XXS", adblHazardRate,
			adblHazardDate, adblRecoveryRate, adblRecoveryDate, java.lang.Double.NaN);

		byte[] abCC = cc.serialize();

		System.out.println ("Input: " + new java.lang.String (abCC));

		System.out.println ("Surv[12/12/20]=" + cc.getSurvival
			(org.drip.analytics.date.JulianDate.CreateFromDDMMMYYYY ("12-DEC-2020")));

		ConstantForwardHazard ccDeser = new ConstantForwardHazard (abCC);

		System.out.println ("Output: " + new java.lang.String (ccDeser.serialize()));

		System.out.println ("Surv[12/12/20]=" + ccDeser.getSurvival
			(org.drip.analytics.date.JulianDate.CreateFromDDMMMYYYY ("12-DEC-2020")));
	}
}


text:
package org.pentaho.di.repository;

import org.xml.sax.SAXParseException;

public interface RepositoryElementReadListener {
  public boolean transformationElementRead(String xml, RepositoryImportFeedbackInterface feedback);
  public boolean jobElementRead(String xml, RepositoryImportFeedbackInterface feedback);
  public void fatalXmlErrorEncountered(SAXParseException e);
}

redpajama_set_name: RedPajamaGithub


text: export { default } from 'ember-ui-kit/components/ui-th/component';


text:
class SwitchProcessor
  include Thymeleaf::Processor

  def call(attribute:nil, context:nil, **_)
    condition = EvalExpression.parse(context, attribute.value)
    new_context = ContextHolder.new({}, context)
    new_context.set_private DefaultDialect::CONTEXT_SWITCH_VAR, condition

    attribute.unlink
    new_context
  end

  def has_subcontext?
    true
  end

end


text:
import * as React from "react";

import { Observable } from "babylonjs/Misc/observable";
import { Nullable } from 'babylonjs/types';

import { PropertyChangedEvent } from "../../../propertyChangedEvent";
import { LineContainerComponent } from "../../lineContainerComponent";
import { LockObject } from "./lockObject";
import { GlobalState } from "../../../globalState";
import { OptionsLineComponent } from '../../lines/optionsLineComponent';

declare type KHR_materials_variants = import("babylonjs-loaders/glTF/2.0/Extensions/KHR_materials_variants").KHR_materials_variants;

interface IVariantsPropertyGridComponentProps {
    globalState: GlobalState;
    host: any;
    lockObject: LockObject;
    onPropertyChangedObservable?: Observable<PropertyChangedEvent>;
}

export class VariantsPropertyGridComponent extends React.Component<IVariantsPropertyGridComponentProps> {

    constructor(props: IVariantsPropertyGridComponentProps) {
        super(props);
    }

    private _getVariantsExtension(): Nullable<KHR_materials_variants> {
        return this.props.globalState?.glTFLoaderExtensions["KHR_materials_variants"] as KHR_materials_variants;
    }

    render() {
        const extension = this._getVariantsExtension();
        if (!extension) {
            return null;
        }
        let variants: string[] = extension.getAvailableVariants(this.props.host);

        if (!variants || variants.length === 0) {
            return null;
        }

        let options = variants.sort().map((v: string, i: number) =>  {
            return {label: v, value: i + 1}
        });

        options.splice(0, 0, {label: "Original", value: 0})

        return (
            <div>
                <LineContainerComponent globalState={this.props.globalState} title="VARIANTS">
                <OptionsLineComponent
                    label="Active variant" options={options} noDirectUpdate={true}
                    target={this.props.host}
                    propertyName=""
                    onSelect={(value: number) => {
                        if (value === 0) {
                            extension.reset(this.props.host);
                        } else {
                            extension.selectVariant(this.props.host, variants[value - 1]);
                        }
                        this.forceUpdate();
                    }}
                    extractValue={() => {
                        let lastPickedVariant = extension.getLastSelectedVariant(this.props.host) || 0;
                        let index = 0;
                        if (lastPickedVariant && Object.prototype.toString.call(lastPickedVariant) === '[object String]') {
                            index = variants.indexOf(lastPickedVariant as string);
                            if (index > -1) {
                                index = index + 1;
                            }
                        }

                        return index;
                    }}
                />
                </LineContainerComponent>
            </div>
        );
    }
}


text:
angular.module('save-my-gas')

.controller('vehicleController', function(
	$scope,
	vehicleService,
	collection
) {
	$scope.collection = collection

	$scope.delete = function(id) {
		vehicleService.deleteById(id)
			.then(function() {
				$scope.collection = vehicleService.getCollection()
			})
	}
})

.controller('vehicleEditController', function(
	$scope,
	$cordovaCamera,
	utilService,
	vehicleService,
	model
) {
	if (model.photo) {
		$scope.vehiclePhoto = vehicleService.getVehiclePhotoPath(model)
	} else {
		$scope.vehiclePhoto = SaveMyGas.rootRoute.getPath('/img/default-car.svg')
	}

	model.photo = model.photo || {
		photo: null
	}

	$scope.model = model
	$scope.anoAtual = (new Date()).getFullYear()

	$scope.photoAttachChanged = function(files) {
		if (files.length) {
			var file = files[0]
			utilService.fileToB64(file).then(function(img) {
				if (img.indexOf('image') === -1) {
					Materialize.toast('Escolha uma IMAGEM')
					$scope.model.photo.photo = null
				} else {
					$scope.vehiclePhoto = img
					$scope.model.photo.photo = file.name
						// $scope.model.photo.thumb = utilService.resizeImg(img, 100, 100)
					vehicleService.uploadPhoto(file, $scope.model)
				}
			})
		}
	}

	$scope.takeCarPicture = function() {
		var options = {
			quality: 80,
			destinationType: Camera.DestinationType.DATA_URL,
			sourceType: Camera.PictureSourceType.CAMERA,
			allowEdit: true,
			encodingType: Camera.EncodingType.JPEG,
			targetWidth: 1280,
			targetHeight: 960,
			popoverOptions: CameraPopoverOptions,
			saveToPhotoAlbum: false,
			correctOrientation: true
		};

		$cordovaCamera.getPicture(options).then(function(imageData) {
			$scope.vehiclePhoto = "data:image/jpeg;base64," + imageData
			var file = utilService.B64ToFile($scope.vehiclePhoto)
			vehicleService.uploadPhoto(file, $scope.model, $scope.model.id)
		}, function(err) {
			if (typeof err === 'string' && err.indexOf('cancelled') > -1) {
				console.info('tirar foto cancelado')
			} else {
				Materialize.toast('Ocorreu um problema ao tirar a foto :(')
			}
		})
	}

	$scope.vehicleModelSelected = function($item) {
		if ($item.vehicleBrand) {
			$scope.model.vehicleBrandId = $item.vehicleBrand
		}
		if ($item.vehicleType) {
			$scope.model.vehicleTypeId = $item.vehicleType
		}
		if ($item.vehicleEngine) {
			$scope.model.vehicleEngineId = $item.vehicleEngine
		}
	}

	$scope.save = function(model) {
		vehicleService.save(model)
	}

	$scope.vehicleEngineParamsMake = function(searchTerm) {
		return {
			filter: {
				where: {
					or: [{
						power: {
							like: searchTerm
						}
					}, {
						valve: {
							like: searchTerm
						}
					}]
				},
				limit: 10
			}
		}
	}

	$scope.vehicleRefuelGasStationParamsMake = function(searchTerm) {
		return {
			filter: {
				where: {
					and: [{
						or: [{
							companyName: {
								like: searchTerm,
								options: 'i'
							}
						}, {
							flag: {
								like: searchTerm,
								options: 'i'
							}
						}]
					}, {
						cityId: $scope.model.cityId
					}]
				},
				limit: 10
			}
		}
	}

	$scope.formatEngine = function(vehicleEngine) {
		return vehicleEngine.power + ' - ' + vehicleEngine.valve + 'v'
	}

	//remove relations to get the relation of fk selected by the autocomplete
	delete $scope.model.vehicleBrand
	delete $scope.model.vehicleModel
	delete $scope.model.vehicleType
	delete $scope.model.vehicleEngine
	delete $scope.model.fuelType

	$scope.model.vehicleBrand = {
		noResults: null
	}
	$scope.model.vehicleModel = {
		noResults: null
	}
	$scope.model.vehicleEngine = {
		power: null,
		valve: null,
		noResults: null
	}
})


text:
require 'net/http'

class ProjectsController < ApplicationController

  before_action :load_project, only: [:qrcode, :edit, :update, :decide_tip_amounts]

  load_and_authorize_resource only: [:commit_suggestions, :donate, :donors]

  def index
    @projects = Project.enabled.order(available_amount_cache: :desc, watchers_count: :desc, full_name: :asc).page(params[:page]).per(30)
  end

  def show
    @project = Project.where(id: params[:id]).first
    unless @project
      redirect_to root_path, alert: "Project not found"
      return
    end
    commontator_thread_show(@project)
  end

  def new
    unless user_signed_in?
      redirect_to new_user_session_path(return_url: request.original_url), flash: {info: "You must be logged in to create a new project"}
      return
    end
    @project = Project.new(params[:project])
  end

  def edit
    authorize! :update, @project
  end

  def update
    authorize! :update, @project
    @project.attributes = project_params
    if @project.tipping_policies_text.try(:text_changed?)
      @project.tipping_policies_text.user = current_user
    end
    if @project.save
      redirect_to project_path(@project), notice: "The project has been updated"
    else
      render 'edit'
    end
  end

  def decide_tip_amounts
    authorize! :decide_tip_amounts, @project
    if request.patch?
      @project.attributes = params.require(:project).permit(tips_attributes: [:id, :decided_amount_percentage, :decided_free_amount])
      @project.tips.each do |tip|
        next if tip.decided?
        if tip.decided_amount_percentage.present?
          tip.amount = @project.available_amount * (tip.decided_amount_percentage.to_f / 100)
        elsif tip.decided_free_amount.present?
          tip.amount = tip.decided_free_amount.to_d * COIN
        end
      end
      if @project.available_amount < 0
        flash.now[:error] = "The project has insufficient funds"
        return
      end
      if @project.save
        message = "The tip amounts have been defined"
        if @project.has_undecided_tips?
          redirect_to decide_tip_amounts_project_path(@project), notice: message
        else
          redirect_to @project, notice: message
        end
      end
    end
  end

  def qrcode
    respond_to do |format|
      format.svg  { render qrcode: @project.bitcoin_address, level: :l, unit: 4 }
    end
  end

  def create
    @project = Project.new(project_params)
    @project.hold_tips = true
    @project.collaborators.build(user: current_user)
    authorize! :create, @project

    if @project.save
      redirect_to @project, notice: "The project was created"
    else
      render "new"
    end
  end

  def commit_suggestions
    respond_to do |format|
      format.json do
        query = params[:query]
        commits = @project.commits.where('sha LIKE ? OR username LIKE ? OR message LIKE ?', "#{query}%", "%#{query}%", "%#{query}%")
        commits = commits.map do |commit|
          {
            sha: commit.sha,
            description: [
              commit.sha[0,10],
              commit.username.present? ? "@#{commit.username}" : nil,
              ERB::Util.html_escape(commit.message).truncate(30),
            ].reject(&:blank?).join(" "),
          }
        end
        render json: commits
      end
    end
  end

  def github_user_suggestions
    respond_to do |format|
      format.json do
        query = params[:query]
        users = User.enabled.where.not(nickname: nil).where.not(nickname: '').where('nickname LIKE ? OR name LIKE ?', "%#{query}%", "%#{query}%")
        users = users.map do |user|
          {
            login: user.nickname,
            description: [
              user.nickname,
              user.name.present? ? "(#{user.name})" : nil,
            ].reject(&:blank?).join(" "),
          }
        end
        render json: users
      end
    end
  end

  def donate
    if params[:donation_address]
      sender_address = params[:donation_address][:sender_address].strip
      @donation_address = @project.donation_addresses.where(sender_address: sender_address).first_or_create
    else
      @donation_address = @project.donation_addresses.build
    end
  end

  private
  def project_params
    params.require(:project).permit(:name, :description, :detailed_description, :full_name, :auto_tip_commits, :hold_tips, tipping_policies_text_attributes: [:text])
  end

  def load_project
    @project = Project.enabled.where(id: params[:id]).first
    unless @project
      redirect_to root_path, alert: "Project not found"
    end
  end
end


text:
/**
 * http://usejsdoc.org/
 */

define(['angularAMD',
        'angular-route',
        'angular-resource',
        'angular-cookies',
        'app/common/userData'], function (angularAMD) {
	// kick starting the whole application
    var app = angular.module('heroesKickStart', ['user.data', 'ngRoute',
                                                 'ngResource',
                                                 'ngCookies']);

    app.run(['$rootScope', '$location', '$cookies', 'UserData', function($rootScope, $location, $cookies, userObj) {
    	$rootScope.$on('$routeChangeStart', function (event, next) {
    		var access = angular.isDefined(next.access) ? next.access : {};
    		if(access.role === 'admin') {
        		$rootScope.isLoggedIn = $cookies.get('Auth');
        		if(access.loginRequired === true && !$cookies.get('Auth')) {
        			$rootScope.isLoggedIn = $rootScope.isLoggedIn || false;
        			$location.path('/'+ access.role +'/login');
        		}
        		if(access.isLogin === true && $cookies.get('Auth')) {
        			$rootScope.navBar = true;
        			$rootScope.isLoggedIn = $rootScope.isLoggedIn || true;
        			$location.path('/'+ access.role +'/dashboard');
        		}
    		}
    	});
    }]);

    app.config(function ($routeProvider) {
        $routeProvider
        	.when('/home', angularAMD.route({
	            templateUrl: 'app/pages/home/home.html',
	            controller: 'HomeCtrl',
	            controllerAs: 'home',
	            controllerUrl: 'app/pages/home/home.js'
	        }))
	        .when('/create', angularAMD.route({
	        	templateUrl: 'app/pages/create/create.html',
	        	controller: 'CreateCtrl',
	        	controllerUrl: 'app/pages/create/create.js'
	        }))
	        .when('/admin/dashboard', angularAMD.route({
	            templateUrl: 'app/pages/dashboard/dashboard.html',
	            controller: 'DashboardCtrl',
	            controllerAs: 'dashboard',
	            controllerUrl: 'app/pages/dashboard/dashboard.js',
	            access: {
	            	loginRequired: true,
	            	role: 'admin'
	            }
	        }))
	        .when('/admin/create', angularAMD.route({
	        	templateUrl: 'app/pages/create/create.html',
	        	controller: 'CreateCtrl',
	        	controllerAs: 'create',
	        	controllerUrl: 'app/pages/create/create.js',
	        	access: {
		           	loginRequired: true,
		           	role: 'admin'
		        }
	        }))
	        .when('/admin/login', angularAMD.route({
	        	templateUrl: 'app/pages/login/login.html',
	        	controller: 'LoginCtrl',
	        	controllerAs: 'login',
	        	controllerUrl: 'app/pages/login/login.js',
	        	access: {
	        		isLogin: true,
	        		role: 'admin'
	        	}
	        }))
	        .otherwise({redirectTo: '/home'});
    });
    return angularAMD.bootstrap(app);
});


text:
module TestSuite.CodeGeneration.AddSub(tests) where

import Data.SBV.Internals
import Data.SBV.Examples.CodeGeneration.AddSub

import Utils.SBVTestFramework

-- Test suite
tests :: TestTree
tests = testGroup "CodeGen.addSub" [
   goldenVsStringShow "addSub" code
 ]
 where code = compileToC' "addSub" $ do
                cgSetDriverValues [76, 92]
                cgPerformRTCs True
                x <- cgInput "x"
                y <- cgInput "y"
                let (s, d) = addSub x y
                cgOutput "sum" s
                cgOutput "dif" d


text:
"""
CADRE MDP Group.
"""

from six.moves import range

import os.path
import numpy as np

from openmdao.api import Group, ParallelGroup, IndepVarComp, ExecComp

from CADRE.CADRE_group import CADRE

class CADRE_MDP_Group(Group):
    """
    CADRE MDP Group. Can be run in Parallel.

    Parameters
    ----------
    n : int
        Number of time integration points.

    m : int
        Number of panels in fin discretization.

    npts : int
        Number of instances of CADRE in the problem.
    """

    def __init__(self, n=1500, m=300, npts=6):
        super(CADRE_MDP_Group, self).__init__()

        self.n = n
        self.m = m
        self.npts = npts

    def setup(self):
        # Raw data to load is in 'data' directory
        data_path = os.path.dirname(os.path.realpath(__file__))
        data_path = os.path.join(data_path, 'data')

        launch_data = np.loadtxt(data_path + '/Launch/launch1.dat')

        # orbit position and velocity data for each design point
        r_e2b_I0s = launch_data[1::2, 1:]

        # number of days since launch for each design point
        LDs = launch_data[1::2, 0] - 2451545

        # Create IndepVarComp for broadcast parameters.
        bp = self.add_subsystem('bp', IndepVarComp())
        bp.add_output('cellInstd', np.ones((7, 12)))
        bp.add_output('finAngle', np.pi/4.0, units='rad')
        bp.add_output('antAngle', 0.0, units='rad')

        # CADRE instances go into a Parallel Group
        para = self.add_subsystem('parallel', ParallelGroup(), promotes=['*'])

        # build design points
        names = ['pt%s' % i for i in range(self.npts)]
        for i, name in enumerate(names):
            # Some initial values
            inits = {
                'LD': float(LDs[i]),
                'r_e2b_I0': r_e2b_I0s[i]
            }

            para.add_subsystem(name, CADRE(n=self.n, m=self.m, initial_inputs=inits))

            # Hook up broadcast inputs
            self.connect('bp.cellInstd', '%s.cellInstd' % name)
            self.connect('bp.finAngle', '%s.finAngle' % name)
            self.connect('bp.antAngle', '%s.antAngle' % name)

            self.add_subsystem('%s_con5' % name, ExecComp('val = SOCi - SOCf'))

            self.connect('%s.SOC' % name, '%s_con5.SOCi' % name,
                         src_indices=[0], flat_src_indices=True)
            self.connect('%s.SOC' % name, '%s_con5.SOCf' % name,
                         src_indices=[self.n-1], flat_src_indices=True)

        # objective: sum of data from all design points
        data_totals = ['%s_DataTot' % name for name in names]
        obj = ''.join([' - %s' % data_tot for data_tot in data_totals])

        meta_dicts = {}
        for dt in data_totals:
            meta_dicts[dt] = {'units': 'Gibyte'}

        self.add_subsystem('obj', ExecComp('val='+obj, **meta_dicts))
        for name in names:
            self.connect('%s.Data' % name, 'obj.%s_DataTot' % name,
                         src_indices=[self.n-1], flat_src_indices=True)


text:
package safefile

import (
	"os"
	"path/filepath"
	"syscall"
	"testing"

	"github.com/Microsoft/hcsshim/internal/winapi"
)

func TestOpenRelative(t *testing.T) {
	badroot, err := tempRoot(t)
	if err != nil {
		t.Fatal(err)
	}

	root, err := tempRoot(t)
	if err != nil {
		t.Fatal(err)
	}

	// Create a file
	f, err := OpenRelative("foo", root, 0, syscall.FILE_SHARE_READ, winapi.FILE_CREATE, 0)
	if err != nil {
		t.Fatal(err)
	}
	f.Close()

	// Create a directory
	err = MkdirRelative("dir", root)
	if err != nil {
		t.Fatal(err)
	}

	// Create a file in the bad root
	f, err = os.Create(filepath.Join(badroot.Name(), "badfile"))
	if err != nil {
		t.Fatal(err)
	}
	f.Close()

	// Create a directory symlink to the bad root
	err = os.Symlink(badroot.Name(), filepath.Join(root.Name(), "dsymlink"))
	if err != nil {
		t.Fatal(err)
	}

	// Create a file symlink to the bad file
	err = os.Symlink(filepath.Join(badroot.Name(), "badfile"), filepath.Join(root.Name(), "symlink"))
	if err != nil {
		t.Fatal(err)
	}

	// Make sure opens cannot happen through the symlink
	f, err = OpenRelative("dsymlink/foo", root, 0, syscall.FILE_SHARE_READ, winapi.FILE_CREATE, 0)
	if err == nil {
		f.Close()
		t.Fatal("created file in wrong tree!")
	}
	t.Log(err)

	// Check again using EnsureNotReparsePointRelative
	err = EnsureNotReparsePointRelative("dsymlink", root)
	if err == nil {
		t.Fatal("reparse check should have failed")
	}
	t.Log(err)

	// Make sure links work
	err = LinkRelative("foo", root, "hardlink", root)
	if err != nil {
		t.Fatal(err)
	}

	// Even inside directories
	err = LinkRelative("foo", root, "dir/bar", root)
	if err != nil {
		t.Fatal(err)
	}

	// Make sure links cannot happen through the symlink
	err = LinkRelative("foo", root, "dsymlink/hardlink", root)
	if err == nil {
		f.Close()
		t.Fatal("created link in wrong tree!")
	}
	t.Log(err)

	// In either direction
	err = LinkRelative("dsymlink/badfile", root, "bar", root)
	if err == nil {
		f.Close()
		t.Fatal("created link in wrong tree!")
	}
	t.Log(err)

	// Make sure remove cannot happen through the symlink
	err = RemoveRelative("symlink/badfile", root)
	if err == nil {
		t.Fatal("remove in wrong tree!")
	}

	// Remove the symlink
	err = RemoveAllRelative("symlink", root)
	if err != nil {
		t.Fatal(err)
	}

	// Make sure it's not possible to escape with .. (NT doesn't support .. at the kernel level)
	f, err = OpenRelative("..", root, syscall.GENERIC_READ, syscall.FILE_SHARE_READ, winapi.FILE_OPEN, 0)
	if err == nil {
		t.Fatal("escaped the directory")
	}
	t.Log(err)

	// Should not have touched the other directory
	if _, err = os.Lstat(filepath.Join(badroot.Name(), "badfile")); err != nil {
		t.Fatal(err)
	}
}


text: print ("This is no longer the test driver, please use jsDriver.pl instead.");


text:
SYNONYM

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

#### Published in
Acta Inst. Bot. Acad. Sci. USSR Plant. Crypt. , Fasc. II 5: 337 (1950)

#### Original name
Hydnum caput-ursi Fr., 1863

### Remarks
null