text:
#include "SODSOSystem.h"

#include "FullSystem/ResidualProjections.h"
#include "IOWrapper/ImageDisplay.h"
#include "stdio.h"
#include "util/globalCalib.h"
#include "util/globalFuncs.h"
#include <Eigen/Eigenvalues>
#include <Eigen/LU>
#include <Eigen/SVD>
#include <algorithm>

#include "OptimizationBackend/EnergyFunctional.h"
#include "OptimizationBackend/EnergyFunctionalStructs.h"

#include <cmath>

#include <algorithm>

namespace dso {

void SODSOSystem::linearizeAll_Reductor(
    bool fixLinearization, std::vector<PointFrameResidual *> *toRemove, int min,
    int max, Vec10 *stats, int tid) {
  for (int k = min; k < max; k++) {
    PointFrameResidual *r = activeResiduals[k];
    (*stats)[0] += r->linearize(&Hcalib);

    if (fixLinearization) {
      r->applyRes(true);

      if (r->efResidual->isActive()) {
        if (r->isNew) {
          PointHessian *p = r->point;
          Vec3f ptp_inf =
              r->host->targetPrecalc[r->target->idx].PRE_KRKiTll *
              Vec3f(p->u, p->v, 1); // projected point assuming infinite depth.
          Vec3f ptp = ptp_inf +
                      r->host->targetPrecalc[r->target->idx].PRE_KtTll *
                          p->idepth_scaled; // projected point with real depth.
          float relBS = 0.01 * ((ptp_inf.head<2>() / ptp_inf[2]) -
                                (ptp.head<2>() / ptp[2]))
                                   .norm(); // 0.01 = one pixel.

          if (relBS > p->maxRelBaseline)
            p->maxRelBaseline = relBS;

          p->numGoodResiduals++;
        }
      } else {
        toRemove[tid].push_back(activeResiduals[k]);
      }
    }
  }
}

void SODSOSystem::applyRes_Reductor(bool copyJacobians, int min, int max,
                                    Vec10 *stats, int tid) {
  for (int k = min; k < max; k++)
    activeResiduals[k]->applyRes(true);
}
void SODSOSystem::setNewFrameEnergyTH() {

  // collect all residuals and make decision on TH.
  allResVec.clear();
  allResVec.reserve(activeResiduals.size() * 2);
  FrameHessian *newFrame = frameHessians.back();

  for (PointFrameResidual *r : activeResiduals)
    if (r->state_NewEnergyWithOutlier >= 0 && r->target == newFrame) {
      allResVec.push_back(r->state_NewEnergyWithOutlier);
    }

  if (allResVec.size() == 0) {
    newFrame->frameEnergyTH = 12 * 12 * patternNum;
    return; // should never happen, but lets make sure.
  }

  int nthIdx = setting_frameEnergyTHN * allResVec.size();

  assert(nthIdx < (int)allResVec.size());
  assert(setting_frameEnergyTHN < 1);

  std::nth_element(allResVec.begin(), allResVec.begin() + nthIdx,
                   allResVec.end());
  float nthElement = sqrtf(allResVec[nthIdx]);

  newFrame->frameEnergyTH = nthElement * setting_frameEnergyTHFacMedian;
  newFrame->frameEnergyTH =
      26.0f * setting_frameEnergyTHConstWeight +
      newFrame->frameEnergyTH * (1 - setting_frameEnergyTHConstWeight);
  newFrame->frameEnergyTH = newFrame->frameEnergyTH * newFrame->frameEnergyTH;
  newFrame->frameEnergyTH *=
      setting_overallEnergyTHWeight * setting_overallEnergyTHWeight;

  //
  //  int good=0,bad=0;
  //  for(float f : allResVec) if(f<newFrame->frameEnergyTH) good++; else bad++;
  //  printf("EnergyTH: mean %f, median %f, result %f (in %d, out %d)! \n",
  //      meanElement, nthElement, sqrtf(newFrame->frameEnergyTH),
  //      good, bad);
}
Vec3 SODSOSystem::linearizeAll(bool fixLinearization) {
  double lastEnergyP = 0;
  double lastEnergyR = 0;
  double num = 0;

  std::vector<PointFrameResidual *> toRemove[NUM_THREADS];
  for (int i = 0; i < NUM_THREADS; i++)
    toRemove[i].clear();

  if (multiThreading) {
    treadReduce.reduce(boost::bind(&SODSOSystem::linearizeAll_Reductor, this,
                                   fixLinearization, toRemove, _1, _2, _3, _4),
                       0, activeResiduals.size(), 0);
    lastEnergyP = treadReduce.stats[0];
  } else {
    Vec10 stats;
    linearizeAll_Reductor(fixLinearization, toRemove, 0, activeResiduals.size(),
                          &stats, 0);
    lastEnergyP = stats[0];
  }

  setNewFrameEnergyTH();

  if (fixLinearization) {

    for (PointFrameResidual *r : activeResiduals) {
      PointHessian *ph = r->point;
      if (ph->lastResiduals[0].first == r)
        ph->lastResiduals[0].second = r->state_state;
      else if (ph->lastResiduals[1].first == r)
        ph->lastResiduals[1].second = r->state_state;
    }

    int nResRemoved = 0;
    for (int i = 0; i < NUM_THREADS; i++) {
      for (PointFrameResidual *r : toRemove[i]) {
        PointHessian *ph = r->point;

        if (ph->lastResiduals[0].first == r)
          ph->lastResiduals[0].first = 0;
        else if (ph->lastResiduals[1].first == r)
          ph->lastResiduals[1].first = 0;

        for (unsigned int k = 0; k < ph->residuals.size(); k++)
          if (ph->residuals[k] == r) {
            ef->dropResidual(r->efResidual);
            deleteOut<PointFrameResidual>(ph->residuals, k);
            nResRemoved++;
            break;
          }
      }
    }
    // printf("FINAL LINEARIZATION: removed %d / %d residuals!\n", nResRemoved,
    // (int)activeResiduals.size());
  }

  return Vec3(lastEnergyP, lastEnergyR, num);
}

// applies step to linearization point.
bool SODSOSystem::doStepFromBackup(float stepfacC, float stepfacT,
                                   float stepfacR, float stepfacA,
                                   float stepfacD) {
  //  float meanStepC=0,meanStepP=0,meanStepD=0;
  //  meanStepC += Hcalib.step.norm();

  Vec10 pstepfac;
  pstepfac.segment<3>(0).setConstant(stepfacT);
  pstepfac.segment<3>(3).setConstant(stepfacR);
  pstepfac.segment<4>(6).setConstant(stepfacA);

  float sumA = 0, sumB = 0, sumT = 0, sumR = 0, sumID = 0, numID = 0;

  float sumNID = 0;

  if (setting_solverMode & SOLVER_MOMENTUM) {
    Hcalib.setValue(Hcalib.value_backup + Hcalib.step);
    for (FrameHessian *fh : frameHessians) {
      Vec10 step = fh->step;
      step.head<6>() += 0.5f * (fh->step_backup.head<6>());

      fh->setState(fh->state_backup + step);
      sumA += step[6] * step[6];
      sumB += step[7] * step[7];
      sumT += step.segment<3>(0).squaredNorm();
      sumR += step.segment<3>(3).squaredNorm();

      for (PointHessian *ph : fh->pointHessians) {
        float step = ph->step + 0.5f * (ph->step_backup);
        ph->setIdepth(ph->idepth_backup + step);
        sumID += step * step;
        sumNID += fabsf(ph->idepth_backup);
        numID++;

        ph->setIdepthZero(ph->idepth_backup + step);
      }
    }
  } else {
    Hcalib.setValue(Hcalib.value_backup + stepfacC * Hcalib.step);
    for (FrameHessian *fh : frameHessians) {
      fh->setState(fh->state_backup + pstepfac.cwiseProduct(fh->step));
      sumA += fh->step[6] * fh->step[6];
      sumB += fh->step[7] * fh->step[7];
      sumT += fh->step.segment<3>(0).squaredNorm();
      sumR += fh->step.segment<3>(3).squaredNorm();

      for (PointHessian *ph : fh->pointHessians) {
        ph->setIdepth(ph->idepth_backup + stepfacD * ph->step);
        sumID += ph->step * ph->step;
        sumNID += fabsf(ph->idepth_backup);
        numID++;

        ph->setIdepthZero(ph->idepth_backup + stepfacD * ph->step);
      }
    }
  }

  sumA /= frameHessians.size();
  sumB /= frameHessians.size();
  sumR /= frameHessians.size();
  sumT /= frameHessians.size();
  sumID /= numID;
  sumNID /= numID;

  if (!setting_debugout_runquiet)
    printf("STEPS: A %.1f; B %.1f; R %.1f; T %.1f. \t",
           sqrtf(sumA) / (0.0005 * setting_thOptIterations),
           sqrtf(sumB) / (0.00005 * setting_thOptIterations),
           sqrtf(sumR) / (0.00005 * setting_thOptIterations),
           sqrtf(sumT) * sumNID / (0.00005 * setting_thOptIterations));

  EFDeltaValid = false;
  setPrecalcValues();

  return sqrtf(sumA) < 0.0005 * setting_thOptIterations &&
         sqrtf(sumB) < 0.00005 * setting_thOptIterations &&
         sqrtf(sumR) < 0.00005 * setting_thOptIterations &&
         sqrtf(sumT) * sumNID < 0.00005 * setting_thOptIterations;
  //
  //  printf("mean steps: %f %f %f!\n",
  //      meanStepC, meanStepP, meanStepD);
}

// sets linearization point.
void SODSOSystem::backupState(bool backupLastStep) {
  if (setting_solverMode & SOLVER_MOMENTUM) {
    if (backupLastStep) {
      Hcalib.step_backup = Hcalib.step;
      Hcalib.value_backup = Hcalib.value;
      for (FrameHessian *fh : frameHessians) {
        fh->step_backup = fh->step;
        fh->state_backup = fh->get_state();
        for (PointHessian *ph : fh->pointHessians) {
          ph->idepth_backup = ph->idepth;
          ph->step_backup = ph->step;
        }
      }
    } else {
      Hcalib.step_backup.setZero();
      Hcalib.value_backup = Hcalib.value;
      for (FrameHessian *fh : frameHessians) {
        fh->step_backup.setZero();
        fh->state_backup = fh->get_state();
        for (PointHessian *ph : fh->pointHessians) {
          ph->idepth_backup = ph->idepth;
          ph->step_backup = 0;
        }
      }
    }
  } else {
    Hcalib.value_backup = Hcalib.value;
    for (FrameHessian *fh : frameHessians) {
      fh->state_backup = fh->get_state();
      for (PointHessian *ph : fh->pointHessians)
        ph->idepth_backup = ph->idepth;
    }
  }
}

// sets linearization point.
void SODSOSystem::loadSateBackup() {
  Hcalib.setValue(Hcalib.value_backup);
  for (FrameHessian *fh : frameHessians) {
    fh->setState(fh->state_backup);
    for (PointHessian *ph : fh->pointHessians) {
      ph->setIdepth(ph->idepth_backup);

      ph->setIdepthZero(ph->idepth_backup);
    }
  }

  EFDeltaValid = false;
  setPrecalcValues();
}

double SODSOSystem::calcMEnergy() {
  if (setting_forceAceptStep)
    return 0;
  // calculate (x-x0)^T * [2b + H * (x-x0)] for everything saved in L.
  // ef->makeIDX();
  // ef->setDeltaF(&Hcalib);
  return ef->calcMEnergyF();
}

void SODSOSystem::printOptRes(const Vec3 &res, double resL, double resM,
                              double resPrior, double LExact, float a,
                              float b) {
  printf("A(%f)=(AV %.3f). Num: A(%'d) + M(%'d); ab %f %f!\n", res[0],
         sqrtf((float)(res[0] / (patternNum * ef->resInA))), ef->resInA,
         ef->resInM, a, b);
}

float SODSOSystem::optimize(int mnumOptIts) {

  if (frameHessians.size() < 2)
    return 0;
  if (frameHessians.size() < 3)
    mnumOptIts = 20;
  if (frameHessians.size() < 4)
    mnumOptIts = 15;

  // get statistics and active residuals.

  activeResiduals.clear();
  int numPoints = 0;
  int numLRes = 0;
  for (FrameHessian *fh : frameHessians)
    for (PointHessian *ph : fh->pointHessians) {
      for (PointFrameResidual *r : ph->residuals) {
        if (!r->efResidual->isLinearized) {
          activeResiduals.push_back(r);
          r->resetOOB();
        } else
          numLRes++;
      }
      numPoints++;
    }

  if (!setting_debugout_runquiet)
    printf("OPTIMIZE %d pts, %d active res, %d lin res!\n", ef->nPoints,
           (int)activeResiduals.size(), numLRes);

  Vec3 lastEnergy = linearizeAll(false);
  double lastEnergyL = calcLEnergy();
  double lastEnergyM = calcMEnergy();

  if (multiThreading)
    treadReduce.reduce(boost::bind(&SODSOSystem::applyRes_Reductor, this, true,
                                   _1, _2, _3, _4),
                       0, activeResiduals.size(), 50);
  else
    applyRes_Reductor(true, 0, activeResiduals.size(), 0, 0);

  if (!setting_debugout_runquiet) {
    printf("Initial Error       \t");
    printOptRes(lastEnergy, lastEnergyL, lastEnergyM, 0, 0,
                frameHessians.back()->aff_g2l().a,
                frameHessians.back()->aff_g2l().b);
  }

  debugPlotTracking();

  double lambda = 1e-1;
  float stepsize = 1;
  VecX previousX = VecX::Constant(CPARS + 8 * frameHessians.size(), NAN);
  for (int iteration = 0; iteration < mnumOptIts; iteration++) {
    // solve!
    backupState(iteration != 0);
    // solveSystemNew(0);
    solveSystem(iteration, lambda);
    double incDirChange = (1e-20 + previousX.dot(ef->lastX)) /
                          (1e-20 + previousX.norm() * ef->lastX.norm());
    previousX = ef->lastX;

    if (std::isfinite(incDirChange) &&
        (setting_solverMode & SOLVER_STEPMOMENTUM)) {
      float newStepsize = exp(incDirChange * 1.4);
      if (incDirChange < 0 && stepsize > 1)
        stepsize = 1;

      stepsize = sqrtf(sqrtf(newStepsize * stepsize * stepsize * stepsize));
      if (stepsize > 2)
        stepsize = 2;
      if (stepsize < 0.25)
        stepsize = 0.25;
    }

    bool canbreak =
        doStepFromBackup(stepsize, stepsize, stepsize, stepsize, stepsize);

    // eval new energy!
    Vec3 newEnergy = linearizeAll(false);
    double newEnergyL = calcLEnergy();
    double newEnergyM = calcMEnergy();

    if (!setting_debugout_runquiet) {
      printf("%s %d (L %.2f, dir %.2f, ss %.1f): \t",
             (newEnergy[0] + newEnergy[1] + newEnergyL + newEnergyM <
              lastEnergy[0] + lastEnergy[1] + lastEnergyL + lastEnergyM)
                 ? "ACCEPT"
                 : "REJECT",
             iteration, log10(lambda), incDirChange, stepsize);
      printOptRes(newEnergy, newEnergyL, newEnergyM, 0, 0,
                  frameHessians.back()->aff_g2l().a,
                  frameHessians.back()->aff_g2l().b);
    }

    if (setting_forceAceptStep ||
        (newEnergy[0] + newEnergy[1] + newEnergyL + newEnergyM <
         lastEnergy[0] + lastEnergy[1] + lastEnergyL + lastEnergyM)) {

      if (multiThreading)
        treadReduce.reduce(boost::bind(&SODSOSystem::applyRes_Reductor, this,
                                       true, _1, _2, _3, _4),
                           0, activeResiduals.size(), 50);
      else
        applyRes_Reductor(true, 0, activeResiduals.size(), 0, 0);

      lastEnergy = newEnergy;
      lastEnergyL = newEnergyL;
      lastEnergyM = newEnergyM;

      lambda *= 0.25;
    } else {
      loadSateBackup();
      lastEnergy = linearizeAll(false);
      lastEnergyL = calcLEnergy();
      lastEnergyM = calcMEnergy();
      lambda *= 1e2;
    }

    if (canbreak && iteration >= setting_minOptIterations)
      break;
  }

  Vec10 newStateZero = Vec10::Zero();
  newStateZero.segment<2>(6) = frameHessians.back()->get_state().segment<2>(6);

  frameHessians.back()->setEvalPT(frameHessians.back()->PRE_worldToCam,
                                  newStateZero);
  EFDeltaValid = false;
  EFAdjointsValid = false;
  ef->setAdjointsF(&Hcalib);
  setPrecalcValues();

  lastEnergy = linearizeAll(true);

  if (!std::isfinite((double)lastEnergy[0]) ||
      !std::isfinite((double)lastEnergy[1]) ||
      !std::isfinite((double)lastEnergy[2])) {
    printf("KF Tracking failed: LOST!\n");
    isLost = true;
  }

  statistics_lastFineTrackRMSE =
      sqrtf((float)(lastEnergy[0] / (patternNum * ef->resInA)));

  if (calibLog != 0) {
    (*calibLog) << Hcalib.value_scaled.transpose() << " "
                << frameHessians.back()->get_state_scaled().transpose() << " "
                << sqrtf((float)(lastEnergy[0] / (patternNum * ef->resInA)))
                << " " << ef->resInM << "\n";
    calibLog->flush();
  }

  {
    boost::unique_lock<boost::mutex> crlock(shellPoseMutex);
    for (FrameHessian *fh : frameHessians) {
      fh->shell->camToWorld = fh->PRE_camToWorld;
      fh->shell->aff_g2l = fh->aff_g2l();
    }
  }

  debugPlotTracking();

  return sqrtf((float)(lastEnergy[0] / (patternNum * ef->resInA)));
}

void SODSOSystem::solveSystem(int iteration, double lambda) {
  ef->lastNullspaces_forLogging =
      getNullspaces(ef->lastNullspaces_pose, ef->lastNullspaces_scale,
                    ef->lastNullspaces_affA, ef->lastNullspaces_affB);

  ef->solveSystemF(iteration, lambda, &Hcalib);
}

double SODSOSystem::calcLEnergy() {
  if (setting_forceAceptStep)
    return 0;

  double Ef = ef->calcLEnergyF_MT();
  return Ef;
}

void SODSOSystem::removeOutliers() {
  int numPointsDropped = 0;
  for (FrameHessian *fh : frameHessians) {
    for (unsigned int i = 0; i < fh->pointHessians.size(); i++) {
      PointHessian *ph = fh->pointHessians[i];
      if (ph == 0)
        continue;

      if (ph->residuals.size() == 0) {
        fh->pointHessiansOut.push_back(ph);
        ph->efPoint->stateFlag = EFPointStatus::PS_DROP;
        fh->pointHessians[i] = fh->pointHessians.back();
        fh->pointHessians.pop_back();
        i--;
        numPointsDropped++;
      }
    }
  }
  ef->dropPointsF();
}

std::vector<VecX> SODSOSystem::getNullspaces(
    std::vector<VecX> &nullspaces_pose, std::vector<VecX> &nullspaces_scale,
    std::vector<VecX> &nullspaces_affA, std::vector<VecX> &nullspaces_affB) {
  nullspaces_pose.clear();
  nullspaces_scale.clear();
  nullspaces_affA.clear();
  nullspaces_affB.clear();

  int n = CPARS + frameHessians.size() * 8;
  std::vector<VecX> nullspaces_x0_pre;
  for (int i = 0; i < 6; i++) {
    VecX nullspace_x0(n);
    nullspace_x0.setZero();
    for (FrameHessian *fh : frameHessians) {
      nullspace_x0.segment<6>(CPARS + fh->idx * 8) = fh->nullspaces_pose.col(i);
      nullspace_x0.segment<3>(CPARS + fh->idx * 8) *= SCALE_XI_TRANS_INVERSE;
      nullspace_x0.segment<3>(CPARS + fh->idx * 8 + 3) *= SCALE_XI_ROT_INVERSE;
    }
    nullspaces_x0_pre.push_back(nullspace_x0);
    nullspaces_pose.push_back(nullspace_x0);
  }
  for (int i = 0; i < 2; i++) {
    VecX nullspace_x0(n);
    nullspace_x0.setZero();
    for (FrameHessian *fh : frameHessians) {
      nullspace_x0.segment<2>(CPARS + fh->idx * 8 + 6) =
          fh->nullspaces_affine.col(i).head<2>();
      nullspace_x0[CPARS + fh->idx * 8 + 6] *= SCALE_A_INVERSE;
      nullspace_x0[CPARS + fh->idx * 8 + 7] *= SCALE_B_INVERSE;
    }
    nullspaces_x0_pre.push_back(nullspace_x0);
    if (i == 0)
      nullspaces_affA.push_back(nullspace_x0);
    if (i == 1)
      nullspaces_affB.push_back(nullspace_x0);
  }

  VecX nullspace_x0(n);
  nullspace_x0.setZero();
  for (FrameHessian *fh : frameHessians) {
    nullspace_x0.segment<6>(CPARS + fh->idx * 8) = fh->nullspaces_scale;
    nullspace_x0.segment<3>(CPARS + fh->idx * 8) *= SCALE_XI_TRANS_INVERSE;
    nullspace_x0.segment<3>(CPARS + fh->idx * 8 + 3) *= SCALE_XI_ROT_INVERSE;
  }
  nullspaces_x0_pre.push_back(nullspace_x0);
  nullspaces_scale.push_back(nullspace_x0);

  return nullspaces_x0_pre;
}

} // namespace dso


