text:
<?php

/**
 * This is the index-action (default), it will display an error depending on a given parameters
 *
 * @author Tijs Verkoyen <tijs@sumocoders.be>
 * @author Davy Hellemans <davy.hellemans@netlash.com>
 */
class BackendErrorIndex extends BackendBaseActionIndex
{
	/**
	 * Execute the action
	 */
	public function execute()
	{
		parent::execute();
		$this->parse();
		$this->display();
	}

	/**
	 * Parse the correct messages into the template
	 */
	protected function parse()
	{
		parent::parse();

		// grab the error-type from the parameters
		$errorType = $this->getParameter('type');

		// set correct headers
		switch($errorType)
		{
			case 'module-not-allowed':
			case 'action-not-allowed':
				SpoonHTTP::setHeadersByCode(403);
				break;

			case 'not-found':
				SpoonHTTP::setHeadersByCode(404);
				break;
		}

		// querystring provided?
		if($this->getParameter('querystring') !== null)
		{
			// split into file and parameters
			$chunks = explode('?', $this->getParameter('querystring'));

			// get extension
			$extension = SpoonFile::getExtension($chunks[0]);

			// if the file has an extension it is a non-existing-file
			if($extension != '' && $extension != $chunks[0])
			{
				// set correct headers
				SpoonHTTP::setHeadersByCode(404);

				// give a nice error, so we can detect which file is missing
				echo 'Requested file (' . htmlspecialchars($this->getParameter('querystring')) . ') not found.';

				// stop script execution
				exit;
			}
		}

		// assign the correct message into the template
		$this->tpl->assign('message', BL::err(SpoonFilter::toCamelCase(htmlspecialchars($errorType), '-')));
	}
}


text:
/**
 *
 * App.react.js
 *
 * This component is the skeleton around the actual pages, and should only
 * contain code that should be seen on all pages. (e.g. navigation bar)
 */

import React from 'react';
import Helmet from 'react-helmet';
import styled from 'styled-components';

import Header from 'components/Header';
import Footer from 'components/Footer';

// component main content container except header
// import { Container } from 'semantic-ui-react';

const AppWrapper = styled.div`
  margin: 0 auto;
  display: flex;
  min-height: 100vh;
  flex-direction: column;
`;

const StyledContainer = styled.div`
  flex: 1;
`;

function App(props) {
  return (
    <AppWrapper>
      <Helmet
        titleTemplate="%s - React.js Boilerplate"
        defaultTitle="React.js Boilerplate"
        meta={[
          { name: 'description', content: 'A React.js Boilerplate application' },
        ]}
      />
      <Header />
      <StyledContainer>
        {React.Children.toArray(props.children)}
      </StyledContainer>
      <Footer />
    </AppWrapper>
  );
}

App.propTypes = {
  children: React.PropTypes.node,
};

export default App;

redpajama_set_name: RedPajamaGithub


text:
namespace fmrcxx {

template <typename T, typename It>
Iterator<T, It>::Iterator(It&& iterator) :
	moved(false),
	iterator(std::move(iterator)) {
}

template <typename T, typename It> template <typename... Args>
Iterator<T, It>::Iterator(Args&&... args) :
	moved(false),
	iterator(std::forward<Args>(args)...) {
}

template <typename T, typename It>
Iterator<T, It>::Iterator(Iterator<T, It>&& iterator) :
	moved(false),
	iterator(std::move(iterator.iterator)) {
	iterator.moved = true;
}

template <typename T, typename It>
T& Iterator<T, It>::next() {
	return this->iterator.next();
}

template <typename T, typename It>
bool Iterator<T, It>::fullyConsumed() {
	if (this->moved) {
		return true;
	}
	return this->iterator.fullyConsumed();
}

template <typename T, typename It>
bool Iterator<T, It>::ownItem() {
	if (this->moved) {
		return false;
	}
	return this->iterator.ownItem();
}

template <typename T, typename It>
bool Iterator<T, It>::areItemAllocatedDynamically() {
	if (this->moved) {
		return false;
	}
	return this->iterator.areItemAllocatedDynamically();
}

template <typename T, typename It>
void Iterator<T, It>::releaseOwnership() {
	if (this->moved) {
		return;
	}
	return this->iterator.releaseOwnership();
}

template <typename T>
class Iterator<T, std::nullptr_t> {
public:
	Iterator() :
		moved(false) {
	}

	Iterator(Iterator&& rhs) :
		moved(false) {
		rhs.moved = true;
	}

	T& next() {
		throw exception::NextOperationOnFullyConsumedIteratorException();
	}

	bool fullyConsumed() {
		return this->moved;
	}

	bool ownItem() {
		return false;
	}

	bool areItemAllocatedDynamically() {
		return false;
	}

	void releaseOwnership() {
		// Nothing to do here since the iterator does not own the items.
	}
private:
	bool moved;
};

}

#endif


text:
package org.apache.camel.component.mllp;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Tests for the class.
 */
public class MllpInvalidAcknowledgementExceptionTest extends MllpExceptionTestSupport {
    static final String EXCEPTION_MESSAGE = "Invalid Acknowledgment Message";

    MllpInvalidAcknowledgementException instance;

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testConstructorOne() throws Exception {
        instance = new MllpInvalidAcknowledgementException(
                EXCEPTION_MESSAGE, HL7_MESSAGE_BYTES, HL7_ACKNOWLEDGEMENT_BYTES, LOG_PHI_TRUE);

        assertTrue(instance.getMessage().startsWith(EXCEPTION_MESSAGE));
        assertNull(instance.getCause());
        assertArrayEquals(HL7_MESSAGE_BYTES, instance.getHl7MessageBytes());
        assertArrayEquals(HL7_ACKNOWLEDGEMENT_BYTES, instance.getHl7AcknowledgementBytes());
    }

    /**
     * Description of test.
     *
     * @throws Exception in the event of a test error.
     */
    @Test
    public void testConstructorTwo() throws Exception {
        instance = new MllpInvalidAcknowledgementException(
                EXCEPTION_MESSAGE, HL7_MESSAGE_BYTES, HL7_ACKNOWLEDGEMENT_BYTES, CAUSE, LOG_PHI_TRUE);

        assertTrue(instance.getMessage().startsWith(EXCEPTION_MESSAGE));
        assertSame(CAUSE, instance.getCause());
        assertArrayEquals(HL7_MESSAGE_BYTES, instance.getHl7MessageBytes());
        assertArrayEquals(HL7_ACKNOWLEDGEMENT_BYTES, instance.getHl7AcknowledgementBytes());
    }
}


text:
#include <Core/Thread/Parallel.h>
#include <Core/Thread/Barrier.h>

#include <Core/Algorithms/Legacy/Fields/Mapping/MapFieldDataOntoElems.h>
#include <Core/Algorithms/Legacy/Fields/Mapping/MappingDataSource.h>

#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/Matrix.h>
#include <Core/Datatypes/SparseRowMatrix.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/GeometryPrimitives/Vector.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/VMesh.h>

using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Utility;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Logging;
using namespace SCIRun::Core::Thread;
using namespace SCIRun;

ALGORITHM_PARAMETER_DEF(Fields, Quantity);
ALGORITHM_PARAMETER_DEF(Fields, InterpolationModel);
ALGORITHM_PARAMETER_DEF(Fields, SamplePoints);
ALGORITHM_PARAMETER_DEF(Fields, SampleMethod);
ALGORITHM_PARAMETER_DEF(Fields, OutsideValue);
ALGORITHM_PARAMETER_DEF(Fields, MaxDistance);

MapFieldDataOntoElemsAlgo::MapFieldDataOntoElemsAlgo()
{
  using namespace Parameters;
  addOption(Quantity, "value", "value|gradient|gradientnorm|flux");
  addOption(InterpolationModel, "interpolateddata","interpolateddataonly|interpolateddata|closestnodedata|closestinterpolateddata");
  addOption(SamplePoints, "regular1","regular1|regular2|regular3|regular4|regular5|gaussian1|gaussian2|gaussian3");
  addOption(SampleMethod, "average","average|integrate|min|max|sum|mostcommon|median");
  addParameter(OutsideValue, 0.0);
  addParameter(MaxDistance, std::numeric_limits<double>::max());
}

namespace detail {

class MapFieldDataOntoElemsPAlgo : public Interruptible
{
  public:
    explicit MapFieldDataOntoElemsPAlgo(unsigned int numProcs) :
    algo_(0), is_flux_(false), has_nan_(false), def_value_(0),
      barrier_("MapFieldDataOntoElemsPAlgo Barrier", numProcs), nproc(numProcs) {}

    void parallel(int proc);

    FieldHandle sfield_;
    FieldHandle wfield_;
    FieldHandle ofield_;

    const AlgorithmBase* algo_;

    bool is_flux_;
    bool has_nan_;

    double def_value_;

    std::vector<bool> success_;

  private:
    Barrier barrier_;

    inline bool exist(double d)
    {
      return IsFinite(d);
    }

    inline bool exist(Vector& d)
    {
      return (exist(d.x())&&exist(d.y())&&exist(d.z()));
    }

