text:
#include <algorithm>
#include "GaussianEconomy.hpp"
#include "QFArrayUtil.hpp"

using namespace quantfin;

GaussianEconomy::GaussianEconomy(std::vector<boost::shared_ptr<BlackScholesAsset> >& xunderlying,
	                             boost::shared_ptr<DeterministicAssetVol> xv,
								 boost::shared_ptr<TermStructure> xinitialTS)
: underlying(xunderlying),v(xv),initialTS(xinitialTS),hjm(new GaussianHJM(&*xv,&*xinitialTS))
{
  int i;
  for (i=0;i<xv->factors();i++) component_vol.push_back(xv->component_vol(i));
}

/// Constructor
GaussMarkovWorld::GaussMarkovWorld(std::vector<boost::shared_ptr<GaussianEconomy> >& xeconomies,
	                               std::vector<boost::shared_ptr<DeterministicAssetVol> >& xvols,Array<double,1> xinitial_exchange_rates)
  : economies(xeconomies),vols(xvols),initial_exchange_rates(xinitial_exchange_rates.copy()),economy_start_index(xeconomies.size()),
    T(NULL),state_variables(NULL),state_variable_drifts(NULL),termstructure_statevariables(xeconomies[0]->v->factors()), // ,timeline_(NULL),time_mapping(NULL),dW(NULL)
	terminal_fwd_exchange_rate(xinitial_exchange_rates.extent(firstDim))
{
  initialise();
}

void GaussMarkovWorld::initialise()
{
  int i;
  current_numeraire = 0;
  if (!check_inputs()) throw std::logic_error("Non-conforming volatility functions in GaussMarkovWorld::GaussMarkovWorld()");
  diffusion_dimension       = economies[0]->v->factors();
  number_of_state_variables = 0;
  int max_number_of_assets  = 0;
  for (i=0;i<economies.size();i++) {
	economy_start_index(i)     = number_of_state_variables;
	max_number_of_assets       = std::max(max_number_of_assets,int(economies[i]->underlying.size()));
	number_of_state_variables += diffusion_dimension + economies[i]->underlying.size(); }
  currency_start_index       = number_of_state_variables;
  number_of_state_variables += vols.size();
  terminal_fwd_asset.resize(economies.size(),max_number_of_assets);
  zsum = z2sum = 0.0;
  zn = 0;
}

bool GaussMarkovWorld::is_asset_index(int i) const
{
  int j;
  bool result = (i<number_of_state_variables-vols.size());
  if (result) {
	j = 0;
	while ((j<economies.size())&&(economy_start_index(j)<=i)) j++;
	result = (i>=economy_start_index(j-1)+diffusion_dimension); }
  return result;
}

int GaussMarkovWorld::economy_index(int j) const
{
  int result = -1;
  if (j<currency_start_index) {
	result = economies.size()-1;
	while (result>0) {
	  if (economy_start_index(result)<=j) return result;
	  result--; }}
  return result;
}

bool GaussMarkovWorld::check_inputs()
{
  int i,j;
  bool result = true;
  int factors = economies[0]->v->factors();
  for (i=0;i<economies.size();i++) {
	for (j=0;j<economies[i]->underlying.size();j++) {
	  if (factors!=(economies[i]->underlying[j]->volatility_function()).factors()) {
	    result = false;
		break; }}
    if (!result) break;
	if (factors!=economies[i]->v->factors()) {
	  result = false;
	  break; }}
  if (result) {
    for (i=0;i<vols.size();i++) {
	  if (factors!=vols[i]->factors()) {
	    result = false;
		break; }}}
  return result;
  }

/// Destructor
GaussMarkovWorld::~GaussMarkovWorld()
{
  if (T) delete T;
  if (state_variables) delete state_variables;
  if (state_variable_drifts) delete state_variable_drifts;
}

/** Determine which asset values should be reported back by operator()
    asset_index of -1 means fixed maturity zero coupon bond
    asset_index of -2 means terminal forward exchange rate (expressed in units of domestic currency)
    asset_index of -3 means fixed time-to-maturity zero coupon bond
	Returns index of reportable asset added. */
int GaussMarkovWorld::set_reporting(int currency_index,int asset_index,double maturity)
{
  reportable r;
  r.currency_index = currency_index;
  r.asset_index    = asset_index;
  r.maturity       = maturity;
  reportable_list.push_back(r);
  return reportable_list.size()-1;
}

/// Query the dimension of the process.
int GaussMarkovWorld::dimension() const
{
  return reportable_list.size();
}

/// Generating a realisation of the process under the martingale measure associated with deterministic bond prices is not applicable in a stochastic term structure model.
void GaussMarkovWorld::operator()(Array<double,2>& underlying_values,const Array<double,2>& x,const TermStructure& ts)
{
  throw std::logic_error("GaussMarkovWorld: Deterministic zero coupon bond prices as numeraire are not applicable in a stochastic term structure model");
}

/** Generate a realisation of the process under the martingale measure associated with a given numeraire asset.
    numeraire_index = 0 means simulation under the domestic rolling spot measure.
	Negative numeraire_index means simulation under a foreign rolling spot measure, i.e. -i corresponds to i-th foreign currency. In this case
	(as in all other cases), the value of the numeraire is expressed in foreign currency.
	Positive numeraire_index means simulation under the martingale measure associated with taking the i-th risky asset in domestic currency as the numeraire.
	*/
void GaussMarkovWorld::operator()(Array<double,2>& underlying_values,Array<double,1>& numeraire_values,const Array<double,2>& x,const TermStructure& ts,int numeraire_index)
{
  int i,j;
  if (!T) throw std::logic_error("Timeline not set in GaussMarkovWorld::operator()");
  if (current_numeraire!=numeraire_index) set_numeraire(numeraire_index); // to ensure that the numeraire (if a risky asset) is in the reportable_list
  if ((x.extent(firstDim)<max_rank)||(x.extent(secondDim)<T->extent(firstDim)-1)) throw std::logic_error("Insufficient random variables passed to GaussMarkovWorld::operator()");
  // propagate state variables
  propagate_state_variables(x);
  // set return values
  for (i=0;i<reportable_list.size();i++) { // Loop over reportable assets
	if ((reportable_list[i].asset_index==-1)||(reportable_list[i].asset_index==-3)) { // zero coupon bond
	  const GaussianHJM& hjm = *(economies[reportable_list[i].currency_index]->hjm);
	  double mat = reportable_list[i].maturity;
	  int start_index = economy_start_index(reportable_list[i].currency_index);
      for (j=0;j<state_variables->extent(secondDim);j++) { // Loop over time line
	    termstructure_statevariables = (*state_variables)(Range(start_index,start_index+diffusion_dimension-1),j);
		double ttm = mat;
		if (reportable_list[i].asset_index==-1) ttm -= (*T)(j);
		underlying_values(i,j) = hjm.bond(termstructure_statevariables,(*T)(j),ttm); }}
	else {
	  if (reportable_list[i].asset_index==-2) { // terminal forward exchange rate
	    int idx = reportable_list[i].currency_index-1;
        for (j=0;j<state_variables->extent(secondDim);j++) { // Loop over time line
		  underlying_values(i,j) = terminal_fwd_exchange_rate(idx) * std::exp((*state_variables)(currency_start_index+idx,j)); }}
	  else {
	    int idx = reportable_list[i].currency_index;
	    int asset_index = economy_start_index(idx) + diffusion_dimension + reportable_list[i].asset_index;
        for (j=0;j<state_variables->extent(secondDim);j++) { // Loop over time line
		  underlying_values(i,j) = terminal_fwd_asset(idx,reportable_list[i].asset_index) * std::exp((*state_variables)(asset_index,j)); }}}}
  // set numeraire values
  if (numeraire_index<=0) { // rolling spot measure
    const GaussianHJM& hjm = *(economies[-numeraire_index]->hjm);
	int start_index = economy_start_index(-numeraire_index);
    numeraire_values(0) = 1.0;
	for (j=0;j<state_variables->extent(secondDim)-1;j++) { // Loop over time line
	  termstructure_statevariables = (*state_variables)(Range(start_index,start_index+diffusion_dimension-1),j);
      double short_bond = hjm.bond(termstructure_statevariables,(*T)(j),(*T)(j+1)-(*T)(j));
	  numeraire_values(j+1) = numeraire_values(j) / short_bond; }}
  else { // domestic risky asset as numeraire
    for (j=0;j<state_variables->extent(secondDim);j++) { // Loop over time line
	  // discount terminal forward to get current asset value
	  numeraire_values(j) = underlying_values(numeraire_reportable_index,j) * underlying_values(numeraire_reportable_ZCB,j); }}
}