text:
/******************************************************************************\
* Author: Matthew Beauregard Smith                                             *
* Affiliation: The University of Texas at Austin                               *
* Department: Oden Institute and Institute for Cellular and Molecular Biology  *
* PI: Edward Marcotte                                                          *
* Project: Protein Fluorosequencing                                            *
\******************************************************************************/

// Boost unit test framework (recommended to be the first include):
#include <boost/test/unit_test.hpp>

// File under test:
#include "parameter-fitter.h"

namespace whatprot {

namespace {
using boost::unit_test::tolerance;
const double TOL = 0.000000001;
}  // namespace

BOOST_AUTO_TEST_SUITE(hmm_suite)
BOOST_AUTO_TEST_SUITE(fit_suite)
BOOST_AUTO_TEST_SUITE(parameter_fitter_suite)

BOOST_AUTO_TEST_CASE(constructor_test, *tolerance(TOL)) {
    ParameterFitter pf;
    BOOST_TEST(pf.numerator == 0.0);
    BOOST_TEST(pf.denominator == 0.0);
}

BOOST_AUTO_TEST_CASE(get_test, *tolerance(TOL)) {
    ParameterFitter pf;
    pf.numerator = 2.71828;
    pf.denominator = 3.14159;
    BOOST_TEST(pf.get() == 2.71828 / 3.14159);
}

BOOST_AUTO_TEST_SUITE_END()  // parameter_fitter_suite
BOOST_AUTO_TEST_SUITE_END()  // fit_suite
BOOST_AUTO_TEST_SUITE_END()  // hmm_suite

}  // namespace whatprot

ext: cc

max_stars_repo_name: erisyon/whatprot

max_issues_repo_name: erisyon/whatprot

max_forks_repo_name: erisyon/whatprot


text:
// record_store_test_manyiter.cpp