    inline bool exist(Tensor& d)
    {
      return (exist(d.xx())&&exist(d.xy())&&exist(d.xz())&&
              exist(d.yy())&&exist(d.yz())&&exist(d.zz()));
    }
    unsigned int nproc;
};

void
MapFieldDataOntoElemsPAlgo::parallel(int proc)
{
  // Each thread has its own Datasource class, so it can preallocate array internally
  success_[proc] = true;

  barrier_.wait();

  MappingDataSourceHandle datasource = CreateDataSource(sfield_,wfield_,algo_);

  if (!datasource)
  {
    success_[proc] = false;
  }

  barrier_.wait();

  for (unsigned int j=0; j<nproc; j++)
  {
    if (success_[j] == false)
    {
      if (proc == 0) algo_->error("Could not allocate data source.");
      return;
    }
  }

  barrier_.wait();

  def_value_ = algo_->get(Parameters::OutsideValue).toDouble();

  VMesh* omesh = ofield_->vmesh();
  VField* ofield = ofield_->vfield();

  VMesh::Elem::size_type  num_elems = omesh->num_elems();
  VField::size_type       localsize = num_elems/nproc;
  VField::index_type      start = localsize*proc;
  VField::index_type      end = localsize*(proc+1);
  if (proc == nproc-1) end = num_elems;

  std::vector<VMesh::coords_type> coords;
  std::vector<double> weights;
  std::vector<Point> points;

  std::string sample_points = algo_->getOption(Parameters::SamplePoints);
  std::string sample_method = algo_->getOption(Parameters::SampleMethod);

  if (sample_points == "regular1")
  {
    omesh->get_regular_scheme(coords,weights,1);
  }
  else if (sample_points == "regular2")
  {
    omesh->get_regular_scheme(coords,weights,2);
  }
  else if (sample_points == "regular3")
  {
    omesh->get_regular_scheme(coords,weights,3);
  }
  else if (sample_points == "regular4")
  {
    omesh->get_regular_scheme(coords,weights,4);
  }
  else if (sample_points == "regular5")
  {
    omesh->get_regular_scheme(coords,weights,5);
  }
  else if (sample_points == "gaussian1")
  {
    omesh->get_gaussian_scheme(coords,weights,1);
  }
  else if (sample_points == "gaussian2")
  {
    omesh->get_gaussian_scheme(coords,weights,2);
  }
  else if (sample_points == "gaussian3")
  {
    omesh->get_gaussian_scheme(coords,weights,3);
  }
  else
  {
    if (proc == 0) algo_->error("Sampling points are not defined for this type of mesh");
    success_[proc] = false;
    barrier_.wait();
    return;
  }

  int cnt = 0;

  if (has_nan_)
  {
    if (is_flux_)
    {
      // To compute flux through a surface
      std::vector<Vector> norms;
      std::vector<Vector> grads;
      std::vector<double> values;
      double val; double rval; double vol;
      values.resize(coords.size());
      if (sample_method== "average")
      {
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          val = 0.0; size_t num = 0;
          for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { val += values[j]; num++; }
          if (num > 0) val /= num; else val = def_value_;
          ofield->set_value(val,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else if (sample_method== "integrate")
      {
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          vol = omesh->get_size(idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          val = 0.0; size_t num = 0;
          for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { val += values[j]*weights[j]; num++; }
          if (num > 0) val *= vol; else val = def_value_;
          ofield->set_value(val,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else if (sample_method== "min")
      {
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          val = std::numeric_limits<double>::max();
          for (size_t j=0; j<values.size(); j++) if (exist(values[j])) if (values[j] < val) val = values[j];
          if (val == std::numeric_limits<double>::max()) val = def_value_;
          ofield->set_value(val,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else if (sample_method== "max")
      {
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          val = -std::numeric_limits<double>::max();
          for (size_t j=0; j<values.size(); j++) if (exist(values[j])) if (values[j] > val) val = values[j];
          if (val == -std::numeric_limits<double>::max()) val = def_value_;
          ofield->set_value(val,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else if (sample_method== "sum")
      {
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          val = 0.0; size_t num = 0;
          for (size_t j=0; j<values.size(); j++) if(exist(val)) { val += values[j]; num++; }
          if (num == 0) val = def_value_;
          ofield->set_value(val,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else if (sample_method== "mostcommon")
      {
        std::vector<double> common;
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          common.clear();
          for (size_t j=0; j<values.size();j++) if (exist(values[j])) common.push_back(values[j]);
          if (common.size() > 0)
          {
            std::sort(common.begin(),common.end());
            val =0.0; rval =0.0;
            size_t rnum =0; size_t p = 0; size_t n = 0;
            while (p <common.size())
            {
              n = 1;
              val = common[p];
              p++;
              while(p <common.size() && values[p] == val) {n++; p++;}
              if (n >= rnum) {rnum = n; rval = val;}
            }
          }
          else
          {
            rval = def_value_;
          }
          ofield->set_value(rval,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else if (sample_method== "median")
      {
        std::vector<double> median;
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          median.clear();
          for (size_t j=0; j<values.size();j++) if (exist(values[j])) median.push_back(values[j]);
          if (median.size() > 0)
          {
            std::sort(median.begin(),median.end());
            index_type x = static_cast<index_type>(median.size()/2);
            if (median.size()%2) val = (median[x]+median[x+1])*0.5;
            else val = median[x];
          }
          else
          {
            val = def_value_;
          }
          ofield->set_value(val,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else
      {
        if (proc == 0) algo_->error("Sampling method was not defined for flux data");
        success_[proc] = false;
        barrier_.wait();
        return;
      }
    }
    else
    {
      // To map value, gradient, or gradientnorm
      if (datasource->is_scalar())
      {
        std::vector<double> values;
        double val; double rval; double vol;
        if (sample_method== "average")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = 0.0; size_t num = 0;
            for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { val += values[j]; num++; }
            if (num > 0) val = val/num; else val = def_value_;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "integrate")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            vol = omesh->get_size(idx);
            datasource->get_data(values,points);
            val = 0.0; size_t num = 0;
            for (size_t j=0; j<values.size(); j++) if (exist(val)) { val += values[j]*weights[j]; num++; }
            if (num > 0) val *= vol;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "min")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = std::numeric_limits<double>::max();
            for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { if (values[j] < val) val = values[j]; }
            if (val == std::numeric_limits<double>::max()) val = def_value_;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "max")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = -std::numeric_limits<double>::max();
            for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { if (values[j] > val) val = values[j]; }
            if (val == -std::numeric_limits<double>::max()) val = def_value_;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "sum")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = 0.0; size_t num = 0;
            for (size_t j=0; j<values.size(); j++) { if (exist(values[j])) { val += values[j]; num++;} }
            if (num == 0) val = def_value_;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "mostcommon")
        {
          std::vector<double> common;
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            common.clear();
            for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { common.push_back(values[j]); }
            if (common.size() > 0)
            {
              std::sort(common.begin(),common.end());
              val =0.0; rval =0.0;
              size_t rnum =0; size_t p = 0; size_t n = 0;
              while (p <common.size())
              {
                n = 1;
                val = common[p];
                p++;
                while(p <common.size() && common[p] == val) {n++; p++;}
                if (n >= rnum) {rnum = n; rval = val;}
              }
            }
            else
            {
              rval = def_value_;
            }
            ofield->set_value(rval,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "median")
        {
          std::vector<double> median;
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            median.clear();
            for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { median.push_back(values[j]); }
            if (median.size())
            {
              std::sort(median.begin(),median.end());
              index_type x = static_cast<index_type>(median.size()/2);
              if (median.size()%2) val = (median[x]+median[x+1])*0.5;
              else val = median[x];
            }
            else
            {
              val = def_value_;
            }
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else
        {
          if (proc == 0) algo_->error("Sampling method was not defined for this type of data");
          success_[proc] = false;
          barrier_.wait();
          return;
        }
      }
      else if (datasource->is_vector())
      {
        std::vector<Vector> values;
        Vector val; double vol;
        if (sample_method== "average")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = Vector(0,0,0); size_t num = 0;
            for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { val += values[j]; num++; }
            if (num > 0) val = val*(1.0/num); else val = def_value_;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "integrate")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            vol = omesh->get_size(idx);
            datasource->get_data(values,points);
            val = Vector(0,0,0);
            for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { val += values[j]*weights[j]; }
            val *= vol;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "sum")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = Vector(0,0,0);
            for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { val += values[j]; }
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else
        {
          if (proc == 0) algo_->error("Sampling method was not defined for this type of data");
          success_[proc] = false;
          barrier_.wait();
          return;
        }
      }
      else
      {
        std::vector<Tensor> values;
        Tensor val; double vol;
        if (sample_method== "average")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = Tensor(0); size_t num = 0;
            for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { val += values[j]; num++; }
            if (num > 0) val = val*(1.0/num);
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "integrate")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            vol = omesh->get_size(idx);
            datasource->get_data(values,points);
            val = Tensor(0);
            for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { val += weights[j]*values[j]; }
            val = val*vol;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "sum")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = Tensor(0);
            for (size_t j=0; j<values.size(); j++) if (exist(values[j])) { val += values[j]; }
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else
        {
          if (proc == 0) algo_->error("Sampling method was not defined for this type of data");
          success_[proc] = false;
          barrier_.wait();
          return;
        }
      }
    }
  }
  else
  {
    if (is_flux_)
    {
      // To compute flux through a surface
      std::vector<Vector> norms;
      std::vector<Vector> grads;
      std::vector<double> values;
      double val; double rval; double vol;
      double scale = 1.0/coords.size();
      values.resize(coords.size());
      if (sample_method== "average")
      {
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          val = values[0];
          for (size_t j=1; j<values.size(); j++) val += values[j];
          val *= scale;
          ofield->set_value(val,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else if (sample_method== "integrate")
      {
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          vol = omesh->get_size(idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          val = values[0];
          for (size_t j=1; j<values.size(); j++) val += values[j]*weights[j];
          val *= vol;
          ofield->set_value(val,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else if (sample_method== "min")
      {
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          val = values[0];
          for (size_t j=1; j<values.size(); j++) if (values[j] < val) val = values[j];
          ofield->set_value(val,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else if (sample_method== "max")
      {
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          val = values[0];
          for (size_t j=1; j<values.size(); j++) if (values[j] > val) val = values[j];
          ofield->set_value(val,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else if (sample_method== "sum")
      {
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          val = values[0];
          for (size_t j=1; j<values.size(); j++) val += values[j];
          ofield->set_value(val,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else if (sample_method== "mostcommon")
      {
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          std::sort(values.begin(),values.end());
          val =0.0; rval =0.0;
          size_t rnum =0; size_t p = 0; size_t n = 0;
          while (p <values.size())
          {
            n = 1;
            val = values[p];
            p++;
            while(p <values.size() && values[p] == val) {n++; p++;}
            if (n >= rnum) {rnum = n; rval = val;}
          }

          ofield->set_value(rval,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else if (sample_method== "median")
      {
        for (VMesh::Elem::index_type idx=start; idx<end; idx++)
        {
          checkForInterruption();
          omesh->minterpolate(points,coords,idx);
          omesh->get_normals(norms,coords,idx);
          datasource->get_data(grads,points);
          for (size_t j=0; j<grads.size();j++) values[j] = Dot(grads[j],norms[j]);
          std::sort(values.begin(),values.end());
          index_type x = static_cast<index_type>(values.size()/2);
          if (values.size()%2) val = (values[x]+values[x+1])*0.5;
          else val = values[x];
          ofield->set_value(val,idx);
          if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
        }
      }
      else
      {
        if (proc == 0) algo_->error("Sampling method was not defined for flux data");
        success_[proc] = false;
        barrier_.wait();
        return;
      }
    }
    else
    {
      // To map value, gradient, or gradientnorm
      if (datasource->is_scalar())
      {
        std::vector<double> values;
        double val; double rval; double vol;
        double scale = 1.0/coords.size();
        if (sample_method== "average")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = values[0];
            for (size_t j=1; j<values.size(); j++) val += values[j];
            val *= scale;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "integrate")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            vol = omesh->get_size(idx);
            datasource->get_data(values,points);
            val = values[0];
            for (size_t j=1; j<values.size(); j++) val += values[j]*weights[j];
            val *= vol;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "min")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = values[0];
            for (size_t j=1; j<values.size(); j++) if (values[j] < val) val = values[j];
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "max")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = values[0];
            for (size_t j=1; j<values.size(); j++) if (values[j] > val) val = values[j];
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "sum")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = values[0];
            for (size_t j=1; j<values.size(); j++) val += values[j];
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "mostcommon")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            std::sort(values.begin(),values.end());
            val =0.0; rval =0.0;
            size_t rnum =0; size_t p = 0; size_t n = 0;
            while (p <values.size())
            {
              n = 1;
              val = values[p];
              p++;
              while(p <values.size() && values[p] == val) {n++; p++;}
              if (n >= rnum) {rnum = n; rval = val;}
            }

            ofield->set_value(rval,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "median")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            std::sort(values.begin(),values.end());
            index_type x = static_cast<index_type>(values.size()/2);
            if (values.size()%2) val = (values[x]+values[x+1])*0.5;
            else val = values[x];
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else
        {
          if (proc == 0) algo_->error("Sampling method was not defined for this type of data");
          success_[proc] = false;
          barrier_.wait();
          return;
        }
      }
      else if (datasource->is_vector())
      {
        std::vector<Vector> values;
        Vector val; double vol;
        double scale = 1.0/coords.size();
        if (sample_method== "average")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = values[0];
            for (size_t j=1; j<values.size(); j++) val += values[j];
            val *= scale;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "integrate")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            vol = omesh->get_size(idx);
            datasource->get_data(values,points);
            val = values[0];
            for (size_t j=1; j<values.size(); j++) val += values[j]*weights[j];
            val *= vol;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "sum")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = values[0];
            for (size_t j=1; j<values.size(); j++) val += values[j];
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else
        {
          if (proc == 0) algo_->error("Sampling method was not defined for this type of data");
          success_[proc] = false;
          barrier_.wait();
          return;
        }
      }
      else
      {
        std::vector<Tensor> values;
        Tensor val; double vol;
        double scale = 1.0/coords.size();
        if (sample_method== "average")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = values[0];
            for (size_t j=1; j<values.size(); j++) val += values[j];
            val = val* scale;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "integrate")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            vol = omesh->get_size(idx);
            datasource->get_data(values,points);
            val = values[0];
            for (size_t j=1; j<values.size(); j++) val += values[j]*weights[j];
            val = val*vol;
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else if (sample_method== "sum")
        {
          for (VMesh::Elem::index_type idx=start; idx<end; idx++)
          {
            checkForInterruption();
            omesh->minterpolate(points,coords,idx);
            datasource->get_data(values,points);
            val = values[0];
            for (size_t j=1; j<values.size(); j++) val += values[j];
            ofield->set_value(val,idx);
            if (proc == 0) { cnt++; if (cnt == 400) {cnt = 0; algo_->update_progress_max(idx,end); } }
          }
        }
        else
        {
          if (proc == 0) algo_->error("Sampling method was not defined for this type of data");
          success_[proc] = false;
          barrier_.wait();
          return;
        }
      }
    }
  }

  // Wait until all of the threads are done
  success_[proc] = true;
  barrier_.wait();
}
}

bool
MapFieldDataOntoElemsAlgo::runImpl(FieldHandle source, FieldHandle weights, FieldHandle destination, FieldHandle& output) const
{
  ScopedAlgorithmStatusReporter asr(this, "MapFieldDataOntoElems");

  if (!source)
  {
    error("No source field");
    return (false);
  }

  if (!destination)
  {
    error("No destination field");
    return (false);
  }

  FieldInformation fi(source);
  FieldInformation fo(destination);

  if (fo.is_pointcloud())
  {
    THROW_ALGORITHM_INPUT_ERROR("Destination field cannot be a point cloud.");
  }

  fo.make_constantdata();

  std::string quantity = getOption(Parameters::Quantity);
  std::string value = getOption(Parameters::InterpolationModel);

  if (value == "closestnodedata")
  {
    if (!fi.is_lineardata())
    {
      error("Closest node data only works for source data located at the nodes.");
      return (false);
    }
  }

  if (fi.is_nodata())
  {
    error("No data in source field.");
    return (false);
  }

  if (weights)
  {
    FieldInformation wfi(weights);
    if (value == "closestnodedata")
    {
      if (!wfi.is_lineardata())
      {
        error("Closest node data only works for weights data located at the nodes.");
        return (false);
      }
    }

    if (wfi.is_nodata())
    {
      error("No data in weights field.");
      return (false);
    }
  }

  // Make sure output equals quantity to be computed

  if (quantity == "value")
  {
    // Copy the output datatype
    fo.set_data_type(fi.get_data_type());
  }
  else  if (quantity == "gradient")
  {
    // Output will be a vector
    if (!fi.is_scalar())
    {
      error("Gradient can only be calculated on a scalar field.");
      return (false);
    }
    fo.make_vector();
  }
  else if (quantity == "gradientnorm")
  {
    // Output will be a double
    if (!fi.is_scalar())
    {
      error("Gradient can only be calculated on a scalar field.");
      return (false);
    }
    fo.make_double();
  }
  else if (quantity == "flux")
  {
    // Only for output surfaces (only field with normals) and output will
    // be double
    if (!fi.is_scalar())
    {
      error("Flux can only be calculated on a scalar field.");
      return (false);
    }
    if (!fo.is_surface())
    {
      error("Flux can only be computed for surfaces meshes as destination");
      return (false);
    }
    fo.make_double();
  }

  // Incorporate the weights and alter the datatype to reflect that
  if (weights)
  {
    FieldInformation wfi(weights);
    if ((!wfi.is_tensor())&&(!wfi.is_scalar()))
    {
      error("Weights field needs to be a scalar or a tensor.");
      return (false);
    }

    if (fo.is_scalar() && wfi.is_tensor())
    {
      fo.make_tensor();
    }

    if (fo.is_tensor() && wfi.is_tensor())
    {
      error("Weights and source field cannot be both tensor data.");
      return (false);
    }
  }

  // Create new output field
  output = CreateField(fo,destination->mesh());
  output->vfield()->resize_values();

  if (!output)
  {
    error("Could not allocate output field");
    return (false);
  }

  // Number of threads is equal to the number of cores
  int np = Parallel::NumCores();
  // Run algorithm in parallel
  detail::MapFieldDataOntoElemsPAlgo algo(np);

  algo.sfield_ = source;
  algo.wfield_ = weights;
  algo.ofield_ = output;
  algo.algo_ = this;

  algo.success_.resize(np,true);
  // Mark whether it is a flux computation
  algo.is_flux_ = false;
  if (quantity == "flux") algo.is_flux_ = true;

  algo.has_nan_ = false;
  std::string valuestr = getOption(Parameters::InterpolationModel);
  if (valuestr == "interpolateddataonly") algo.has_nan_ = true;

  // Parallel algorithm
  auto task_i = [&algo,this](int i) { algo.parallel(i); };
  Parallel::RunTasks(task_i, Parallel::NumCores());

  // Check whether algorithm succeeded
  for (int j=0; j<np; j++)
  {
    if (!algo.success_[j])
    {
      // We get here if sample_method is incorrect
      return (false);
    }
  }
  CopyProperties(*destination, *output);

  return (true);
}

bool
MapFieldDataOntoElemsAlgo::runImpl(FieldHandle source, FieldHandle destination, FieldHandle& output) const
{
  ScopedAlgorithmStatusReporter asr(this, "MapFieldDataOntoElems");

  if (!source)
  {
    error("No source field");
    return (false);
  }

  if (!destination)
  {
    error("No destination field");
    return (false);
  }

  FieldInformation fi(source);
  FieldInformation fo(destination);
  fo.make_constantdata();

  std::string quantity = getOption(Parameters::Quantity);
  std::string value = getOption(Parameters::InterpolationModel);

  if (value == "closestnodedata")
  {
    if (!fi.is_lineardata())
    {
      error("Closest node data only works for source data located at the nodes.");
      return (false);
    }
  }

  if (fi.is_nodata())
  {
    error("No data in source field.");
    return (false);
  }

  // Make sure output equals quantity to be computed

  if (quantity == "value")
  {
    // Copy the output datatype
    fo.set_data_type(fi.get_data_type());
  }
  else  if (quantity == "gradient")
  {
    // Output will be a vector
    if (!fi.is_scalar())
    {
      error("Gradient can only be calculated on a scalar field.");
      return (false);
    }
    fo.make_vector();
  }
  else if (quantity == "gradientnorm")
  {
    // Output will be a double
    if (!fi.is_scalar())
    {
      error("Gradient can only be calculated on a scalar field.");
      return (false);
    }
    fo.make_double();
  }
  else if (quantity == "flux")
  {
    // Only for output surfaces (only field with normals) and output will
    // be double
    if (!fi.is_scalar())
    {
      error("Flux can only be calculated on a scalar field.");
      return (false);
    }
    if (!fo.is_surface())
    {
      error("Flux can only be computed for surfaces meshes as destination");
      return (false);
    }
    fo.make_double();
  }

  // Create new output field
  output = CreateField(fo,destination->mesh());
  output->vfield()->resize_values();

  if (!output)
  {
    error("Could not allocate output field");
    return (false);
  }

  // Number of threads is equal to the number of cores
  int np = Parallel::NumCores();
  // Run algorithm in parallel
  detail::MapFieldDataOntoElemsPAlgo algo(np);

  algo.sfield_ = source;
  algo.ofield_ = output;
  algo.algo_ = this;

  algo.success_.resize(np,true);
  // Mark whether it is a flux computation
  algo.is_flux_ = quantity == "flux";

  algo.has_nan_ = false;
  std::string valuestr = getOption(Parameters::InterpolationModel);
  if (valuestr == "interpolateddataonly") algo.has_nan_ = true;

  // Parallel algorithm
  auto task_i = [&algo,this](int i) { algo.parallel(i); };
  Parallel::RunTasks(task_i, Parallel::NumCores());

 // Check whether algorithm succeeded
  for (int j=0; j<np; j++)
  {
    if (!algo.success_[j])
    {
      // We get here if sample_method is incorrect
      return (false);
    }
  }

#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER
  // Copy properties
  output->vfield()->copy_properties(destination->vfield());
#endif

  return (true);
}

const AlgorithmInputName MapFieldDataOntoElemsAlgo::Source("Source");
const AlgorithmInputName MapFieldDataOntoElemsAlgo::Destination("Destination");
const AlgorithmInputName MapFieldDataOntoElemsAlgo::Weights("Weights");

AlgorithmOutput MapFieldDataOntoElemsAlgo::run(const AlgorithmInput& input) const
{
  auto source = input.get<Field>(Source);
  auto destination = input.get<Field>(Destination);
  auto weights = input.get<Field>(Weights);

  FieldHandle outputField;

  if (!runImpl(source, weights, destination, outputField))
    THROW_ALGORITHM_PROCESSING_ERROR("False thrown on legacy run call");

  AlgorithmOutput output;
  output[Variables::OutputField] = outputField;

  return output;
}


text:
'use strict';

/**
 * The body of a PUT request to modify a Visual Studio account resource.
 *
 */
class AccountResourceRequest {
  /**
   * Create a AccountResourceRequest.
   * @member {string} [accountName] The account name.
   * @member {string} [location] The Azure instance location.
   * @member {object} [operationType] The type of the operation.
   * @member {object} [properties] The custom properties of the resource.
   * @member {object} [tags] The custom tags of the resource.
   */
  constructor() {
  }

  /**
   * Defines the metadata of AccountResourceRequest
   *
   * @returns {object} metadata of AccountResourceRequest
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'AccountResourceRequest',
      type: {
        name: 'Composite',
        className: 'AccountResourceRequest',
        modelProperties: {
          accountName: {
            required: false,
            serializedName: 'accountName',
            type: {
              name: 'String'
            }
          },
          location: {
            required: false,
            serializedName: 'location',
            type: {
              name: 'String'
            }
          },
          operationType: {
            required: false,
            serializedName: 'operationType',
            type: {
              name: 'Object'
            }
          },
          properties: {
            required: false,
            serializedName: 'properties',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          tags: {
            required: false,
            serializedName: 'tags',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          }
        }
      }
    };
  }
}

module.exports = AccountResourceRequest;


text:
extern crate derive_builder;
extern crate serde;
extern crate serde_json;

#[derive(Builder)]
#[builder(setter(into), derive(serde::Serialize))]
#[builder_struct_attr(serde(rename_all = "camelCase"))]
#[allow(dead_code)]
struct Example {
    first_name: String,
    middle_name: String,
    #[builder_field_attr(serde(rename = "familyName"))]
    last_name: String,
}

#[test]
fn serialize_builder() {
    assert_eq!(
        serde_json::to_string(
            &ExampleBuilder::default()
                .first_name("Jane")
                .middle_name("Alice")
                .last_name("Doe"),
        )
        .unwrap(),
        r#"{"firstName":"Jane","middleName":"Alice","familyName":"Doe"}"#
    );
}


text:
package com.github.basking2.otternet;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import com.github.basking2.jiraffet.db.LogDbManager;
import com.github.basking2.jiraffet.db.LogMyBatis;
import com.github.basking2.otternet.http.ControlService;
import com.github.basking2.otternet.jiraffet.OtterLogApplier;
import com.github.basking2.otternet.jiraffet.OtterAccess;
import com.github.basking2.otternet.util.App;
import org.apache.commons.cli.*;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.glassfish.grizzly.http.server.*;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ContainerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.wadl.WadlFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.basking2.otternet.http.JiraffetJsonService;
import com.github.basking2.otternet.jiraffet.OtterIO;
import com.github.basking2.otternet.util.Ip;

/**
 * Startup Main line that does surprisingly little of the work and magic.
 *
 * @see OtterIO
 * @see OtterAccess
 * @see OtterLogApplier
 */
public class OtterNet implements AutoCloseable {
    final HttpServer httpServer;
    private static final Logger LOG = LoggerFactory.getLogger(OtterNet.class);
    static private App otterNetApp;

    final private ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors());
    final private OtterAccess access;
    final private Configuration config;

    public static final void main(final String[] argv) throws InterruptedException, IOException, ConfigurationException, ParseException, SQLException, ClassNotFoundException {

        // Parse CLI arguments.
        mainParseArgs(argv);

        otterNetApp = new App("otternet");

        final OtterNet otterNet = new OtterNet();
        otterNet.start();

        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            try {
                otterNet.close();
            }
            catch (final Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }));

        Thread.currentThread().join();
    }

    /**
     * Parse the command line arguments into System properties to be picked up by the application.
     *
     * @param argv The user's command line options.
     * @throws ParseException On a parser exception.
     */
    public static void mainParseArgs(final String[] argv) throws ParseException {
        //================================================================================
        // Option parsing
        //================================================================================
        final CommandLineParser cliParser = new DefaultParser();
        final Options cliOptions = new Options().
                addOption("p", "port", true, "Port to listen on.").
                addOption("i", "ip", true, "IP to bind to. If set to \"auto\" an external site is used.").
                addOption("I", "id", true, "http://address:port id used to locate this host and join clusters.").
                addOption("H", "home", true, "Home directory.").
                addOption("h", "help", false, "Help.");
        final CommandLine commandLine = cliParser.parse(cliOptions, argv);

        if (commandLine.hasOption('h')) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("otternet", "", cliOptions, "\nExiting.\n", true);
            System.exit(1);
        }

        // Move all of our command line parsed options into the system properties where we'll pick them up.
        if (commandLine.hasOption("p")) {
            System.setProperty("otternet.port", commandLine.getOptionValue("p"));
        }
        if (commandLine.hasOption("i")) {
            System.setProperty("otternet.addr", commandLine.getOptionValue("i"));
        }
        if (commandLine.hasOption("I")) {
            System.setProperty("otternet.id", commandLine.getOptionValue("I"));
        }
        if (commandLine.hasOption("H")) {
            System.setProperty("otternet.home", commandLine.getOptionValue("I"));
        }
        //================================================================================
    }

    public OtterNet() throws ConfigurationException, SQLException, ClassNotFoundException {
        config = otterNetApp.buildConfiguration();

        String ip = config.getString("otternet.addr", "0.0.0.0");
        if ("auto".equalsIgnoreCase(ip)) {
            ip = Ip.whatsMyIp();
        }

        int port = config.getInt("otternet.port", 8080);

        final String id;
        if (config.getString("otter.id", null) != null) {
            id = config.getString("otter.id");
        }
        else {
            id = "http://" + ip + ":" + port;
        }

        LOG.info("Starting OtterNet bound to {}:{} with id {}.", ip, port, id);

        final OtterAccess.JiraffetIoFactory ioFactory = new OtterAccess.JiraffetIoFactory() {
            @Override
            public OtterIO getInstance(String instanceName) {
                return new OtterIO(instanceName, id, new ArrayList<>(), executorService);
            }
        };

        /**
         * Where all the databases get created.
         */
        final File logs = new File(System.getProperty("otternet.home"), "logs");

        final OtterAccess.JiraffetLogFactory logFactory = new OtterAccess.JiraffetLogFactory() {
            @Override
            public LogDbManager getInstance(String instanceName) {
                try {
                    final LogDbManager logDbManager = new LogDbManager(new File(logs, instanceName));

                    return logDbManager;
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        };

        access = new OtterAccess(ioFactory, logFactory, executorService);

        httpServer = new HttpServer();

        final NetworkListener networkListener = new NetworkListener("otter", ip, port);

        /*
        networkListener.setDefaultErrorPageGenerator(new ErrorPageGenerator() {
            @Override
            public String generate(final Request request, final int status, final String reasonPhrase, final String description, final Throwable exception) {
                return new StringBuilder().
                        append("").
                        append("
").append(reasonPhrase).append("
").
                        append("
").append(description).append("
").
                        append("").append(exception).append("").
                        append("").
                        toString();
            }
        });
        */

        final HttpHandler dynamicHandler = ContainerFactory.createContainer(HttpHandler.class, resourceConfig());

        httpServer.addListener(networkListener);

        httpServer.getServerConfiguration().addHttpHandler(dynamicHandler, "/");

    }

    public void start() throws IOException {

        httpServer.start();

    }

    public ResourceConfig resourceConfig() {
        final ResourceConfig rc = new ResourceConfig();
        rc.register(new JiraffetJsonService(access));
        rc.register(new ControlService(access));
        rc.register(WadlFeature.class);
        rc.register(JacksonFeature.class);
        rc.packages("com.github.basking2.otternet.http.scanned");
        //rc.register(HTTPResponseFilter.class);
        return rc;
    }

    @Override
    public void close() throws Exception {
        try {
            httpServer.shutdown();
        }
        catch (final Throwable t) {
            // Nope
        }

        try {
            access.close();
        }
        catch (final Throwable t) {
            // Nop.
        }
    }
}


text:
package net.explorviz.security.server.resources;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import javax.annotation.security.PermitAll;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

/**
 * Entry point for this service.
 */
@Path("v1/users/entry")
@Tag(name = "Entry")
public class EntryPointResource {

  /**
   * This method is the entry point for this service and returns (in the future) a HATEOAS-based
   * payload for clients.
   */
  @GET
  @PermitAll
  @Operation(description = "Show this API's entry point.")
  @ApiResponse(responseCode = "200", description = "Returns the entry point for this API, "
      + "so that users can follow the included links in terms of HATEOAS.")
  public String showEntryPoint() {

    return "Entry Point";
  }

}


text:
package org.apache.camel.component.elasticsearch;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.node.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Represents an Elasticsearch endpoint.
 */
@UriEndpoint(scheme = "elasticsearch", title = "Elasticsearch", syntax = "elasticsearch:clusterName", producerOnly = true, label = "monitoring,search")
public class ElasticsearchEndpoint extends DefaultEndpoint {

    private static final Logger LOG = LoggerFactory.getLogger(ElasticsearchEndpoint.class);

    private Node node;
    private Client client;
    @UriParam
    private ElasticsearchConfiguration configuration;

    public ElasticsearchEndpoint(String uri, ElasticsearchComponent component, Map<String, Object> parameters) throws Exception {
        super(uri, component);
        this.configuration = new ElasticsearchConfiguration(new URI(uri), parameters);
    }

    public Producer createProducer() throws Exception {
        return new ElasticsearchProducer(this);
    }

    public Consumer createConsumer(Processor processor) throws Exception {
        throw new RuntimeCamelException("Cannot consume to a ElasticsearchEndpoint: " + getEndpointUri());
    }

    public boolean isSingleton() {
        return true;
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();
        if (configuration.isLocal()) {
            LOG.info("Starting local ElasticSearch server");
        } else {
            LOG.info("Joining ElasticSearch cluster " + configuration.getClusterName());
        }
        if (configuration.getIp() != null) {
            this.client = new TransportClient(getSettings())
                    .addTransportAddress(new InetSocketTransportAddress(configuration.getIp(), configuration.getPort()));

        } else if (configuration.getTransportAddresses() != null
               && !configuration.getTransportAddresses().isEmpty()) {
            List<TransportAddress> addresses = new ArrayList(configuration.getTransportAddresses().size());
            for (TransportAddress address : configuration.getTransportAddresses()) {
                addresses.add(address);
            }
            this.client = new TransportClient(getSettings())
                   .addTransportAddresses(addresses.toArray(new TransportAddress[0]));
        } else {
            node = configuration.buildNode();
            client = node.client();
        }
    }

    private Settings getSettings() {
        return ImmutableSettings.settingsBuilder()
                        // setting the classloader here will allow the underlying elasticsearch-java
                        // class to find its names.txt in an OSGi environment (otherwise the thread
                        // classloader is used, which won't be able to see the file causing a startup
                // exception).
                .classLoader(Settings.class.getClassLoader())
                .put("cluster.name", configuration.getClusterName())
                .put("client.transport.ignore_cluster_name", false)
                        .put("node.client", true)
                .put("client.transport.sniff", true)
                        .build();
    }

    @Override
    protected void doStop() throws Exception {
        if (configuration.isLocal()) {
            LOG.info("Stopping local ElasticSearch server");
        } else {
            LOG.info("Leaving ElasticSearch cluster " + configuration.getClusterName());
        }
        client.close();
        if (node != null) {
            node.close();
        }
        super.doStop();
    }

    public Client getClient() {
        return client;
    }

    public ElasticsearchConfiguration getConfig() {
        return configuration;
    }

    public void setOperation(String operation) {
        configuration.setOperation(operation);
    }

}


text:
package org.squbs.cluster

import java.util.concurrent.atomic.AtomicBoolean

import akka.actor.{Actor, Address, AddressFromURIString}
import com.typesafe.scalalogging.LazyLogging
import org.apache.curator.framework.CuratorFramework
import org.apache.curator.framework.api.CuratorWatcher
import org.apache.curator.framework.recipes.leader.{LeaderLatch, LeaderLatchListener}
import org.apache.zookeeper.Watcher.Event.EventType
import org.apache.zookeeper.{CreateMode, WatchedEvent}

import scala.jdk.CollectionConverters._

@deprecated("The zkcluster is deprecated in lieu of maturity of Akka cluster and more modern cluster coordinators",
  since = "0.15.0")
private[cluster] case class ZkLeaderElected(address: Option[Address])

@deprecated("The zkcluster is deprecated in lieu of maturity of Akka cluster and more modern cluster coordinators",
  since = "0.15.0")
private[cluster] case class ZkMembersChanged(members: Set[Address])

/**
 * The membership monitor has a few responsibilities,
 * most importantly to enroll the leadership competition and get membership,
 * leadership information immediately after change
 */
@deprecated("The zkcluster is deprecated in lieu of maturity of Akka cluster and more modern cluster coordinators",
  since = "0.15.0")
private[cluster] class ZkMembershipMonitor extends Actor with LazyLogging {

  private[this] val zkCluster = ZkCluster(context.system)
  import zkCluster._

  private[this] implicit val log = logger
  private[this] var zkLeaderLatch: Option[LeaderLatch] = None
  private[this] val stopped = new AtomicBoolean(false)

  private def initialize()(implicit curatorFwk: CuratorFramework) = {
    //watch over leader changes
    curatorFwk.getData.usingWatcher(new CuratorWatcher {
      override def process(event: WatchedEvent): Unit = {
        log.debug("[membership] leader watch event:{} when stopped:{}", event, stopped.toString)
        if(!stopped.get && event.getType == EventType.NodeDataChanged) {
          zkClusterActor ! ZkLeaderElected(curatorFwk.getData.usingWatcher(this).forPath("/leader").toAddress)
        }
      }
    }).forPath("/leader")

    //watch over my self
    val me = guarantee(s"/members/${keyToPath(zkAddress.toString)}", Some(Array[Byte]()), CreateMode.EPHEMERAL)
    // Watch and recreate member node because it's possible for ephemeral node to be deleted while session is
    // still alive (https://issues.apache.org/jira/browse/ZOOKEEPER-1740)
    curatorFwk.getData.usingWatcher(new CuratorWatcher {
      def process(event: WatchedEvent): Unit = {
        log.debug("[membership] self watch event: {} when stopped:{}", event, stopped.toString)
        if(!stopped.get && event.getType == EventType.NodeDeleted) {
          log.info("[membership] member node was deleted unexpectedly, recreate")
          curatorFwk.getData.usingWatcher(this).forPath(guarantee(me, Some(Array[Byte]()), CreateMode.EPHEMERAL))
        }
      }
    }).forPath(me)

    //watch over members changes
    lazy val members = curatorFwk.getChildren.usingWatcher(new CuratorWatcher {
      override def process(event: WatchedEvent): Unit = {
        log.debug("[membership] membership watch event:{} when stopped:{}", event, stopped.toString)
        if(!stopped.get && event.getType == EventType.NodeChildrenChanged) {
          refresh(curatorFwk.getChildren.usingWatcher(this).forPath("/members").asScala.toSeq)
        }
      }
    }).forPath("/members")

    def refresh(members: Seq[String]) = {
      // tell the zkClusterActor to update the memory snapshot
      zkClusterActor ! ZkMembersChanged(members.map(m => AddressFromURIString(pathToKey(m))).toSet)
    }

    refresh(members.asScala.toSeq)
  }

  override def postStop(): Unit = {
    //stop the leader latch to quit the competition
    stopped set true
    zkLeaderLatch foreach (_.close())
    zkLeaderLatch = None
  }

  def receive: Actor.Receive = {
    case ZkClientUpdated(updated) =>
      // differentiate first connected to ZK or reconnect after connection lost
      implicit val curatorFwk = updated
      zkLeaderLatch foreach (_.close())
      zkLeaderLatch = Option(new LeaderLatch(curatorFwk, "/leadership"))
      initialize()
      zkLeaderLatch foreach {latch =>
        latch.addListener(new LeaderLatchListener {
          override def isLeader(): Unit = {
            log.info("[membership] leadership acquired @ {}", zkAddress)
            guarantee("/leader", Some(zkAddress))(curatorFwk, log)
          }
          override def notLeader(): Unit = {
            zkClusterActor ! ZkLeaderElected(curatorFwk.getData.forPath("/leader").toAddress)
          }
        }, context.dispatcher)
        latch.start()
        zkClusterActor ! ZkLeaderElected(curatorFwk.getData.forPath("/leader").toAddress)
      }
  }
}


text:
'''
    :codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>`
'''
# Import Python libs
from __future__ import absolute_import

# Import Salt Testing Libs
from salttesting import skipIf, TestCase
from salttesting.mock import (
    NO_MOCK,
    NO_MOCK_REASON,
    MagicMock,
    patch
)

from salttesting.helpers import ensure_in_syspath

ensure_in_syspath('../../')

# Import Salt Libs
from salt.states import serverdensity_device

serverdensity_device.__salt__ = {}

@skipIf(NO_MOCK, NO_MOCK_REASON)
class ServerdensityDeviceTestCase(TestCase):
    '''
    Test cases for salt.states.serverdensity_device
    '''
    # 'monitored' function tests: 1

    def test_monitored(self):
        '''
        Test to device is monitored with Server Density.
        '''
        name = 'my_special_server'

        ret = {'name': name,
               'changes': {},
               'result': True,
               'comment': ''}

        mock_dict = MagicMock(return_value={'id': name})
        mock_t = MagicMock(side_effect=[True, {'agentKey': True},
                                        [{'agentKey': True}]])
        mock_sd = MagicMock(side_effect=[['sd-agent'], [], True])
        with patch.dict(serverdensity_device.__salt__,
                        {'status.all_status': mock_dict,
                         'grains.items': mock_dict,
                         'serverdensity_device.ls': mock_t,
                         'pkg.list_pkgs': mock_sd,
                         'serverdensity_device.install_agent': mock_sd}):
            comt = ('Such server name already exists in this'
                    ' Server Density account. And sd-agent is installed')
            ret.update({'comment': comt})
            self.assertDictEqual(serverdensity_device.monitored(name), ret)

            comt = ('Successfully installed agent and created'
                    ' device in Server Density db.')
            ret.update({'comment': comt, 'changes': {'created_device':
                                                     {'agentKey': True},
                                                     'installed_agent': True}})
            self.assertDictEqual(serverdensity_device.monitored(name), ret)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(ServerdensityDeviceTestCase, needs_daemon=False)


text:
int main() {
  return 0;
}
#else

#include <iostream>
#include <cassert>
#include <windows.h>

bool get_version_info(const char* fileName,
                      int& major,
                      int& minor,
                      int& patch,
                      int& build)
{
  std::cout << "Query FileVersion of \"" << fileName << "\"\n";
  DWORD handle = 0;
  DWORD size = GetFileVersionInfoSize(fileName, &handle);
  BYTE* versionInfo = new BYTE[size];
  if (!GetFileVersionInfo(fileName, handle, size, versionInfo))
  {
    delete[] versionInfo;
    return false;
  }
  // we have version information
  UINT len = 0;
  VS_FIXEDFILEINFO*   vsfi = NULL;
  VerQueryValue(versionInfo, "\\", (void**)&vsfi, &len);
  major = HIWORD(vsfi->dwFileVersionMS);
  minor = LOWORD(vsfi->dwFileVersionMS);
  patch = HIWORD(vsfi->dwFileVersionLS);
  build = LOWORD(vsfi->dwFileVersionLS);
  delete[] versionInfo;
  return true;
}

int main(int argc, char** argv) {
  if(argc == 2) {
    int major, minor, patch, build;
    bool result = get_version_info(argv[1], major, minor, patch, build);
    assert(result);
    std::cout << "version "
              << major << "."
              << minor << "."
              << patch << "."
              << build << "\n";
  } else {
    std::cerr << "Usage:\n"
              << "  display_dll_version_info /path/to/a.dll\n";
    return 0;
  }
}
#endif


text:
layout: article
title: "Brightly colored hair"
excerpt: "PaperFaces portrait of @berniecakez drawn with Paper by 53 on an iPad."
image:
  feature: paperfaces-berniecakez-twitter-lg.jpg
  thumb: paperfaces-berniecakez-twitter-150.jpg
category: paperfaces
tags: [portrait, illustration, paper by 53]
---

PaperFaces portrait of [@berniecakez](http://twitter.com/berniecakez).

{% include paperfaces-boilerplate.html %}


text:
package org.orangepalantir.filters;
import Jama.LUDecomposition;
import Jama.Matrix;

/** Class implements the Savitzy-Golay filter.  The algorithm is based on
 * the algorithm used in
 *
 * Numerical Methods in C: The art of scientific computing second edition
 *
 * This filter is used for smoothing data.  The current implementation is
 * a 1-d approach and a symmetric 2-d approach.
 *
 *
 *     @Author: Matthew B. Smith
 *     @Url: http://orangepalantir.org
 *     @Version: 0.8
 *     @Date: 2/10/2010
 *
 **/
public class SavitzyGolayFilter{
    double[] coefficients;
    int LEFT, RIGHT, ORDER;
    /**
     * Prepares the filter coefficients
     *
     * @param left number of places to the left of the origion
     * @param right number of places to the right of the origion
     * @param order of polynomial used to fit data
     * */
    public SavitzyGolayFilter(int left, int right, int order){

        coefficients = SavitzkyGolayCoefficients(left,right,order);
        LEFT = left;
        RIGHT = right;
        ORDER = order;
    }

    /**
     * Prepares the filter coefficients
     *
     * @param left number of places to the left of the origion
     * @param right number of places to the right of the origion
     * @param order of polynomial used to fit data
     * @param derivative use a SavitzkyGolayFilter to calculate the derivative or order.
     * */
    public SavitzyGolayFilter(int left, int right, int order, int derivative){

        coefficients = SavitzkyGolayCoefficients(left,right,order, derivative);
        LEFT = left;
        RIGHT = right;
        ORDER = order;
    }

    /**
     * filters the data by assuming the ends are reflected.
     *
     * @param data the array that is going to be filtered.
     * */
    public double[] filterData(double[] data){
        int pts = data.length;
        double[] ret_value = new double[pts];

        int j;
        //reflected
        for(j = 0; j<LEFT; j++)
            ret_value[j] = rFilter(data, coefficients, j, LEFT);

        //normal
        for(j = LEFT; j<pts - RIGHT; j++)
            ret_value[j] = filter(data, coefficients, j, LEFT);

        //reflected
        for(j = pts - RIGHT; j<pts; j++)
            ret_value[j] = rFilter(data, coefficients, j, LEFT);

        return ret_value;
    }
    /**
     * filters the data by assuming the ends are reflected.
     *
     * @param data
     * */
    public float[] filterData(float[] data){
        int pts = data.length;
        float[] ret_value = new float[pts];

        int j;
        //reflected
        for(j = 0; j<LEFT; j++)
            ret_value[j] = (float)rFilter(data, coefficients, j, LEFT);

        //normal
        for(j = LEFT; j<pts - RIGHT; j++)
            ret_value[j] = filter(data, coefficients, j, LEFT);

        //reflected
        for(j = pts - RIGHT; j<pts; j++)
            ret_value[j] = (float)rFilter(data, coefficients, j, LEFT);

        return ret_value;
    }

    /**
     *  Calculates one point in the data, similar to one step of a
     *  convolution.
     *
     * @param o - data that will be convolved
     * @param mask - kernel
     * @param start - position of the 'middle point' on the data
     * @param middle - postion of the center of the kernel on the kernel
     *
     * */
    public float filter(float[] o, double[] mask, int start, int middle){
        float out = 0;
        for(int i = 0; i<mask.length; i++)
            out += (float)mask[i]*o[start - middle + i];

        return out;

    }

    /**
     *  Calculates one point in the data, similar to one step of a
     *  convolution.
     *
     * @param o - data that will be convolved
     * @param mask - kernel
     * @param start - position of the 'middle point' on the data
     * @param middle - postion of the center of the kernel on the kernel
     *
     * */
    public double filter(double[] o, double[] mask, int start, int middle){
        double out = 0;
        for(int i = 0; i<mask.length; i++)
            out += mask[i]*o[start - middle + i];

        return out;

    }

    /**
     *  Calculates one point in the data, similar to one step of a
     *  convolution.  This one will wrap the ends of the mask.  Something
     *  like a convolution with reflected boundary conditions.
     *
     * @param o - data that will be convolved
     * @param mask - kernel
     * @param start - position of the 'middle point' on the data
     * @param middle - postion of the center of the kernel on the kernel
     *
     * */
    public double rFilter(double[] o, double[] mask, int start, int middle){
        double out = 0;
        int dex;
        for(int i = 0; i<mask.length; i++){
            dex = Math.abs(start - middle + 1 +i);
            dex = (dex<o.length)?dex: 2*o.length - dex - 1;
            out += mask[i]*o[dex];
        }

        return out;

    }

    /**
     *  Calculates one point in the data, similar to one step of a
     *  convolution.  This one will wrap the ends of the mask.  Something
     *  like a convolution with reflected boundary conditions.
     *
     * @param o - data that will be convolved
     * @param mask - kernel
     * @param start - position of the 'middle point' on the data
     * @param middle - postion of the center of the kernel on the kernel
     *
     * */
    public float rFilter(float[] o, double[] mask, int start, int middle){
        double out = 0;
        int dex;
        for(int i = 0; i<mask.length; i++){
            dex = Math.abs(start - middle + 1 +i);
            dex = (dex<o.length)?dex: 2*o.length - dex - 1;
            out += mask[i]*o[dex];
        }

        return (float)out;

    }

    /**
     *
     *   Creates the array of coefficients for using a least squares polynomial fit
     *   of the data.  Due to the fact the points are equally spaced
     *   and the polynomial least squares is linear in the coefficients,
     *   a set of coefficients can be used for every element.
     *
     *   @param nl - spaces to the left
     *   @param nr - spaces to the right
     *   @param order - the order of the polynomial being used, not that nl+nr+1 must be more than the order of the polynomial
     *   @return a 'time kernel' for convolving in time.
     * */

    public static double[] SavitzkyGolayCoefficients(int nl, int nr, int order){
        if( nl + nr + 1<= order)
            throw new java.lang.IllegalArgumentException(" The order of polynomial cannot exceed the number of points being used." +
                    "If they are equal the input equals the output.");
        int N = nr + nl + 1;
        double[] ret_values = new double[N];
        double[] xvalues = new double[N];
        for(int i = 0; i<N; i++){

            xvalues[i] = -nl + i;

        }

        int counts = 2*order+1;
        double[] moments = new double[counts];
        for(int i = 0; i<counts; i++){
            for(int j = 0; j<N; j++){

                moments[i] += Math.pow(xvalues[j],i);

            }

            moments[i] = moments[i]/N;
        }

        double[][] matrix = new double[order+1][order+1];

        for(int i = 0; i<order+1; i++){
            for(int j = 0; j<order+1; j++){
                matrix[i][j] = moments[counts - i - j - 1];
            }
            System.out.println("");
        }

        Matrix A = new Matrix(matrix);

        LUDecomposition lu = A.lu();

        Matrix x = new Matrix(new double[order+1],order+1);
        Matrix y;
        double[] polynomial;

        for(int i = 0; i<N; i++){

            for(int j = 0; j<order+1; j++)
                x.set( j , 0, Math.pow(xvalues[i],order - j));

            y = lu.solve(x);

            polynomial = y.getColumnPackedCopy();
            ret_values[i] = evaluatePolynomial(polynomial, xvalues[nl])/N;
        }

        return ret_values;

    }

    /**
     *
     *   Creates the array of coefficients for using a least squares polynomial fit
     *   of the data.  Due to the fact the points are equally spaced
     *   and the polynomial least squares is linear in the coefficients,
     *   a set of coefficients can be used for every element.
     *
     *   @param nl - spaces to the left
     *   @param nr - spaces to the right
     *   @param order - the order of the polynomial being used, not that nl+nr+1 must be more than the order of the polynomial
     *   @param derivative - returns a set of derivative coefficients
     * */

    public static double[] SavitzkyGolayCoefficients(int nl, int nr, int order, int derivative){
        if( nl + nr + 1<= order)
            throw new java.lang.IllegalArgumentException(" The order of polynomial cannot exceed the number of points being used." +
                    "If they are equal the input equals the output.");
        int N = nr + nl + 1;
        double[] ret_values = new double[N];
        double[] xvalues = new double[N];
        for(int i = 0; i<N; i++){

            xvalues[i] = -nl + i;

        }

        int counts = 2*order+1;
        double[] moments = new double[counts];
        for(int i = 0; i<counts; i++){
            for(int j = 0; j<N; j++){

                moments[i] += Math.pow(xvalues[j],i);

            }

            moments[i] = moments[i]/N;
        }

        double[][] matrix = new double[order+1][order+1];

        for(int i = 0; i<order+1; i++){
            for(int j = 0; j<order+1; j++){
                matrix[i][j] = moments[counts - i - j - 1];
            }
            System.out.println("");
        }

        Matrix A = new Matrix(matrix);

        LUDecomposition lu = A.lu();

        Matrix x = new Matrix(new double[order+1],order+1);
        Matrix y;
        double[] polynomial;

        for(int i = 0; i<N; i++){

            for(int j = 0; j<order+1; j++)
                x.set( j , 0, Math.pow(xvalues[i],order - j));

            y = lu.solve(x);

            polynomial = y.getColumnPackedCopy();
            ret_values[i] = evaluatePolynomial(polynomial, xvalues[nl], derivative)/N;
        }

        return ret_values;

    }
    /**
     * Creates a 2-d Kernel for using a savitzky-golay filter in 2-d.
     * It fits a 2-d polynomial to the data set if the order was 2.
     *
     * f(x) = a*x**2 + b*x + c*x*y + d*y + e*y**2 + f
     *
     * It is solved by least squares fiting '1' functions to polynomials
     * to 2-d polynomials, then these 1 functions can be summed as a linear
     * sum to create a 2d kernel.
     *
     * The kernel is a symmetric square kernel
     *
     *
     * @param size is the halfwidth of the kernel.
     * @param order is the order of polynomial being fit.
     * */
    public static double[][] getKernel(int size, int order){
        int N = 2*size+1;
        double[][] xyvalues = new double[N][2];

        for(int i = 0; i<N; i++){
            xyvalues[i][0] = i - size;
            xyvalues[i][1] = i - size;
        }
        int M = 0;
        for(int i = 1; i<=order+1; i++)
            M += i;

        double[][] matrix = new double[M][M];
        int pqdex = 0;
        int mndex = 0;
        //the coefficients for a_(pq) for the _XX_ equation
        for(int p = 0; p<=order; p++){
            for(int q = 0; q <= (order - p); q++){

                mndex = 0;
                for(int m = 0; m<=order; m++){
                    for(int n = 0; n<=order-m; n++){

                        double sum = 0;
                        for(int i = 0; i<N; i++){
                            for(int j = 0; j<N; j++){
                                sum += Math.pow(xyvalues[i][0], p + m)*Math.pow(xyvalues[j][1], q + n);

                            }

                        }

                        matrix[pqdex][mndex] = sum;
                        mndex++;
                    }
                }
                pqdex++;
            }
        }

        Matrix mat = new Matrix(matrix);
        LUDecomposition lud = mat.lu();

        //now we want to solve all of the different functions to get our kernel
        double[][] kernel = new double[N][N];
        for(int i = 0; i<N; i++){
            for(int j = 0; j<N; j++){

                double[] equals = new double[M];

                int xp = 0;
                int yp = 0;

                for(int k = 0; k<M; k++){

                    equals[k] = Math.pow(xyvalues[i][0], xp)*Math.pow(xyvalues[j][1],yp);
                    yp++;
                    if(yp>order - xp){

                        yp = 0;
                        xp++;

                    }
                }

                Matrix rs = new Matrix(equals, M);
                Matrix ls = lud.solve(rs);

                //evaluate 2-d function;
                double sum = 0;

                xp = 0;
                yp = 0;

                for(int k = 0; k<M; k++){

                    sum += ls.get(k,0)*Math.pow(xyvalues[size][0], xp)*Math.pow(xyvalues[size][1],yp);

                    yp++;
                    if(yp>order - xp){

                        yp = 0;
                        xp++;

                    }
                }

                kernel[j][i] = sum;
            }

        }

        return kernel;
    }

    /**
     *      Evaluates a polynomial where:
     *      p(x) = poly[0] * x**m + poly[1] * x**(m-1) + ... + poly[m]
     *
     *  @param poly - double array representation of a polynomial
     *  @param x - the variable that will be evaluated.
     **/
    public static double evaluatePolynomial(double[] poly, double x){

        double val = 0;
        int m = poly.length;
        for(int j = 0; j<m; j++){
            val += Math.pow(x,m-j-1)*poly[j];
        }
        return val;
    }

    /**
     *      Evaluates derivative of polynomial where with:
     *      p(x) = poly[0] * x**m + poly[1] * x**(m-1) + ... + poly[m]
     *
     *  @param poly - double array representation of a polynomial
     *  @param x - the variable that will be evaluated.
     *  @param order - the order of the derivative. (n in description)
     *  @return m*(m-1)*...(m - n)*poly[0]*x**(m-n) + (m-1)*...(m - n - 1)*poly[1] * x**(m-2) ... + n!*poly[m - n]
     **/
    public static double evaluatePolynomial(double[] poly, double x, int order){

        double val = 0;
        int m = poly.length;
        for(int j = 0; j<m-order; j++){
            int pow = m - j - 1; //original power before derivatives
            val += Math.pow(x,pow - order)*poly[j]*pfact(pow,order);
        }
        return val;
    }

    /**
     * Partial factorial,
     * @param m power of x
     * @param n number of derivatives
     *
     * @return m*(m-1)*...(m - n)
     */
    public static double pfact(int m, int n){
        int p = 1;
        for(int i = 0; i<n; i++){
            p*=(m - i);
        }
        return p;
    }
}


text:
package io.hawkcd.agent.models;

import io.hawkcd.agent.enums.MaterialType;

public class NugetMaterial extends MaterialDefinition {
    private String repositoryUrl;
    private String packageId;
    private boolean isPrerelease;
    private String packageVersion;

    public NugetMaterial() {
        super.setType(MaterialType.NUGET);
    }

    public String getRepositoryUrl() {
        return this.repositoryUrl;
    }

    public void setRepositoryUrl(String repositoryUrl) {
        this.repositoryUrl = repositoryUrl;
    }

    public String getPackageId() {
        return this.packageId;
    }

    public void setPackageId(String packageId) {
        this.packageId = packageId;
    }

    public boolean isPrerelease() {
        return this.isPrerelease;
    }

    public void setPrerelease(boolean prerelease) {
        this.isPrerelease = prerelease;
    }

    public String getPackageVersion() {
        return this.packageVersion;
    }

    public void setPackageVersion(String packageVersion) {
        this.packageVersion = packageVersion;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>net.jsign.timestamp Class Hierarchy (Jsign - Authenticode implementation in Java (Core) 4.2 API)</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package net.jsign.timestamp

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

java.lang.Throwable (implements java.io.Serializable)

java.lang.Exception

java.lang.RuntimeException

net.jsign.timestamp.TimestampingException

net.jsign.timestamp.Timestamper

net.jsign.timestamp.AuthenticodeTimestamper

net.jsign.timestamp.RFC3161Timestamper

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

net.jsign.timestamp.TimestampingMode

Skip navigation links

Overview

Package

Class

Use

Tree

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2012–2022. All rights reserved.


text:
import re

# from https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case
def snake_case(string):
    ''' Takes a string that represents for example a class name and returns
    the snake case version of it. It is used for model-to-key conversion '''
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string)

    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()

def camelCase(string):
    ''' Takes a string that represents the redis key version of a model name
    and returns its camel case version. It is used for key-to-model
    conversion. '''
    return ''.join(s[0].upper() + s[1:] for s in string.split('_'))

def parse_embed(embed_array):
    if not embed_array:
        return []

    fields = {}

    for item in embed_array:
        pieces = item.split('.', maxsplit=1)

        if pieces[0] not in fields:
            fields[pieces[0]] = None

        if len(pieces) == 2:
            if fields[pieces[0]] is None:
                fields[pieces[0]] = []

            fields[pieces[0]].append(pieces[1])

    return sorted(map(
        lambda item: list(item),
        fields.items()
    ), key=lambda x: x[0])


text:
require 'rexml/document'

module Matchers
  module XML

    class DocumentContainsXPath

      # @param xpath_expr_s [String] - the XPath expression
      # @param optional occurences [Integer] - the number of occurences expected in document
      def initialize(xpath_expr_s, occurrences = 1)
        @xpath_expr_s = xpath_expr_s
        @occurrences = occurrences
      end

      # @param document_s [String] - the document given as String
      def matches?(document_s)
        xml_doc = REXML::Document.new(document_s)
        nodes = REXML::XPath.match(xml_doc, @xpath_expr_s)
        nodes.count >= @occurrences
      end

    end

  end
end


text:
/* -*- Mode: Java; tab-width: 2; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 * acp-java : Arcus Java Client Performance benchmark program
 * Copyright 2013-2014 NAVER Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import net.spy.memcached.collection.BTreeGetResult;
import net.spy.memcached.collection.ByteArrayBKey;
import net.spy.memcached.collection.CollectionAttributes;
import net.spy.memcached.collection.CollectionOverflowAction;
import net.spy.memcached.collection.CollectionResponse;
import net.spy.memcached.collection.Element;
import net.spy.memcached.collection.ElementFlagFilter;
import net.spy.memcached.collection.ElementFlagUpdate;
import net.spy.memcached.collection.ElementValueType;
import net.spy.memcached.collection.SMGetElement;
import net.spy.memcached.internal.CollectionFuture;
import net.spy.memcached.internal.CollectionGetBulkFuture;
import net.spy.memcached.internal.SMGetFuture;
import net.spy.memcached.ops.CollectionOperationStatus;

public class set_bulk_piped_ins implements client_profile {

  public boolean do_test(client cli) {
    try {
      if (!do_set_test(cli))
        return false;
    } catch (Exception e) {
      System.out.printf("client_profile exception. id=%d exception=%s\n",
                        cli.id, e.toString());
      if (cli.conf.print_stack_trace)
        e.printStackTrace();
    }
    return true;
  }

  public boolean do_set_test(client cli) throws Exception {
    // Pick a key
    String key = cli.ks.get_key();

    String[] temp = key.split("-");
    long base = Long.parseLong(temp[1]);
    base = base * 64*1024;

    // Create a set item
    if (!cli.before_request())
      return false;
    ElementValueType vtype = ElementValueType.BYTEARRAY;
    CollectionAttributes attr =
      new CollectionAttributes(cli.conf.client_exptime,
                               new Long(10000),
                               CollectionOverflowAction.error);
    CollectionFuture<Boolean> fb = cli.next_ac.asyncSopCreate(key, vtype, attr);
    boolean ok = fb.get(cli.conf.client_timeout, TimeUnit.MILLISECONDS);
    if (!ok) {
      System.out.printf("sop create failed. id=%d key=%s: %s\n", cli.id,
                        key, fb.getOperationStatus().getResponse());
    }
    if (!cli.after_request(ok))
      return false;
    if (!ok)
      return true;

    // SopInsert Bulk (Piped)
    {
      List<Object> elements = new LinkedList<Object>();
      for (long skey = base; skey < base + 100; skey++) {
        byte[] val = cli.vset.get_value();
        assert(val.length <= 4096);

        long n = skey;
        int i = 0;
        while (n != 0 && i < val.length) {
          val[i] = (byte)(n % 10);
          n = n / 10;
          i++;
        }
        elements.add(val);
      }
      if (!cli.before_request())
        return false;
      CollectionFuture<Map<Integer, CollectionOperationStatus>> f =
        cli.next_ac.asyncSopPipedInsertBulk(key, elements,
                                            new CollectionAttributes());
      Map<Integer, CollectionOperationStatus> status_map =
        f.get(cli.conf.client_timeout, TimeUnit.MILLISECONDS);
      Iterator<CollectionOperationStatus> status_iter =
        status_map.values().iterator();
      while (status_iter.hasNext()) {
        CollectionOperationStatus status = status_iter.next();
        CollectionResponse resp = status.getResponse();
        if (resp != CollectionResponse.STORED) {
          System.out.printf("Collection Set: SopPipedInsertBulk failed." +
	                    " id=%d key=%s response=%s\n", cli.id,
                            key, resp);
        }
      }
      if (!cli.after_request(true))
        return false;
    }

    return true;
  }
}