/// Set process timeline.
bool GaussMarkovWorld::set_timeline(const Array<double,1>& timeline)
{
  int i,j,k,covar_i,covar_j;
  if (T) delete T;
  T = new Array<double,1>(timeline.copy());
  double T_N = (*T)(T->extent(firstDim)-1);
  Array<double,2> covar(number_of_state_variables,number_of_state_variables);
  const DeterministicAssetVol* row_v  = NULL;
  const DeterministicAssetVol* row_fv = NULL;
  const DeterministicAssetVol* col_v  = NULL;
  const DeterministicAssetVol* col_fv = NULL;
  max_rank = 0;
  // delete existing multivariate distributions of state variable increments
  j = mvn.size();
  for (i=0;i<j;i++) mvn.pop_back();
  int dim1 = number_of_state_variables-vols.size();
  const DeterministicAssetVol* domesticTS_vol = &*economies[0]->v;
  const DeterministicAssetVol* TS_vol  = NULL;
  const DeterministicAssetVol* TS_vol2 = NULL;
  for (i=0;i<timeline.extent(firstDim)-1;i++) {
    double dt = timeline(i+1) - timeline(i);
    // create covar matrix for each time step in T
	// ordering: interest rate & asset state variables for each economy first, then exchange rate state variables
	for (j=0;j<number_of_state_variables;j++) {
	  row_v = get_vol(j);
	  covar(j,j) = row_v->volproduct(timeline(i),dt,*row_v);
	  if (is_asset_index(j)) {
		TS_vol = &*economies[economy_index(j)]->v;
	    covar(j,j) -= 2.0*TS_vol->bondvolproduct(timeline(i),dt,T_N,*row_v);
	    covar(j,j) += TS_vol->bondbondvolproduct(timeline(i),dt,T_N,T_N,*TS_vol); }
	  if (j>=dim1) {
	    row_fv = &*economies[j-dim1+1]->v;
	    covar(j,j) += 2.0*row_fv->bondvolproduct(timeline(i),dt,T_N,*row_v);
	    covar(j,j) -= 2.0*domesticTS_vol->bondvolproduct(timeline(i),dt,T_N,*row_v);
	    covar(j,j) += row_fv->bondbondvolproduct(timeline(i),dt,T_N,T_N,*row_fv);
	    covar(j,j) -= 2.0*row_fv->bondbondvolproduct(timeline(i),dt,T_N,T_N,*domesticTS_vol);
	    covar(j,j) += domesticTS_vol->bondbondvolproduct(timeline(i),dt,T_N,T_N,*domesticTS_vol); }
	  for (k=0;k<j;k++) {
	    col_v = get_vol(k);
		covar(k,j) = row_v->volproduct(timeline(i),dt,*col_v);
        if (is_asset_index(k)) {
		  TS_vol2 = &*economies[economy_index(k)]->v;
		  covar(k,j) -= TS_vol2->bondvolproduct(timeline(i),dt,T_N,*row_v); }
        if (is_asset_index(j)) {
	      covar(k,j) -= TS_vol->bondvolproduct(timeline(i),dt,T_N,*col_v);
          if (is_asset_index(k)) {
	        covar(k,j) += TS_vol2->bondbondvolproduct(timeline(i),dt,T_N,T_N,*TS_vol); }}
	    if (j>=dim1) {
	      covar(k,j) += row_fv->bondvolproduct(timeline(i),dt,T_N,*col_v);
	      covar(k,j) -= domesticTS_vol->bondvolproduct(timeline(i),dt,T_N,*col_v);
          if (is_asset_index(k)) {
	        covar(k,j) -= row_fv->bondbondvolproduct(timeline(i),dt,T_N,T_N,*TS_vol2);
			covar(k,j) += domesticTS_vol->bondbondvolproduct(timeline(i),dt,T_N,T_N,*TS_vol2); }
	      if (k>=dim1) {
	        col_fv = &*economies[k-dim1+1]->v;
	        covar(k,j) += col_fv->bondvolproduct(timeline(i),dt,T_N,*row_v);
	        covar(k,j) -= domesticTS_vol->bondvolproduct(timeline(i),dt,T_N,*row_v);
	        covar(k,j) += row_fv->bondbondvolproduct(timeline(i),dt,T_N,T_N,*col_fv);
	        covar(k,j) -= domesticTS_vol->bondbondvolproduct(timeline(i),dt,T_N,T_N,*col_fv);
	        covar(k,j) -= row_fv->bondbondvolproduct(timeline(i),dt,T_N,T_N,*domesticTS_vol);
	        covar(k,j) += domesticTS_vol->bondbondvolproduct(timeline(i),dt,T_N,T_N,*domesticTS_vol); }}
		covar(j,k) = covar(k,j); }}
    // create MultivariateNormal from each covar matrix
	boost::shared_ptr<MultivariateNormal> mv(new MultivariateNormal(covar));
	mvn.push_back(mv);
    // required dimension of random variables on each time step is maximum rank of covar matrices
	max_rank = std::max(max_rank,mv->rank()); }
  // resize scratch arrays
  if (!state_variables) state_variables = new Array<double,2>(number_of_state_variables,T->extent(firstDim));
  if (state_variables->extent(secondDim)!=T->extent(firstDim)) state_variables->resize(number_of_state_variables,T->extent(firstDim));
  for (i=0;i<number_of_state_variables;i++) (*state_variables)(i,0) = 0.0;
  if (!state_variable_drifts) state_variable_drifts = new Array<double,2>(number_of_state_variables,T->extent(firstDim)-1);
  if (state_variable_drifts->extent(secondDim)!=T->extent(firstDim)-1) state_variable_drifts->resize(number_of_state_variables,T->extent(firstDim)-1);
  set_numeraire(current_numeraire);
  // Set terminal forwards
  for (i=0;i<terminal_fwd_exchange_rate.extent(firstDim);i++)
	terminal_fwd_exchange_rate(i) = initial_exchange_rates(i) * (*(economies[i+1]->initialTS))(T_N) / (*(economies[0]->initialTS))(T_N);
  for (i=0;i<economies.size();i++) {
    for (j=0;j<economies[i]->underlying.size();j++) {
	  terminal_fwd_asset(i,j)  = economies[i]->underlying[j]->initial_value();
	  // added next line to account for dividends
	  terminal_fwd_asset(i,j) *= economies[i]->underlying[j]->dividend_discount((*T)(0),T_N);
	  terminal_fwd_asset(i,j) /= (*(economies[i]->initialTS))(T_N); }}
  return T;
}

const DeterministicAssetVol* GaussMarkovWorld::get_vol(int index)
{
  int i,economy_k;
  // exchange rate state variable?
  if (index>=number_of_state_variables-vols.size()) return &*vols[index-(number_of_state_variables-vols.size())];
  else {
    // which economy?
    i = index;
	economy_k = 0;
	while ((i>=0)&&(economy_k<economies.size())) {
	  if (i<diffusion_dimension) return &*economies[economy_k]->component_vol[i];
	  else {
	    i -= diffusion_dimension;
		if (i<economies[economy_k]->underlying.size()) return &(economies[economy_k]->underlying[i]->volatility_function());
		else {
		  i -= economies[economy_k]->underlying.size();
		  economy_k++; }}}}
  throw std::logic_error("Volatility function not found in GaussMarkovWorld::get_vol()");
  return NULL;
}

/** Set state variable drifts, etc. for simulation of the process under the martingale measure associated with a given numeraire asset.
    numeraire_index = 0 means simulation under the domestic rolling spot measure.
	Negative numeraire_index means simulation under a foreign rolling spot measure, i.e. -i corresponds to i-th foreign currency. In this case
	(as in all other cases), the value of the numeraire is expressed in foreign currency.
	Positive numeraire_index means simulation under the martingale measure associated with taking the i-th risky asset in domestic currency as the numeraire.
	*/