/**
 *    Copyright (C) 2014 MongoDB Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/db/storage/record_store_test_harness.h"

#include <boost/scoped_ptr.hpp>

#include "mongo/db/record_id.h"
#include "mongo/db/storage/record_data.h"
#include "mongo/db/storage/record_store.h"
#include "mongo/unittest/unittest.h"

using std::set;
using std::string;
using std::stringstream;
using std::vector;

namespace mongo {

using boost::scoped_ptr;

// Create multiple iterators over an empty record store.
TEST(RecordStoreTestHarness, GetManyIteratorsEmpty) {
    scoped_ptr<HarnessHelper> harnessHelper(newHarnessHelper());
    scoped_ptr<RecordStore> rs(harnessHelper->newNonCappedRecordStore());

    {
        scoped_ptr<OperationContext> opCtx(harnessHelper->newOperationContext());
        ASSERT_EQUALS(0, rs->numRecords(opCtx.get()));
    }

    {
        scoped_ptr<OperationContext> opCtx(harnessHelper->newOperationContext());
        vector<RecordIterator*> v = rs->getManyIterators(opCtx.get());

        for (vector<RecordIterator*>::iterator vIter = v.begin(); vIter != v.end(); vIter++) {
            RecordIterator* rIter = *vIter;
            ASSERT(rIter->isEOF());
            ASSERT_EQUALS(RecordId(), rIter->curr());
            ASSERT_EQUALS(RecordId(), rIter->getNext());
            ASSERT(rIter->isEOF());
            ASSERT_EQUALS(RecordId(), rIter->curr());

            delete rIter;
        }
    }
}

// Create multiple iterators over a nonempty record store.
TEST(RecordStoreTestHarness, GetManyIteratorsNonEmpty) {
    scoped_ptr<HarnessHelper> harnessHelper(newHarnessHelper());
    scoped_ptr<RecordStore> rs(harnessHelper->newNonCappedRecordStore());

    {
        scoped_ptr<OperationContext> opCtx(harnessHelper->newOperationContext());
        ASSERT_EQUALS(0, rs->numRecords(opCtx.get()));
    }

    const int nToInsert = 10;
    RecordId locs[nToInsert];
    for (int i = 0; i < nToInsert; i++) {
        scoped_ptr<OperationContext> opCtx(harnessHelper->newOperationContext());
        {
            stringstream ss;
            ss << "record " << i;
            string data = ss.str();

            WriteUnitOfWork uow(opCtx.get());
            StatusWith<RecordId> res =
                rs->insertRecord(opCtx.get(), data.c_str(), data.size() + 1, false);
            ASSERT_OK(res.getStatus());
            locs[i] = res.getValue();
            uow.commit();
        }
    }

    {
        scoped_ptr<OperationContext> opCtx(harnessHelper->newOperationContext());
        ASSERT_EQUALS(nToInsert, rs->numRecords(opCtx.get()));
    }

    set<RecordId> remain(locs, locs + nToInsert);
    {
        scoped_ptr<OperationContext> opCtx(harnessHelper->newOperationContext());
        vector<RecordIterator*> v = rs->getManyIterators(opCtx.get());

        for (vector<RecordIterator*>::iterator vIter = v.begin(); vIter != v.end(); vIter++) {
            RecordIterator* rIter = *vIter;
            while (!rIter->isEOF()) {
                RecordId loc = rIter->curr();
                ASSERT(1 == remain.erase(loc));
                ASSERT_EQUALS(loc, rIter->getNext());
            }

            ASSERT_EQUALS(RecordId(), rIter->curr());
            ASSERT_EQUALS(RecordId(), rIter->getNext());
            ASSERT(rIter->isEOF());
            ASSERT_EQUALS(RecordId(), rIter->curr());

            delete rIter;
        }
        ASSERT(remain.empty());
    }
}

}  // namespace mongo

ext: cpp

max_stars_repo_name: DavidAlphaFox/mongodb

max_issues_repo_name: DavidAlphaFox/mongodb

max_forks_repo_name: DavidAlphaFox/mongodb


text:
// Andrew Naplavkov

#ifndef BRIG_NULL_T_HPP
#define BRIG_NULL_T_HPP

#include <boost/none_t.hpp>
#include <ostream>

namespace brig {

typedef ::boost::none_t null_t;

} // brig

namespace std {

template <class CharT, class TraitsT>
basic_ostream<CharT, TraitsT>& operator<<(basic_ostream<CharT, TraitsT>& stream, const brig::null_t&)
{
  return stream;
}

} // std

#endif // BRIG_NULL_T_HPP

ext: hpp

max_stars_repo_name: isadchenko/brig

max_issues_repo_name: isadchenko/brig

max_forks_repo_name: isadchenko/brig


text:
// stdafx.cpp : source file that includes just the standard includes
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

#define BOOST_TEST_NO_MAIN
#include <boost/test/included/unit_test.hpp>

CMyString generateItem(const std::string& str)
{
	return CMyString(str);
}

CMyString generateEmptyItem()
{
	return CMyString();
}

max_stars_repo_name: denis-petrov/oop

max_issues_repo_name: denis-petrov/oop

max_forks_repo_name: denis-petrov/oop


text:
#include <cyberway/chaindb/names.hpp>
#include <cyberway/chaindb/exception.hpp>
#include <boost/algorithm/string.hpp>

namespace cyberway { namespace chaindb {

    using eosio::chain::name_type_exception;

    string db_name_to_string(const uint64_t& value) {
        // Copy-paste of eosio::name::to_string(),
        //     but instead of the symbol '.' the symbol '_' is used
        static const char* charmap = "_12345abcdefghijklmnopqrstuvwxyz";

        string str(13,'_');

        uint64_t tmp = value;

        str[12] = charmap[tmp & 0x0f];
        tmp >>= 4;

        for (uint32_t i = 1; i <= 12; ++i) {
            char c = charmap[tmp & 0x1f];
            str[12-i] = c;
            tmp >>= 5;
        }

        boost::algorithm::trim_right_if( str, [](char c){ return c == '_'; } );
        return str;
    }

    uint64_t db_char_to_symbol(char c) {
        if (c >= 'a' && c <= 'z') {
            return (c - 'a') + 6;
        }
        if (c >= '1' && c <= '5') {
            return (c - '1') + 1;
        }

        CYBERWAY_ASSERT('_' == c, name_type_exception,
            "Name contains bad character '${c}'", ("c", string(1, c)));
        return 0;
    }

    uint64_t db_string_to_name(const char* str) {
        const auto len = strnlen(str, 14);
        CYBERWAY_ASSERT(len <= 13, name_type_exception,
            "Name is longer than 13 characters (${name}...)", ("name", string(str, len)));

        uint64_t value = 0;
        int i = 0;
        for ( ; str[i] && i < 12; ++i) {
            value |= (db_char_to_symbol(str[i]) & 0x1f) << (64 - 5 * (i + 1));
        }

        if (len == 13) {
            value |= db_char_to_symbol(str[12]) & 0x0F;
        }
        return value;
    }

    // name can't start from _ that is why they are used for internal db and key names

    const string names::unknown          = "_UNKNOWN_";

    const string names::system_code      = "_CYBERWAY_";

    const string names::undo_table       = "undo";

    const string names::service_field    = "_SERVICE_";

    const string names::code_field       = "code";
    const string names::table_field      = "table";
    const string names::scope_field      = "scope";
    const string names::pk_field         = "pk";

    const string names::amount_field     = "_amount";
    const string names::decs_field       = "_decs";
    const string names::sym_field        = "_sym";

    const string names::next_pk_field    = "npk";
    const string names::undo_pk_field    = "upk";
    const string names::undo_payer_field = "uyr";
    const string names::undo_size_field  = "usz";
    const string names::undo_ram_field   = "urm";
    const string names::undo_rec_field   = "uct";
    const string names::undo_rev_field   = "uvs";
    const string names::revision_field   = "rev";

    const string names::payer_field      = "payer";
    const string names::size_field       = "size";
    const string names::ram_field        = "ram";

    const string names::scope_path       = string(names::service_field).append(".").append(names::scope_field);
    const string names::undo_pk_path     = string(names::service_field).append(".").append(names::undo_pk_field);
    const string names::revision_path    = string(names::service_field).append(".").append(names::revision_field);

    const string names::asc_order        = "asc";
    const string names::desc_order       = "desc";

} } // namespace cyberway::chaindb

max_stars_repo_name: GolosChain/eos

max_issues_repo_name: GolosChain/eos

max_forks_repo_name: GolosChain/eos


text:
#include <fstream>
#include <iterator>
#include <boost/regex.hpp>
#include <string>
#include <iostream>

int main( int argc , char *argv[ ] ) {
   boost::regex to_be_replaced( "Goodbye London\\s*!" ) ;
   std::string replacement( "Hello New York!" ) ;
   for ( int i = 1 ; i < argc ; i++ ) {
      std::ifstream infile ( argv[ i ] ) ;
      if ( infile ) {
	 std::string filetext( (std::istreambuf_iterator<char>( infile )) ,
	       std::istreambuf_iterator<char>( ) ) ;
	 std::string changed ( boost::regex_replace( filetext , to_be_replaced , replacement )) ;
	 infile.close( ) ;
	 std::ofstream outfile( argv[ i ] , std::ios_base::out | std::ios_base::trunc ) ;
	 if ( outfile.is_open( ) ) {
	    outfile << changed ;
	    outfile.close( ) ;
	 }
      }
      else
	 std::cout << "Can't find file " << argv[ i ] << " !\n" ;
   }
   return 0 ;
}

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
// Author(s): Aad Mathijssen, Wieger Wesselink
// Copyright: see the accompanying file COPYING or copy at
// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
/// \file typecheck_test.cpp
/// \brief Add your file description here.

#include <iostream>
#include <sstream>
#include <string>
#include <boost/test/minimal.hpp>
#include "mcrl2/core/parse.h"
#include "mcrl2/pbes/typecheck.h"
#include "mcrl2/pbes/parse.h"

using namespace mcrl2;

void test_pbes_specification(const std::string& pbes_in, bool test_type_checker = true)
{
  pbes_system::pbes p = pbes_system::detail::parse_pbes_new(pbes_in).construct_pbes();
  if (test_type_checker)
  {
    pbes_system::type_check_pbes(p);
    std::string pbes_out = pbes_system::pp(p);

    if (pbes_in!=pbes_out)
    {
      std::cerr << "PBES IN AND PBES OUT ARE DIFFERENT (with typechecking).\n";
      std::cerr << "PBES IN: " << pbes_in << "\n";
      std::cerr << "PBES OUT: " << pbes_out << "\n";
    }
    BOOST_CHECK(pbes_in == pbes_out);
  }
}

void test_pbes_specification1()
{
  //test PBES specification involving global variables
  test_pbes_specification(
    "glob dc: Bool;\n"
    "\n"
    "pbes nu X(b: Bool) =\n"
    "       val(b) && X(dc);\n"
    "\n"
    "init X(dc);\n"
  );
}

void test_pbes_specification2()
{
  //test PBES specification where the type of [10,m] should become List(Nat), not List(Pos).
  //This failed in revision 10180 and before.
  test_pbes_specification(
   "pbes nu X0(m: Nat) =\n"
   "       forall i: Nat. val(!(i < 2)) || X0([10, m] . i);\n"
   "\n"
   "init X0(0);\n"
  );
}

int test_main(int argc, char* argv[])
{
 test_pbes_specification1();
  test_pbes_specification2();

  return 0;
}


text:
#pragma once

#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
#include <boost/asio.hpp>
#include "network/timer/timer_manager.hpp"
#include "network/util/time.hpp"

namespace cytx
{
    namespace thread
    {
        class executor
        {
            using io_service_t = boost::asio::io_service;
        public:
            executor() {}
            ~executor() {}

        public:
            io_service_t& get_service() { return io_service_; }

            bool is_stoped() const
            {
                return io_service_.stopped();
            }

            void stop()
            {
                io_service_.stop();
            }
        public:
            template<typename F, typename... Args>
            void execute(F&& f, Args&&... args)
            {
                if (io_service_.stopped())
                    throw std::runtime_error("enqueue on stoped thread_pool");

                io_service_.post(cytx::bind(f, std::forward<Args>(args)...));
            }

            template<typename F, typename... Args>
            auto invoke(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>
            {
                if (io_service_.stopped())
                    throw std::runtime_error("enqueue on stoped thread_pool");

                using return_type = typename std::result_of<F(Args...)>::type;
                auto task = std::make_shared<std::packaged_task<return_type()>>(
                    std::bind(std::forward<F>(f), std::forward<Args>(args)...));
                std::future<return_type> res = task->get_future();
                io_service_.post([task]() {(*task)(); });
                return res;
            }

            template<typename F, typename T>
            auto invoke(F&& f, T&& result) -> std::future<T>
            {
                return invoke([r = std::forward<T>(result)](){ f(); return r; });
            }

            template<typename F>
            auto invoke_all(const std::vector<F>& tasks) -> std::vector<std::future<typename std::result_of<F()>::type>>
            {
                if (io_service_.stopped())
                    throw std::runtime_error("enqueue on stoped thread_pool");

                using return_t = std::future<typename std::result_of<F()>::type>;
                std::vector<return_t> futures;
                futures.reserve(tasks.size());

                for (auto& task : tasks)
                {
                    futures.emplace_back(invoke(task));
                }

                for (auto& future : futures)
                {
                    future.get();
                }

                return futures;
            }

            template<typename F>
            auto schedule(F&& f, int64_t delay_time, int64_t time_unit = time_util::millisecond) -> std::future<typename std::result_of<F()>::type>
            {
                if (io_service_.stopped())
                    throw std::runtime_error("enqueue on stoped thread_pool");

                using return_type = typename std::result_of<F()>::type;
                auto task = std::make_shared<std::packaged_task<return_type()>>(std::forward<F>(f));
                std::future<return_type> res = task->get_future();

                timer_mgr_.set_once_timer((int32_t)(delay_time * time_unit), [task]() {(*task)(); });
                return res;
            }

            template<typename F>
            timer_proxy schedule_at_fixed_rate(F&& f, int64_t period, int64_t time_unit = time_util::millisecond)
            {
                if (io_service_.stopped())
                    throw std::runtime_error("enqueue on stoped thread_pool");

                timer_proxy result = timer_mgr_.set_fix_timer((int32_t)(period * time_unit), std::forward<F>(f));
                result.start();
                return result;
            }

            template<typename F>
            timer_proxy schedule_at_fixed_delay(F&& f, int64_t delay_time, int64_t time_unit = time_util::millisecond)
            {
                if (io_service_.stopped())
                    throw std::runtime_error("enqueue on stoped thread_pool");

                timer_proxy result = timer_mgr_.set_auto_timer((int32_t)(delay_time * time_unit), std::forward<F>(f));
                result.start();
                return result;
            }
        protected:
            io_service_t io_service_;
            timer_manager timer_mgr_{ io_service_ };
        };
    }
}

max_stars_repo_name: hbccdf/network-core

max_issues_repo_name: hbccdf/network-core

max_forks_repo_name: hbccdf/network-core


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_CORE_FUNCTIONS_SCALAR_OUTER_FOLD_HPP_INCLUDED
#define NT2_CORE_FUNCTIONS_SCALAR_OUTER_FOLD_HPP_INCLUDED

#include <nt2/core/functions/outer_fold.hpp>
#include <boost/fusion/include/pop_front.hpp>
#include <nt2/include/functions/scalar/numel.hpp>

namespace nt2 { namespace details
{
  template <class X, class N, class B, class U>
  BOOST_FORCEINLINE typename X::value_type
  outer_fold_step(X const& in, const std::size_t& p, const std::size_t& mbound, N const& neutral, B const& bop, U const&)
  {
    typedef typename X::value_type   value_type;
    typedef typename X::extent_type  extent_type;
    extent_type ext = in.extent();

    std::size_t ibound  = boost::fusion::at_c<0>(ext);
    value_type out = neutral(nt2::meta::as_<value_type>());

    for(std::size_t m = 0, m_ = 0; m < mbound; ++m, m_+=ibound)
    {
      out = bop(out, nt2::run(in, m_+p, meta::as_<value_type>()));
    }
    return out;
  }
} }

namespace nt2 { namespace ext
{
  //============================================================================
  // Generates outer_fold
  //============================================================================
  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::outer_fold_, tag::cpu_, (A0)(A1)(A2)(A3)(A4)
                            , ((ast_< A0, nt2::container::domain>))
                              ((ast_< A1, nt2::container::domain>))
                              (unspecified_<A2>)
                              (unspecified_<A3>)
                              (unspecified_<A4>)
                            )
  {
    typedef void                                                               result_type;
    typedef typename A0::value_type                                            value_type;
    typedef typename boost::remove_reference<A1>::type::extent_type            extent_type;

    BOOST_FORCEINLINE result_type
    operator()( A0& out, A1& in , A2 const& neutral
              , A3 const& bop   , A4 const& uop
              ) const
    {
      extent_type ext = in.extent();

      std::size_t ibound  = boost::fusion::at_c<0>(ext);
      std::size_t mbound =  boost::fusion::at_c<1>(ext);
      std::size_t obound =  boost::fusion::at_c<2>(ext);
      std::size_t id;

      for(std::size_t o = 0, o_ = 0; o < obound; ++o, o_+=ibound)
      {
        for(std::size_t i = 0; i < ibound; ++i)
        {
          id = i+o_;
          nt2::run(out, id, details::outer_fold_step(in,id,mbound,neutral,bop,uop));
        }
      }
    }
  };
} }

#endif


text:
//--------------------------------------------------------------------------------
//This is a file from Arkengine
//
//
//Copyright (c) arkenthera.All rights reserved.
//
//BasicRenderWindow.cpp
//--------------------------------------------------------------------------------

#include "Core/YumeHeaders.h"
#include "HelloWorld.h"
#include "Logging/logging.h"
#include "Core/YumeMain.h"

#include <boost/shared_ptr.hpp>

#include "Input/YumeInput.h"

#include "Renderer/YumeTexture2D.h"

#include "Renderer/YumeResourceManager.h"

#include "Engine/YumeEngine.h"

#include "UI/YumeDebugOverlay.h"

#include "Renderer/Light.h"
#include "Renderer/StaticModel.h"
#include "Renderer/Scene.h"

#include "UI/YumeOptionsMenu.h"

YUME_DEFINE_ENTRY_POINT(YumeEngine::HelloWorld);

namespace YumeEngine
{

	HelloWorld::HelloWorld()
	{
		REGISTER_ENGINE_LISTENER;
	}

	HelloWorld::~HelloWorld()
	{

	}

	void HelloWorld::Start()
	{
		YumeResourceManager* rm_ = gYume->pResourceManager;
		YumeMiscRenderer* renderer = gYume->pRenderer;
		Scene* scene = renderer->GetScene();
		YumeCamera* camera = renderer->GetCamera();

		gYume->pInput->AddListener(this);

#ifndef DISABLE_CEF
		optionsMenu_ = new YumeOptionsMenu;
		gYume->pUI->AddUIElement(optionsMenu_);
		optionsMenu_->SetVisible(true);

		overlay_ = new YumeDebugOverlay;
		gYume->pUI->AddUIElement(overlay_);
		overlay_->SetVisible(true);
		overlay_->GetBinding("SampleName")->SetValue("Sponza PBR");
#endif

		StaticModel* dragon= CreateModel("Models/Mitsuba/mitsuba-sphere.yume",DirectX::XMFLOAT3(-40,150,0),DirectX::XMFLOAT4(0,0,0,0),DirectX::XMFLOAT3(15,15,15));
		StaticModel* dragon2= CreateModel("Models/Mitsuba/mitsuba-sphere.yume",DirectX::XMFLOAT3(0,150,0),DirectX::XMFLOAT4(0,0,0,0),DirectX::XMFLOAT3(15,15,15));
		StaticModel* dragon3= CreateModel("Models/Mitsuba/mitsuba-sphere.yume",DirectX::XMFLOAT3(40,150,0),DirectX::XMFLOAT4(0,0,0,0),DirectX::XMFLOAT3(15,15,15));
		StaticModel* dragon4= CreateModel("Models/Mitsuba/mitsuba-sphere.yume",DirectX::XMFLOAT3(80,150,0),DirectX::XMFLOAT4(0,0,0,0),DirectX::XMFLOAT3(15,15,15));
		StaticModel* dragon5= CreateModel("Models/Mitsuba/mitsuba-sphere.yume",DirectX::XMFLOAT3(120,150,0),DirectX::XMFLOAT4(0,0,0,0),DirectX::XMFLOAT3(15,15,15));

		StaticModel* sponza = CreateModel("Models/sponza/sponza.yume");

		RenderPass* dp = renderer->GetDefaultPass();
		dp->Load("RenderCalls/Bloom.xml",true);
		dp->Load("RenderCalls/FXAA.xml",true);
		dp->Load("RenderCalls/LensDistortion.xml",true);
		dp->Load("RenderCalls/ShowGBuffer.xml",true);
		dp->DisableRenderCalls("ShowGBuffer");
		dp->DisableRenderCalls("Bloom");

		MaterialPtr diff = YumeAPINew Material;
		diff->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(0.4f,0.4f,0.4f,1));
		diff->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1));
		diff->SetShaderParameter("FloorRoughness",0.05f);
		diff->SetShaderParameter("Roughness",0.05f);
		diff->SetShaderParameter("has_diffuse_tex",false);
		diff->SetShaderParameter("has_alpha_tex",false);
		diff->SetShaderParameter("has_specular_tex",false);
		diff->SetShaderParameter("has_normal_tex",false);
		diff->SetShaderParameter("has_roughness_tex",false);
		dragon->SetMaterial(diff);

		MaterialPtr diff2 = YumeAPINew Material;
		diff2->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(0.4f,0.4f,0.4f,1));
		diff2->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(0.8f,0.8f,0.8f,1));
		diff2->SetShaderParameter("FloorRoughness",0.05f);
		diff2->SetShaderParameter("Roughness",0.05f);
		diff2->SetShaderParameter("has_diffuse_tex",false);
		diff2->SetShaderParameter("has_alpha_tex",false);
		diff2->SetShaderParameter("has_specular_tex",false);
		diff2->SetShaderParameter("has_normal_tex",false);
		diff2->SetShaderParameter("has_roughness_tex",false);
		dragon2->SetMaterial(diff2);

		MaterialPtr diff3 = YumeAPINew Material;
		diff3->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(0.4f,0.4f,0.4f,1));
		diff3->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(0.8f,0.8f,0.8f,1));
		diff3->SetShaderParameter("FloorRoughness",0.129f);
		diff3->SetShaderParameter("Roughness",0.129f);
		diff3->SetShaderParameter("has_diffuse_tex",false);
		diff3->SetShaderParameter("has_alpha_tex",false);
		diff3->SetShaderParameter("has_specular_tex",false);
		diff3->SetShaderParameter("has_normal_tex",false);
		diff3->SetShaderParameter("has_roughness_tex",false);
		dragon3->SetMaterial(diff3);

		MaterialPtr diff4 = YumeAPINew Material;
		diff4->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(0.4f,0.4f,0.4f,1));
		diff4->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(0.8f,0.9f,0.8f,1));
		diff4->SetShaderParameter("FloorRoughness",0.3f);
		diff4->SetShaderParameter("Roughness",0.3f);
		diff4->SetShaderParameter("has_diffuse_tex",false);
		diff4->SetShaderParameter("has_alpha_tex",false);
		diff4->SetShaderParameter("has_specular_tex",false);
		diff4->SetShaderParameter("has_normal_tex",false);
		diff4->SetShaderParameter("has_roughness_tex",false);
		dragon4->SetMaterial(diff4);

		MaterialPtr diff5 = YumeAPINew Material;
		diff5->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(0.4f,0.4f,0.4f,1));
		diff5->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(0.8,0.8,0.8,1));
		diff5->SetShaderParameter("FloorRoughness",1);
		diff5->SetShaderParameter("Roughness",1);
		diff5->SetShaderParameter("has_diffuse_tex",false);
		diff5->SetShaderParameter("has_alpha_tex",false);
		diff5->SetShaderParameter("has_specular_tex",false);
		diff5->SetShaderParameter("has_normal_tex",false);
		diff5->SetShaderParameter("has_roughness_tex",false);
		dragon5->SetMaterial(diff5);

		Light* dirLight = new Light;
		dirLight->SetName("DirLight");
		dirLight->SetType(LT_DIRECTIONAL);
		dirLight->SetPosition(DirectX::XMVectorSet(100,2000,200,0));
		dirLight->SetDirection(DirectX::XMVectorSet(0,-1,0,0));
		dirLight->SetRotation(DirectX::XMVectorSet(-1,0,0,0));
		dirLight->SetColor(YumeColor(1,1,1,0));

		scene->AddNode(dirLight);
	}

	void HelloWorld::MoveCamera(float timeStep)
	{

	}

	void HelloWorld::HandleUpdate(float timeStep)
	{

	}

	void HelloWorld::Setup()
	{
		engineVariants_["GI"] = SVO;
		engineVariants_["WindowWidth"] = 1024;
		engineVariants_["WindowHeight"] = 768;

		BaseApplication::Setup();
	}
}

max_stars_repo_name: rodrigobmg/YumeEngine

max_issues_repo_name: rodrigobmg/YumeEngine

max_forks_repo_name: rodrigobmg/YumeEngine


text:
/* rtb_router_js.cc
   Jeremy Barnes, 5 April 2011
   Copyright (c) 2011 Datacratic.  All rights reserved.

   JS bindings for RTB router.
*/

#include "rtbkit/core/router/router_stack.h"
#include "rtb_js.h"
#include "auction_js.h"
#include "banker_js.h"
#include "v8.h"
#include "node.h"
#include "soa/js/js_value.h"
#include "soa/js/js_utils.h"
#include "soa/js/js_wrapped.h"
#include "soa/js/js_call.h"
#include "soa/js/js_registry.h"
#include "jml/arch/timers.h"
#include "soa/sigslot/slot.h"
#include "jml/utils/guard.h"
#include <boost/make_shared.hpp>
#include "rtbkit/plugins/bidding_agent/bidding_agent.h"
#include "node/uv.h"
#include "soa/types/js/id_js.h"
#include "bid_request_js.h"
#include "currency_js.h"

using namespace std;
using namespace v8;
using namespace node;
using namespace ML;
using namespace RTBKIT;

namespace Datacratic {
namespace JS {

extern Registry registry;

/*****************************************************************************/
/* RTB ROUTER JS                                                             */
/*****************************************************************************/

/** A combination of enough of a router to run a simulation:
    - Router
    - Post auction service
    - Banker
*/

const char * RTBRouterStackName = "Router";

struct RTBRouterStackJS
    : public JSWrapped2<RTBKIT::RouterStack, RTBRouterStackJS, RTBRouterStackName,
                        rtbModule, false> {

    RTBRouterStackJS(const v8::Handle<v8::Object> & This,
                      const std::shared_ptr<RTBKIT::RouterStack> & router
                          = std::shared_ptr<RTBKIT::RouterStack>())
    {
        wrap(This, router);
    }

    static Handle<v8::Value>
    New(const Arguments & args)
    {
        try {
            new RTBRouterStackJS
                (args.This(),
                 std::shared_ptr<RTBKIT::RouterStack>
                 (new RTBKIT::RouterStack(std::make_shared<ServiceProxies>(),
                                  getArg(args, 2, "router", "routerName"),
                                  getArg(args, 0, 2.0,
                                         "secondsUntilLossAssumed"))));
            return args.This();
        } HANDLE_JS_EXCEPTIONS;
    }

    static void Initialize()
    {
        Persistent<FunctionTemplate> t = Register(New);

        // Instance methods
        //NODE_SET_PROTOTYPE_METHOD(t, "initEndpoints", initEndpoints);
        NODE_SET_PROTOTYPE_METHOD(t, "createProxy", createProxy);
        NODE_SET_PROTOTYPE_METHOD(t, "bindAgents", bindAgents);
        NODE_SET_PROTOTYPE_METHOD(t, "start", start);
        NODE_SET_PROTOTYPE_METHOD(t, "sleepUntilIdle", sleepUntilIdle);
        NODE_SET_PROTOTYPE_METHOD(t, "shutdown", shutdown);
        NODE_SET_PROTOTYPE_METHOD(t, "injectAuction", injectAuction);
        NODE_SET_PROTOTYPE_METHOD(t, "injectWin", injectWin);
        NODE_SET_PROTOTYPE_METHOD(t, "injectLoss", injectLoss);
        NODE_SET_PROTOTYPE_METHOD(t, "injectCampaignEvent", injectCampaignEvent);
        NODE_SET_PROTOTYPE_METHOD(t, "numAuctionsInProgress",
                                  numAuctionsInProgress);
        NODE_SET_PROTOTYPE_METHOD(t, "getStats", getStats);

#if 0

        t->InstanceTemplate()
            ->SetAccessor(String::NewSymbol("banker"),
                          bankerGetter, bankerSetter);
#endif

#if 0
        registerRWPropertyGetterSetter(&RTBKIT::RouterStack::getBanker,
                                       &RTBKIT::RouterStack::setBanker,
                                       "banker", v8::DontDelete);
#endif
        registerMemberFn(&RTBKIT::RouterStack::notifyFinishedAuction,
                         "notifyFinishedAuction");
        registerMemberFn(&RTBKIT::RouterStack::init, "init");
    }

#if 0
    static Handle<v8::Value>
    initEndpoints(const Arguments & args)
    {
        try {
            getShared(args)
                ->initEndpoints(getArg(args, 0, -1, "bidPort"),
                                //getArg(args, 1, -1, "backchannelPort"),
                                getArg(args, 2, "localhost", "hostname"),
                                getArg(args, 3,  1, "nThreads"));
            return args.This();
        } HANDLE_JS_EXCEPTIONS;
    }
#endif

    static Handle<v8::Value>
    createProxy(const Arguments & args)
    {
        try {

            return JS::toJS
                (std::make_shared<RTBKIT::BiddingAgent>
                 (getShared(args)->getServices(), "bidding_agent"));
        } HANDLE_JS_EXCEPTIONS;
    }

    static Handle<v8::Value>
    bindAgents(const Arguments & args)
    {
        try {
            getShared(args)
                ->router.bindAgents(getArg(args, 0, "agentsUri"));
            return args.This();
        } HANDLE_JS_EXCEPTIONS;
    }

    static Handle<v8::Value>
    start(const Arguments & args)
    {
        try {
            // Make sure Node doesn't exit and we don't get GCd when the
            // event loop is running.

            ev_ref(ev_default_loop());
            v8::Persistent<v8::Object> phandle
                = v8::Persistent<v8::Object>::New(args.This());

            auto cleanup = [=] ()
                {
                    //cerr << "calling cleanup" << endl;

                    v8::Persistent<v8::Object> handle = phandle;
                    ev_unref(ev_default_loop());

                    //cerr << "done loop unref" << endl;
                    //cerr << "depth " << ev_depth(loop) << endl;
                    //cerr << "iter " << ev_iteration(loop) << endl;
                    //cerr << "watching " << ev_pending_count(loop) << endl;
                    //ev_break(loop, EVBREAK_ONE);

                    handle.Clear();
                    handle.Dispose();

                };

            getShared(args)->start(cleanup);

            // TODO: add something to node to stop it from returning?

            return args.This();
        } HANDLE_JS_EXCEPTIONS;
    }

    static Handle<v8::Value>
    shutdown(const Arguments & args)
    {
        try {
            getShared(args)->shutdown();
            //cerr << "finished shutdown" << endl;
            return args.This();
        } HANDLE_JS_EXCEPTIONS;
    }

    static Handle<v8::Value>
    sleepUntilIdle(const Arguments & args)
    {
        try {
            getShared(args)->sleepUntilIdle();
            //cerr << "finished shutdown" << endl;
            return args.This();
        } HANDLE_JS_EXCEPTIONS;
    }

    struct CallbackData {
        Slot onAuctionFinished;
        std::shared_ptr<Auction> auction;
        v8::Persistent<v8::Object> This;

        ~CallbackData()
        {
            if (!This.IsEmpty()) {
                This.Dispose();
                This.Clear();
            }
        }
    };

    static void doNothing(eio_req * req)
    {
        // TODO: don't do this; find how to use libeio properly
    }

    static int finishedCallback(eio_req * req)
    {
        HandleScope scope;

        auto_ptr<CallbackData> data((CallbackData *)req->data);

        TryCatch try_catch;

        try {
            const int argc = 1;
            v8::Handle<v8::Value> argv[argc] = { JS::toJS(data->auction) };
            data->onAuctionFinished.call(data->This, argc, argv);
        } catch (const JSPassException & exc) {
            // Corner case... but probably shouldn't happen
        } catch (...) {
            v8::Handle<v8::Value> result = translateCurrentException();
            v8::ThrowException(result);
        }

        if (try_catch.HasCaught())
            FatalException(try_catch);

        return 0;
    }

    static Handle<v8::Value>
    injectAuction(const Arguments & args)
    {
        try {
            Slot onAuctionFinished = getArg(args, 0, "onAuctionFinished");
            double startTime       = getArg(args, 2,
                                            Date::now().secondsSinceEpoch(),
                                            "startTime");
            double expiryTime      = getArg(args, 3, startTime + 0.03,
                                            "expiryTime");
            double lossTime        = getArg(args, 4,
                                            Date::positiveInfinity()
                                                .secondsSinceEpoch(),
                                            "lossTime");

            std::shared_ptr<BidRequest> request;
            std::string requestStr;

            v8::Handle<v8::Value> requestArg = args[1];
            std::string requestFormat;
            if (requestArg->IsString()) {
                requestStr = getArg<string>(args, 1, "requestStr");
                requestFormat = getArg<string>(args, 5, "datacratic",
                                               "requestFormat");
                request.reset(BidRequest::parse(requestFormat, requestStr));
            }
            else if (request = getBidRequestSharedPointer(requestArg)) {
                requestStr = request->toJsonStr();
                requestFormat = "datacratic";
            }
            else throw ML::Exception("don't know how to turn " + cstr(requestArg)
                                     + " into a bidRequest for injectAuction");

            CallbackData * data = new CallbackData();
            Call_Guard deleteDataGuard([&] () { delete data; });

            data->onAuctionFinished = onAuctionFinished;
            data->This = v8::Persistent<v8::Object>::New(args.This());

            /* Create an asynchronous, libeioified wrapper that will call
               back to the JS callback from the correct callback thread.
            */
            auto onAuctionFinished2 = [=] (std::shared_ptr<Auction> auction)
                {
                    data->auction = auction;

                    eio_custom(doNothing, EIO_PRI_DEFAULT, finishedCallback,
                               data);

                    return true;
                };

            getShared(args)
                ->router.injectAuction(onAuctionFinished2,
                                       request, requestStr, requestFormat,
                                       startTime, expiryTime, lossTime);

            deleteDataGuard.clear();

            return args.This();
        } HANDLE_JS_EXCEPTIONS;
    }

    static Handle<v8::Value>
    injectWin(const Arguments & args)
    {
        try {
            Id auctionId = getArg(args, 0, "auctionId");
            Id adSpot = getArg(args, 1, "adspot");
            Amount winAmount = getArg(args, 2, "winPrice");
            Date timestamp
                = Date::fromSecondsSinceEpoch
                    (getArg<double>(args, 3, "timestamp"));
            Json::Value meta = getArg(args, 4, Json::Value(), "meta");
            UserIds uids = getArg(args, 5, UserIds(), "userIds");
            AccountKey account = getArg(args, 6, AccountKey(), "account");
            Date bidTimestamp
                = Date::fromSecondsSinceEpoch
                    (getArg<double>(args, 7, -1, "bidTimestamp"));
            getShared(args)->injectWin(auctionId, adSpot, winAmount,
                                       timestamp, meta, uids,
                                       account, bidTimestamp);
            return args.This();
        } HANDLE_JS_EXCEPTIONS;
    }

    static Handle<v8::Value>
    injectLoss(const Arguments & args)
    {
        try {
            Id auctionId = getArg(args, 0, "auctionId");
            Id adSpot = getArg(args, 1, "adspot");
            Date timestamp
                = Date::fromSecondsSinceEpoch
                    (getArg<double>(args, 2, "timestamp"));
            Json::Value meta = getArg(args, 3, Json::Value(), "meta");
            AccountKey account = getArg(args, 4, AccountKey(), "account");
            Date bidTimestamp
                = Date::fromSecondsSinceEpoch
                    (getArg<double>(args, 5, -1, "bidTimestamp"));
            getShared(args)->injectLoss(auctionId, adSpot, timestamp,
                                        meta, account, bidTimestamp);
            return args.This();
        } HANDLE_JS_EXCEPTIONS;
    }

    static Handle<v8::Value>
    injectCampaignEvent(const Arguments & args)
    {
        try {
            string label = getArg(args, 0, "label");
            Id auctionId = getArg(args, 1, "auctionId");
            Id adSpot = getArg(args, 2, "adspot");
            Date timestamp
                = Date::fromSecondsSinceEpoch
                    (getArg<double>(args, 3, "timestamp"));
            Json::Value meta = getArg(args, 4, Json::Value(), "meta");
            UserIds uids = getArg(args, 5, UserIds(), "userIds");
            getShared(args)->injectCampaignEvent(label, auctionId, adSpot,
                                                 timestamp, meta, uids);
            return args.This();
        } HANDLE_JS_EXCEPTIONS;
    }

    static Handle<v8::Value>
    numAuctionsInProgress(const Arguments & args)
    {
        try {
            return JS::toJS(getShared(args)->numAuctionsInProgress());
        } HANDLE_JS_EXCEPTIONS;
    }

    static Handle<v8::Value>
    getStats(const Arguments & args)
    {
        try {
            return JS::toJS(getShared(args)->getStats());
        } HANDLE_JS_EXCEPTIONS;
    }

#if 0
    static Handle<v8::Value>
    addBudget(const Arguments & args)
    {
        try {
            return JS::toJS(getShared(args)
                            ->addBudget(getArg(args, 0, "account"),
                                        getArg(args, 1, "amount")));
        } HANDLE_JS_EXCEPTIONS;
    }

    static Handle<v8::Value>
    setBudget(const Arguments & args)
    {
        try {
            return JS::toJS(getShared(args)
                            ->setBudget(getArg(args, 0, "account"),
                                        getArg(args, 1, "amount")));
        } HANDLE_JS_EXCEPTIONS;
    }
#endif

#if 0
    static v8::Handle<v8::Value>
    bankerGetter(v8::Local<v8::String> property,
                 const AccessorInfo & info)
    {
        try {
            return JS::toJS(getShared(info.This())->getBanker());
        } HANDLE_JS_EXCEPTIONS;
    }

    static void
    bankerSetter(v8::Local<v8::String> property,
                 v8::Local<v8::Value> value,
                 const AccessorInfo & info)
    {
        try {
            getShared(info.This())->setBanker(JS::fromJS(value));
        } HANDLE_JS_EXCEPTIONS_SETTER;
    }
#endif

};

RegisterJsOps<void (std::shared_ptr<Auction>)> reg_handleAuction;

} // namespace JS
} // namespace Datacratic