bool GaussMarkovWorld::set_numeraire(int numeraire_index)
{
  int i,j,k,base_j;
  double T_N = (*T)(T->extent(firstDim)-1);
  if (numeraire_index>(long)(economies[0]->underlying.size())) numeraire_index = 0;
  // base case: numeraire_index==0
  const DeterministicAssetVol* adjust_vol = NULL; // for deviations from the base case
  if (numeraire_index>0) adjust_vol = &(economies[0]->underlying[numeraire_index-1]->volatility_function());
  if (numeraire_index<0) adjust_vol = &*vols[-numeraire_index-1];
  Array<double,1> svm(economies[0]->v->factors());
  for (i=0;i<T->extent(firstDim)-1;i++) {
    double dt = (*T)(i+1) - (*T)(i);
    // domestic term structure state variables
	if (numeraire_index>=0) for (j=0;j<svm.extent(firstDim);j++) {  // expected value of the state variable increment under the discrete rolling spot measure
	  svm(j) = economies[0]->v->bondvolproduct((*T)(i),dt,(*T)(i+1),*economies[0]->component_vol[j]); }
	if (numeraire_index<0) {  // adjustment from foreign discrete rolling spot measure to foreign continuous spot measure
	  for (j=0;j<svm.extent(firstDim);j++) svm(j) = economies[-numeraire_index]->v->bondvolproduct((*T)(i),dt,(*T)(i+1),*economies[0]->component_vol[j]); }
	for (j=0;j<svm.extent(firstDim);j++) {
	  (*state_variable_drifts)(j,i) = svm(j); // if random variables are being generated under the discrete rolling spot measure, the expected value under this measure must be subtracted to convert to state variables defined as Ito integrals wrt Brownian motion under the continuous spot measure
	  if (adjust_vol) (*state_variable_drifts)(j,i) = economies[0]->component_vol[j]->volproduct((*T)(i),dt,*adjust_vol); } // adjust for domestic risky asset numeraire if applicable
    // domestic asset state variables
	for (j=0;j<economies[0]->underlying.size();j++) {
	  if (numeraire_index!=0) {
		// adjustment from foreign discrete rolling spot measure to foreign continuous spot measure
	    if (numeraire_index<0) (*state_variable_drifts)(j+svm.extent(firstDim),i) = economies[-numeraire_index]->v->bondvolproduct((*T)(i),dt,(*T)(i+1),economies[0]->underlying[j]->volatility_function());
		else                   (*state_variable_drifts)(j+svm.extent(firstDim),i) = 0.0;
		// from foreign continuous spot measure (or domestic risky asset measure) to domestic continuous spot measure
        if (adjust_vol) {
		  (*state_variable_drifts)(j+svm.extent(firstDim),i) += (economies[0]->underlying[j]->volatility_function()).volproduct((*T)(i),dt,*adjust_vol);
		  (*state_variable_drifts)(j+svm.extent(firstDim),i) -= economies[0]->v->bondvolproduct((*T)(i),dt,T_N,*adjust_vol); }
		// from domestic continuous spot measure to domestic terminal forward measure
		(*state_variable_drifts)(j+svm.extent(firstDim),i) -= economies[0]->v->bondvolproduct((*T)(i),dt,T_N,economies[0]->underlying[j]->volatility_function());
		(*state_variable_drifts)(j+svm.extent(firstDim),i) += economies[0]->v->bondbondvolproduct((*T)(i),dt,T_N,T_N,*(economies[0]->v)); }
	  else {
		// from domestic discrete rolling spot measure to domestic continuous spot measure
        (*state_variable_drifts)(j+svm.extent(firstDim),i) = economies[0]->v->bondvolproduct((*T)(i),dt,(*T)(i+1),economies[0]->underlying[j]->volatility_function());
        (*state_variable_drifts)(j+svm.extent(firstDim),i) -= economies[0]->v->bondbondvolproduct((*T)(i),dt,(*T)(i+1),T_N,*(economies[0]->v));
		// from domestic continuous spot measure to domestic terminal forward measure
		(*state_variable_drifts)(j+svm.extent(firstDim),i) -= economies[0]->v->bondvolproduct((*T)(i),dt,T_N,economies[0]->underlying[j]->volatility_function());
		(*state_variable_drifts)(j+svm.extent(firstDim),i) += economies[0]->v->bondbondvolproduct((*T)(i),dt,T_N,T_N,*(economies[0]->v)); }
	  // additional drift terms not dependent on measure changes
	  double tmp = (economies[0]->underlying[j]->volatility_function()).volproduct((*T)(i),dt,economies[0]->underlying[j]->volatility_function());
	  tmp -= 2.0*economies[0]->v->bondvolproduct((*T)(i),dt,T_N,economies[0]->underlying[j]->volatility_function());
	  tmp += economies[0]->v->bondbondvolproduct((*T)(i),dt,T_N,T_N,*economies[0]->v);
	  (*state_variable_drifts)(j+svm.extent(firstDim),i) -= 0.5*tmp; }
	base_j = j + svm.extent(firstDim);
	// foreign economies
	for (k=1;k<economies.size();k++) {
	  // foreign term structure state variables
	  if (numeraire_index==-k) { // expected value of the state variable increment under the foreign discrete rolling spot measure
        for (j=0;j<svm.extent(firstDim);j++) {  // expected value of the state variable increment under the foreign discrete rolling spot measure
		  svm(j) = economies[k]->v->bondvolproduct((*T)(i),dt,(*T)(i+1),*economies[k]->component_vol[j]); }}
	  else {
	    if (numeraire_index<0) {  // needs fixing: adjustment from foreign discrete rolling spot measure to foreign continuous spot measure
	      for (j=0;j<svm.extent(firstDim);j++) svm(j) = economies[-numeraire_index]->v->bondvolproduct((*T)(i),dt,(*T)(i+1),*economies[k]->component_vol[j]); }
		else { // adjustment from foreign continuous rolling spot measure to domestic discrete rolling spot measure - note that state variable expectation under foreign continuous rolling spot measure is zero
		  for (j=0;j<svm.extent(firstDim);j++) svm(j) = -economies[k]->component_vol[j]->volproduct((*T)(i),dt,*vols[k-1]);
		  if (numeraire_index==0) for (j=0;j<svm.extent(firstDim);j++) svm(j) += economies[0]->v->bondvolproduct((*T)(i),dt,(*T)(i+1),*economies[k]->component_vol[j]); }}
	  for (j=0;j<svm.extent(firstDim);j++) {
	    (*state_variable_drifts)(base_j+j,i) = svm(j); // if random variables are being generated under the discrete rolling spot measure, the expected value under this measure must be subtracted to convert to state variables defined as Ito integrals wrt Brownian motion under the continuous spot measure
	    if (adjust_vol) (*state_variable_drifts)(base_j+j,i) += economies[k]->component_vol[j]->volproduct((*T)(i),dt,*adjust_vol); } // adjust for domestic risky asset numeraire if appicable
	  base_j += j;
	  // foreign asset state variables
	  for (j=0;j<economies[k]->underlying.size();j++) {
		(*state_variable_drifts)(j+base_j,i) = 0.0;
	    if (numeraire_index!=-k) {
		  // adjustment from numeraire_index discrete rolling spot measure to numeraire_index continuous spot measure
	      if (numeraire_index<0) (*state_variable_drifts)(j+base_j,i) = economies[-numeraire_index]->v->bondvolproduct((*T)(i),dt,(*T)(i+1),economies[k]->underlying[j]->volatility_function());
		  else                   (*state_variable_drifts)(j+base_j,i) = 0.0;
		  // from numeraire_index continuous spot measure (or domestic risky asset measure) to domestic continuous spot measure
          if (adjust_vol) {
			(*state_variable_drifts)(j+base_j,i) += (economies[k]->underlying[j]->volatility_function()).volproduct((*T)(i),dt,*adjust_vol);
		    (*state_variable_drifts)(j+base_j,i) -= economies[k]->v->bondvolproduct((*T)(i),dt,T_N,*adjust_vol); }
		  else { // from domestic discrete rolling spot measure to domestic continuous spot measure
            (*state_variable_drifts)(j+base_j,i) += economies[0]->v->bondvolproduct((*T)(i),dt,(*T)(i+1),economies[k]->underlying[j]->volatility_function());
			(*state_variable_drifts)(j+base_j,i) -= economies[0]->v->bondbondvolproduct((*T)(i),dt,(*T)(i+1),T_N,*(economies[k]->v)); }
		  // from domestic continuous spot measure to k-th foreign continuous spot measure
          (*state_variable_drifts)(j+base_j,i) -= (economies[k]->underlying[j]->volatility_function()).volproduct((*T)(i),dt,*vols[k-1]);
          (*state_variable_drifts)(j+base_j,i) += economies[k]->v->bondvolproduct((*T)(i),dt,T_N,*vols[k-1]);
		  // from k-th foreign continuous spot measure to k-th foreign terminal forward measure
		  (*state_variable_drifts)(j+base_j,i) -= economies[k]->v->bondvolproduct((*T)(i),dt,T_N,economies[k]->underlying[j]->volatility_function());
		  (*state_variable_drifts)(j+base_j,i) += economies[k]->v->bondbondvolproduct((*T)(i),dt,T_N,T_N,*(economies[k]->v)); }
	    else {
          // from k-th foreign discrete spot measure to k-th foreign terminal forward measure
		  (*state_variable_drifts)(j+base_j,i) = economies[k]->v->bondvolproduct((*T)(i),dt,(*T)(i+1),economies[k]->underlying[j]->volatility_function());
		  (*state_variable_drifts)(j+base_j,i) -= economies[k]->v->bondvolproduct((*T)(i),dt,T_N,economies[k]->underlying[j]->volatility_function()); }
	    // additional drift terms not dependent on measure changes
	    double tmp = (economies[k]->underlying[j]->volatility_function()).volproduct((*T)(i),dt,economies[k]->underlying[j]->volatility_function());
	    tmp -= 2.0*economies[k]->v->bondvolproduct((*T)(i),dt,T_N,economies[k]->underlying[j]->volatility_function());
	    tmp += economies[k]->v->bondbondvolproduct((*T)(i),dt,T_N,T_N,*economies[k]->v);
		(*state_variable_drifts)(j+base_j,i) -= 0.5*tmp; }
	  base_j += j; }
	// exchange rates
	for (j=0;j<vols.size();j++) {
	  if (numeraire_index!=0) {
		// adjustment from foreign discrete rolling spot measure to foreign continuous spot measure
		if (numeraire_index<0) {
		  (*state_variable_drifts)(j+base_j,i) = economies[-numeraire_index]->v->bondvolproduct((*T)(i),dt,(*T)(i+1),*vols[j]);
		  (*state_variable_drifts)(j+base_j,i) += economies[-numeraire_index]->v->bondbondvolproduct((*T)(i),dt,(*T)(i+1),T_N,*economies[j+1]->v);
		  (*state_variable_drifts)(j+base_j,i) -= economies[-numeraire_index]->v->bondbondvolproduct((*T)(i),dt,(*T)(i+1),T_N,*economies[0]->v); }
		else (*state_variable_drifts)(j+base_j,i) = 0.0;
		// from foreign continuous spot measure (or domestic risky asset measure) to domestic continuous spot measure
		if (adjust_vol) {
		  (*state_variable_drifts)(j+base_j,i) += vols[j]->volproduct((*T)(i),dt,*adjust_vol);
		  (*state_variable_drifts)(j+base_j,i) += economies[j+1]->v->bondvolproduct((*T)(i),dt,T_N,*adjust_vol);
		  (*state_variable_drifts)(j+base_j,i) -= economies[0]->v->bondvolproduct((*T)(i),dt,T_N,*adjust_vol); }
		// from domestic continuous spot measure to domestic terminal forward measure
		(*state_variable_drifts)(j+base_j,i) -= economies[0]->v->bondvolproduct((*T)(i),dt,T_N,*vols[j]);
		(*state_variable_drifts)(j+base_j,i) -= economies[0]->v->bondbondvolproduct((*T)(i),dt,T_N,T_N,*(economies[j+1]->v));
		(*state_variable_drifts)(j+base_j,i) += economies[0]->v->bondbondvolproduct((*T)(i),dt,T_N,T_N,*(economies[0]->v)); }
	  else {
        // from domestic discrete spot measure to domestic terminal forward measure
		(*state_variable_drifts)(j+base_j,i) = economies[0]->v->bondvolproduct((*T)(i),dt,(*T)(i+1),*vols[j]);
		(*state_variable_drifts)(j+base_j,i) += economies[0]->v->bondbondvolproduct((*T)(i),dt,(*T)(i+1),T_N,*(economies[j+1]->v));
		(*state_variable_drifts)(j+base_j,i) -= economies[0]->v->bondbondvolproduct((*T)(i),dt,(*T)(i+1),T_N,*(economies[0]->v));
		(*state_variable_drifts)(j+base_j,i) -= economies[0]->v->bondvolproduct((*T)(i),dt,T_N,*vols[j]);
		(*state_variable_drifts)(j+base_j,i) -= economies[0]->v->bondbondvolproduct((*T)(i),dt,T_N,T_N,*(economies[j+1]->v));
		(*state_variable_drifts)(j+base_j,i) += economies[0]->v->bondbondvolproduct((*T)(i),dt,T_N,T_N,*(economies[0]->v)); }
	  // additional drift terms not dependent on measure changes
	  double tmp = vols[j]->volproduct((*T)(i),dt,*vols[j]);
	  tmp += 2.0*economies[j+1]->v->bondvolproduct((*T)(i),dt,T_N,*vols[j]);
	  tmp -= 2.0*economies[0]->v->bondvolproduct((*T)(i),dt,T_N,*vols[j]);
	  tmp += economies[j+1]->v->bondbondvolproduct((*T)(i),dt,T_N,T_N,*economies[j+1]->v);
	  tmp -= 2.0*economies[j+1]->v->bondbondvolproduct((*T)(i),dt,T_N,T_N,*economies[0]->v);
	  tmp += economies[0]->v->bondbondvolproduct((*T)(i),dt,T_N,T_N,*economies[0]->v);
	  (*state_variable_drifts)(j+base_j,i) -= 0.5*tmp; }}
  current_numeraire = numeraire_index;
  // Ensure that the numeraire (if a risky asset) and the associated terminal zero coupon bond is in the reportable_list
  if (numeraire_index>0)  {
    bool numeraire_found     = false;
    bool numeraire_ZCB_found = false;
	for (i=0;i<reportable_list.size();i++) {
	  if (reportable_list[i].currency_index==0) {
		if ((reportable_list[i].asset_index==numeraire_index-1)) {
	      numeraire_found = true;
		  numeraire_reportable_index = i;
		  if (numeraire_ZCB_found) break; }
	    if ((reportable_list[i].asset_index==-1)&&(reportable_list[i].maturity==T_N)) {
	      numeraire_ZCB_found = true;
		  numeraire_reportable_ZCB = i;
		  if (numeraire_found) break; }}}
	if (!numeraire_found) numeraire_reportable_index = set_reporting(0,numeraire_index-1,0.0);
	if (!numeraire_ZCB_found) numeraire_reportable_ZCB = set_reporting(0,-1,T_N); }
  return true;
}

void GaussMarkovWorld::propagate_state_variables(const Array<double,2>& x)
{
  int j;
  Array<double,1> current_x(number_of_state_variables);
  // propagate state variables
  for (j=1;j<state_variables->extent(secondDim);j++) { // Loop over time line
	// ordering: interest rate & asset state variables for each economy first, then exchange rate state variables
    // term structure state variables are defined under the native currency spot measure
    // all asset and exchange rate state variables are defined under the domestic terminal measure
    current_x(Range(0,max_rank-1)) = x(Range(0,max_rank-1),j-1);
    mvn[j-1]->transform_random_variables(current_x);
	(*state_variables)(Range::all(),j) = (*state_variables)(Range::all(),j-1) + (*state_variable_drifts)(Range::all(),j-1) + current_x; }
  zsum += (*state_variables)(0,1);
  z2sum += (*state_variables)(0,1)*(*state_variables)(0,1);
  zn++;
}

/** Generate a realisation of the process under the martingale measure associated with a given numeraire asset,
    returning the state variables. underlying_values is an asset x (time points) Array. */