max_stars_repo_name: etnrlz/rtbkit

max_issues_repo_name: TuanTranEngineer/rtbkit

max_forks_repo_name: TuanTranEngineer/rtbkit


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
 *************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#include <hintids.hxx>
#include <poolfmt.hxx>
#include "unomid.h"

#include <basic/sbxvar.hxx>
#include <svl/macitem.hxx>
#include <svl/stritem.hxx>
#include <svl/stylepool.hxx>
#include <fmtautofmt.hxx>
#include <fchrfmt.hxx>
#include <fmtinfmt.hxx>
#include <txtatr.hxx>
#include <fmtruby.hxx>
#include <charfmt.hxx>
#include <hints.hxx>        // SwUpdateAttr
#include <unostyle.hxx>
#include <unoevent.hxx>		// SwHyperlinkEventDescriptor
#include <com/sun/star/text/RubyAdjust.hdl>

#include <cmdid.h>
#include <com/sun/star/uno/Any.h>
#include <SwStyleNameMapper.hxx>

#include <fmtmeta.hxx>
#include <ndtxt.hxx> // for meta
#include <doc.hxx> // for meta
#include <unometa.hxx>
#include <docsh.hxx>
#include <svl/zforlist.hxx> // GetNumberFormat

#include <boost/bind.hpp>
#include <algorithm>

using namespace ::com::sun::star;
using ::rtl::OUString;

TYPEINIT1_AUTOFACTORY(SwFmtINetFmt, SfxPoolItem);
TYPEINIT1_AUTOFACTORY(SwFmtAutoFmt, SfxPoolItem);

/*************************************************************************
|*
|*    class SwFmtCharFmt
|*    Beschreibung
|*    Ersterstellung    JP 23.11.90
|*    Letzte Aenderung  JP 09.08.94
|*
*************************************************************************/

SwFmtCharFmt::SwFmtCharFmt( SwCharFmt *pFmt )
	: SfxPoolItem( RES_TXTATR_CHARFMT ),
	SwClient(pFmt),
    pTxtAttr( 0 )
{
}

SwFmtCharFmt::SwFmtCharFmt( const SwFmtCharFmt& rAttr )
	: SfxPoolItem( RES_TXTATR_CHARFMT ),
	SwClient( rAttr.GetCharFmt() ),
    pTxtAttr( 0 )
{
}

SwFmtCharFmt::~SwFmtCharFmt() {}

int SwFmtCharFmt::operator==( const SfxPoolItem& rAttr ) const
{
	ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" );
	return GetCharFmt() == ((SwFmtCharFmt&)rAttr).GetCharFmt();
}

SfxPoolItem* SwFmtCharFmt::Clone( SfxItemPool* ) const
{
	return new SwFmtCharFmt( *this );
}

// weiterleiten an das TextAttribut
void SwFmtCharFmt::Modify( const SfxPoolItem* pOld, const SfxPoolItem* pNew )
{
	if( pTxtAttr )
		pTxtAttr->ModifyNotification( pOld, pNew );
}

// weiterleiten an das TextAttribut
sal_Bool SwFmtCharFmt::GetInfo( SfxPoolItem& rInfo ) const
{
	return pTxtAttr ? pTxtAttr->GetInfo( rInfo ) : sal_False;
}
sal_Bool SwFmtCharFmt::QueryValue( uno::Any& rVal, sal_uInt8 ) const
{
	String sCharFmtName;
	if(GetCharFmt())
		SwStyleNameMapper::FillProgName(GetCharFmt()->GetName(), sCharFmtName,  nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True );
	rVal <<= OUString( sCharFmtName );
	return sal_True;
}
sal_Bool SwFmtCharFmt::PutValue( const uno::Any& , sal_uInt8   )
{
	DBG_ERROR("Zeichenvorlage kann mit PutValue nicht gesetzt werden!");
	return sal_False;
}

/*************************************************************************
|*
|*    class SwFmtAutoFmt
|*    Beschreibung
|*    Ersterstellung    AMA 12.05.06
|*    Letzte Aenderung  AMA 12.05.06
|*
*************************************************************************/

SwFmtAutoFmt::SwFmtAutoFmt( sal_uInt16 nInitWhich )
    : SfxPoolItem( nInitWhich )
{
}

SwFmtAutoFmt::SwFmtAutoFmt( const SwFmtAutoFmt& rAttr )
    : SfxPoolItem( rAttr.Which() ), mpHandle( rAttr.mpHandle )
{
}

SwFmtAutoFmt::~SwFmtAutoFmt()
{
}

int SwFmtAutoFmt::operator==( const SfxPoolItem& rAttr ) const
{
	ASSERT( SfxPoolItem::operator==( rAttr ), "different attributes" );
    return mpHandle == ((SwFmtAutoFmt&)rAttr).mpHandle;
}

SfxPoolItem* SwFmtAutoFmt::Clone( SfxItemPool* ) const
{
	return new SwFmtAutoFmt( *this );
}

sal_Bool SwFmtAutoFmt::QueryValue( uno::Any& rVal, sal_uInt8 ) const
{
	String sCharFmtName = StylePool::nameOf( mpHandle );
	rVal <<= OUString( sCharFmtName );
	return sal_True;
}

sal_Bool SwFmtAutoFmt::PutValue( const uno::Any& , sal_uInt8 )
{
    //the format is not renameable via API
	return sal_False;
}

/*************************************************************************
|*
|*    class SwFmtINetFmt
|*    Beschreibung
|*    Ersterstellung    AMA 02.08.96
|*    Letzte Aenderung  AMA 02.08.96
|*
*************************************************************************/

SwFmtINetFmt::SwFmtINetFmt()
	: SfxPoolItem( RES_TXTATR_INETFMT )
    , msURL()
    , msTargetFrame()
    , msINetFmtName()
    , msVisitedFmtName()
    , msHyperlinkName()
    , mpMacroTbl( 0 )
    , mpTxtAttr( 0 )
    , mnINetFmtId( 0 )
    , mnVisitedFmtId( 0 )
{}

SwFmtINetFmt::SwFmtINetFmt( const XubString& rURL, const XubString& rTarget )
    : SfxPoolItem( RES_TXTATR_INETFMT )
    , msURL( rURL )
    , msTargetFrame( rTarget )
    , msINetFmtName()
    , msVisitedFmtName()
    , msHyperlinkName()
    , mpMacroTbl( 0 )
    , mpTxtAttr( 0 )
    , mnINetFmtId( RES_POOLCHR_INET_NORMAL )
    , mnVisitedFmtId( RES_POOLCHR_INET_VISIT )
{
    SwStyleNameMapper::FillUIName( mnINetFmtId, msINetFmtName );
    SwStyleNameMapper::FillUIName( mnVisitedFmtId, msVisitedFmtName );
}

SwFmtINetFmt::SwFmtINetFmt( const SwFmtINetFmt& rAttr )
	: SfxPoolItem( RES_TXTATR_INETFMT )
    , msURL( rAttr.GetValue() )
    , msTargetFrame( rAttr.msTargetFrame )
    , msINetFmtName( rAttr.msINetFmtName )
    , msVisitedFmtName( rAttr.msVisitedFmtName )
    , msHyperlinkName( rAttr.msHyperlinkName )
    , mpMacroTbl( 0 )
    , mpTxtAttr( 0 )
    , mnINetFmtId( rAttr.mnINetFmtId )
    , mnVisitedFmtId( rAttr.mnVisitedFmtId )
{
    if ( rAttr.GetMacroTbl() )
        mpMacroTbl = new SvxMacroTableDtor( *rAttr.GetMacroTbl() );
}

SwFmtINetFmt::~SwFmtINetFmt()
{
	delete mpMacroTbl;
}