const Array<double,2>& GaussMarkovWorld::generate_state_variables(Array<double,1>& numeraire_values,const Array<double,2>& x,int numeraire_index)
{
  int j;
  if (!T) throw std::logic_error("Timeline not set in GaussMarkovWorld::generate_state_variables");
  if (numeraire_index>0) throw std::logic_error("Cannot generate risky asset as numeraire in GaussMarkovWorld::generate_state_variables. Use operator() instead.");
  if (current_numeraire!=numeraire_index) set_numeraire(numeraire_index); // to ensure that the numeraire (if a risky asset) is in the reportable_list
  if ((x.extent(firstDim)<max_rank)||(x.extent(secondDim)<T->extent(firstDim)-1)) throw std::logic_error("Insufficient random variables passed to GaussMarkovWorld::operator()");
  // propagate state variables
  propagate_state_variables(x);
  // set numeraire values
  const GaussianHJM& hjm = *(economies[-numeraire_index]->hjm);
  int start_index = economy_start_index(-numeraire_index);
  numeraire_values(0) = 1.0;
  for (j=0;j<state_variables->extent(secondDim)-1;j++) { // Loop over time line
	termstructure_statevariables = (*state_variables)(Range(start_index,start_index+diffusion_dimension-1),j);
    double short_bond = hjm.bond(termstructure_statevariables,(*T)(j),(*T)(j+1));
	numeraire_values(j+1) = numeraire_values(j) / short_bond; }
  return *state_variables;
}

GaussMarkovTermStructure GaussMarkovWorld::get_TermStructure(int i,int j)
{
  const GaussianHJM& hjm = *(economies[j]->hjm);
  int start_index = economy_start_index(j);
  termstructure_statevariables = (*state_variables)(Range(start_index,start_index+diffusion_dimension-1),i);
  GaussMarkovTermStructure result((*T)(i),hjm,termstructure_statevariables);
  return result;
}


text:
namespace leveldb {
namespace {

template <typename... Args>
void IgnoreAllArgs(Args&&...) {}

template <typename... Args>
void DoCaptures(typename std::decay<Args>::type*... out_args,
                const base::Closure& quit_closure,
                Args... in_args) {
  IgnoreAllArgs((*out_args = std::move(in_args))...);
  quit_closure.Run();
}

template <typename T1>
base::Callback<void(T1)> Capture(T1* t1, const base::Closure& quit_closure) {
  return base::Bind(&DoCaptures<T1>, t1, quit_closure);
}

base::Callback<void(const base::UnguessableToken&)> CaptureToken(
    base::UnguessableToken* t1,
    const base::Closure& quit_closure) {
  return base::Bind(&DoCaptures<const base::UnguessableToken&>, t1,
                    quit_closure);
}

class RemoteIteratorTest : public service_manager::test::ServiceTest {
 public:
  RemoteIteratorTest() : ServiceTest("leveldb_service_unittests") {}
  ~RemoteIteratorTest() override {}

 protected:
  // Overridden from mojo::test::ApplicationTestBase:
  void SetUp() override {
    ServiceTest::SetUp();
    connector()->ConnectToInterface("leveldb", &leveldb_);

    mojom::DatabaseError error;
    base::RunLoop run_loop;
    leveldb()->OpenInMemory(GetProxy(&database_),
                            Capture(&error, run_loop.QuitClosure()));
    run_loop.Run();
    EXPECT_EQ(mojom::DatabaseError::OK, error);

    std::map<std::string, std::string> data{
        {"a", "first"}, {"b:suffix", "second"}, {"c", "third"}};

    for (auto p : data) {
      // Write a key to the database.
      error = mojom::DatabaseError::INVALID_ARGUMENT;
      base::RunLoop run_loop;
      database_->Put(StdStringToUint8Vector(p.first),
                     StdStringToUint8Vector(p.second),
                     Capture(&error, run_loop.QuitClosure()));
      run_loop.Run();
      EXPECT_EQ(mojom::DatabaseError::OK, error);
    }
  }

  void TearDown() override {
    leveldb_.reset();
    ServiceTest::TearDown();
  }

  mojom::LevelDBServicePtr& leveldb() { return leveldb_; }
  mojom::LevelDBDatabasePtr& database() { return database_; }

 private:
  mojom::LevelDBServicePtr leveldb_;
  mojom::LevelDBDatabasePtr database_;

  DISALLOW_COPY_AND_ASSIGN(RemoteIteratorTest);
};

TEST_F(RemoteIteratorTest, Seeking) {
  base::UnguessableToken iterator;
  base::RunLoop run_loop;
  database()->NewIterator(CaptureToken(&iterator, run_loop.QuitClosure()));
  run_loop.Run();
  EXPECT_FALSE(iterator.is_empty());

  RemoteIterator it(database().get(), iterator);
  EXPECT_FALSE(it.Valid());

  it.SeekToFirst();
  EXPECT_TRUE(it.Valid());
  EXPECT_EQ("a", it.key());
  EXPECT_EQ("first", it.value());

  it.SeekToLast();
  EXPECT_TRUE(it.Valid());
  EXPECT_EQ("c", it.key());
  EXPECT_EQ("third", it.value());

  it.Seek("b");
  EXPECT_TRUE(it.Valid());
  EXPECT_EQ("b:suffix", it.key());
  EXPECT_EQ("second", it.value());
}

TEST_F(RemoteIteratorTest, Next) {
  base::UnguessableToken iterator;
  base::RunLoop run_loop;
  database()->NewIterator(CaptureToken(&iterator, run_loop.QuitClosure()));
  run_loop.Run();
  EXPECT_FALSE(iterator.is_empty());

  RemoteIterator it(database().get(), iterator);
  EXPECT_FALSE(it.Valid());

  it.SeekToFirst();
  EXPECT_TRUE(it.Valid());
  EXPECT_EQ("a", it.key());
  EXPECT_EQ("first", it.value());

  it.Next();
  EXPECT_TRUE(it.Valid());
  EXPECT_EQ("b:suffix", it.key());
  EXPECT_EQ("second", it.value());

  it.Next();
  EXPECT_TRUE(it.Valid());
  EXPECT_EQ("c", it.key());
  EXPECT_EQ("third", it.value());

  it.Next();
  EXPECT_FALSE(it.Valid());
}

TEST_F(RemoteIteratorTest, Prev) {
  base::UnguessableToken iterator;
  base::RunLoop run_loop;
  database()->NewIterator(CaptureToken(&iterator, run_loop.QuitClosure()));
  run_loop.Run();
  EXPECT_FALSE(iterator.is_empty());

  RemoteIterator it(database().get(), iterator);
  EXPECT_FALSE(it.Valid());

  it.SeekToLast();
  EXPECT_TRUE(it.Valid());
  EXPECT_EQ("c", it.key());
  EXPECT_EQ("third", it.value());

  it.Prev();
  EXPECT_TRUE(it.Valid());
  EXPECT_EQ("b:suffix", it.key());
  EXPECT_EQ("second", it.value());

  it.Prev();
  EXPECT_TRUE(it.Valid());
  EXPECT_EQ("a", it.key());
  EXPECT_EQ("first", it.value());

  it.Prev();
  EXPECT_FALSE(it.Valid());
}

}  // namespace
}  // namespace leveldb

redpajama_set_name: RedPajamaGithub


text:
require "rails_helper"

RSpec.describe Api::Users::AccountsController,
               type: :request do
  describe "#update" do
    it "persists attrs" do
      me = create :user
      login_as me
      params = {
        account: {
          username: 'moi.user.updated',
          age: 15,
          city: 'Loja',
          country: 'Ecuador1',
          school: 'myschool',
          authorization_key: 'numbers'
        }
      }
      put '/api/users/account', params
      me.reload
      expect(response.code).to eq("202")
      params[:account].keys.each do |attribute|
        expect(me.send(attribute)).to eq(params[:account][attribute])
      end
    end
  end
end


text:
'''base_bolt.py'''
import copy

from heronpy.api.tuple import TupleHelper

from heronpy.api.component.component_spec import HeronComponentSpec
from heronpy.api.component.base_component import BaseComponent
from heronpy.api.stream import Stream

class BaseBolt(BaseComponent):
  """BaseBolt class

  This is the base for heron bolt, which wraps the implementation of publicly available methods.
  This includes:
    - <classmethod> spec()
    - emit()
    - <staticmethod> is_tick()
    - ack()
    - fail()

  They are compatible with StreamParse API.
  """
  # pylint: disable=no-member
  @classmethod
  def spec(cls, name=None, inputs=None, par=1, config=None, optional_outputs=None):
    """Register this bolt to the topology and create ``HeronComponentSpec``

    This method takes an optional ``outputs`` argument for supporting dynamic output fields
    declaration. However, it is recommended that ``outputs`` should be declared as
    an attribute of your ``Bolt`` subclass. Also, some ways of declaring inputs is not supported
    in this implementation; please read the documentation below.

    :type name: str
    :param name: Name of this bolt.
    :type inputs: dict or list
    :param inputs: Streams that feed into this Bolt.

                   Two forms of this are acceptable:

                   1. A `dict` mapping from ``HeronComponentSpec`` to ``Grouping``.
                      In this case, default stream is used.
                   2. A `dict` mapping from ``GlobalStreamId`` to ``Grouping``.
                      This ``GlobalStreamId`` object itself is different from StreamParse, because
                      Heron does not use thrift, although its constructor method is compatible.
                   3. A `list` of ``HeronComponentSpec``. In this case, default stream with
                      SHUFFLE grouping is used.
                   4. A `list` of ``GlobalStreamId``. In this case, SHUFFLE grouping is used.
    :type par: int
    :param par: Parallelism hint for this spout.
    :type config: dict
    :param config: Component-specific config settings.
    :type optional_outputs: list of (str or Stream) or tuple of (str or Stream)
    :param optional_outputs: Additional output fields for this bolt. These fields are added to
                             existing ``outputs`` class attributes of your bolt. This is an optional
                             argument, and exists only for supporting dynamic output field
                             declaration.
    """
    python_class_path = f"{cls.__module__}.{cls.__name__}"

    if hasattr(cls, 'outputs'):
      # avoid modification to cls.outputs
      _outputs = copy.copy(cls.outputs)
    else:
      _outputs = []

    if optional_outputs is not None:
      assert isinstance(optional_outputs, (list, tuple))
      for out in optional_outputs:
        assert isinstance(out, (str, Stream))
        _outputs.append(out)

    return HeronComponentSpec(name, python_class_path, is_spout=False, par=par,
                              inputs=inputs, outputs=_outputs, config=config)

  def emit(self, tup, stream=Stream.DEFAULT_STREAM_ID,
           anchors=None, direct_task=None, need_task_ids=False):
    """Emits a new tuple from this Bolt

    It is compatible with StreamParse API.

    :type tup: list or tuple
    :param tup: the new output Tuple to send from this bolt,
                which should contain only serializable data.
    :type stream: str
    :param stream: the ID of the stream to emit this Tuple to.
                   Leave empty to emit to the default stream.
    :type anchors: list
    :param anchors: a list of HeronTuples to which the emitted Tuples should be anchored.
    :type direct_task: int
    :param direct_task: the task to send the Tuple to if performing a direct emit.
    :type need_task_ids: bool
    :param need_task_ids: indicate whether or not you would like the task IDs the Tuple was emitted.
    """
    self.delegate.emit(tup, stream, anchors, direct_task, need_task_ids)

  @staticmethod
  def is_tick(tup):
    """Returns whether or not a given HeronTuple is a tick Tuple

    It is compatible with StreamParse API.
    """
    return tup.stream == TupleHelper.TICK_TUPLE_ID

  def ack(self, tup):
    """Indicate that processing of a Tuple has succeeded

    It is compatible with StreamParse API.
    """
    self.delegate.ack(tup)

  def fail(self, tup):
    """Indicate that processing of a Tuple has failed

    It is compatible with StreamParse API.
    """
    self.delegate.fail(tup)


text:
import Ember from 'ember';

export default Ember.Controller.extend({
    session: Ember.inject.service(),

    banners: Ember.computed(function() {
        return this.get('store').findAll('site-banner');
    }),
});


text:
package edu.hm.hafner.analysis.parser.pvsstudio;

import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;

import edu.hm.hafner.util.IntegerParser;

import static edu.hm.hafner.analysis.IssueParser.*;

/**
 * The AnalyzerType for PVS-Studio static analyzer.
 *
 * @author PVS-Studio Team
 */
final class AnalyzerType {
    /**
     * Diagnosis of 64-bit errors (Viva64, C++).
     * https://pvs-studio.com/en/docs/warnings/#64CPP
     */
    private static final int VIVA64_CCPP_ERRORCODE_BEGIN = 100;
    /**
     * Diagnosis of 64-bit errors (Viva64, C++).
     * https://pvs-studio.com/en/docs/warnings/#64CPP
     */
    private static final int VIVA64_CCPP_ERRORCODE_END = 499;
    /**
     * General Analysis (C++).
     * https://pvs-studio.com/en/docs/warnings/#GeneralAnalysisCPP
     */
    private static final int GENERAL_CCPP_LOW_ERRORCODE_BEGIN = 500;
    /**
     * General Analysis (C++).
     * https://pvs-studio.com/en/docs/warnings/#GeneralAnalysisCPP
     */
    private static final int GENERAL_CCPP_LOW_ERRORCODE_END = 799;
    /**
     * Diagnosis of micro-optimizations (C++).
     * https://pvs-studio.com/en/docs/warnings/#MicroOptimizationsCPP
     */
    private static final int OPTIMIZATION_CCPP_ERRORCODE_BEGIN = 800;
    /**
     * Diagnosis of micro-optimizations (C++).
     * https://pvs-studio.com/en/docs/warnings/#MicroOptimizationsCPP
     */
    private static final int OPTIMIZATION_CCPP_ERRORCODE_END = 999;
    /**
     * General Analysis (C++).
     * https://pvs-studio.com/en/docs/warnings/
     */
    private static final int GENERAL_CCPP_HIGH_ERRORCODE_BEGIN = 1000;
    /**
     * General Analysis (C++).
     * https://pvs-studio.com/en/docs/warnings/
     */
    private static final int GENERAL_CCPP_HIGH_ERRORCODE_END = 1999;
    /**
     * Customers Specific Requests (C++).
     * https://pvs-studio.com/en/docs/warnings/#CustomersSpecificRequestsCPP
     */
    private static final int CUSTOMERSPECIFIC_CCPP_ERRORCODE_BEGIN = 2000;
    /**
     * Customers Specific Requests (C++).
     * https://pvs-studio.com/en/docs/warnings/#CustomersSpecificRequestsCPP
     */
    private static final int CUSTOMERSPECIFIC_CCPP_ERRORCODE_END = 2499;
    /**
     * MISRA errors.
     * https://pvs-studio.com/en/docs/warnings/#MISRA
     */
    private static final int MISRA_CCPP_ERRORCODE_BEGIN = 2500;
    /**
     * MISRA errors.
     * https://pvs-studio.com/en/docs/warnings/#MISRA
     */
    private static final int MISRA_CCPP_ERRORCODE_END = 2999;
    /**
     * General Analysis (C#).
     * https://pvs-studio.com/en/docs/warnings/#GeneralAnalysisCS
     */
    private static final int GENERAL_CS_ERRORCODE_BEGIN = 3000;
    /**
     * General Analysis (C#).
     * https://pvs-studio.com/en/docs/warnings/#GeneralAnalysisCS
     */
    private static final int GENERAL_CS_ERRORCODE_END = 3499;
    /**
     * General Analysis (Java).
     * https://pvs-studio.com/en/docs/warnings/#GeneralAnalysisJAVA
     */
    private static final int GENERAL_JAVA_ERRORCODE_BEGIN = 6000;
    /**
     * General Analysis (Java).
     * https://pvs-studio.com/en/docs/warnings/#GeneralAnalysisJAVA
     */
    private static final int GENERAL_JAVA_ERRORCODE_END = 6999;

    static final String VIVA_64_MESSAGE = "64-bit";
    static final String GENERAL_MESSAGE = "General Analysis";
    static final String OPTIMIZATION_MESSAGE = "Micro-optimization";
    static final String CUSTOMER_SPECIFIC_MESSAGE = "Specific Requests";
    static final String MISRA_MESSAGE = "MISRA";
    static final String UNKNOWN_MESSAGE = "Unknown";

    private AnalyzerType() {
        // prevents instantiation
    }

    private static final AnalysisType[] ANALYSIS_TYPES = {new Viva64(), new GENERAL(),
            new OPTIMIZATION(), new CustomerSpecific(), new MISRA()};

    static AnalysisType fromErrorCode(final String errorCodeStr) {
        if (equalsIgnoreCase(errorCodeStr, "External")) {
            return new GENERAL();
        }

        // errorCodeStr format is Vnnn.
        int errorCode = IntegerParser.parseInt(errorCodeStr.substring(1));

        return Arrays.stream(ANALYSIS_TYPES)
                .map(type -> type.create(errorCode))
                .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
                .findFirst()
                .orElse(new UNKNOWN());
    }

    /**
     * Viva64 AnalysisType.
     */
    static final class Viva64 implements AnalysisType {
        @Override
        public String getMessage() {
            return VIVA_64_MESSAGE;
        }

        @Override
        public Optional<AnalysisType> create(final int errorCode) {
            if (errorCode >= VIVA64_CCPP_ERRORCODE_BEGIN && errorCode <= VIVA64_CCPP_ERRORCODE_END) {
                return Optional.of(new Viva64());
            }

            return Optional.empty();
        }
    }

    /**
     * GENERAL AnalysisType.
     */
    static final class GENERAL implements AnalysisType {
        @Override
        public String getMessage() {
            return GENERAL_MESSAGE;
        }

        @Override
        public Optional<AnalysisType> create(final int errorCode) {
            if (errorCode >= GENERAL_CCPP_LOW_ERRORCODE_BEGIN && errorCode <= GENERAL_CCPP_LOW_ERRORCODE_END) {
                return Optional.of(new GENERAL());
            }
            else if (errorCode >= GENERAL_CCPP_HIGH_ERRORCODE_BEGIN && errorCode <= GENERAL_CCPP_HIGH_ERRORCODE_END) {
                return Optional.of(new GENERAL());
            }
            else if (errorCode >= GENERAL_CS_ERRORCODE_BEGIN && errorCode <= GENERAL_CS_ERRORCODE_END) {
                return Optional.of(new GENERAL());
            }
            else if (errorCode >= GENERAL_JAVA_ERRORCODE_BEGIN && errorCode <= GENERAL_JAVA_ERRORCODE_END) {
                return Optional.of(new GENERAL());
            }
            else {
                return Optional.empty();
            }
        }
    }

    /**
     * OPTIMIZATION AnalysisType.
     */
    static final class OPTIMIZATION implements AnalysisType {
        @Override
        public String getMessage() {
            return OPTIMIZATION_MESSAGE;
        }

        @Override
        public Optional<AnalysisType> create(final int errorCode) {
            if (errorCode >= OPTIMIZATION_CCPP_ERRORCODE_BEGIN && errorCode <= OPTIMIZATION_CCPP_ERRORCODE_END) {
                return Optional.of(new OPTIMIZATION());
            }

            return Optional.empty();
        }
    }

    /**
     * CustomerSpecific AnalysisType.
     */
    static final class CustomerSpecific implements AnalysisType {
        @Override
        public String getMessage() {
            return CUSTOMER_SPECIFIC_MESSAGE;
        }

        @Override
        public Optional<AnalysisType> create(final int errorCode) {
            if (errorCode >= CUSTOMERSPECIFIC_CCPP_ERRORCODE_BEGIN && errorCode <= CUSTOMERSPECIFIC_CCPP_ERRORCODE_END) {
                return Optional.of(new CustomerSpecific());
            }

            return Optional.empty();
        }
    }

    /**
     * MISRA AnalysisType.
     */
    static final class MISRA implements AnalysisType {
        @Override
        public String getMessage() {
            return MISRA_MESSAGE;
        }

        @Override
        public Optional<AnalysisType> create(final int errorCode) {
            if (errorCode >= MISRA_CCPP_ERRORCODE_BEGIN && errorCode <= MISRA_CCPP_ERRORCODE_END) {
                return Optional.of(new MISRA());
            }

            return Optional.empty();
        }
    }

    /**
     * Unkonwn AnalysisType.
     */
    static final class UNKNOWN implements AnalysisType {
        @Override
        public String getMessage() {
            return UNKNOWN_MESSAGE;
        }

        @Override
        public Optional<AnalysisType> create(final int errorCode) {
            return Optional.empty();
        }
    }

    interface AnalysisType {
        String getMessage();

        Optional<AnalysisType> create(int errorCodeStr);
    }
}


text:
const {gets, throws, returns, testSaga} = require('.');

test('testSaga', () => {
  function* regeneratedTestGen() {
    try {
      const valueFromNext = yield 1;
      yield valueFromNext;
    } catch (err) {
      yield err;
    }
    yield 2;
    yield 3;
    return 4;
  }

  const testVal = '__TEST_PASSED_VALUE__';
  const testErr = '__TEST_ERR__';

  expect(() =>
    testSaga(regeneratedTestGen, [null, undefined, 1, '', {}, [], false])
  ).not.toThrow();

  const check = number => value =>
    expect(value).toEqual({value: number, done: false});

  testSaga(regeneratedTestGen, [
    check(1),
    value => expect(value).toEqual({value: undefined, done: false})
  ]);

  testSaga(regeneratedTestGen, [
    check(1),
    gets(testVal),
    value => expect(value).toEqual({value: testVal, done: false})
  ]);

  expect(() =>
    testSaga(regeneratedTestGen, [
      check(1),
      throws(testErr),
      value => expect(value).toEqual({value: testErr, done: false}),
      check(2),
      check(3),
      returns(4)
    ])
  ).not.toThrow();

  let counter = 0;
  function* counterGen() {
    yield 1;
    yield 2;
    yield 3;
    yield 4;
  }
  const inc = ({value: x}) => (counter += x);
  testSaga(counterGen, [[inc], [[inc], inc], inc]);
  expect(counter).toBe(10);
});


text:
require('./c');
require('./d');

console.log('b');


text:
YUI.add('aui-image-viewer-base', function (A, NAME) {

/**
 * The ImageViewer Utility
 *
 * @module aui-image-viewer
 * @submodule aui-image-viewer-base
 */

var L = A.Lang,
    isBoolean = L.isBoolean,
    isNumber = L.isNumber,
    isObject = L.isObject,
    isString = L.isString,

    NodeFx = A.Plugin.NodeFX,

    DOC = A.config.doc,

    isNodeList = function(v) {
        return (v instanceof A.NodeList);
    },

    concat = function() {
        return Array.prototype.slice.call(arguments).join(' ');
    },

    getCN = A.getClassName,

    CSS_CAROUSEL_CONTROL = getCN('carousel', 'control'),
    CSS_CLOSE = getCN('close'),
    CSS_HELPER_SCROLL_LOCK = getCN('helper', 'scroll', 'lock'),
    CSS_HIDE = getCN('hide'),
    CSS_ICON_TIME = getCN('icon', 'time'),
    CSS_IMAGE_VIEWER_BD = getCN('image-viewer', 'bd'),
    CSS_IMAGE_VIEWER_CAPTION = getCN('image-viewer', 'caption'),
    CSS_IMAGE_VIEWER_CLOSE = getCN('image-viewer', 'close'),
    CSS_IMAGE_VIEWER_CONTROL = getCN('image-viewer', 'control'),
    CSS_IMAGE_VIEWER_IMAGE = getCN('image-viewer', 'image'),
    CSS_IMAGE_VIEWER_INFO = getCN('image-viewer', 'info'),
    CSS_IMAGE_VIEWER_LINK = getCN('image-viewer', 'link'),
    CSS_IMAGE_VIEWER_LOADER = getCN('image-viewer', 'loader'),
    CSS_IMAGE_VIEWER_LOADING = getCN('image-viewer', 'loading'),
    CSS_LEFT = getCN('left'),
    CSS_RIGHT = getCN('right'),
    CSS_WELL = getCN('well'),

    MAP_RESET_DIMENSIONS = {
        height: 'auto',
        width: 'auto'
    },

    NODE_BLANK_TEXT = DOC.createTextNode(''),

    INFO_LABEL_TEMPLATE = 'Image {current} of {total}',

    TPL_CAPTION = '

',
    TPL_CLOSE = '<button class="' + concat(CSS_IMAGE_VIEWER_CLOSE, CSS_CLOSE) + '" type="button">?</button>',
    TPL_CONTROL_LEFT = '‹',
    TPL_CONTROL_RIGHT = '›',
    TPL_IMAGE = '',
    TPL_INFO = '

',
    TPL_LOADER = '

',
    TPL_LOADING = '

';

/**
 * A base class for `A.ImageViewer`, providing:
 *
 * - Widget Lifecycle (initializer, renderUI, bindUI, syncUI, destructor)
 * - Displays an image in a Overlay
 * - Keyboard navigation support
 *
 * Check the [live demo](http://alloyui.com/examples/image-viewer/).
 *
 * @class A.ImageViewer
 * @extends Widget
 * @uses WidgetStdMod, WidgetPosition, WidgetStack, WidgetPositionAlign,
 *     WidgetPositionConstrain, WidgetModality
 * @param {Object} config Object literal specifying widget configuration
 *     properties.
 * @constructor
 * @include http://alloyui.com/examples/image-viewer/basic-markup.html
 * @include http://alloyui.com/examples/image-viewer/basic.js
 */
var ImageViewer = A.Base.create(
    'aui-image-viewer',
    A.Widget, [
        A.WidgetCssClass,
        A.WidgetStdMod,
        A.WidgetToggle,
        A.WidgetPosition,
        A.WidgetStack,
        A.WidgetPositionAlign,
        A.WidgetPositionConstrain,
        A.WidgetModality
    ], {
        /**
         * Handler for the key events.
         *
         * @property _keyHandler
         * @type EventHandler
         * @protected
         */
        _keyHandler: null,

        /**
         * Create the DOM structure for the `A.ImageViewer`. Lifecycle.
         *
         * @method renderUI
         * @protected
         */
        renderUI: function() {
            var instance = this;

            instance._renderControls();
            instance._renderFooter();

            instance.get('links').addClass(CSS_IMAGE_VIEWER_LINK);
        },

        /**
         * Bind the events on the `A.ImageViewer` UI. Lifecycle.
         *
         * @method bindUI
         * @protected
         */
        bindUI: function() {
            var instance = this;
            var links = instance.get('links');
            var controlLeftEl = instance.get('controlLeftEl');
            var controlRightEl = instance.get('controlRightEl');
            var closeEl = instance.get('closeEl');

            closeEl.on('click', A.bind(instance._onClickCloseEl, instance));
            controlLeftEl.on('click', A.bind(instance._onClickLeftControl, instance));
            controlRightEl.on('click', A.bind(instance._onClickRightControl, instance));
            links.on('click', A.bind(instance._onClickLinks, instance));

            instance._keyHandler = A.bind(instance._onKeyInteraction, instance);

            // NOTE: using keydown to avoid keyCode bug on IE
            A.getDoc().on('keydown', instance._keyHandler);

            A.getWin().on(
                'resize',
                function() {
                    instance._setAlignCenter(true);
                }
            );

            instance.after('render', instance._afterRender);
            instance.after('loadingChange', instance._afterLoadingChange);
            instance.after('visibleChange', instance._afterVisibleChange);
        },

        /**
         * Destructor lifecycle implementation for the `A.ImageViewer` class.
         * Purges events attached to the node (and all child nodes).
         *
         * @method destructor
         * @protected
         */
        destructor: function() {
            var instance = this;

            var links = instance.get('links');

            instance.close();

            links.detach('click');
            links.removeClass(CSS_IMAGE_VIEWER_LINK);

            // detach key global listener from the document
            A.getDoc().detach('keydown', instance._keyHandler);

            instance.get('controlLeftEl').remove(true);
            instance.get('controlRightEl').remove(true);
            instance.get('closeEl').remove(true);
            instance.get('loader').remove(true);
        },

        /**
         * Hides the `A.ImageViewer` instance.
         *
         * @method close
         */
        close: function() {
            var instance = this;

            instance.hide();
        },

        /**
         * Gets the `Node` reference to the `currentIndex` element from
         * the [links](A.ImageViewer.html#attr_links).
         *
         * @method getLink
         * @param {Number} currentIndex
         * @return {Node}
         */
        getLink: function(currentIndex) {
            var instance = this;

            return instance.get('links').item(currentIndex);
        },

        /**
         * Gets the current loaded node link reference.
         *
         * @method getCurrentLink
         * @return {Node}
         */
        getCurrentLink: function() {
            var instance = this;

            return instance.getLink(
                instance.get('currentIndex')
            );
        },

        /**
         * Loads an image `src` on the `A.ImageViewer`.
         *
         * @method loadImage
         * @param {String} src Image src.
         */
        loadImage: function(src) {
            var instance = this;

            var loader = instance.get('loader');

            instance.set('loading', true);

            var activeImagePool = instance._activeImagePool;

            if (!activeImagePool) {
                activeImagePool = [];

                // creating the placeholder image
                var placeholder = instance.get('image');

                var image0 = placeholder.clone();
                var image1 = placeholder.clone();

                // bind the onLoad handler to the image, this handler should
                // append the loaded image
                var onload = A.bind(instance._onLoadImage, instance);

                image0.on('load', onload);
                image1.on('load', onload);

                activeImagePool.push(image0, image1);

                instance._activeImagePool = activeImagePool;
            }

            var image = activeImagePool[0];

            image.removeAttribute('height');
            image.removeAttribute('width');

            image.setStyles(MAP_RESET_DIMENSIONS);

            // append the placeholder image to the loader div
            loader.append(image);

            // re-sort the pool
            activeImagePool.push(activeImagePool.shift(image));

            // set the src of the image to be loaded on the placeholder image.
            // dataURI allows cached images to refire load event in webkit, and
            // bypass the MimeType error (c/o Paul Irish & Doug Jones)
            if (A.UA.webkit) {
                image.attr('src', 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==');
            }

            image.attr('src', src);

            instance.fire('request', {
                image: image
            });
        },

        /**
         * Checks if there is a node reference for the `currentIndex`.
         *
         * @method hasLink
         * @param {Number} currentIndex
         * @return {Boolean}
         */
        hasLink: function(currentIndex) {
            var instance = this;

            return instance.getLink(currentIndex);
        },

        /**
         * Checks if there is a next element to navigate.
         *
         * @method hasNext
         * @return {Boolean}
         */
        hasNext: function() {
            var instance = this;

            return instance.hasLink(
                instance.get('currentIndex') + 1
            );
        },

        /**
         * Checks if there is a previous element to navigate.
         *
         * @method hasPrev
         * @return {Boolean}
         */
        hasPrev: function() {
            var instance = this;

            return instance.hasLink(
                instance.get('currentIndex') - 1
            );
        },

        /**
         * Hide all UI controls (i.e., arrows, close icon etc).
         *
         * @method hideControls
         */
        hideControls: function() {
            var instance = this;

            instance.get('controlLeftEl').hide();
            instance.get('controlRightEl').hide();
            instance.get('closeEl').hide();
        },

        /**
         * Loads the next image.
         *
         * @method next
         */
        next: function() {
            var instance = this;

            if (instance.hasNext()) {
                instance.set(
                    'currentIndex',
                    instance.get('currentIndex') + 1
                );

                instance.show();
            }
        },

        /**
         * Preloads all images.
         *
         * @method preloadAllImages
         */
        preloadAllImages: function() {
            var instance = this;

            instance.get('links').each(function(link, index) {
                instance.preloadImage(index);
            });
        },

        /**
         * Preloads an image based on its `index`.
         *
         * @method preloadImage
         * @param {Number} currentIndex
         */
        preloadImage: function(currentIndex) {
            var instance = this;
            var link = instance.getLink(currentIndex);

            if (link) {
                var src = link.attr('href');

                instance._createPreloadImage(src);
            }
        },

        /**
         * Loads the previous image.
         *
         * @method next
         */
        prev: function() {
            var instance = this;

            if (instance.hasPrev()) {
                instance.set(
                    'currentIndex',
                    instance.get('currentIndex') - 1
                );

                instance.show();
            }
        },

        /**
         * Shows the loading icon.
         *
         * @method showLoading
         */
        showLoading: function() {
            var instance = this;
            var loadingEl = instance.get('loadingEl');

            instance.setStdModContent('body', loadingEl);

            loadingEl.center(instance.bodyNode);
        },

        /**
         * Shows the `A.ImageViewer` UI.
         *
         * @method show
         */
        show: function() {
            var instance = this;
            var currentLink = instance.getCurrentLink();

            if (currentLink) {
                ImageViewer.superclass.show.apply(this, arguments);

                instance.loadImage(
                    currentLink.attr('href')
                );
            }
        },

        /**
         * Removes the references to the preload images to free up memory.
         *
         * @method _clearPreloadImageFn
         * @protected
         */
        _clearPreloadImageFn: function() {
            var instance = this;

            var preloadImagePool = instance._preloadImagePool;
            var image;

            for (var i in preloadImagePool) {
                image = preloadImagePool[i];

                if (image && image.complete) {
                    preloadImagePool[i] = null;
                }
            }
        },

        /**
         * Creates the preload image instance, and add's it to the internal
         * pool.
         *
         * @method _createPreloadImage
         * @param src
         * @protected
         */
        _createPreloadImage: function(src) {
            var instance = this;

            var preloadImagePool = instance._preloadImagePool;

            if (!preloadImagePool) {
                preloadImagePool = instance._preloadImagePool = {};

                instance._clearPreloadImageTask = A.debounce(instance._clearPreloadImageFn, 50, instance);
            }

            if (!(src in preloadImagePool)) {
                var image = new Image();

                image.onload = instance._clearPreloadImageTask;
                image.src = src;

                preloadImagePool[src] = image;
            }
        },

        /**
         * Renders the controls UI.
         *
         * @method _renderControls
         * @protected
         */
        _renderControls: function() {
            var instance = this;
            var body = A.one('body');

            body.append(
                instance.get('controlLeftEl').hide()
            );

            body.append(
                instance.get('controlRightEl').hide()
            );

            body.append(
                instance.get('closeEl').hide()
            );
        },

        /**
         * Renders the footer UI.
         *
         * @method _renderFooter
         * @protected
         */
        _renderFooter: function() {
            var instance = this;

            var boundingBox = instance.get('boundingBox');

            var docFrag = boundingBox.get('ownerDocument').invoke('createDocumentFragment');

            docFrag.append(
                instance.get('captionEl')
            );
            docFrag.append(
                instance.get('infoEl')
            );

            instance.setStdModContent(
                'footer',
                docFrag
            );
        },

        /**
         * Sync the caption UI.
         *
         * @method _syncCaptionUI
         * @protected
         */
        _syncCaptionUI: function() {
            var instance = this;
            var caption = instance.get('caption');
            var captionEl = instance.get('captionEl');
            var captionFromTitle = instance.get('captionFromTitle');

            if (captionFromTitle) {
                var currentLink = instance.getCurrentLink();

                if (currentLink) {
                    var title = currentLink.attr('title');

                    if (title) {
                        caption = currentLink.attr('title');
                    }
                }
            }

            captionEl.html(caption);
        },

        /**
         * Sync the controls UI.
         *
         * @method _syncControlsUI
         * @protected
         */
        _syncControlsUI: function() {
            var instance = this;
            var boundingBox = instance.get('boundingBox');
            var controlLeftEl = instance.get('controlLeftEl');
            var controlRightEl = instance.get('controlRightEl');
            var closeEl = instance.get('closeEl');

            if (instance.get('visible')) {
                if (instance.get('showControls')) {
                    // get the viewportRegion to centralize the controls on the
                    // middle of the window viewport
                    var viewportRegion = boundingBox.get('viewportRegion');
                    var heightRegion = Math.floor(viewportRegion.height / 2) + viewportRegion.top;

                    // show or hide controls based on the hasPrev/hasNext
                    // information
                    controlLeftEl[instance.hasPrev() ? 'show' : 'hide']();
                    controlRightEl[instance.hasNext() ? 'show' : 'hide']();

                    closeEl.show();
                }
            }
            else {
                // if the overlay is not visible hide all controls
                instance.hideControls();
            }
        },

        /**
         * Sync the `A.ImageViewer` UI.
         *
         * @method _syncImageViewerUI
         * @protected
         */
        _syncImageViewerUI: function() {
            var instance = this;

            instance._syncControlsUI();
            instance._syncCaptionUI();
            instance._syncInfoUI();
        },

        /**
         * Sync the info UI.
         *
         * @method _syncInfoUI
         * @protected
         */
        _syncInfoUI: function() {
            var instance = this;
            var infoEl = instance.get('infoEl');

            infoEl.html(
                instance.get('infoTemplate')
            );
        },

        /**
         * Calculates the resize ratio for the loaded image.
         *
         * @method _getRatio
         * @param {Number} width Image width
         * @param {Number} height Image height
         * @protected
         * @return {Number}
         */
        _getRatio: function(width, height) {
            var instance = this;

            var ratio = 1;
            var maxHeight = instance.get('maxHeight');
            var maxWidth = instance.get('maxWidth');

            if ((height > maxHeight) || (width > maxWidth)) {
                var hRatio = (height / maxHeight);
                var wRatio = (width / maxWidth);

                ratio = Math.max(hRatio, wRatio);
            }

            return ratio;
        },

        /**
         * Gets the [info](A.ImageViewer.html#attr_info) template.
         *
         * @method _getInfoTemplate
         * @param {String} v template
         * @protected
         * @return {String} Parsed string.
         */
        _getInfoTemplate: function(v) {
            var instance = this;
            var total = instance.get('totalLinks');
            var current = instance.get('currentIndex') + 1;

            return L.sub(v, {
                current: current,
                total: total
            });
        },

        /**
         * Displays the image once it's been loaded.
         *
         * @method _displayLoadedImage
         * @param {Node} image The loaded image
         * @protected
         */
        _displayLoadedImage: function(image) {
            var instance = this;

            instance._uiSetImageSize(image);

            instance.setStdModContent('body', image);

            instance.set('loading', false);

            instance._syncImageViewerUI();

            // invoke WidgetPosition _setAlignCenter to force center alignment
            instance._setAlignCenter(true);

            instance.fire('load', {
                image: image
            });

            if (instance.get('preloadNeighborImages')) {
                // preload neighbor images
                var currentIndex = instance.get('currentIndex');

                instance.preloadImage(currentIndex + 1);
                instance.preloadImage(currentIndex - 1);
            }
        },

        /**
         * Fires after the `A.ImageViewer` render phase.
         *
         * @method _afterRender
         * @protected
         */
        _afterRender: function() {
            var instance = this;
            var bodyNode = instance.bodyNode;
            var boundingBox = instance.get('boundingBox');

            bodyNode.addClass(CSS_IMAGE_VIEWER_BD);
            boundingBox.addClass(CSS_WELL);

            if (instance.get('preloadAllImages')) {
                instance.preloadAllImages();
            }
        },

        /**
         * Fires after the value of the
         * [loading](A.ImageViewer.html#attr_loading) attribute change.
         *
         * @method _afterLoadingChange
         * @param {EventFacade} event
         * @protected
         */
        _afterLoadingChange: function(event) {
            var instance = this;
            var boundingBox = instance.get('boundingBox');

            if (event.newVal) {
                boundingBox.addClass(CSS_IMAGE_VIEWER_LOADING);

                instance.showLoading();
            }
            else {
                boundingBox.removeClass(CSS_IMAGE_VIEWER_LOADING);
            }
        },

        /**
         * Fires after the value of the
         * [visible](A.ImageViewer.html#attr_visible) attribute change.
         *
         * @method _afterVisibleChange
         * @param {EventFacade} event
         * @protected
         */
        _afterVisibleChange: function(event) {
            var instance = this;

            instance._syncControlsUI();
        },

        /**
         * Fires the click event on the close icon.
         *
         * @method _onClickCloseEl
         * @param {EventFacade} event Click event facade
         * @protected
         */
        _onClickCloseEl: function(event) {
            var instance = this;

            instance.close();

            event.halt();
        },

        /**
         * Fires the click event on the left control icon.
         *
         * @method _onClickLeftControl
         * @param {EventFacade} event Click event facade
         * @protected
         */
        _onClickLeftControl: function(event) {
            var instance = this;

            instance.prev();

            event.halt();
        },

        /**
         * Fires the click event on the right control icon.
         *
         * @method _onClickRightControl
         * @param {EventFacade} event Click event facade
         * @protected
         */
        _onClickRightControl: function(event) {
            var instance = this;

            instance.next();

            event.halt();
        },

        /**
         * Fires the click event on the links.
         *
         * @method _onClickLinks
         * @param {EventFacade} event Click event facade
         * @protected
         */
        _onClickLinks: function(event) {
            var instance = this;
            var target = event.currentTarget;

            // set the current currentIndex of the clicked image
            instance.set(
                'currentIndex',
                instance.get('links').indexOf(target)
            );

            instance.show();

            event.preventDefault();
        },

        /**
         * Handles the key interaction (i.e., next, prev etc).
         *
         * @method _onKeyInteraction
         * @param {EventFacade} event Click event facade
         * @protected
         */
        _onKeyInteraction: function(event) {
            var instance = this;

            if (!instance.get('visible')) {
                return false; // NOTE: return
            }

            if (event.isKey('LEFT')) {
                instance.prev();
            }
            else if (event.isKey('RIGHT')) {
                instance.next();
            }
            else if (event.isKey('ESC')) {
                instance.close();
            }
        },

        /**
         * Fires on a image load.
         *
         * @method _onLoadImage
         * @param {EventFacade} event
         * @protected
         */
        _onLoadImage: function(event) {
            var instance = this;
            var image = event.currentTarget;

            instance._displayLoadedImage(image);

            var imageAnim = instance.get('imageAnim');

            if (instance.get('anim')) {
                image.setStyle('opacity', 0);

                if (!image.fx) {
                    image.plug(NodeFx, imageAnim);
                }

                image.fx.on('end', function(info) {
                    instance.fire('anim', {
                        anim: info,
                        image: image
                    });
                });

                image.fx.stop().run();
            }
        },

        /**
         * Sets the size of the image and the overlay respecting the
         * maxHeight/maxWidth ratio.
         *
         * @method _uiSetImageSize
         * @param {HTMLImage} image Image
         * @protected
         */
        _uiSetImageSize: function(image) {
            var instance = this;
            var bodyNode = instance.bodyNode;
            var footerNode = instance.footerNode;
            var imageRegion = image.get('region');

            var ratio = instance._getRatio(
                imageRegion.width,
                imageRegion.height
            );

            var height = (imageRegion.height / ratio);
            var width = (imageRegion.width / ratio);

            image.set('offsetHeight', height);
            image.set('offsetWidth', width);

            footerNode.setStyle('width', width + 'px');

            bodyNode.setStyles({
                height: height + 'px',
                width: width + 'px'
            });
        }
    },

    {
        /**
         * Static property provides a string to identify the class.
         *
         * @property NAME
         * @type String
         * @static
         */
        NAME: 'image-viewer',

        /**
         * Static property provides a string to identify the CSS prefix.
         *
         * @property CSS_PREFIX
         * @type String
         * @static
         */
        CSS_PREFIX: getCN('image-viewer'),

        /**
         * Static property used to define the default attribute
         * configuration for the `A.ImageViewer`.
         *
         * @property ATTRS
         * @type Object
         * @static
         */
        ATTRS: {

            /**
             * If `true` the navigation is animated.
             *
             * @attribute anim
             * @default true
             * @type Boolean
             */
            anim: {
                value: true,
                validator: isBoolean
            },

            /**
             * The content of body.
             *
             * @attribute bodyContent
             * @type String
             */
            bodyContent: {
                value: NODE_BLANK_TEXT
            },

            /**
             * The caption of the displayed image.
             *
             * @attribute caption
             * @default ''
             * @type String
             */
            caption: {
                value: 'blank',
                validator: isString
            },

            /**
             * If `true` the [caption](A.ImageViewer.html#attr_caption) will be
             * pulled from the title DOM attribute.
             *
             * @attribute captionFromTitle
             * @default true
             * @type Boolean
             */
            captionFromTitle: {
                value: true,
                validator: isBoolean
            },

            /**
             * If `true` the Overlay with the image will be positioned
             * on the center of the viewport.
             *
             * @attribute centered
             * @default true
             * @type Boolean
             */
            centered: {
                value: true
            },

            /**
             * Index of the current image.
             *
             * @attribute currentIndex
             * @default 0
             * @type Number
             */
            currentIndex: {
                value: 0,
                validator: isNumber
            },

            /**
             * Image node element used to load the images.
             *
             * @attribute image
             * @default Generated img element.
             * @readOnly
             * @type Node
             */
            image: {
                readOnly: true,
                valueFn: function() {
                    return A.Node.create(TPL_IMAGE);
                }
            },

            /**
             * Configuration attributes passed to the [Anim](Anim.html) class.
             *
             * @attribute imageAnim
             * @default Predefined [Anim](Anim.html) configuration.
             * @type Object
             */
            imageAnim: {
                value: {},
                setter: function(value) {
                    return A.merge({
                            to: {
                                opacity: 1
                            },
                            duration: 0.8
                        },
                        value
                    );
                },
                validator: isObject
            },

            /**
             * String template used to display the information.
             *
             * @attribute infoTemplate
             * @default 'Image {current} of {total}'
             * @type String
             */
            infoTemplate: {
                getter: function(v) {
                    return this._getInfoTemplate(v);
                },
                value: INFO_LABEL_TEMPLATE,
                validator: isString
            },

            /**
             * Selector or NodeList containing the links where the
             * `A.ImageViewer` extracts the information to generate the
             * thumbnails.
             *
             * @attribute links
             * @type String | NodeList
             */
            links: {
                setter: function(v) {
                    var instance = this;

                    if (isNodeList(v)) {
                        return v;
                    }
                    else if (isString(v)) {
                        return A.all(v);
                    }

                    return new A.NodeList([v]);
                }
            },

            /**
             * Whether the image is during a loading state.
             *
             * @attribute loading
             * @default false
             * @type Boolean
             */
            loading: {
                value: false,
                validator: isBoolean
            },

            /**
             * Displays the modal the viewport. Set to `false` to disable.
             *
             * @attribute modal
             * @default true
             * @type Boolean
             */
            modal: {
                value: true
            },

            /**
             * Preloads all images grabbed from the
             * [links](A.ImageViewer.html#attr_links) attribute.
             *
             * @attribute preloadAllImages
             * @default false
             * @type Boolean
             */
            preloadAllImages: {
                value: false,
                validator: isBoolean
            },

            /**
             * Preloads the neighbor image (i.e., the previous and next image
             * based on the current load one).
             *
             * @attribute preloadAllImages
             * @default false
             * @type Boolean
             */
            preloadNeighborImages: {
                value: true,
                validator: isBoolean
            },

            /**
             * Shows close icon control.
             *
             * @attribute showClose
             * @default true
             * @type Boolean
             */
            showClose: {
                value: true,
                validator: isBoolean
            },

            /**
             * Shows the controls.
             *
             * @attribute showControls
             * @default true
             * @type Boolean
             */
            showControls: {
                value: true,
                validator: isBoolean
            },

            /**
             * Specify the tab order of elements.
             *
             * @attribute tabIndex
             * @default null
             * @type Number
             */
            tabIndex: {
                value: null
            },

            /**
             * Helper attribute to get the `size` of the
             * [links](A.ImageViewer.html#attr_links) NodeList.
             *
             * @attribute totalLinks
             * @default true
             * @readOnly
             * @type Boolean
             */
            totalLinks: {
                readOnly: true,
                getter: function(v) {
                    return this.get('links').size();
                }
            },

            /**
             * Determines if the `A.ImageViewer` should be visible or not.
             *
             * @attribute visible
             * @default false
             * @type Boolean
             */
            visible: {
                value: false
            },

            /**
             * Specify the stack order of elements.
             *
             * @attribute zIndex
             * @default 3000
             * @type Number
             */
            zIndex: {
                value: 3000,
                validator: isNumber
            },

            /**
             * The element to be used as left control.
             *
             * @attribute controlLeftEl
             * @default Generated HTML div element.
             * @readOnly
             * @type Node
             */
            controlLeftEl: {
                readOnly: true,
                valueFn: function() {
                    return A.Node.create(TPL_CONTROL_LEFT);
                }
            },

            /**
             * The element to be used as right control.
             *
             * @attribute controlRightEl
             * @default Generated HTML div element.
             * @readOnly
             * @type Node
             */
            controlRightEl: {
                readOnly: true,
                valueFn: function() {
                    return A.Node.create(TPL_CONTROL_RIGHT);
                }
            },

            /**
             * The element to be used as caption.
             *
             * @attribute captionEl
             * @default Generated HTML div element.
             * @readOnly
             * @type Node
             */
            captionEl: {
                readOnly: true,
                valueFn: function() {
                    return A.Node.create(TPL_CAPTION);
                }
            },

            /**
             * The element to be used as close.
             *
             * @attribute closeEl
             * @default Generated HTML div element.
             * @readOnly
             * @type Node
             */
            closeEl: {
                readOnly: true,
                valueFn: function() {
                    return A.Node.create(TPL_CLOSE);
                }
            },

            /**
             * The element to be used as info.
             *
             * @attribute infoEl
             * @default Generated HTML div element.
             * @readOnly
             * @type Node
             */
            infoEl: {
                readOnly: true,
                valueFn: function() {
                    return A.Node.create(TPL_INFO);
                }
            },

            /**
             * HTML element to contain the `img` which is being loaded.
             *
             * @attribute loader
             * @default Generated HTML div element.
             * @type Node
             */
            loader: {
                readOnly: true,
                valueFn: function() {
                    return A.Node.create(TPL_LOADER).appendTo(DOC.body);
                }
            },

            /**
             * The element to be used as loading.
             *
             * @attribute loadingEl
             * @default Generated HTML div element.
             * @type Node
             */
            loadingEl: {
                valueFn: function() {
                    return A.Node.create(TPL_LOADING);
                }
            },

            /**
             * The maximum height of the element.
             *
             * @attribute maxHeight
             * @default Infinity
             * @type Number
             */
            maxHeight: {
                value: Infinity,
                validator: isNumber
            },

            /**
             * The maximum width of the element.
             *
             * @attribute maxWidth
             * @default Infinity
             * @type Number
             */
            maxWidth: {
                value: Infinity,
                validator: isNumber
            }
        }
    }
);

A.ImageViewer = ImageViewer;

}, '2.5.0', {
    "requires": [
        "anim",
        "widget",
        "widget-modality",
        "widget-position",
        "widget-position-align",
        "widget-position-constrain",
        "widget-stack",
        "widget-stdmod",
        "aui-event",
        "aui-node-base",
        "aui-widget-cssclass",
        "aui-widget-toggle"
    ],
    "skinnable": true
});


text:
GO_EASY_ON_ME=1
TARGET = iphone:clang:latest:6.0
THEOS_BUILD_DIR=build
OPTFLAG = -Ofast
CFLAGS = -Wall

include theos/makefiles/common.mk

TWEAK_NAME = CoverMeNot
CoverMeNot_FILES = Tweak.xm
CoverMeNot_FRAMEWORKS = UIKit

include $(THEOS_MAKE_PATH)/tweak.mk


text:
using RoboticsTxt.Lib.Components.Communicator;
using RoboticsTxt.Lib.Messages;

namespace RoboticsTxt.Lib.Interfaces
{
    internal interface IControllerCommand
    {
        void Execute(ControllerCommunicator controllerCommunicator, ExchangeDataCommandMessage message);
    }
}


text:
#include "datamatrix/DMReader.h"
#include "datamatrix/DMDecoder.h"
#include "datamatrix/DMDetector.h"
#include "Result.h"
#include "BitMatrix.h"
#include "BinaryBitmap.h"
#include "DecodeHints.h"
#include "DecoderResult.h"
#include "DetectorResult.h"

namespace ZXing {
namespace DataMatrix {

static int
GetModuleSize(int x, int y, const BitMatrix& image)
{
	int oldX = x;
	int width = image.width();
	while (x < width && image.get(x, y)) {
		x++;
	}
	if (x == width) {
		return 0;
	}
	return x - oldX;
}

/**
* This method detects a code in a "pure" image -- that is, pure monochrome image
* which contains only an unrotated, unskewed, image of a code, with some white border
* around it. This is a specialized method that works exceptionally fast in this special
* case.
*
* @see com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix)
*/
static BitMatrix
ExtractPureBits(const BitMatrix& image)
{
	int left, top, right, bottom;
	if (!image.getTopLeftOnBit(left, top) || !image.getBottomRightOnBit(right, bottom)) {
		return {};
	}

	int moduleSize = GetModuleSize(left, top, image);
	int matrixWidth = (right - left + 1) / moduleSize;
	int matrixHeight = (bottom - top + 1) / moduleSize;
	if (matrixWidth <= 0 || matrixHeight <= 0) {
		return {};
	}

	// Push in the "border" by half the module width so that we start
	// sampling in the middle of the module. Just in case the image is a
	// little off, this will help recover.
	int nudge = moduleSize / 2;
	top += nudge;
	left += nudge;

	// Now just read off the bits (this is a crop + subsample)
	return Deflate(image, matrixWidth, matrixHeight, top, left, moduleSize);
}

Reader::Reader(const DecodeHints& hints) : _tryRotate(hints.shouldTryRotate()), _tryHarder(hints.shouldTryHarder())
{
}

/**
* Locates and decodes a Data Matrix code in an image.
*
* @return a string representing the content encoded by the Data Matrix code
* @throws NotFoundException if a Data Matrix code cannot be found
* @throws FormatException if a Data Matrix code cannot be decoded
* @throws ChecksumException if error correction fails
*/
Result
Reader::decode(const BinaryBitmap& image) const
{
	auto binImg = image.getBlackMatrix();
	if (binImg == nullptr) {
		return Result(DecodeStatus::NotFound);
	}

	DecoderResult decoderResult;
	std::vector<ResultPoint> points;
	if (image.isPureBarcode()) {
		BitMatrix bits = ExtractPureBits(*binImg);
		if (bits.empty())
			return Result(DecodeStatus::NotFound);

		decoderResult = Decoder::Decode(bits);
	}
	else {
		DetectorResult detectorResult = Detector::Detect(*binImg, _tryHarder, _tryRotate);
		if (!detectorResult.isValid())
			return Result(DecodeStatus::NotFound);

		decoderResult = Decoder::Decode(detectorResult.bits());
		points = detectorResult.points();
	}

	return Result(std::move(decoderResult), std::move(points), BarcodeFormat::DATA_MATRIX);
}

} // DataMatrix
} // ZXing


text:
Component::Component() : Drawable() {}

void Component::setUserData(void *data) {
    this->user_data = data;
}

void* Component::getUserData() {
    return this->user_data;
}


text:
package org.yi.happy.archive.key;

/**
 * a full key. the data parts vary by type.
 */
public interface FullKey {
    /**
     * @return the type of the key
     */
    public String getType();

    /**
     * @return the string that parses into this key
     */
    @Override
    public String toString();

    /**
     * Get the locator key for this key.
     *
     * @return A locator key.
     */
    public LocatorKey toLocatorKey();

    @Override
    public int hashCode();

    @Override
    public boolean equals(Object obj);
}