int SwFmtINetFmt::operator==( const SfxPoolItem& rAttr ) const
{
	ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" );
	sal_Bool bRet = SfxPoolItem::operator==( (SfxPoolItem&) rAttr )
				&& msURL == ((SwFmtINetFmt&)rAttr).msURL
				&& msHyperlinkName == ((SwFmtINetFmt&)rAttr).msHyperlinkName
				&& msTargetFrame == ((SwFmtINetFmt&)rAttr).msTargetFrame
				&& msINetFmtName == ((SwFmtINetFmt&)rAttr).msINetFmtName
				&& msVisitedFmtName == ((SwFmtINetFmt&)rAttr).msVisitedFmtName
				&& mnINetFmtId == ((SwFmtINetFmt&)rAttr).mnINetFmtId
				&& mnVisitedFmtId == ((SwFmtINetFmt&)rAttr).mnVisitedFmtId;

	if( !bRet )
		return sal_False;

	const SvxMacroTableDtor* pOther = ((SwFmtINetFmt&)rAttr).mpMacroTbl;
	if( !mpMacroTbl )
		return ( !pOther || !pOther->Count() );
	if( !pOther )
		return 0 == mpMacroTbl->Count();

	const SvxMacroTableDtor& rOwn = *mpMacroTbl;
	const SvxMacroTableDtor& rOther = *pOther;

	// Anzahl unterschiedlich => auf jeden Fall ungleich
	if( rOwn.Count() != rOther.Count() )
		return sal_False;

	// einzeln vergleichen; wegen Performance ist die Reihenfolge wichtig
	for( sal_uInt16 nNo = 0; nNo < rOwn.Count(); ++nNo )
	{
		const SvxMacro *pOwnMac = rOwn.GetObject(nNo);
		const SvxMacro *pOtherMac = rOther.GetObject(nNo);
		if ( 	rOwn.GetKey(pOwnMac) != rOther.GetKey(pOtherMac)  ||
				pOwnMac->GetLibName() != pOtherMac->GetLibName() ||
				pOwnMac->GetMacName() != pOtherMac->GetMacName() )
			return sal_False;
	}
	return sal_True;
}

SfxPoolItem* SwFmtINetFmt::Clone( SfxItemPool* ) const
{
	return new SwFmtINetFmt( *this );
}

void SwFmtINetFmt::SetMacroTbl( const SvxMacroTableDtor* pNewTbl )
{
	if( pNewTbl )
	{
		if( mpMacroTbl )
			*mpMacroTbl = *pNewTbl;
		else
			mpMacroTbl = new SvxMacroTableDtor( *pNewTbl );
	}
	else if( mpMacroTbl )
		delete mpMacroTbl, mpMacroTbl = 0;
}

void SwFmtINetFmt::SetMacro( sal_uInt16 nEvent, const SvxMacro& rMacro )
{
	if( !mpMacroTbl )
		mpMacroTbl = new SvxMacroTableDtor;

	SvxMacro *pOldMacro;
	if( 0 != ( pOldMacro = mpMacroTbl->Get( nEvent )) )
	{
		delete pOldMacro;
		mpMacroTbl->Replace( nEvent, new SvxMacro( rMacro ) );
	}
	else
		mpMacroTbl->Insert( nEvent, new SvxMacro( rMacro ) );
}

const SvxMacro* SwFmtINetFmt::GetMacro( sal_uInt16 nEvent ) const
{
	const SvxMacro* pRet = 0;
	if( mpMacroTbl && mpMacroTbl->IsKeyValid( nEvent ) )
		pRet = mpMacroTbl->Get( nEvent );
	return pRet;
}

sal_Bool SwFmtINetFmt::QueryValue( uno::Any& rVal, sal_uInt8 nMemberId ) const
{
	sal_Bool bRet = sal_True;
	XubString sVal;
    nMemberId &= ~CONVERT_TWIPS;
	switch(nMemberId)
	{
		case MID_URL_URL:
			sVal = msURL;
		break;
		case MID_URL_TARGET:
			sVal = msTargetFrame;
		break;
		case MID_URL_HYPERLINKNAME:
			sVal = msHyperlinkName;
		break;
		case MID_URL_VISITED_FMT:
			sVal = msVisitedFmtName;
			if( !sVal.Len() && mnVisitedFmtId != 0 )
				SwStyleNameMapper::FillUIName( mnVisitedFmtId, sVal );
			if( sVal.Len() )
				SwStyleNameMapper::FillProgName( sVal, sVal, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True );
		break;
		case MID_URL_UNVISITED_FMT:
			sVal = msINetFmtName;
			if( !sVal.Len() && mnINetFmtId != 0 )
				SwStyleNameMapper::FillUIName( mnINetFmtId, sVal );
			if( sVal.Len() )
				SwStyleNameMapper::FillProgName( sVal, sVal, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True );
		break;
		case MID_URL_HYPERLINKEVENTS:
		{
			// create (and return) event descriptor
			SwHyperlinkEventDescriptor* pEvents =
				new SwHyperlinkEventDescriptor();
			pEvents->copyMacrosFromINetFmt(*this);
			uno::Reference<container::XNameReplace> xNameReplace(pEvents);

			// all others return a string; so we just set rVal here and exit
			rVal <<= xNameReplace;
			return bRet;
		}
        default:
        break;
	}
	rVal <<= OUString(sVal);
	return bRet;
}
sal_Bool SwFmtINetFmt::PutValue( const uno::Any& rVal, sal_uInt8 nMemberId  )
{
	sal_Bool bRet = sal_True;
    nMemberId &= ~CONVERT_TWIPS;

	// all properties except HyperlinkEvents are of type string, hence
	// we treat HyperlinkEvents specially
	if (MID_URL_HYPERLINKEVENTS == nMemberId)
	{
		uno::Reference<container::XNameReplace> xReplace;
		rVal >>= xReplace;
		if (xReplace.is())
		{
			// Create hyperlink event descriptor. Then copy events
			// from argument into descriptor. Then copy events from
			// the descriptor into the format.
			SwHyperlinkEventDescriptor* pEvents = new SwHyperlinkEventDescriptor();
            uno::Reference< lang::XServiceInfo> xHold = pEvents;
			pEvents->copyMacrosFromNameReplace(xReplace);
			pEvents->copyMacrosIntoINetFmt(*this);
		}
		else
		{
			// wrong type!
			bRet = sal_False;
		}
	}
	else
	{
		// all string properties:
		if(rVal.getValueType() != ::getCppuType((rtl::OUString*)0))
			return sal_False;
		XubString sVal = *(rtl::OUString*)rVal.getValue();
		switch(nMemberId)
		{
			case MID_URL_URL:
				msURL = sVal;
				break;
			case MID_URL_TARGET:
				msTargetFrame = sVal;
				break;
			case MID_URL_HYPERLINKNAME:
				msHyperlinkName = sVal;
				break;
			case MID_URL_VISITED_FMT:
			{
				String aString;
				SwStyleNameMapper::FillUIName( sVal, aString, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True );
				msVisitedFmtName = OUString ( aString );
				mnVisitedFmtId = SwStyleNameMapper::GetPoolIdFromUIName( msVisitedFmtName,
											   nsSwGetPoolIdFromName::GET_POOLID_CHRFMT );
			}
			break;
			case MID_URL_UNVISITED_FMT:
			{
				String aString;
				SwStyleNameMapper::FillUIName( sVal, aString, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True );
				msINetFmtName = OUString ( aString );
				mnINetFmtId = SwStyleNameMapper::GetPoolIdFromUIName( msINetFmtName,	nsSwGetPoolIdFromName::GET_POOLID_CHRFMT );
			}
			break;
			default:
				bRet = sal_False;
		}
	}
	return bRet;
}

/*************************************************************************
|*    class SwFmtRuby
*************************************************************************/

SwFmtRuby::SwFmtRuby( const String& rRubyTxt )
	: SfxPoolItem( RES_TXTATR_CJK_RUBY ),
	sRubyTxt( rRubyTxt ),
    pTxtAttr( 0 ),
    nCharFmtId( 0 ),
    nPosition( 0 ),
    nAdjustment( 0 )
{
}

SwFmtRuby::SwFmtRuby( const SwFmtRuby& rAttr )
	: SfxPoolItem( RES_TXTATR_CJK_RUBY ),
	sRubyTxt( rAttr.sRubyTxt ),
	sCharFmtName( rAttr.sCharFmtName ),
    pTxtAttr( 0 ),
    nCharFmtId( rAttr.nCharFmtId),
    nPosition( rAttr.nPosition ),
    nAdjustment( rAttr.nAdjustment )
{
}

SwFmtRuby::~SwFmtRuby()
{
}

SwFmtRuby& SwFmtRuby::operator=( const SwFmtRuby& rAttr )
{
	sRubyTxt = rAttr.sRubyTxt;
	sCharFmtName = rAttr.sCharFmtName;
	nCharFmtId = rAttr.nCharFmtId;
	nPosition = rAttr.nPosition;
	nAdjustment = rAttr.nAdjustment;
	pTxtAttr =  0;
	return *this;
}

int SwFmtRuby::operator==( const SfxPoolItem& rAttr ) const
{
	ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" );
	return sRubyTxt == ((SwFmtRuby&)rAttr).sRubyTxt &&
		   sCharFmtName == ((SwFmtRuby&)rAttr).sCharFmtName &&
		   nCharFmtId == ((SwFmtRuby&)rAttr).nCharFmtId &&
		   nPosition == ((SwFmtRuby&)rAttr).nPosition &&
		   nAdjustment == ((SwFmtRuby&)rAttr).nAdjustment;
}

SfxPoolItem* SwFmtRuby::Clone( SfxItemPool* ) const
{
	return new SwFmtRuby( *this );
}

sal_Bool SwFmtRuby::QueryValue( uno::Any& rVal,
							sal_uInt8 nMemberId ) const
{
	sal_Bool bRet = sal_True;
    nMemberId &= ~CONVERT_TWIPS;
	switch( nMemberId )
	{
		case MID_RUBY_TEXT: rVal <<= (OUString)sRubyTxt; 					break;
 		case MID_RUBY_ADJUST:	rVal <<= (sal_Int16)nAdjustment;	break;
		case MID_RUBY_CHARSTYLE:
		{
			String aString;
			SwStyleNameMapper::FillProgName(sCharFmtName, aString, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT, sal_True );
			rVal <<= OUString ( aString );
		}
		break;
        case MID_RUBY_ABOVE:
        {
            sal_Bool bAbove = !nPosition;
            rVal.setValue(&bAbove, ::getBooleanCppuType());
        }
        break;
        default:
			bRet = sal_False;
	}
	return bRet;
}
sal_Bool SwFmtRuby::PutValue( const uno::Any& rVal,
							sal_uInt8 nMemberId  )
{
	sal_Bool bRet = sal_True;
    nMemberId &= ~CONVERT_TWIPS;
	switch( nMemberId )
	{
		case MID_RUBY_TEXT:
		{
			OUString sTmp;
			bRet = rVal >>= sTmp;
			sRubyTxt = sTmp;
		}
		break;
 		case MID_RUBY_ADJUST:
		{
			sal_Int16 nSet = 0;
			rVal >>= nSet;
            if(nSet >= 0 && nSet <= text::RubyAdjust_INDENT_BLOCK)
				nAdjustment = nSet;
			else
				bRet = sal_False;
		}
		break;
        case MID_RUBY_ABOVE:
        {
            const uno::Type& rType = ::getBooleanCppuType();
            if(rVal.hasValue() && rVal.getValueType() == rType)
            {
                sal_Bool bAbove = *(sal_Bool*)rVal.getValue();
                nPosition = bAbove ? 0 : 1;
            }
        }
        break;
        case MID_RUBY_CHARSTYLE:
        {
            OUString sTmp;
            bRet = rVal >>= sTmp;
            if(bRet)
                sCharFmtName = SwStyleNameMapper::GetUIName(sTmp, nsSwGetPoolIdFromName::GET_POOLID_CHRFMT );
        }
        break;
		default:
			bRet = sal_False;
	}
	return bRet;
}

/*************************************************************************
 class SwFmtMeta
 ************************************************************************/

SwFmtMeta * SwFmtMeta::CreatePoolDefault(const sal_uInt16 i_nWhich)
{
    return new SwFmtMeta(i_nWhich);
}

SwFmtMeta::SwFmtMeta(const sal_uInt16 i_nWhich)
    : SfxPoolItem( i_nWhich )
    , m_pMeta()
    , m_pTxtAttr( 0 )
{
    ASSERT((RES_TXTATR_META == i_nWhich) || (RES_TXTATR_METAFIELD == i_nWhich),
            "ERROR: SwFmtMeta: invalid which id!");
}

SwFmtMeta::SwFmtMeta( ::boost::shared_ptr< ::sw::Meta > const & i_pMeta,
                        const sal_uInt16 i_nWhich )
    : SfxPoolItem( i_nWhich )
    , m_pMeta( i_pMeta )
    , m_pTxtAttr( 0 )
{
    ASSERT((RES_TXTATR_META == i_nWhich) || (RES_TXTATR_METAFIELD == i_nWhich),
            "ERROR: SwFmtMeta: invalid which id!");
    ASSERT(m_pMeta, "SwFmtMeta: no Meta ?");
    // DO NOT call m_pMeta->SetFmtMeta(this) here; only from SetTxtAttr!
}

SwFmtMeta::~SwFmtMeta()
{
    if (m_pMeta && (m_pMeta->GetFmtMeta() == this))
    {
        NotifyChangeTxtNode(0);
        m_pMeta->SetFmtMeta(0);
    }
}

int SwFmtMeta::operator==( const SfxPoolItem & i_rOther ) const
{
    ASSERT( SfxPoolItem::operator==( i_rOther ), "i just copied this assert" );
    return SfxPoolItem::operator==( i_rOther )
        && (m_pMeta == static_cast<SwFmtMeta const &>( i_rOther ).m_pMeta);
}

SfxPoolItem * SwFmtMeta::Clone( SfxItemPool * /*pPool*/ ) const
{
    // if this is indeed a copy, then DoCopy must be called later!
    return (m_pMeta) // #i105148# pool default may be cloned also!
        ? new SwFmtMeta( m_pMeta, Which() ) : new SwFmtMeta( Which() );
}

void SwFmtMeta::SetTxtAttr(SwTxtMeta * const i_pTxtAttr)
{
    OSL_ENSURE(!(m_pTxtAttr && i_pTxtAttr),
        "SwFmtMeta::SetTxtAttr: already has text attribute?");
    OSL_ENSURE(  m_pTxtAttr || i_pTxtAttr ,
        "SwFmtMeta::SetTxtAttr: no attribute to remove?");
    m_pTxtAttr = i_pTxtAttr;
    OSL_ENSURE(m_pMeta, "inserted SwFmtMeta has no sw::Meta?");
    // the sw::Meta must be able to find the current text attribute!
    if (m_pMeta)
    {
        if (i_pTxtAttr)
        {
            m_pMeta->SetFmtMeta(this);
        }
        else if (m_pMeta->GetFmtMeta() == this)
        {   // text attribute gone => de-register from text node!
            NotifyChangeTxtNode(0);
            m_pMeta->SetFmtMeta(0);
        }
    }
}

void SwFmtMeta::NotifyChangeTxtNode(SwTxtNode *const pTxtNode)
{
    // N.B.: do not reset m_pTxtAttr here: see call in nodes.cxx,
    // where the hint is not deleted!
    OSL_ENSURE(m_pMeta, "SwFmtMeta::NotifyChangeTxtNode: no Meta?");
    if (m_pMeta && (m_pMeta->GetFmtMeta() == this))
    {   // do not call Modify, that would call SwXMeta::Modify!
        m_pMeta->NotifyChangeTxtNode(pTxtNode);
    }
}

// this SwFmtMeta has been cloned and points at the same sw::Meta as the source
// this method copies the sw::Meta
void SwFmtMeta::DoCopy(::sw::MetaFieldManager & i_rTargetDocManager,
        SwTxtNode & i_rTargetTxtNode)
{
    OSL_ENSURE(m_pMeta, "DoCopy called for SwFmtMeta with no sw::Meta?");
    if (m_pMeta)
    {
        const ::boost::shared_ptr< ::sw::Meta> pOriginal( m_pMeta );
        if (RES_TXTATR_META == Which())
        {
            m_pMeta.reset( new ::sw::Meta(this) );
        }
        else
        {
            ::sw::MetaField *const pMetaField(
                static_cast< ::sw::MetaField* >(pOriginal.get()));
            m_pMeta = i_rTargetDocManager.makeMetaField( this,
                pMetaField->m_nNumberFormat, pMetaField->IsFixedLanguage() );
        }
        // Meta must have a text node before calling RegisterAsCopyOf
        m_pMeta->NotifyChangeTxtNode(& i_rTargetTxtNode);
        // this cannot be done in Clone: a Clone is not necessarily a copy!
        m_pMeta->RegisterAsCopyOf(*pOriginal);
    }
}

namespace sw {

/*************************************************************************
 class sw::Meta
 ************************************************************************/

Meta::Meta(SwFmtMeta * const i_pFmt)
    : ::sfx2::Metadatable()
    , SwModify()
    , m_pFmt( i_pFmt )
{
}

Meta::~Meta()
{
}

SwTxtMeta * Meta::GetTxtAttr() const
{
    return (m_pFmt) ? m_pFmt->GetTxtAttr() : 0;
}

SwTxtNode * Meta::GetTxtNode() const
{
    return m_pTxtNode;
}

void Meta::NotifyChangeTxtNodeImpl()
{
    if (m_pTxtNode && (GetRegisteredIn() != m_pTxtNode))
    {
        m_pTxtNode->Add(this);
    }
    else if (!m_pTxtNode && GetRegisteredIn())
    {
        GetRegisteredInNonConst()->Remove(this);
    }
}

void Meta::NotifyChangeTxtNode(SwTxtNode *const pTxtNode)
{
    m_pTxtNode = pTxtNode;
    NotifyChangeTxtNodeImpl();
    if (!pTxtNode) // text node gone? invalidate UNO object!
    {
        SwPtrMsgPoolItem aMsgHint( RES_REMOVE_UNO_OBJECT,
            &static_cast<SwModify&>(*this) ); // cast to base class!
        this->Modify(&aMsgHint, &aMsgHint);
    }
}

// SwClient
void Meta::Modify( const SfxPoolItem *pOld, const SfxPoolItem *pNew )
{
    NotifyClients(pOld, pNew);
    if (pOld && (RES_REMOVE_UNO_OBJECT == pOld->Which()))
    {   // invalidate cached uno object
        SetXMeta(uno::Reference<rdf::XMetadatable>(0));
    }
}

// sfx2::Metadatable
::sfx2::IXmlIdRegistry& Meta::GetRegistry()
{
    SwTxtNode * const pTxtNode( GetTxtNode() );
    // GetRegistry may only be called on a meta that is actually in the
    // document, which means it has a pointer to its text node
    OSL_ENSURE(pTxtNode, "ERROR: GetRegistry: no text node?");
    if (!pTxtNode)
        throw uno::RuntimeException();
    return pTxtNode->GetRegistry();
}

bool Meta::IsInClipboard() const
{
    const SwTxtNode * const pTxtNode( GetTxtNode() );
// no text node: in UNDO  OSL_ENSURE(pTxtNode, "IsInClipboard: no text node?");
    return (pTxtNode) ? pTxtNode->IsInClipboard() : false;
}

bool Meta::IsInUndo() const
{
    const SwTxtNode * const pTxtNode( GetTxtNode() );
// no text node: in UNDO  OSL_ENSURE(pTxtNode, "IsInUndo: no text node?");
    return (pTxtNode) ? pTxtNode->IsInUndo() : true;
}

bool Meta::IsInContent() const
{
    const SwTxtNode * const pTxtNode( GetTxtNode() );
    OSL_ENSURE(pTxtNode, "IsInContent: no text node?");
    return (pTxtNode) ? pTxtNode->IsInContent() : true;
}

::com::sun::star::uno::Reference< ::com::sun::star::rdf::XMetadatable >
Meta::MakeUnoObject()
{
    return SwXMeta::CreateXMeta(*this);
}

/*************************************************************************
 class sw::MetaField
 ************************************************************************/

MetaField::MetaField(SwFmtMeta * const i_pFmt,
            const sal_uInt32 nNumberFormat, const bool bIsFixedLanguage)
    : Meta(i_pFmt)
    , m_nNumberFormat( nNumberFormat )
    , m_bIsFixedLanguage( bIsFixedLanguage )
{
}

void MetaField::GetPrefixAndSuffix(
        ::rtl::OUString *const o_pPrefix, ::rtl::OUString *const o_pSuffix)
{
    try
    {
        const uno::Reference<rdf::XMetadatable> xMetaField( MakeUnoObject() );
        OSL_ENSURE(dynamic_cast<SwXMetaField*>(xMetaField.get()),
                "GetPrefixAndSuffix: no SwXMetaField?");
        if (xMetaField.is())
        {
            SwTxtNode * const pTxtNode( GetTxtNode() );
            SwDocShell const * const pShell(pTxtNode->GetDoc()->GetDocShell());
            const uno::Reference<frame::XModel> xModel(
                (pShell) ? pShell->GetModel() : 0,  uno::UNO_SET_THROW);
            getPrefixAndSuffix(xModel, xMetaField, o_pPrefix, o_pSuffix);
        }
    } catch (uno::Exception) {
        OSL_ENSURE(false, "exception?");
    }
}

sal_uInt32 MetaField::GetNumberFormat(::rtl::OUString const & rContent) const
{
    //TODO: this probably lacks treatment for some special cases
    sal_uInt32 nNumberFormat( m_nNumberFormat );
    SwTxtNode * const pTxtNode( GetTxtNode() );
    if (pTxtNode)
    {
        SvNumberFormatter *const pNumberFormatter(
                pTxtNode->GetDoc()->GetNumberFormatter() );
        double number;
        (void) pNumberFormatter->IsNumberFormat(
                rContent, nNumberFormat, number );
    }
    return nNumberFormat;
}

void MetaField::SetNumberFormat(sal_uInt32 nNumberFormat)
{
    // effectively, the member is only a default:
    // GetNumberFormat checks if the text actually conforms
    m_nNumberFormat = nNumberFormat;
}

/*************************************************************************
 class sw::MetaFieldManager
 ************************************************************************/

MetaFieldManager::MetaFieldManager()
{
}

::boost::shared_ptr<MetaField>
MetaFieldManager::makeMetaField(SwFmtMeta * const i_pFmt,
        const sal_uInt32 nNumberFormat, const bool bIsFixedLanguage)
{
    const ::boost::shared_ptr<MetaField> pMetaField(
        new MetaField(i_pFmt, nNumberFormat, bIsFixedLanguage) );
    m_MetaFields.push_back(pMetaField);
    return pMetaField;
}

struct IsInUndo
{
    bool operator()(::boost::weak_ptr<MetaField> const & pMetaField) {
        return pMetaField.lock()->IsInUndo();
    }
};

struct MakeUnoObject
{
    uno::Reference<text::XTextField>
    operator()(::boost::weak_ptr<MetaField> const & pMetaField) {
        return uno::Reference<text::XTextField>(
                pMetaField.lock()->MakeUnoObject(), uno::UNO_QUERY);
    }
};

::std::vector< uno::Reference<text::XTextField> >
MetaFieldManager::getMetaFields()
{
    // erase deleted fields
    const MetaFieldList_t::iterator iter(
        ::std::remove_if(m_MetaFields.begin(), m_MetaFields.end(),
            ::boost::bind(&::boost::weak_ptr<MetaField>::expired, _1)));
    m_MetaFields.erase(iter, m_MetaFields.end());
    // filter out fields in UNDO
    MetaFieldList_t filtered(m_MetaFields.size());
    const MetaFieldList_t::iterator iter2(
    ::std::remove_copy_if(m_MetaFields.begin(), m_MetaFields.end(),
        filtered.begin(), IsInUndo()));
    filtered.erase(iter2, filtered.end());
    // create uno objects
    ::std::vector< uno::Reference<text::XTextField> > ret(filtered.size());
    ::std::transform(filtered.begin(), filtered.end(), ret.begin(),
            MakeUnoObject());
    return ret;
}

} // namespace sw

ext: cxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice