text:
'use strict';

/* eslint-disable node/no-extraneous-import */
import { Networkish } from '@ethersproject/networks';

/* eslint-disable node/no-extraneous-import */
import { Logger } from '@ethersproject/logger';
import { version } from 'ethers';
import { JSONRPCRequestPayload, JSONRPCResponsePayload } from 'ethereum-protocol';
import JsonRpcProvider from './json-rpc-provider';
const logger = new Logger(version);

// Exported Types
export interface ExternalProvider {
  isMetaMask?: boolean;
  isStatus?: boolean;
  host?: string;
  path?: string;
  sendAsync?: (
    request: JSONRPCRequestPayload,
    callback: (error: any, response: JSONRPCResponsePayload) => void
  ) => void;
  send?: (request: JSONRPCRequestPayload, callback: (error: any, response: JSONRPCResponsePayload) => void) => void;
  request?: (request: JSONRPCRequestPayload) => Promise<any>;
}

let _nextId = 1;

export type JsonRpcFetchFunc = (method: string, params: any[]) => Promise<any>;

type Web3LegacySend = (request: any, callback: (error: Error, response: any) => void) => void;

function buildWeb3LegacyFetcher(sendFunc: Web3LegacySend): JsonRpcFetchFunc {
  return function (method: string, params: any[]): Promise<any> {
    const request = {
      method: method,
      params: params,
      id: _nextId++,
      jsonrpc: '2.0',
    };

    return new Promise((resolve, reject) => {
      sendFunc(request, (error, response) => {
        if (error) {
          return reject(error);
        }
        if (response.error) {
          const error = new Error(response.error.message);
          (error as any).code = response.error.code;
          (error as any).data = response.error.data;
          return reject(error);
        }
        resolve(response.result);
      });
    });
  };
}

function buildEip1193Fetcher(provider: ExternalProvider): JsonRpcFetchFunc {
  return function (method: string, params: any[]): Promise<any> {
    if (!provider.request) {
      throw new Error('request function is not exist');
    }
    if (params == null) {
      params = [];
    }

    const request = { method, params, id: _nextId++, jsonrpc: '2.0' };

    return provider.request(request).then(
      (response) => {
        return response;
      },
      (error) => {
        throw error;
      }
    );
  };
}

// This is the patched @ethersproject/providers/Web3Provider
// that make ExternalProvider class compatible
// with existing cardpay WalletConnectProvider
// and extend from JSONRpcProvider
// to get the same behavior on handling error messages
export default class Web3Provider extends JsonRpcProvider {
  readonly provider: ExternalProvider;
  readonly jsonRpcFetchFunc: JsonRpcFetchFunc;

  constructor(provider: ExternalProvider | JsonRpcFetchFunc, network?: Networkish) {
    logger.checkNew(new.target, Web3Provider);

    if (provider == null) {
      logger.throwArgumentError('missing provider', 'provider', provider);
    }

    let path: string;
    let jsonRpcFetchFunc: JsonRpcFetchFunc | null = null;
    let subprovider: ExternalProvider | null = null;

    if (typeof provider === 'function') {
      path = 'unknown:';
      jsonRpcFetchFunc = provider;
    } else {
      path = provider.host || provider.path || '';
      if (!path && provider.isMetaMask) {
        path = 'metamask';
      }

      subprovider = provider;

      if (provider.request) {
        if (path === '') {
          path = 'eip-1193:';
        }
        jsonRpcFetchFunc = buildEip1193Fetcher(provider);
      } else if (provider.sendAsync) {
        jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider.sendAsync.bind(provider));
      } else if (provider.send) {
        jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider.send.bind(provider));
      } else {
        logger.throwArgumentError('unsupported provider', 'provider', provider);
      }

      if (!path) {
        path = 'unknown:';
      }
    }

    super(path, network);

    this.jsonRpcFetchFunc = jsonRpcFetchFunc as JsonRpcFetchFunc;
    this.provider = subprovider as ExternalProvider;
  }

  send(method: string, params: any[]): Promise<any> {
    return this.jsonRpcFetchFunc(method, params);
  }
}


text:
using std::vector;
using std::string;

class IConfigureService;
class CDbDataHandler
{
    typedef IConfigureService *(*FnCreateObj)();
    typedef void  (*FnDestroyObj)(IConfigureService*);
    struct SConfServcie
    {
        IConfigureService *pServiceObj;
        FnCreateObj fnCreateObj;
        FnDestroyObj fnDestroyObj;
        void *pLibHandle;
    };

	typedef vector<SConfServcie> plugin_container;
    typedef plugin_container::iterator plugin_iterator;
    typedef plugin_container::const_iterator plugin_citerator;

public:
    static CDbDataHandler* GetInstance();
public:
	int LoadPlugins();
	int LoadData()const;
    int FastLoadData()const;
	void Dump();
private:
    CDbDataHandler(){}
    CDbDataHandler(const CDbDataHandler& rhd){}
    CDbDataHandler& operator=(const CDbDataHandler& rhd){return *this;}
private:
	int LoadSO(const char* pSoObj, SConfServcie &sService);
private:
    static CDbDataHandler* pInstance_;
	vector<SConfServcie> m_confServcies;
	static const char* SERVICE_PATH;
};

#endif

redpajama_set_name: RedPajamaGithub


text:
"""
Example Airflow DAG for Google BigQuery service.
"""
from __future__ import annotations

import os
from datetime import datetime

from airflow import models
from airflow.providers.google.cloud.operators.bigquery import (
    BigQueryCreateEmptyDatasetOperator,
    BigQueryCreateEmptyTableOperator,
    BigQueryDeleteDatasetOperator,
)
from airflow.providers.google.cloud.operators.gcs import GCSCreateBucketOperator, GCSDeleteBucketOperator
from airflow.providers.google.cloud.transfers.bigquery_to_bigquery import BigQueryToBigQueryOperator
from airflow.providers.google.cloud.transfers.bigquery_to_gcs import BigQueryToGCSOperator
from airflow.utils.trigger_rule import TriggerRule

ENV_ID = os.environ.get("SYSTEM_TESTS_ENV_ID")
PROJECT_ID = os.environ.get("SYSTEM_TESTS_GCP_PROJECT")
DAG_ID = "example_bigquery_transfer"

DATASET_NAME = f"dataset_{DAG_ID}_{ENV_ID}"
BUCKET_NAME = f"bucket_{DAG_ID}_{ENV_ID}"

ORIGIN = "origin"
TARGET = "target"

with models.DAG(
    DAG_ID,
    schedule="@once",  # Override to match your needs
    start_date=datetime(2021, 1, 1),
    catchup=False,
    tags=["example", "bigquery"],
) as dag:
    create_bucket = GCSCreateBucketOperator(
        task_id="create_bucket", bucket_name=BUCKET_NAME, project_id=PROJECT_ID
    )

    create_dataset = BigQueryCreateEmptyDatasetOperator(task_id="create_dataset", dataset_id=DATASET_NAME)

    create_origin_table = BigQueryCreateEmptyTableOperator(
        task_id=f"create_{ORIGIN}_table",
        dataset_id=DATASET_NAME,
        table_id=ORIGIN,
        schema_fields=[
            {"name": "emp_name", "type": "STRING", "mode": "REQUIRED"},
            {"name": "salary", "type": "INTEGER", "mode": "NULLABLE"},
        ],
    )

    create_target_table = BigQueryCreateEmptyTableOperator(
        task_id=f"create_{TARGET}_table",
        dataset_id=DATASET_NAME,
        table_id=TARGET,
        schema_fields=[
            {"name": "emp_name", "type": "STRING", "mode": "REQUIRED"},
            {"name": "salary", "type": "INTEGER", "mode": "NULLABLE"},
        ],
    )

    copy_selected_data = BigQueryToBigQueryOperator(
        task_id="copy_selected_data",
        source_project_dataset_tables=f"{DATASET_NAME}.{ORIGIN}",
        destination_project_dataset_table=f"{DATASET_NAME}.{TARGET}",
    )

    bigquery_to_gcs = BigQueryToGCSOperator(
        task_id="bigquery_to_gcs",
        source_project_dataset_table=f"{DATASET_NAME}.{ORIGIN}",
        destination_cloud_storage_uris=[f"gs://{BUCKET_NAME}/export-bigquery.csv"],
    )

    delete_dataset = BigQueryDeleteDatasetOperator(
        task_id="delete_dataset",
        dataset_id=DATASET_NAME,
        delete_contents=True,
        trigger_rule=TriggerRule.ALL_DONE,
    )

    delete_bucket = GCSDeleteBucketOperator(
        task_id="delete_bucket", bucket_name=BUCKET_NAME, trigger_rule=TriggerRule.ALL_DONE
    )

    (
        # TEST SETUP
        create_bucket
        >> create_dataset
        >> create_origin_table
        >> create_target_table
        # TEST BODY
        >> copy_selected_data
        >> bigquery_to_gcs
        # TEST TEARDOWN
        >> delete_dataset
        >> delete_bucket
    )

    from tests.system.utils.watcher import watcher

    # This test needs watcher in order to properly mark success/failure
    # when "tearDown" task with trigger rule is part of the DAG
    list(dag.tasks) >> watcher()

from tests.system.utils import get_test_run  # noqa: E402

# Needed to run the example DAG with pytest (see: tests/system/README.md#run_via_pytest)
test_run = get_test_run(dag)


text:
package org.apache.servicecomb.foundation.protobuf;

import java.lang.reflect.Type;
import java.util.Map;

import org.apache.servicecomb.foundation.common.concurrent.ConcurrentHashMapEx;
import org.apache.servicecomb.foundation.protobuf.internal.bean.BeanDescriptorManager;
import org.apache.servicecomb.foundation.protobuf.internal.schema.deserializer.DeserializerSchemaManager;
import org.apache.servicecomb.foundation.protobuf.internal.schema.serializer.SerializerSchemaManager;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

import io.protostuff.compiler.model.Message;
import io.protostuff.compiler.model.Proto;
import io.protostuff.compiler.model.Service;
import io.protostuff.compiler.model.ServiceMethod;

public class ProtoMapper {
  private final ObjectMapper jsonMapper;

  private final BeanDescriptorManager beanDescriptorManager;

  private final Proto proto;

  private final SerializerSchemaManager serializerSchemaManager;

  private final DeserializerSchemaManager deserializerSchemaManager;

  // key is message canonical name
  // this allowed developer to control any type deserializer
  // otherwise any type will be deserialized to LinkedHashMap
  private final Map<String, JavaType> anyTypes = new ConcurrentHashMapEx<>();

  protected ProtoMapper(ObjectMapper jsonMapper, BeanDescriptorManager beanDescriptorManager, Proto proto) {
    this.jsonMapper = jsonMapper;
    this.beanDescriptorManager = beanDescriptorManager;
    this.proto = proto;

    serializerSchemaManager = new SerializerSchemaManager(this);
    deserializerSchemaManager = new DeserializerSchemaManager(this);
  }

  public Proto getProto() {
    return proto;
  }

  public SerializerSchemaManager getSerializerSchemaManager() {
    return serializerSchemaManager;
  }

  public DeserializerSchemaManager getDeserializerSchemaManager() {
    return deserializerSchemaManager;
  }

  public ObjectMapper getJsonMapper() {
    return jsonMapper;
  }

  public BeanDescriptorManager getBeanDescriptorManager() {
    return beanDescriptorManager;
  }

  public Map<String, JavaType> getAnyTypes() {
    return anyTypes;
  }

  public void addAnyType(String canonicalName, Type type) {
    anyTypes.put(canonicalName, TypeFactory.defaultInstance().constructType(type));
  }

  public Message getMessageFromCanonicaName(String messageCanonicalName) {
    for (Message message : proto.getMessages()) {
      if (message.getCanonicalName().equals(messageCanonicalName)) {
        return message;
      }
    }

    return null;
  }

  public Message getRequestMessage(String operationId) {
    Service service = proto.getServices().get(0);
    ServiceMethod serviceMethod = service.getMethod(operationId);
    if (serviceMethod == null) {
      throw new IllegalArgumentException("operation not found, operation id=" + operationId);
    }
    return serviceMethod.getArgType();
  }

  public Message getResponseMessage(String operationId) {
    Service service = proto.getServices().get(0);
    ServiceMethod serviceMethod = service.getMethod(operationId);
    return serviceMethod.getReturnType();
  }

  public synchronized RootSerializer createRootSerializer(String shortMessageName, Type type) {
    Message message = proto.getMessage(shortMessageName);
    if (message == null) {
      throw new IllegalStateException("can not find proto message to create serializer, name=" + shortMessageName);
    }

    return createRootSerializer(message, type);
  }

  public synchronized RootSerializer createRootSerializer(Message message, Type type) {
    return serializerSchemaManager.createRootSerializer(message, type);
  }

  public synchronized <T> RootDeserializer<T> createRootDeserializer(String shortMessageName, Type type) {
    Message message = proto.getMessage(shortMessageName);
    if (message == null) {
      throw new IllegalStateException("can not find proto message to create deserializer, name=" + shortMessageName);
    }

    return createRootDeserializer(message, type);
  }

  public synchronized <T> RootDeserializer<T> createRootDeserializer(Message message, Type type) {
    return deserializerSchemaManager.createRootDeserializer(message, type);
  }

  public synchronized <T> RootDeserializer<T> createRootDeserializer(Message message, Map<String, Type> types) {
    return deserializerSchemaManager.createRootDeserializer(message, types);
  }
}


text:
#include "tensorflow/c/eager/gradient_checker.h"

#include <memory>

#include "absl/types/span.h"
#include "tensorflow/c/eager/abstract_tensor_handle.h"
#include "tensorflow/c/experimental/ops/math_ops.h"
#include "tensorflow/c/tf_tensor.h"

namespace tensorflow {
namespace gradients {

using namespace std;

// ================== Helper functions =================

// Fills data with values [start,end) with given step size.
void Range(vector<int32_t>* data, int32_t start, int32_t end,
           int32_t step = 1) {
  for (int32_t i = start; i < end; i += step) {
    (*data)[i] = i;
  }
}

// Fills out_dims with the dimensions of the given tensor.
void GetDims(const TF_Tensor* t, int64_t* out_dims) {
  int num_dims = TF_NumDims(t);
  for (int i = 0; i < num_dims; i++) {
    out_dims[i] = TF_Dim(t, i);
  }
}

// Runs model as is if output is a scalar,
// else sums the output tensor before returning.
Status RunAndMaybeSum(AbstractContext* ctx, Model forward,
                      absl::Span<AbstractTensorHandle* const> inputs,
                      absl::Span<AbstractTensorHandle*> outputs,
                      bool use_function) {
  AbstractTensorHandle* model_outputs[1];

  // Run the model.
  TF_RETURN_IF_ERROR(
      RunModel(forward, ctx, inputs, model_outputs, use_function));
  AbstractTensorHandlePtr model_out(model_outputs[0]);

  TF_Tensor* model_out_tensor;
  TF_RETURN_IF_ERROR(GetValue(model_out.get(), &model_out_tensor));
  int num_dims_out = TF_NumDims(model_out_tensor);
  TF_DeleteTensor(model_out_tensor);

  // If the output is a scalar, then return the scalar output
  if (num_dims_out == 0) {
    outputs[0] = model_out.release();
    return Status::OK();
  }

  // Else, reduce sum the output to get a scalar

  // Will sum all dimensions, so get a Tensor containing [0,...,num_dims_out-1].
  AbstractTensorHandlePtr sum_dims;
  {
    vector<int32_t> vals(num_dims_out);
    int64_t vals_shape[] = {num_dims_out};
    Range(&vals, 0, num_dims_out);
    AbstractTensorHandle* sum_dims_raw = nullptr;
    TF_RETURN_IF_ERROR(TestTensorHandleWithDims<int32_t, TF_INT32>(
        ctx, vals.data(), vals_shape, 1, &sum_dims_raw));
    sum_dims.reset(sum_dims_raw);
  }

  // Reduce sum the output on all dimensions.
  TF_RETURN_IF_ERROR(ops::Sum(ctx, model_out.get(), sum_dims.get(), &outputs[0],
                              /*keep_dims=*/false, "sum_output"));
  return Status::OK();
}
// ========================= End Helper Functions==============================

Status CalcNumericalGrad(AbstractContext* ctx, Model forward,
                         absl::Span<AbstractTensorHandle* const> inputs,
                         int input_index, bool use_function,
                         AbstractTensorHandle** numerical_grad) {
  vector<AbstractTensorHandle*> theta_inputs(inputs.size());
  for (int i{}; i < inputs.size(); ++i) {
    theta_inputs[i] = inputs[i];
  }

  AbstractTensorHandle* theta =
      theta_inputs[input_index];  // parameter we are grad checking

  // Convert from AbstractTensor to TF_Tensor.
  TF_Tensor* theta_tensor;
  TF_RETURN_IF_ERROR(GetValue(theta, &theta_tensor));

  // Get number of elements and fill data.
  int num_elems = TF_TensorElementCount(theta_tensor);
  vector<float> theta_data(num_elems);
  memcpy(theta_data.data(), TF_TensorData(theta_tensor),
         TF_TensorByteSize(theta_tensor));

  // Initialize space for the numerical gradient.
  vector<float> dtheta_approx(num_elems);

  // Get theta shape and store in theta_dims.
  int num_dims = TF_NumDims(theta_tensor);
  vector<int64_t> theta_dims(num_dims);
  GetDims(theta_tensor, theta_dims.data());

  // Initialize auxilary data structures.
  vector<float> thetaPlus_data(num_elems);
  vector<float> thetaMinus_data(num_elems);
  AbstractTensorHandle* f_outputs[1];

  // Numerical Grad Check
  for (int i = 0; i < num_elems; i++) {
    // Get relative epsilon value
    float epsilon = theta_data[i] == 0 ? 1e-4 : std::abs(theta_data[i] * 1e-4);
    AbstractTensorHandlePtr two_eps;
    {
      AbstractTensorHandle* two_eps_raw = nullptr;
      TF_RETURN_IF_ERROR(TestScalarTensorHandle<float, TF_FLOAT>(
          ctx, 2 * epsilon, &two_eps_raw));
      two_eps.reset(two_eps_raw);
    }

    // Initialize theta[i] + epsilon.
    memcpy(thetaPlus_data.data(), TF_TensorData(theta_tensor),
           TF_TensorByteSize(theta_tensor));
    thetaPlus_data[i] += epsilon;
    AbstractTensorHandlePtr thetaPlus;
    {
      AbstractTensorHandle* thetaPlus_raw = nullptr;
      TF_RETURN_IF_ERROR(TestTensorHandleWithDims<float, TF_FLOAT>(
          ctx, thetaPlus_data.data(), theta_dims.data(), num_dims,
          &thetaPlus_raw));
      thetaPlus.reset(thetaPlus_raw);
    }

    // Initialize theta[i] - epsilon.
    memcpy(&thetaMinus_data[0], TF_TensorData(theta_tensor),
           TF_TensorByteSize(theta_tensor));
    thetaMinus_data[i] -= epsilon;
    AbstractTensorHandlePtr thetaMinus;
    {
      AbstractTensorHandle* thetaMinus_raw = nullptr;
      TF_RETURN_IF_ERROR(TestTensorHandleWithDims<float, TF_FLOAT>(
          ctx, thetaMinus_data.data(), theta_dims.data(), num_dims,
          &thetaMinus_raw));
      thetaMinus.reset(thetaMinus_raw);
    }

    // Get f(theta + eps):
    theta_inputs[input_index] = thetaPlus.get();
    TF_RETURN_IF_ERROR(
        RunAndMaybeSum(ctx, forward, theta_inputs, f_outputs, use_function));
    AbstractTensorHandlePtr fPlus(f_outputs[0]);

    // Get f(theta - eps):
    theta_inputs[input_index] = thetaMinus.get();
    TF_RETURN_IF_ERROR(
        RunAndMaybeSum(ctx, forward, theta_inputs, f_outputs, use_function));
    AbstractTensorHandlePtr fMinus(f_outputs[0]);

    // Take Difference of both estimates: (f(theta + eps) - f(theta - eps)).
    TF_RETURN_IF_ERROR(
        ops::Sub(ctx, fPlus.get(), fMinus.get(), f_outputs, "sub_top"));
    AbstractTensorHandlePtr fDiff(f_outputs[0]);

    // Calculate using the difference quotient definition:
    // (f(theta + eps) - f(theta - eps)) / (2 * eps).
    TF_RETURN_IF_ERROR(
        ops::Div(ctx, fDiff.get(), two_eps.get(), f_outputs, "diff_quotient"));
    AbstractTensorHandlePtr diff_quotient(f_outputs[0]);

    TF_Tensor* grad_tensor;
    TF_RETURN_IF_ERROR(GetValue(diff_quotient.get(), &grad_tensor));
    float grad_data[1];
    memcpy(&grad_data[0], TF_TensorData(grad_tensor),
           TF_TensorByteSize(grad_tensor));
    TF_DeleteTensor(grad_tensor);
    dtheta_approx[i] = grad_data[0];
  }

  // Populate *numerical_grad with the data from dtheta_approx.
  TF_RETURN_IF_ERROR(TestTensorHandleWithDims<float, TF_FLOAT>(
      ctx, dtheta_approx.data(), theta_dims.data(), num_dims, numerical_grad));
  TF_DeleteTensor(theta_tensor);
  return Status::OK();
}

}  // namespace gradients
}  // namespace tensorflow


text:
#ifndef __GRAPHICS3D_H__
#define __GRAPHICS3D_H__

#include <SDL.h>
#include <GL/glew.h>

#define EPSILON   1e-6f

#define TWOPI 6.283185308

/* conversion factor for converting from radians to degrees*/
#define RADTODEG  57.295779513082

/* conversion factor for converting from degrees to radians*/
#define DEGTORAD  0.017453292519943295769236907684886

/**
 * @brief initialize the 3d graphics system
 * @param sw the screen width you want
 * @param sh the screen height you want
 * @param fullscreen set true to initialize to fullscreen
 * @param project the name to appear on the game window
 * @param frameDelay the desired delay (in ms) between frames
 * @return -1 on error, 0 otherwise
 */
int graphics3d_init(float sw,float sh,int fullscreen,const char *project, Uint32 frameDelay);

/**
 * @brief get the active shader program index
 * @return 0 on error or the index of the active shader program
 */
GLuint graphics3d_get_shader_program();

/**
 * @brief clear the drawing context and ready the next frame
 */
void graphics3d_frame_begin();

/**
 * @brief advance the frame, taking into account desired frame rate
 */
void graphics3d_next_frame();

void draw_title();

void draw_speed();

void orthogonalStart();

void orthogonalEnd();

void drawQuad(Vec2D size, Vec2D pos, GLuint tex_id, GLfloat angle, int depthTest);

void bind_image(char* file, GLuint *id);

void draw_gear();

void draw_lap();

extern GLfloat needleRotation;

extern int gear;

extern int lap;

#endif


text:
/*
*  BuildBEMatrix.cc:  class to build Boundary Elements matrix
*
*  Written by:
*   Saeed Babaeizadeh
*   Northeastern University
*   January 2006
*/

#include <Core/Algorithms/Legacy/Forward/BuildBEMatrixAlgo.h>

#include <algorithm>
#include <map>
#include <iostream>
#include <string>
#include <fstream>
#include <numeric>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm/copy.hpp>

#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/BlockMatrix.h>
#include <Core/Basis/TriLinearLgn.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/Legacy/Field/TriSurfMesh.h>
#include <Core/GeometryPrimitives/Vector.h>
#include <Core/GeometryPrimitives/Point.h>
#include <Core/GeometryPrimitives/PointVectorOperators.h>

using namespace SCIRun;
using namespace SCIRun::Core::Algorithms::Forward;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;

ALGORITHM_PARAMETER_DEF(Forward, FieldNameList);
ALGORITHM_PARAMETER_DEF(Forward, FieldTypeList);
ALGORITHM_PARAMETER_DEF(Forward, BoundaryConditionList);
ALGORITHM_PARAMETER_DEF(Forward, InsideConductivityList);
ALGORITHM_PARAMETER_DEF(Forward, OutsideConductivityList);

void BuildBEMatrixBase::getOmega(
  const Vector& y1,
  const Vector& y2,
  const Vector& y3,
  DenseMatrix& coef)
{
  /*
  This function deals with the analytical solutions of the various integrals in the stiffness matrix
  The function is concerned with the integrals of the linear interpolations functions over the triangles
  and takes care of the solid spherical angle. As in most cases not all values are needed the computation
  is split up in integrals from one surface to another one

  The computational scheme follows the analytical formulas derived by the
  de Munck 1992 (IEEE Trans Biomed Engng, 39-9, pp 986-90)
  */
  const double epsilon  = 1e-12;
  Vector y21 = y2 - y1;
  Vector y32 = y3 - y2;
  Vector y13 = y1 - y3;

  Vector Ny( y1.length() , y2.length() , y3.length() );

  Vector Nyij( y21.length() , y32.length() , y13.length() );

  Vector gamma( 0 , 0 , 0 );
  double NomGamma , DenomGamma;

  NomGamma = Ny[0]*Nyij[0] + Dot(y1,y21);
  DenomGamma = Ny[1]*Nyij[0] + Dot(y2,y21);
  if (fabs(DenomGamma-NomGamma) > epsilon && (DenomGamma != 0) && NomGamma != 0 ){
    gamma[0] = -1/Nyij[0] * log(NomGamma/DenomGamma);
  }
  NomGamma = Ny[1]*Nyij[1] + Dot(y2,y32);
  DenomGamma = Ny[2]*Nyij[1] + Dot(y3,y32);
  if (fabs(DenomGamma-NomGamma) > epsilon && (DenomGamma != 0) && NomGamma != 0 ){
    gamma[1] = -1/Nyij[1] * log(NomGamma/DenomGamma);
  }
  NomGamma = Ny[2]*Nyij[2] + Dot(y3,y13);
  DenomGamma = Ny[0]*Nyij[2] + Dot(y1,y13);
  if (fabs(DenomGamma-NomGamma) > epsilon && (DenomGamma != 0) && NomGamma != 0 ){
    gamma[2] = -1/Nyij[2] * log(NomGamma/DenomGamma);
  }

  double d = Dot( y1, Cross(y2, y3) );

  Vector OmegaVec = (gamma[2]-gamma[0])*y1 + (gamma[0]-gamma[1])*y2 + (gamma[1]-gamma[2])*y3;

  /*
  In order to avoid problems with the arctan used in de Muncks paper
  the result is tested. A problem is that his formula under certain
  circumstances leads to unexpected changes of signs. Hence to avoid
  this, the denominator is checked and 2*pi is added if necessary.
  The problem without the two pi results in the following situation in
  which division of the triangle into three pieces results into
  an opposite sign compared to the spherical angle of the total
  triangle. These cases are rare but existing.
  */

  double Nn=0 , Omega=0 ;
  Nn = Ny[0]*Ny[1]*Ny[2] + Ny[0]*Dot(y2,y3) + Ny[2]*Dot(y1,y2) + Ny[1]*Dot(y3,y1);

  if (Nn > 0)  Omega = 2 * atan( d / Nn );
  if (Nn < 0)  Omega = 2 * atan( d / Nn ) + 2*M_PI ;
  if (Nn == 0)
  {
    if ( d > 0 )
      Omega = M_PI;
    else
      Omega = -M_PI;
  }

  Vector N = Cross(y21, -y13);
  double Zn1 = Dot(Cross(y2, y3) , N);
  double Zn2 = Dot(Cross(y3, y1) , N);
  double Zn3 = Dot(Cross(y1, y2) , N);

  double A2 = N.length2();
  coef(0,0) = (1/A2) * ( Zn1*Omega + d * Dot(y32, OmegaVec) );
  coef(0,1) = (1/A2) * ( Zn2*Omega + d * Dot(y13, OmegaVec) );
  coef(0,2) = (1/A2) * ( Zn3*Omega + d * Dot(y21, OmegaVec) );

}

void  BuildBEMatrixBase::get_cruse_weights(
  const Vector& p1,
  const Vector& p2,
  const Vector& p3,
  double s,
  double r,
  double area,
  DenseMatrix& cruse_weights)
{
  /*
  Inputs: p1,p2,p3= cartesian coordiantes of the triangle vertices ;
  area = triangle area
  Output: cruse_weights = The weighting factors for the 7 Radon points of the triangle
  Format of the cruse_weights matrix
  Radon point 1       Radon Point 2    ...     Radon Point 7
  Vertex 1 ->
  Vertex 2 ->
  Vertex 3 ->

  Set up the local coordinate system around the triangle. This is a 2-D system and
  for ease of use, the x-axis is chosen as the line between the first and second vertex
  of the triangle. From that the vertex of the third point is found in local coordinates.
  */

  // The angle between the F2 and F3, at vertex 1 is (pi - 'alpha').
  Vector fg2 = p1 - p3;
  double fg2_length = fg2.length();

  Vector fg3 = p2 - p1;
  double fg3_length = fg3.length();

  double cos_alpha = - Dot(fg3,fg2) / (fg2_length * fg3_length);
  double sin_alpha = sqrt(1 - cos_alpha * cos_alpha);

  // Now the vertices in local coordinates
  Vector locp1(0 , 0 , 0);
  Vector locp2(fg3_length , 0 , 0);
  Vector locp3(fg2_length * cos_alpha , fg2_length * sin_alpha , 0);

  DenseMatrix Fx(3, 1);
  Fx << locp3[0] - locp2[0],
    locp1[0] - locp3[0],
    locp2[0] - locp1[0];

  DenseMatrix Fy(3, 1);
  Fy << locp3[1] - locp2[1],
    locp1[1] - locp3[1],
    locp2[1] - locp1[1];

  Vector centroid = (locp1 + locp2 + locp3) / 3;
  DenseMatrix loc_radpt_x(1, 7);
  DenseMatrix loc_radpt_y(1, 7);
  loc_radpt_x(0,0) = centroid[0];
  loc_radpt_y(0,0) = centroid[1];
  Vector temp = (1-s) * centroid;
  loc_radpt_x(0,1) = temp[0] + locp1[0]*s;
  loc_radpt_y(0,1) = temp[1] + locp1[1]*s;
  loc_radpt_x(0,2) = temp[0] + locp2[0]*s;
  loc_radpt_y(0,2) = temp[1] + locp2[1]*s;
  loc_radpt_x(0,3) = temp[0] + locp3[0]*s;
  loc_radpt_y(0,3) = temp[1] + locp3[1]*s;
  temp = (1-r) * centroid;
  loc_radpt_x(0,4) = temp[0] + locp1[0]*r;
  loc_radpt_y(0,4) = temp[1] + locp1[1]*r;
  loc_radpt_x(0,5) = temp[0] + locp2[0]*r;
  loc_radpt_y(0,5) = temp[1] + locp2[1]*r;
  loc_radpt_x(0,6) = temp[0] + locp3[0]*r;
  loc_radpt_y(0,6) = temp[1] + locp3[1]*r;

  auto A = (0.5/area) * (Fy * loc_radpt_x - Fx * loc_radpt_y);

  DenseMatrix ones(1, 7, 1.0);
  DenseMatrix E(3, 1);
  /*
  E is a 1X3 matrix: [1st vertex  ;  2nd vertex  ;  3rd vertex]
  E = [1/3 ; 1/3 ; 1/3] + (0.5/area)*(Fy*xmid - Fx*ymid);
  but there is no need to compute the E because by our choice of the
  local coordinates, it is easy to show that the E is always [1 ; 0 ; 0]!
  */
  E << 1,0,0;
  cruse_weights = (E * ones) - A;
}

void BuildBEMatrixBase::get_g_coef(
  const Vector& p1,
  const Vector& p2,
  const Vector& p3,
  const Vector& op,
  double s,
  double r,
  const Vector& centroid,
  DenseMatrix& g_coef)
{
  // Inputs: p1,p2,p3= cartesian coordiantes of the triangle vertices ; op= Observation Point
  // Output: g_coef = G Values (Coefficients) at 7 Radon's points = 1/r
  Vector radpt = centroid - op;
  g_coef(0,0) = 1 / radpt.length();

  Vector temp = centroid * (1-s) - op;
  radpt = temp + p1 * s;
  g_coef(0,1) = 1 / radpt.length();
  radpt = temp + p2 * s;
  g_coef(0,2) = 1 / radpt.length();
  radpt = temp + p3 * s;
  g_coef(0,3) = 1 / radpt.length();

  temp = centroid * (1-r) - op;
  radpt = temp + p1 * r;
  g_coef(0,4) = 1 / radpt.length();
  radpt = temp + p2 * r;
  g_coef(0,5) = 1 / radpt.length();
  radpt = temp + p3 * r;
  g_coef(0,6) = 1 / radpt.length();
}

void BuildBEMatrixBase::bem_sing(
  const Vector& p1,
  const Vector& p2,
  const Vector& p3,
  unsigned int op_n,
  DenseMatrix& g_values,
  double s,
  double r,
  DenseMatrix& R_W)
{
  /*
  This is Jeroen's method, converted from his Matlab code, for dealing with weightings corresponding to singular triangles
  */
  Vector A,B,C,P,BC,BA,AC,AP;
  DenseMatrix WAPB(3,1);
  DenseMatrix WAPC(3,1);
  int one=0,two=1,three=2;

  switch(op_n)
  {
  case 0:
    A = p1; B=p2; C=p3;
    one=0; two=1; three=2;
    break;
  case 1:
    A = p2; B=p3; C=p1;
    one=1; two=2; three=0;
    break;
  case 2:
    A = p3; B=p1; C=p2;
    one=2; two=0; three=1;
    break;
  default:;
  }

  BC=C-B; BA=A-B; AC=C-A;
  double RL = Dot(BA,BC/BC.length())/BC.length();
  P=RL*BC+B;
  AP=A-P;
  double lAP=AP.length();
  double lBC=BC.length();
  double lBP=fabs(RL)*lBC;
  double lCP=fabs(1-RL)*lBC;
  double lAB=BA.length();
  double lAC=AC.length();
  double a,b,c,w,log_term;

  if(fabs(RL) > 0)
  {
    a=lAP; b=lBP; c=lAB;
    log_term=log( (b+c)/a );
    WAPB(0,0)=a/2 * log_term;
    w=1-RL;
    WAPB(1,0)=a* (( a-c)*(-1+w) + b*w*log_term )/(2*b);
    w=RL;
    WAPB(2,0)=a*w *( a-c  +  b*log_term )/(2*b);
  }
  else
  {
    WAPB(0,0)=0; WAPB(1,0)=0; WAPB(2,0)=0;
  }

  if(fabs(RL-1) > 0)
  {
    a = lAP; b = lCP; c = lAC;
    log_term = log( (b+c)/a );
    WAPC(0,0)=a/2 * log_term;
    w = 1-RL;
    WAPC(1,0)=a*w *( a-c  +  b*log_term )/(2*b);
    w = RL;
    WAPC(2,0)=a* (( a-c)*(-1+w) + b*w*log_term )/(2*b);
  }
  else
  {
    WAPC(0,0)=0; WAPC(1,0)=0; WAPC(2,0)=0;
  }

  if(RL<0)
  {
    WAPB(0,0)*=-1.0; WAPB(1,0)*=-1.0; WAPB(2,0)*=-1.0;
  }
  if(RL>1)
  {
    WAPC(0,0)*=-1.0; WAPC(1,0)*=-1.0; WAPC(2,0)*=-1.0;
  }

  g_values(one,0) = WAPB(0,0) + WAPC(0,0);
  g_values(two,0) = WAPB(1,0) + WAPC(1,0);
  g_values(three,0) = WAPB(2,0) + WAPC(2,0);
}

void BuildBEMatrixBase::get_auto_g(
  const Vector& p1,
  const Vector& p2,
  const Vector& p3,
  unsigned int op_n,
  DenseMatrix& g_values,
  double s,
  double r,
  DenseMatrix& R_W)
{
  /*
  A routine to solve the Auto G-parameter integral for a triangle from
  a "closed" observation point.
  The scheme is the standard one for all the BEM routines.
  Input are the observation point and triangle co-ordinates
  Input:
  op_n = observation point number (1, 2 or 3)
  p1,p2,p3 = triangle co-ordinates (REAL)

  Output:
  g_values
  = the total values for the 1/r integral for
  each of the subtriangles associated with each
  integration triangle vertex about the observation
  point defined by the calling
  program.
  */

  Vector p5 = (p1 + p2) / 2;
  Vector p6 = (p2 + p3) / 2;
  Vector p4 = (p1 + p3) / 2;
  Vector ctroid = (p1 + p2 + p3) / 3;
  Vector op;

  switch(op_n)
  {
  case 0:
    op = p1;
    g_values(0,0) = get_new_auto_g(op, p5, p4) + do_radon_g(p5, ctroid, p4, op, s, r, R_W);
    g_values(1,0) = do_radon_g(p2, p6, p5, op, s, r, R_W) + do_radon_g(p5, p6, ctroid, op, s, r, R_W);
    g_values(2,0) = do_radon_g(p3, p4, p6, op, s, r, R_W) + do_radon_g(p4, ctroid, p6, op, s, r, R_W);
    break;
  case 1:
    op = p2;
    g_values(0,0) = do_radon_g(p1, p5, p4, op, s, r, R_W) + do_radon_g(p5, ctroid, p4, op, s, r, R_W);
    g_values(1,0) = get_new_auto_g(op, p6, p5) + do_radon_g(p5, p6, ctroid, op, s, r, R_W);
    g_values(2,0) = do_radon_g(p3, p4, p6, op, s, r, R_W) + do_radon_g(p4, ctroid, p6, op, s, r, R_W);
    break;
  case 2:
    op = p3;
    g_values(0,0) = do_radon_g(p1, p5, p4, op, s, r, R_W) + do_radon_g(p5, ctroid, p4, op, s, r, R_W);
    g_values(1,0) = do_radon_g(p2, p6, p5, op, s, r, R_W) + do_radon_g(p5, p6, ctroid, op, s, r, R_W);
    g_values(2,0) = get_new_auto_g(op, p4, p6) + do_radon_g(p4, ctroid, p6, op, s, r, R_W);
    break;
  }
}

double BuildBEMatrixBase::get_new_auto_g(
  const Vector& op,
  const Vector& p2,
  const Vector& p3)
{
  //  Inputs: op,p2,p3= cartesian coordiantes of the triangle vertices ; op= Observation Point
  //  Output: g1 = G value for the triangle for "auto_g"
  //  This function is called from get_auto_g.m

  double delta_min = 0.00001;
  unsigned int max_number_of_divisions = 256;

  Vector a = p2 - op; double a_mag = a.length();
  Vector b = p3 - p2; double b_mag = b.length();
  Vector c = op - p3; double c_mag = c.length();

  Vector aV = Cross(p2 - op, p3 - p2)*0.5;
  double area = aV.length();
  double area2 = 2.0*area;
  double h = (area2) / b_mag;
  double alfa=0;  if (h<a_mag) alfa = acos(h/a_mag);
  double AC = a_mag*c_mag;
  double teta = 0; if (area2<=AC) teta = asin( area2 / AC );

  unsigned int nod = 1;
  double sai_old = sqrt(area2 * teta);
  double delta = 1;

  double gama, gama_j, rhoj_1, rhoj, sum, sai_new=0;

  while( (delta >= delta_min) && (nod <= max_number_of_divisions) )
  {
    nod = 2*nod;
    gama = teta / nod;
    sum = 0;
    gama_j = 0;
    rhoj_1 = a_mag;
    for ( unsigned int j = 1; j <= nod; j++)
    {
      gama_j = gama_j + gama;
      rhoj = h / cos(alfa - gama_j);
      sum = sum + sqrt( std::fabs(rhoj * rhoj_1) );
      rhoj_1 = rhoj;
    }
    sai_new = sum * sqrt(std::fabs(gama * sin(gama)));
    delta = 0;
    if (sai_new + sai_old)
      delta = std::fabs((sai_new - sai_old) / (sai_new + sai_old));
    sai_old = sai_new;
  }
  return sai_new;
}

double BuildBEMatrixBase::do_radon_g(
  const Vector& p1,
  const Vector& p2,
  const Vector& p3,
  const Vector& op,
  double s,
  double r,
  DenseMatrix& R_W)
{
  //  Inputs: p1,p2,p3= cartesian coordiantes of the triangle vertices ; op= Observation Point
  //  Output: g2 = G value for the triangle for "auto_g"
  //  This function is called from get_auto_g.m

  Vector centroid = (p1 + p2 + p3) / 3;

  DenseMatrix g_coef(1, 7);
  get_g_coef(p1, p2, p3, op, s, r, centroid, g_coef);

  double g2 = 0;
  for (int i=0; i<7; i++)   g2 = g2 + g_coef(0,i)*R_W(0,i);

  Vector aV = Cross(p2 - p1, p3 - p2)*0.5;

  return g2 * aV.length();
}

class BuildBEMatrixBaseCompute : public BuildBEMatrixBase
{
public:
  template <class MatrixType>
  static void make_auto_P_compute(VMesh* hsurf, MatrixType& auto_P, double in_cond, double out_cond, double op_cond);

  template <class MatrixType>
  static void make_cross_P_compute(VMesh* hsurf1, VMesh* hsurf2, MatrixType& cross_P, double in_cond, double out_cond, double op_cond);

  template <class MatrixType>
  static void make_auto_G_compute(VMesh* hsurf, MatrixType& auto_G, double in_cond, double out_cond, double op_cond, const std::vector<double>& avInn);

  template <class MatrixType>
  static void make_cross_G_compute( VMesh*,
  VMesh*,
  MatrixType&,
  double,
  double,
  double,
  const std::vector<double>& );
};

void BuildBEMatrixBase::make_auto_G_allocate(VMesh* hsurf, DenseMatrixHandle &h_GG_)
{
  auto nnodes = numNodes(hsurf);
  h_GG_.reset(new DenseMatrix(nnodes, nnodes, 0.0));
}

void BuildBEMatrixBase::make_auto_G(VMesh* hsurf, DenseMatrixHandle &h_GG_,
double in_cond, double out_cond, double op_cond, const std::vector<double>& avInn)
{
  make_auto_G_allocate(hsurf, h_GG_);
  BuildBEMatrixBaseCompute::make_auto_G_compute(hsurf, *h_GG_, in_cond, out_cond, op_cond, avInn);
}

template <class MatrixType>
void BuildBEMatrixBaseCompute::make_auto_G_compute(VMesh* hsurf, MatrixType& auto_G,
  double in_cond, double out_cond, double op_cond, const std::vector<double>& avInn)
{
  //const double mult = 1/(2*M_PI)*((out_cond - in_cond)/op_cond);  // op_cond=out_cond for all the surfaces but the outermost surface which in op_cond=in_cond
  const double mult = 1/(4*M_PI)*(out_cond - in_cond);  // op_cond=out_cond for all the surfaces but the outermost surface which in op_cond=in_cond

  VMesh::Node::array_type nodes;

  VMesh::Node::iterator ni, nie;
  VMesh::Face::iterator fi, fie;
  DenseMatrix cruse_weights(3, 7);
  DenseMatrix g_coef(1, 7);
  DenseMatrix R_W(1,7); // Radon Points Weights
  DenseMatrix temp(1,7);
  DenseMatrix g_values(3, 1);

  double area;

  double sqrt15 = sqrt(15.0);
  //R_W(0,0) = 9/40; // <- Burak! FIX ME!
  R_W(0,0) = 9.0/40.0;
  R_W(0,1) = (155 + sqrt15) / 1200;
  R_W(0,2) = R_W(0,1);
  R_W(0,3) = R_W(0,1);
  R_W(0,4) = (155 - sqrt15) / 1200;
  R_W(0,5) = R_W(0,4);
  R_W(0,6) = R_W(0,4);

  double s = (1 - sqrt15) / 7;
  double r = (1 + sqrt15) / 7;

  hsurf->begin(fi); hsurf->end(fie);
  for (; fi != fie; ++fi)
  { //! find contributions from every triangle
    hsurf->get_nodes(nodes, *fi);
    Vector p1(hsurf->get_point(nodes[0]));
    Vector p2(hsurf->get_point(nodes[1]));
    Vector p3(hsurf->get_point(nodes[2]));

    area = avInn[*fi];

    get_cruse_weights(p1, p2, p3, s, r, area, cruse_weights);
    Vector centroid = (p1 + p2 + p3) / 3.0;
    hsurf->begin(ni); hsurf->end(nie);
    for (; ni != nie; ++ni)
    { //! for every node
      VMesh::Node::index_type ppi = *ni;
      Vector op(hsurf->get_point(ppi));

      if (ppi == nodes[0])       bem_sing(p1, p2, p3, 0, g_values, s, r, R_W);
      else if (ppi == nodes[1])       bem_sing(p1, p2, p3, 1, g_values, s, r, R_W);
      else if (ppi == nodes[2])       bem_sing(p1, p2, p3, 2, g_values, s, r, R_W);
      else
      {
        get_g_coef(p1, p2, p3, op, s, r, centroid, g_coef);

        for (int i=0; i<7; i++)  temp(0,i) = g_coef(0,i)*R_W(0,i);

        g_values = area * (cruse_weights * temp.transpose());
      } // else

      for (int i=0; i<3; ++i)
        auto_G(ppi, nodes[i])+=g_values(i,0)*mult;
    }
  }
}

void BuildBEMatrixBase::make_cross_G_allocate(VMesh* hsurf1, VMesh* hsurf2, DenseMatrixHandle &h_GG_)
{
  h_GG_.reset(new DenseMatrix(numNodes(hsurf1), numNodes(hsurf2), 0.0));
}

void BuildBEMatrixBase::make_cross_G(VMesh* hsurf1, VMesh* hsurf2, DenseMatrixHandle &h_GG_,
  double in_cond, double out_cond, double op_cond, const std::vector<double>& avInn)
{
  make_cross_G_allocate(hsurf1, hsurf2, h_GG_);
  BuildBEMatrixBaseCompute::make_cross_G_compute(hsurf1, hsurf2, *h_GG_, in_cond, out_cond, op_cond, avInn);
}

template <class MatrixType>
void BuildBEMatrixBaseCompute::make_cross_G_compute(VMesh* hsurf1, VMesh* hsurf2, MatrixType& cross_G,
  double in_cond, double out_cond, double op_cond, const std::vector<double>& avInn)
{
  const double mult = 1/(4*M_PI)*(out_cond - in_cond);
  //   out_cond and in_cond belong to hsurf2 and op_cond is the out_cond of hsurf1 for all the surfaces but the outermost surface which in op_cond=in_cond

  VMesh::Node::array_type nodes;

  VMesh::Node::iterator  ni, nie;
  VMesh::Face::iterator  fi, fie;

  DenseMatrix cruse_weights(3, 7);
  DenseMatrix g_coef(1, 7);
  DenseMatrix R_W(1,7); // Radon Points Weights
  DenseMatrix temp(1,7);
  DenseMatrix g_values(3, 1);

  double area;

  double sqrt15 = sqrt(15.0);
  //R_W(0,0) = 9/40; // <- Burak! FIX ME!
  R_W(0,0) = 9.0/40.0;
  R_W(0,1) = (155 + sqrt15) / 1200;
  R_W(0,2) = R_W(0,1);
  R_W(0,3) = R_W(0,1);
  R_W(0,4) = (155 - sqrt15) / 1200;
  R_W(0,5) = R_W(0,4);
  R_W(0,6) = R_W(0,4);

  double s = (1 - sqrt15) / 7;
  double r = (1 + sqrt15) / 7;

  hsurf2->begin(fi); hsurf2->end(fie);
  for (; fi != fie; ++fi)
  { //! find contributions from every triangle
    hsurf2->get_nodes(nodes, *fi);
    Vector p1(hsurf2->get_point(nodes[0]));
    Vector p2(hsurf2->get_point(nodes[1]));
    Vector p3(hsurf2->get_point(nodes[2]));

    area = avInn[*fi];

    get_cruse_weights(p1, p2, p3, s, r, area, cruse_weights);
    Vector centroid = (p1 + p2 + p3) / 3.0;

    hsurf1->begin(ni); hsurf1->end(nie);
    for (; ni != nie; ++ni)
    { //! for every node
      VMesh::Node::index_type ppi = *ni;
      Vector op(hsurf1->get_point(ppi));
      get_g_coef(p1, p2, p3, op, s, r, centroid, g_coef);

      for (int i=0; i<7; i++)  temp(0,i) = g_coef(0,i)*R_W(0,i);

      g_values = area * (cruse_weights * temp.transpose());

      for (int i=0; i<3; ++i)
        cross_G(ppi, nodes[i])+=g_values(i,0)*mult;
    }
  }
}

void BuildBEMatrixBase::make_cross_P_allocate(VMesh* hsurf1, VMesh* hsurf2, DenseMatrixHandle &h_PP_)
{
  h_PP_.reset(new DenseMatrix(numNodes(hsurf1), numNodes(hsurf2), 0.0));
}

void BuildBEMatrixBase::make_cross_P(VMesh* hsurf1, VMesh* hsurf2, DenseMatrixHandle &h_PP_,
  double in_cond, double out_cond, double op_cond)
{
  make_cross_P_allocate(hsurf1, hsurf2, h_PP_);
  BuildBEMatrixBaseCompute::make_cross_P_compute(hsurf1, hsurf2, *h_PP_, in_cond, out_cond, op_cond);
}

template <class MatrixType>
void BuildBEMatrixBaseCompute::make_cross_P_compute(VMesh* hsurf1, VMesh* hsurf2, MatrixType& cross_P, double in_cond, double out_cond, double op_cond)
{
  const double mult = 1/(4*M_PI)*(out_cond - in_cond);
  //   out_cond and in_cond belong to hsurf2 and op_cond is the out_cond of hsurf1 for all the surfaces but the outermost surface which in op_cond=in_cond
  VMesh::Node::array_type nodes;
  DenseMatrix coef(1, 3);
  int i;

  VMesh::Node::iterator  ni, nie;
  VMesh::Face::iterator  fi, fie;

  hsurf1->begin(ni); hsurf1->end(nie);
  for (; ni != nie; ++ni){ //! for every node
    VMesh::Node::index_type ppi = *ni;
    Point pp = hsurf1->get_point(ppi);

    hsurf2->begin(fi); hsurf2->end(fie);
    for (; fi != fie; ++fi){ //! find contributions from every triangle

      hsurf2->get_nodes(nodes, *fi);
      Vector v1 = hsurf2->get_point(nodes[0]) - pp;
      Vector v2 = hsurf2->get_point(nodes[1]) - pp;
      Vector v3 = hsurf2->get_point(nodes[2]) - pp;

      getOmega(v1, v2, v3, coef);

      for (i=0; i<3; ++i)
        cross_P(ppi, nodes[i])-=coef(0,i)*mult;
    }
  }
}

void BuildBEMatrixBase::make_auto_P_allocate(VMesh* hsurf, DenseMatrixHandle &h_PP_)
{
  auto nnodes = numNodes(hsurf);
  h_PP_.reset(new DenseMatrix(nnodes, nnodes, 0.0));
}

int BuildBEMatrixBase::numNodes(FieldHandle f)
{
  return numNodes(f->vmesh());
}

int BuildBEMatrixBase::numNodes(VMesh* hsurf)
{
  VMesh::Node::size_type nsize;
  hsurf->size(nsize);
  return static_cast<int>(nsize);
}

template <class MatrixType>
void BuildBEMatrixBaseCompute::make_auto_P_compute(VMesh* hsurf, MatrixType& auto_P, double in_cond, double out_cond, double op_cond)
{
  auto nnodes = auto_P.rows();

  //const double mult = 1/(2*M_PI)*((out_cond - in_cond)/op_cond);  // op_cond=out_cond for all the surfaces but the outermost surface which in op_cond=in_cond
  const double mult = 1/(4*M_PI)*(out_cond - in_cond);

  VMesh::Node::array_type nodes;
  DenseMatrix coef(1, 3);

  VMesh::Node::iterator ni, nie;
  VMesh::Face::iterator fi, fie;

  unsigned int i;

  hsurf->begin(ni); hsurf->end(nie);

  for (; ni != nie; ++ni){ //! for every node
    VMesh::Node::index_type ppi = *ni;
    Point pp = hsurf->get_point(ppi);

    hsurf->begin(fi); hsurf->end(fie);

    for (; fi != fie; ++fi) { //! find contributions from every triangle

      hsurf->get_nodes(nodes, *fi);
      if (ppi!=nodes[0] && ppi!=nodes[1] && ppi!=nodes[2]){
        Vector v1 = hsurf->get_point(nodes[0]) - pp;
        Vector v2 = hsurf->get_point(nodes[1]) - pp;
        Vector v3 = hsurf->get_point(nodes[2]) - pp;

        getOmega(v1, v2, v3, coef);

        for (i=0; i<3; ++i)
          auto_P(ppi, nodes[i])-=coef(0,i)*mult;
      }
    }
  }

  //! accounting for autosolid angle
  auto sumOfRows = auto_P.rowwise().sum().eval();
  for (i=0; i<nnodes; ++i)
  {
    auto_P(i,i) = out_cond - sumOfRows(i);
  }
}

void BuildBEMatrixBase::make_auto_P(VMesh* hsurf, DenseMatrixHandle &h_PP_,
  double in_cond, double out_cond, double op_cond)
{
  make_auto_P_allocate(hsurf, h_PP_);
  BuildBEMatrixBaseCompute::make_auto_P_compute(hsurf, *h_PP_, in_cond, out_cond, op_cond);
}

// precalculate triangles area
void BuildBEMatrixBase::pre_calc_tri_areas(VMesh* hsurf, std::vector<double>& areaV){

  VMesh::Face::iterator  fi, fie;

  hsurf->begin(fi);
  hsurf->end(fie);
  for (; fi != fie; ++fi)
    areaV.push_back(hsurf->get_area(*fi));
}

// C++ized MollerTrumbore97 Ray Triangle intersection test.
bool BuildBEMatrixBase::ray_triangle_intersect(double &t,
  const Point &point,
  const Vector &dir,
  const Point &p0,
  const Point &p1,
  const Point &p2)
{
  // Find vectors for two edges sharing p0.
  const Vector edge1 = p1 - p0;
  const Vector edge2 = p2 - p0;

  // begin calculating determinant - also used to calculate U parameter.
  const Vector pvec = Cross(dir, edge2);

  // if determinant is near zero, ray lies in plane of triangle.
  const double det = Dot(edge1, pvec);
  const double EPSILON = 1.0e-6;
  if (det > -EPSILON && det < EPSILON)
  {
    return false;
  }
  const double inv_det = 1.0 / det;

  // Calculate distance from vert0 to ray origin.
  const Vector tvec = point - p0;

  // Calculate U parameter and test bounds.
  const double u = Dot(tvec, pvec) * inv_det;
  if (u < 0.0 || u > 1.0)
  {
    return false;
  }

  // Prepare to test V parameter.
  const Vector qvec = Cross(tvec, edge1);

  // Calculate V parameter and test bounds.
  const double v = Dot(dir, qvec) * inv_det;
  if (v < 0.0 || u + v > 1.0)
  {
    return false;
  }

  // Calculate t, ray intersects triangle.
  t = Dot(edge2, qvec) * inv_det;

  return true;
}

void BuildBEMatrixBase::compute_intersections(std::vector<std::pair<double, int> >
  &results,
  const VMesh* mesh,
  const Point &p, const Vector &v,
  int marker)
{
  VMesh::Face::iterator itr, eitr;
  mesh->begin(itr);
  mesh->end(eitr);
  double t;
  while (itr != eitr)
  {
    VMesh::Node::array_type nodes;
    mesh->get_nodes(nodes, *itr);
    Point p0, p1, p2;
    mesh->get_center(p0, nodes[0]);
    mesh->get_center(p1, nodes[1]);
    mesh->get_center(p2, nodes[2]);
    if (ray_triangle_intersect(t, p, v, p0, p1, p2))
    {
      results.push_back(std::make_pair(t, marker));
    }
    ++itr;
  }
}

static bool
  pair_less(const std::pair<double, int> &a,
  const std::pair<double, int> &b)
{
  return a.first < b.first;
}

int BuildBEMatrixBase::compute_parent(const std::vector<VMesh*> &meshes, int index)
{
  Point point;
  meshes[index]->get_center(point, VMesh::Node::index_type(0));
  Vector dir(1.0, 1.0, 1.0);
  std::vector<std::pair<double, int> > intersections;

  unsigned int i;
  for (i = 0; i < (unsigned int)meshes.size(); i++)
  {
    compute_intersections(intersections, meshes[i], point, dir, i);
  }

  std::sort(intersections.begin(), intersections.end(), pair_less);

  std::vector<int> counts(meshes.size(), 0);
  for (i = 0; i < intersections.size(); i++)
  {
    if (intersections[i].second == index)
    {
      // First odd count is parent.
      for (int j = i-1; j >= 0; j--)
      {
        // TODO: unusual odd/even number test?
        if (counts[intersections[j].second] & 1)
        {
          return intersections[j].second;
        }
      }
      // No odd parent, is outside.
      return static_cast<int>( meshes.size() );
    }
    counts[intersections[i].second]++;
  }

  // Indeterminate, we should intersect with ourselves.
  return static_cast<int>( meshes.size() );
}

bool BuildBEMatrixBase::compute_nesting(std::vector<int> &nesting, const std::vector<VMesh*> &meshes)
{
  nesting.resize(meshes.size());

  unsigned int i;
  for (i = 0; i < (unsigned int)meshes.size(); i++)
  {
    nesting[i] = compute_parent(meshes, i);
  }

  return true;
}

class SurfaceAndPoints : public BEMAlgoImpl, public BuildBEMatrixBaseCompute
{
public:
  virtual MatrixHandle compute(const bemfield_vector& fields) const override;
};

class SurfaceToSurface : public BEMAlgoImpl, public BuildBEMatrixBaseCompute
{
public:
  virtual MatrixHandle compute(const bemfield_vector& fields) const override;
};

BEMAlgoPtr BEMAlgoImplFactory::create(const bemfield_vector& fields)
{
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Check for special case where the potentials need to be evaluated at the nodes of a lead
  // This case assumes the first input is the surface mesh and the second is the location of the
  // nodes

  const bemfield_vector::size_type SPECIAL_CASE_LEN = 2;

  if ( fields.size() == SPECIAL_CASE_LEN )
  {
    VMesh *surface, *nodes;
    int surfcount=0, pointcloudcount=0;

    bool meets_conditions = true;

    for (bemfield_vector::size_type i = 0; i < SPECIAL_CASE_LEN; i++)
    {
      if (fields[i].surface)
      {
        surface = fields[i].field_->vmesh();
        if (! surface->is_trisurfmesh() ) meets_conditions = false;
        surfcount++;
      }
      else
      {
        nodes = fields[i].field_->vmesh();
        if (! ( nodes->is_pointcloudmesh() ) || nodes->is_curvemesh() )
        {
          meets_conditions = false;
        }
        pointcloudcount++;
      }
    }

    if ( (surfcount == 0) || (pointcloudcount == 0) )
    {
      meets_conditions = false;
    }

    // If all of the checks above don't flag meets_conditions as false,
    // return a value that indicates the algorithm to use is the surface-to-nodes case
    if ( meets_conditions )
      return boost::make_shared<SurfaceAndPoints>();
  }

  //////////////////////////////////////////////////////////////////////////////////////////////////
  // Check for case where all inputs are triangle surfaces, and there is at least one source and
  // one measurement surface

  bool allsurfaces=true, hasmeasurementsurf=false, hassourcesurf=false;

  for (bemfield_vector::size_type i = 0; i < fields.size(); i++)
  {
    // if the current field is not marked to be used as a surface OR it's not of trisurfmesh type, this algorithm does not apply
    if ( (! fields[i].field_->vmesh()->is_trisurfmesh()) || (! fields[i].surface) )
    {
      allsurfaces=false;
      break;
    }

    if (fields[i].measurement) hasmeasurementsurf = true;
    if (fields[i].source) hassourcesurf = true;
  }

  // if all fields are surfaces, there exists a measurement and a source surface, then use the surface-to-surface algorithm... else fail
  if (allsurfaces && hasmeasurementsurf && hassourcesurf)
  {
    return boost::make_shared<SurfaceToSurface>();
  }
  else
  {
    return nullptr;
  }
}

static void printInfo(const DenseMatrix& m, const std::string& name)
{
#if 0
  std::cout << name << ": " << m.rows() << " x " << m.cols() << std::endl;
  std::cout << name << " min: " << m.minCoeff() << std::endl;
  std::cout << name << " max: " << m.maxCoeff() << std::endl;
#endif
}

MatrixHandle SurfaceToSurface::compute(const bemfield_vector& fields) const
{
  // Math for surface-to-surface BEM algorithm (based on Jeroen Stinstra's BEM Matlab code that's part of SCIRun)
  // -------------------------------------------------------------------------------------------------------------
  // EE = matrix relating potentials on surfaces to potentials on other surfaces
  // EJ = matrix relating current density on surfaces (normal to surface) to potentials on surfaces
  // u  = potentials on the surfaces
  // j  = current density normal to the surfaces
  //
  // General equation: EE*u + EJ*j = (dipolar sources not on the surfaces)
  // Assuming all sources are on surfaces: EE*u + EJ*j = 0
  // (below assumes that measurement=Neumann boundary conditions and source=Dirichlet boundary conditions)
  //
  // s = source indices
  // m = measurement indices
  //
  // Pmm = EE(m,m)
  // Pss = EE(s,s)
  // Pms = EE(m,s)
  // Psm = EE(s,m)
  //
  // Gms = EJ(m,s)
  // Gss = EJ(s,s)
  //
  // After some block-matrix math to eliminate j from the equation and find T s.t. u(m)=T*u(s), we get:
  // iGss = inv(Gss)
  // T = inv(Pmm - Gms*iGss*Psm)*(Gms*iGss*Pss - Pms)
  //

  const size_t Nfields = fields.size();
  double op_cond=0.0; // op_cond is not used in this formulation -- someone needs to check this math and make a better decision about how to handle this value below

  // Count the number of fields that have been specified as being "sources" or "measurements" (and keep track of indices)
  int Nsources = 0;
  std::vector<int> sourcefieldindices;
  int Nmeasurements = 0;
  std::vector<int> measurementfieldindices;

  for(int i=0; i < Nfields; i++)
  {
    if(fields[i].source)
    {
      Nsources++;
      sourcefieldindices.push_back(i);
    }
    else if(fields[i].measurement)
    {
      Nmeasurements++;
      measurementfieldindices.push_back(i);
    }
  }

  std::vector<int> fieldNodeSize(fields.size());
  std::transform(fields.begin(), fields.end(), fieldNodeSize.begin(), [](const bemfield& f) { return numNodes(f.field_); } );
  DenseBlockMatrix EE(fieldNodeSize, fieldNodeSize);

  // Calculate EE in block matrix form
  for(int i = 0; i < Nfields; i++)
  {
    for(int j = 0; j < Nfields; j++)
    {
      if (i == j)
      {
        auto block = EE.blockRef(i, j);
        make_auto_P_compute(fields[i].field_->vmesh(), block, fields[i].insideconductivity, fields[i].outsideconductivity, op_cond);
      }
      else
      {
        auto block = EE.blockRef(i, j);
        make_cross_P_compute(fields[i].field_->vmesh(), fields[j].field_->vmesh(), block, fields[j].insideconductivity, fields[j].outsideconductivity, op_cond);
      }
    }
  }

  printInfo(EE.matrix(), "EE");

  std::vector<int> sourceFieldNodeSize(sourcefieldindices.size());
  auto sourceFields = fields | boost::adaptors::filtered([](const bemfield& f) { return f.source; });
  //following doesn't compile in VS2010, but does in clang: enable it after upgrading to 2013
  //auto transformer = [this](const bemfield& f) -> int { return numNodes(f.field_); };
  //auto trans = filt | boost::adaptors::transformed(transformer);
  //boost::copy(trans, sourceFieldNodeSize.begin());
  std::transform(sourceFields.begin(), sourceFields.end(), sourceFieldNodeSize.begin(), [](const bemfield& f) { return numNodes(f.field_); } );

  DenseBlockMatrix EJ(fieldNodeSize, sourceFieldNodeSize);

  // Calculate EJ(:,s) in block matrix form
  // ***NOTE THE CHANGE IN INDEXING!!!***
  // (The indices of block columns of EJ correspond to field indices according to "sourcefieldindices", and this affects everything with EJ below this point too!)
  for(int j = 0; j < Nsources; j++)
  {
    // Precalculate triangle areas for this source field/surface
    std::vector<double> triangleareas;
    pre_calc_tri_areas(fields[sourcefieldindices[j]].field_->vmesh(), triangleareas);

    for(int i = 0; i < Nfields; i++)
    {
      if (i == sourcefieldindices[j])
      {
        auto block = EJ.blockRef(i,j);
        make_auto_G_compute(fields[i].field_->vmesh(), block, fields[i].insideconductivity, fields[i].outsideconductivity, op_cond, triangleareas);
      }
      else
      {
        auto block = EJ.blockRef(i,j);
        make_cross_G_compute(fields[i].field_->vmesh(), fields[sourcefieldindices[j]].field_->vmesh(), block, fields[j].insideconductivity, fields[j].outsideconductivity, op_cond, triangleareas);
      }
    }
  }

  printInfo(EJ.matrix(), "EJ");

  // This needs to be checked.  It was taken out because the deflation was producing errors
  // Jeroen's matlab code, which was the basis of this code, only does a defation in test cases.

  // Perform deflation on EE matrix
  //const double deflationconstant = 1.0/EE.matrix().ncols();
  //EE.matrix() = EE.matrix().array() + deflationconstant;

  std::vector<int> measurementNodeSize(measurementfieldindices.size());
  auto measFields = fields | boost::adaptors::filtered([](const bemfield& f) { return f.measurement; });
  //following doesn't compile in VS2010, but does in clang: enable it after upgrading to 2013
  //auto transformer = [this](const bemfield& f) -> int { return numNodes(f.field_); };
  //auto trans = filt | boost::adaptors::transformed(transformer);
  //boost::copy(trans, sourceFieldNodeSize.begin());
  std::transform(measFields.begin(), measFields.end(), measurementNodeSize.begin(), [](const bemfield& f) { return numNodes(f.field_); } );

  // Split EE apart into Pmm, Pss, Pms, and Psm
  // -----------------------------------------------
  // Pmm:
  DenseBlockMatrix Pmm(measurementNodeSize, measurementNodeSize);
  for(int i = 0; i < Nmeasurements; i++)
  {
    for(int j = 0; j < Nmeasurements; j++)
    {
      Pmm.blockRef(i,j) = EE.blockRef(measurementfieldindices[i], measurementfieldindices[j]);
    }
  }
  printInfo(Pmm.matrix(), "Pmm");

  // Pss:
  DenseBlockMatrix Pss(sourceFieldNodeSize, sourceFieldNodeSize);
  for(int i = 0; i < Nsources; i++)
  {
    for(int j = 0; j < Nsources; j++)
    {
      Pss.blockRef(i,j) = EE.blockRef(sourcefieldindices[i],sourcefieldindices[j]);
    }
  }
  printInfo(Pss.matrix(), "Pss");

  // Pms:
  DenseBlockMatrix Pms(measurementNodeSize, sourceFieldNodeSize);
  for(int i = 0; i < Nmeasurements; i++)
  {
    for(int j = 0; j < Nsources; j++)
    {
      Pms.blockRef(i,j) = EE.blockRef(measurementfieldindices[i],sourcefieldindices[j]);
    }
  }
  printInfo(Pms.matrix(), "Pms");

  // Psm:
  DenseBlockMatrix Psm(sourceFieldNodeSize, measurementNodeSize);
  for(int i = 0; i < Nsources; i++)
  {
    for(int j = 0; j < Nmeasurements; j++)
    {
      Psm.blockRef(i,j) = EE.blockRef(sourcefieldindices[i],measurementfieldindices[j]);
    }
  }
  printInfo(Psm.matrix(), "Psm");

  // Split EJ apart into Gms and Gss (see ALL-CAPS note above about differences in block row vs column indexing in EJ matrix)
  // -----------------------------------------------
  // Gms:
  DenseBlockMatrix Gms(measurementNodeSize, sourceFieldNodeSize);
  for(int i = 0; i < Nmeasurements; i++)
  {
    for(int j = 0; j < Nsources; j++)
    {
      Gms.blockRef(i,j) = EJ.blockRef(measurementfieldindices[i],j);
    }
  }
  printInfo(Gms.matrix(), "Gms");

  // Gss:
  DenseBlockMatrix Gss(sourceFieldNodeSize, sourceFieldNodeSize);
  for(int i = 0; i < Nsources; i++)
  {
    for(int j = 0; j < Nsources; j++)
    {
      Gss.blockRef(i,j) = EJ.blockRef(sourcefieldindices[i],j);
    }
  }
  printInfo(Gss.matrix(), "Gss");

  // TODO: add deflation step

  // Compute T here (see math in comments above)
  // TransferMatrix = T = inv(Pmm - Gms*iGss*Psm)*(Gms*iGss*Pss - Pms) = inv(C)*D

  auto Y = Gms.matrix() * Gss.matrix().inverse();
  auto C = Pmm.matrix() - Y * Psm.matrix();
  auto D = Y * Pss.matrix() - Pms.matrix();

  auto T = C.inverse() * D; // T = inv(C)*D
  return boost::make_shared<DenseMatrix>(T);

  //This could be done on one line (see below), but Y (see above) would need to be calculated twice:
  //MatrixHandle TransferMatrix1 = inv(Pmm - Gms * Gss * Psm) * (Gms * Gss * Pss - Pms);
}

MatrixHandle SurfaceAndPoints::compute(const bemfield_vector& fields) const
{
  // NOTE: This is Jeroen's code that has been adapted to fit the new module structure
  //
  // Math:
  // The boundary element formulation is based on Matlab code
  // bemMatrixPP2.m, which can be found in the matlab package

  // The BEM formulation assumes the following matrix equations
  // P_surf_surf * PHI_surf + G_surf_surf * J_surf =  sources_in_volume
  //
  // PHI_surf are the potentials on the surface
  // J_surf are the currents passing perpendicular to the surface
  // sources_in_volume is empty in this case
  //
  // P_surf_surf is the matrix that connects the potentials at the nodes to the integral over the
  // potential at the surface. Its terms consist of Green's function ( 1/ ( 4pi*||r-r'|| ) ) over
  // the surface of each element. As this integral becomes singular for a node and a triangle that
  // share a corner node, we use a trick to avoid computing this integral as we know that the
  // the system should reference potential invariant. Hence the rows of the matrix need to sum to
  // to zero
  //
  // G_surf_surf is the matrix that connects the potentials at the nodes to the integral over the
  // currents flowing through the surface.
  //
  // The second equation that we use is the expression of the potentials at an arbitrary point
  // to the potentials at the surface and the current flowing through the surface
  //
  // PHI_nodes = P_nodes_surf * PHI_surf + G_nodes_surf * J_surf
  //
  // Here matrix P_nodes_surf is the matrix that projects the contribution of the potentials of the
  // surface to the nodes within the volume
  //
  // Here G_nodes_surf is the matrix that projects the contribution of the currents flowing through
  // the surface to the nodes within the volume
  //
  // Adding both equations together will result in
  //
  // PHI_nodes = P_nodes_surf* PHI_surf - G_nodes_surf * inv( G_surf_surf) * P_surf_surf * PHI_surf
  //
  // In other words the transfer matrix is
  // P_nodes_surf - G_nodes_surf * inv( G_surf_surf) * P_surf_surf

  VMesh *nodes = 0;
  VMesh *surface = 0;

  for (int i=0; i<2; i++)
  {
    if (fields[i].surface)
      surface = fields[i].field_->vmesh();
    else
      nodes = fields[i].field_->vmesh();
  }

  DenseMatrixHandle Pss;
  DenseMatrixHandle Gss;
  DenseMatrixHandle Pns;
  DenseMatrixHandle Gns;
  make_auto_P( surface, Pss, 1.0, 0.0, 1.0 );
  make_cross_P( nodes, surface, Pns, 1.0, 0.0, 1.0 );

  std::vector<double> area;
  pre_calc_tri_areas( surface, area );

  make_auto_G( surface, Gss, 1.0, 0.0, 1.0, area );
  make_cross_G( nodes, surface, Gns, 1.0, 0.0, 1.0, area );

  return boost::make_shared<DenseMatrix>(*Pns - (*Gns * Gss->inverse() * *Pss));
}


text:
package com.github.chrisgleissner.behaim.builder.producer;

import com.github.chrisgleissner.behaim.builder.adapter.SeedAdapter;
import com.github.chrisgleissner.behaim.builder.seeder.Seeder;
import com.github.chrisgleissner.behaim.explorer.FieldUtil;
import com.github.chrisgleissner.behaim.explorer.VisitationResult;
import com.github.chrisgleissner.behaim.explorer.Visitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

public class ProducerVisitor implements Visitor {

    private final static class CreationResult {
        private final Object createdObject;
        private final Class elementClass;

        public CreationResult(Object createdObject, Class elementClass) {
            this.createdObject = createdObject;
            this.elementClass = elementClass;
        }
    }

    private final static Map<Class<?>, Class<?>> CONCRETE_COLLECTION_CLASSES = new HashMap<Class<?>, Class<?>>();
    private final static Logger logger = LoggerFactory.getLogger(ProducerVisitor.class);

    static {
        CONCRETE_COLLECTION_CLASSES.put(Collection.class, ArrayList.class);
        CONCRETE_COLLECTION_CLASSES.put(List.class, ArrayList.class);
        CONCRETE_COLLECTION_CLASSES.put(Set.class, HashSet.class);
        CONCRETE_COLLECTION_CLASSES.put(Queue.class, ArrayBlockingQueue.class);
    }

    private final ProducerVisitorContext context;

    public ProducerVisitor(ProducerVisitorContext producerVisitorContext) {
        context = producerVisitorContext;
    }

    private CreationResult createObjectFor(Field field) {
        Object fieldValue = null;
        Class elementClass = null;
        // TODO gleissc Obtain from configuration
        int collectionSize = 3;
        try {
            if (isCollection(field)) {
                Class collectionSubclass = getConcreteCollectionClassFor(field.getType());
                if (collectionSubclass != null) {
                    Collection collection = (Collection) collectionSubclass.newInstance();
                    elementClass = getCollectionParameter(field);
                    for (int i = 0; i < collectionSize; i++) {
                        collection.add(elementClass.newInstance());
                    }
                    fieldValue = collection;
                }
            } else if (isArray(field)) {
                Object[] array = new Object[collectionSize];
                Class elementType = field.getType().getComponentType();
                for (int i = 0; i < collectionSize; i++) {
                    array[i] = elementType.newInstance();
                }
                fieldValue = array;
            } else if (!field.getType().isEnum()) {
                fieldValue = field.getType().newInstance();
            }
        } catch (Exception e) {
            logger.warn("Could not instantiate field", FieldUtil.getNameAndTypeFor(field), e);
        }
        return new CreationResult(fieldValue, elementClass);
    }

    private Class getCollectionParameter(Field field) {
        Class fieldParameterClass = null;
        Type genericType = field.getGenericType();
        if (genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            if (actualTypeArguments != null && actualTypeArguments.length >= 1) {
                fieldParameterClass = (Class) actualTypeArguments[0];
            }
        }
        return fieldParameterClass;
    }

    private Class getConcreteCollectionClassFor(Class<?> clazz) {
        Class subclass = CONCRETE_COLLECTION_CLASSES.get(clazz);
        if (subclass == null) {
            if (!Modifier.isAbstract(clazz.getModifiers()) && !Modifier.isInterface(clazz.getModifiers())) {
                subclass = clazz;
            }
        }
        return subclass;
    }

    private boolean isArray(Field field) {
        return field.getType().isArray();
    }

    private boolean isClassExcluded(Class clazz) {
        boolean excluded = false;
        String className = clazz.getName();
        for (String excludedClassName : context.getConfig().getExcludedClassNames()) {
            if (className.startsWith(excludedClassName)) {
                excluded = true;
                break;
            }
        }
        return excluded;
    }

    private boolean isCollection(Field field) {
        return Collection.class.isAssignableFrom(field.getType());
    }

    @Override
    public VisitationResult visit(Object object, Field field) {
        Object fieldValue = null;
        Class fieldClass = field.getType();
        ProducerFieldContext fieldContext = context.getFieldContextFor(field);
        Seeder seeder = fieldContext.getSeeder();
        SeedAdapter<?> seedAdapter = context.getSeedAdapterFor(field);
        boolean visitOfValueRequired = true;
        if (seedAdapter != null) {
            fieldValue = seedAdapter.convert(seeder);
            visitOfValueRequired = !isClassExcluded(fieldClass);
        }
        if (fieldValue == null) {
            CreationResult creationResult = createObjectFor(field);
            fieldValue = creationResult.createdObject;
        }
        try {
            field.setAccessible(true);
            field.set(object, fieldValue);
        } catch (Exception e) {
            logger.warn("Could not set " + FieldUtil.getNameFor(field) + "=" + fieldValue + " provided by "
                    + seedAdapter + " on " + object, e);
        }
        return new VisitationResult(fieldContext, fieldValue, visitOfValueRequired);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace AForge.Wpf
{
    static class BitmapHelpers
    {
        public static BitmapImage ToBitmapImage(this Bitmap bitmap)
        {
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Bmp);
            ms.Seek(0, SeekOrigin.Begin);
            bi.StreamSource = ms;
            bi.EndInit();
            return bi;
        }
    }
}


text:
namespace Poco {
namespace MongoDB {

class MongoDB_API QueryRequest : public RequestMessage
	/// Class for creating an OP_QUERY client request. This request
	/// is used to query documents from the database.
{
public:
	typedef enum
	{
		QUERY_NONE = 0,
		QUERY_TAILABLECURSOR = 2,
		QUERY_SLAVE_OK = 4,
		//QUERY_OPLOG_REPLAY = 8 (internal replication use only - drivers should not implement)
		QUERY_NOCUROSR_TIMEOUT = 16,
		QUERY_AWAIT_DATA = 32,
		QUERY_EXHAUST = 64,
		QUERY_PARTIAL = 128
	} Flags;

	QueryRequest(const std::string& collectionName, Flags flags = QUERY_NONE);
		/// Constructor.
		/// The full collection name is the concatenation of the database
		/// name with the collection name, using a "." for the concatenation. For example,
		/// for the database "foo" and the collection "bar", the full collection name is
		/// "foo.bar".

	virtual ~QueryRequest();
		/// Destructor

	Flags getFlags() const;
		/// Returns the flags

	void setFlags(Flags flag);
		/// Set the flags

	std::string fullCollectionName() const;
		/// Returns the <db>.<collection> used for this query

	Int32 getNumberToSkip() const;
		/// Returns the number of documents to skip

	void setNumberToSkip(Int32 n);
		/// Sets the number of documents to skip

	Int32 getNumberToReturn() const;
		/// Returns the number to return

	void setNumberToReturn(Int32 n);
		/// Sets the number to return (limit)

	Document& selector();
		/// Returns the selector document

	Document& returnFieldSelector();
		/// Returns the field selector document

protected:
	void buildRequest(BinaryWriter& writer);

private:
	Flags       _flags;
	std::string _fullCollectionName;
	Int32       _numberToSkip;
	Int32       _numberToReturn;
	Document    _selector;
	Document    _returnFieldSelector;
};

inline QueryRequest::Flags QueryRequest::getFlags() const
{
	return _flags;
}

inline void QueryRequest::setFlags(QueryRequest::Flags flags)
{
	_flags = flags;
}

inline std::string QueryRequest::fullCollectionName() const
{
	return _fullCollectionName;
}

inline Document& QueryRequest::selector()
{
	return _selector;
}

inline Document& QueryRequest::returnFieldSelector()
{
	return _returnFieldSelector;
}

inline Int32 QueryRequest::getNumberToSkip() const
{
	return _numberToSkip;
}

inline void QueryRequest::setNumberToSkip(Int32 n)
{
	_numberToSkip = n;
}

inline Int32 QueryRequest::getNumberToReturn() const
{
	return _numberToReturn;
}

inline void QueryRequest::setNumberToReturn(Int32 n)
{
	_numberToReturn = n;
}

} } // namespace Poco::MongoDB

#endif //MongoDB_QueryRequest_INCLUDED


text:
<?php
// Create new PHPExcel object
$objPHPExcel = new \PHPExcel();

// Set document properties
$objPHPExcel->getProperties()->setCreator("QualityCrowd 2")
							 ->setTitle("$batchId - results")
							 ->setDescription("QualityCrowd 2 results for $batchId");

// fill in results
outputResults($objPHPExcel->getSheet(0), $columns, $workers);
$objPHPExcel->getSheet(0)->setTitle('results');

// fill in durations
$objPHPExcel->createSheet();
outputDurations($objPHPExcel->getSheet(1), $columns, $workers);
$objPHPExcel->getSheet(1)->setTitle('durations');

// fill in durations
$objPHPExcel->createSheet();
outputStepMaps($objPHPExcel->getSheet(2), $columns, $workers);
$objPHPExcel->getSheet(2)->setTitle('step maps');

// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

// redirect output to client browser
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $batchId . '.xlsx"');
header('Cache-Control: max-age=0');

$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');

function outputResults($sheet, $columns, $workers)
{
	// Header
	$sheet->setCellValue('A1', 'Worker ID')
          ->setCellValue('B1', 'Finished')
          ->setCellValue('C1', 'Steps');
	$c = 3;

	foreach($columns as $stepId => $cols) {
		$sheet->setCellValueByColumnAndRow($c, 1, 'Step ' . ($stepId + 1));
		$sheet->setCellValueByColumnAndRow($c, 2, 'Step Id');
    	$c++;

		foreach($cols as $col) {
			$sheet->setCellValueByColumnAndRow($c, 1, 'Step ' . ($stepId + 1));
			$sheet->setCellValueByColumnAndRow($c, 2, $col);
	    	$c++;
		}
	}

	// Data
	$r = 4;
	foreach($workers as $worker) {
		$sheet->setCellValueExplicitByColumnAndRow(0, $r, $worker['workerId'],
			PHPExcel_Cell_DataType::TYPE_STRING);
	    $sheet->setCellValueByColumnAndRow(1, $r, ($worker['finished'] ? 'Yes' : 'No'));
	    $sheet->setCellValueByColumnAndRow(2, $r, count($worker['results']));

		if (!is_array($worker['results'])) {
			continue;
		}

		$stepMap = $worker['stepMap'];

		$c = 3;
		foreach($worker['results'] as $stepNum => $result) {
			array_shift($result); // step number
			array_shift($result); // timestamp

			// step id
			$sheet->setCellValueByColumnAndRow($c, $r, $stepMap[$stepNum] + 1);
			$c++;

			foreach($result as $value) {
				$sheet->setCellValueByColumnAndRow($c, $r, $value);
				$c++;
			}
		}

		$r++;
	}
}

function outputDurations($sheet, $columns, $workers)
{
	// Header
	$sheet->setCellValue('A1', 'Worker ID')
          ->setCellValue('B1', 'Finished')
          ->setCellValue('C1', 'Steps');

	$c = 3;
	foreach($columns as $stepId => $cols) {
		$sheet->setCellValueByColumnAndRow($c, 1, 'Step ' . ($stepId + 1));
    	$c++;
	}

	// Data
	$r = 3;
	foreach($workers as $worker) {
		$sheet->setCellValueExplicitByColumnAndRow(0, $r, $worker['workerId'],
			PHPExcel_Cell_DataType::TYPE_STRING);
	    $sheet->setCellValueByColumnAndRow(1, $r, ($worker['finished'] ? 'Yes' : 'No'));
	    $sheet->setCellValueByColumnAndRow(2, $r, count($worker['results']));

		if (is_array($worker['durations'])) {
			$c = 3;
			foreach($worker['durations'] as $stepId => $duration) {
				$sheet->setCellValueByColumnAndRow($c, $r, $duration);
				$c++;
			}
		}

		$r++;
	}
}

function outputStepMaps($sheet, $columns, $workers)
{
	// Header
	$sheet->setCellValue('A1', 'Worker ID')
          ->setCellValue('B1', 'Finished')
          ->setCellValue('C1', 'Steps');

	$c = 3;
	foreach($columns as $stepId => $cols) {
		$sheet->setCellValueByColumnAndRow($c, 1, 'Step ' . ($stepId + 1));
    	$c++;
	}

	// Data
	$r = 3;
	foreach($workers as $worker) {
		$sheet->setCellValueExplicitByColumnAndRow(0, $r, $worker['workerId'],
			PHPExcel_Cell_DataType::TYPE_STRING);
	    $sheet->setCellValueByColumnAndRow(1, $r, ($worker['finished'] ? 'Yes' : 'No'));
	    $sheet->setCellValueByColumnAndRow(2, $r, count($worker['results']));

		if (is_array($worker['stepMap'])) {
			$c = 3;
			foreach($worker['stepMap'] as $stepNum => $stepId) {
				$sheet->setCellValueByColumnAndRow($c, $r, $stepId + 1);
				$c++;
			}
		}

		$r++;
	}
}


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview
 * 'cr-card-radio-button' is a radio button in the style of a card. A checkmark
 * is displayed in the upper right hand corner if the radio button is selected.
 */
import '//resources/polymer/v3_0/iron-icon/iron-icon.js';
import './cr_radio_button_style.css.js';
import '../cr_shared_vars.css.js';
import '../icons.html.js';

import {mixinBehaviors, PolymerElement} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {PaperRippleBehavior} from 'chrome://resources/polymer/v3_0/paper-behaviors/paper-ripple-behavior.js';

import {getTemplate} from './cr_card_radio_button.html.js';
import {CrRadioButtonMixin, CrRadioButtonMixinInterface} from './cr_radio_button_mixin.js';

const CrCardRadioButtonElementBase =
    mixinBehaviors([PaperRippleBehavior], CrRadioButtonMixin(PolymerElement)) as
    {
      new (): PolymerElement & CrRadioButtonMixinInterface &
          PaperRippleBehavior,
    };

export interface CrCardRadioButtonElement {
  $: {
    button: HTMLElement,
  };
}

export class CrCardRadioButtonElement extends CrCardRadioButtonElementBase {
  static get is() {
    return 'cr-card-radio-button';
  }

  static get template() {
    return getTemplate();
  }

  // Overridden from CrRadioButtonMixin
  override getPaperRipple() {
    return this.getRipple();
  }

  // Overridden from PaperRippleBehavior
  /* eslint-disable-next-line @typescript-eslint/naming-convention */
  override _createRipple() {
    this._rippleContainer = this.shadowRoot!.querySelector('.disc-wrapper');
    const ripple = super._createRipple();
    ripple.id = 'ink';
    ripple.setAttribute('recenters', '');
    ripple.classList.add('circle', 'toggle-ink');
    return ripple;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'cr-card-radio-button': CrCardRadioButtonElement;
  }
}

customElements.define(CrCardRadioButtonElement.is, CrCardRadioButtonElement);


text:
import { defineStore } from "pinia";
import { useStorage } from "@vueuse/core";

const buffer_default = 7;
const truncate_default = false;
const fullRunTitle_default = "$game $category speedrun in $gametime [ifNotIGT]RTA[/ifNotIGT][ifIGT]IGT ($realtime RTA)[/ifIGT]";
const segmentTitle_default = "$game $category - $segment in $gametime [ifNotIGT]RTA[/ifNotIGT][ifIGT]IGT ($realtime RTA)[/ifIGT]";
const description_default = "";

interface AppSettings {
    buffer: number;
    truncate: boolean;
    fullRunTitle: string;
    segmentTitle: string;
    description: string;
}

const createDefaultSettings = (): AppSettings => ({
    buffer: buffer_default,
    truncate: truncate_default,
    fullRunTitle: fullRunTitle_default,
    segmentTitle: segmentTitle_default,
    description: description_default
})

const key = "appSettings";
export const useAppSettingsStore = defineStore(key, {
    state: () => useStorage(key, createDefaultSettings()),
});


text:
#include <QFile>
#include <QList>
#include <QHash>
#include "json.h"

enum Token {
	TokenNULL,
	TokenTRUE,
	TokenFALSE,
	TokenString,
	TokenNumber,
	TokenObject,
	TokenArray,
	TokenObjectClose,
	TokenArrayClose,
	TokenKeySeparator,
	TokenValueSeparator,
	TokenEOF,
	TokenInvalid
};

class JSONHelper
{
public:
	JSONHelper(QString data) : data(data) { pos=0;len=data.length();}
	Token peekToken()
	{
		int oldpos=pos;
		Token t=nextToken();
		pos=oldpos;
		return t;
	}
	Token nextToken()
	{
		while (pos<len && data.at(pos).isSpace()) pos++;
		if (pos==len) return TokenEOF;
		QChar c=data.at(pos++);
		if (c.isLetter()) //keyword like NULL, TRUE, or FALSE
		{
			int start=pos-1;
			while (pos<len && data.at(pos).isLetter())
				pos++;
			QStringRef ref=data.midRef(start,pos-start);
			if (ref.compare("null",Qt::CaseInsensitive)==0)
				return TokenNULL;
			if (ref.compare("true",Qt::CaseInsensitive)==0)
				return TokenTRUE;
			if (ref.compare("false",Qt::CaseInsensitive)==0)
				return TokenFALSE;
			return TokenInvalid;
		}
		if (c.isDigit() || c=='-') //double or hex
		{
			pos--;
			return TokenNumber;
		}
		switch (c.unicode())
		{
		case '"': return TokenString;
		case '{': return TokenObject;
		case '}': return TokenObjectClose;
		case '[': return TokenArray;
		case ']': return TokenArrayClose;
		case ':': return TokenKeySeparator;
		case ',': return TokenValueSeparator;
		default: return TokenInvalid;
		}
	}
	QString readString()
	{
		QString r;
		while (pos<len && data.at(pos)!='"')
		{
			if (data.at(pos)=='\\')
			{
				pos++; if (pos==len) return r;
				switch (data.at(pos++).unicode())
				{
				case '"': r+='"'; break;
				case '\\': r+='\\'; break;
				case '/': r+='/'; break;
				case 'b': r+='\b'; break;
				case 'f': r+='\f'; break;
				case 'n': r+='\n'; break;
				case 'r': r+='\r'; break;
				case 't': r+='\t'; break;
				case 'u': //hex
						  {
							  int num=0;
							  for (int i=0;i<4;i++)
							  {
								  if (pos==len)
									  return r;
								  num<<=4;
								  char c=data.at(pos++).unicode();
								  if (c>='0' && c<='9')
									  num|=c-'0';
								  else if (c>='a' && c<='f')
									  num|=c-'a'+10;
								  else if (c>='A' && c<='F')
									  num|=c-'A'+10;
								  else
									  return r;
							  }
							  r+=QChar(num);
						  }
						  break;
				default: return r;
				}
			}
			else
				r+=data.at(pos++);
		}
		pos++;
		return r;
	}
	double readDouble()
	{
		double sign=1.0;
		if (data.at(pos)=='-')
		{
			sign=-1.0;
			pos++;
		}
		else if (data.at(pos)=='+')
			pos++;
		double value=0.0;
		while (pos<len && data.at(pos).isDigit())
		{
			value*=10.0;
			value+=data.at(pos++).unicode()-'0';
		}
		if (pos==len) return sign*value;
		if (data.at(pos)=='.')
		{
			double pow10=10.0;
			pos++;
			while (pos<len && data.at(pos).isDigit())
			{
				value+=(data.at(pos++).unicode()-'0')/pow10;
				pow10*=10.0;
			}
		}
		if (pos==len) return sign*value;
		double scale=1.0;
		bool frac=false;
		if (data.at(pos)=='e' || data.at(pos)=='E')
		{
			pos++;
			if (pos==len) return sign*value;
			if (data.at(pos)=='-')
			{
				frac=true;
				pos++;
			}
			else if (data.at(pos)=='+')
				pos++;
			unsigned int expon=0;
			while (pos<len && data.at(pos).isDigit())
			{
				expon*=10.0;
				expon+=data.at(pos++).unicode()-'0';
			}
			if (expon>308) expon=308;
			while (expon>=50) { scale *= 1E50; expon-=50; }
			while (expon>=8) { scale *= 1E8; expon-=8; }
			while (expon>0) { scale *= 10.0; expon--; }
		}
		return sign*(frac?(value/scale):(value*scale));
	}
private:
	int pos,len;
	QString data;
};

class JSONNull : public JSON {
public:
	virtual bool isNull() const { return true; }
};
class JSONBool : public JSON {
public:
	JSONBool(bool b) : data(b) {}
	virtual bool toBoolean() const { return data; }
private:
	bool data;
};
class JSONString : public JSON {
public:
	JSONString(const QString s) : data(s) {}
	virtual const QString toString() const { return data; }
private:
	const QString data;
};
class JSONNumber : public JSON {
public:
	JSONNumber(double d) : data(d) {}
	virtual double toNumber() const { return data; }
private:
	double data;
};
class JSONObject : public JSON {
public:
	bool load(JSONHelper &reader);
	virtual ~JSONObject();
	virtual bool contains(const QString key) const;
	virtual const JSON &operator[](const QString key) const;
private:
	QHash<QString,JSON *> children;
};
class JSONArray : public JSON {
public:
	bool load(JSONHelper &reader);
	virtual ~JSONArray();
	virtual int length() const;
	virtual const JSON &operator[](int index) const;
private:
	QList<JSON *> children;
};
static JSONNull Null;

static JSON *parse(JSONHelper &reader)
{
	Token token=reader.nextToken();
	switch (token)
	{
		case TokenNULL: return new JSONNull();
		case TokenTRUE: return new JSONBool(true);
		case TokenFALSE: return new JSONBool(false);
		case TokenString: return new JSONString(reader.readString());
		case TokenNumber: return new JSONNumber(reader.readDouble());
		case TokenObject:
			{
				JSONObject *o=new JSONObject();
				if (!o->load(reader))
				{
					delete o;
					o=NULL;
				}
				return o;
			}
		case TokenArray:
			{
				JSONArray *a=new JSONArray();
				if (!a->load(reader))
				{
					delete a;
					a=NULL;
				}
				return a;
			}
		default: return NULL;
	}
	return NULL;
}

bool JSONObject::load(JSONHelper &reader)
{
	while (true)
	{
		Token token=reader.nextToken();
		if (token==TokenObjectClose)
			break;
		if (token!=TokenString) //error: object doesn't start with key
			return false;
		QString key=reader.readString();
		if (key.length()==0) //error: empty key
			return false;
		if (reader.nextToken()!=TokenKeySeparator) //error: no colon after key
			return false;
		JSON *child=parse(reader);
		if (!child)  //error: child failed to parse
			return false;
		children.insert(key,child);
		token=reader.nextToken();
		if (token==TokenObjectClose)
			break;
		if (token!=TokenValueSeparator) //error: no comma
			return false;
	}
	return true;
}
JSONObject::~JSONObject()
{
	QHashIterator<QString,JSON*>i(children);
	while (i.hasNext())
	{
		i.next();
		delete i.value();
	}
}
bool JSONObject::contains(const QString key) const
{
	return children.contains(key);
}
const JSON &JSONObject::operator[](const QString key) const
{
	if (children.contains(key))
		return *children[key];
	return Null;
}

bool JSONArray::load(JSONHelper &reader)
{
	Token token=reader.peekToken();
	if (token==TokenArrayClose)
	{
		reader.nextToken();
		return true;
	}
	while (true)
	{
		JSON *child=parse(reader);
		if (!child)	//error: child failed to parse
			return false;
		children.append(child);
		token=reader.nextToken();
		if (token==TokenArrayClose)
			break;
		if (token!=TokenValueSeparator) //error: no comma
			return false;
	}
	return true;
}
JSONArray::~JSONArray()
{
	QListIterator<JSON *>i(children);
	while (i.hasNext())
		delete i.next();
}
int JSONArray::length() const
{
	return children.length();
}
const JSON &JSONArray::operator[](int index) const
{
	if (index<children.length())
		return *children[index];
	return Null;
}

JSON::JSON()
{
	root=NULL;
}
JSON::~JSON()
{
	if (root)
		delete root;
}
bool JSON::open(const QString filename)
{
	QFile f(filename);
	f.open(QIODevice::ReadOnly);
	JSONHelper reader(f.readAll());
	f.close();

	root=parse(reader);
	return root!=NULL;
}
bool JSON::isNull() const
{
	if (root)
		return root->isNull();
	return false;
}
bool JSON::contains(const QString key) const
{
	if (root)
		return root->contains(key);
	return false;
}
const JSON &JSON::operator[](const QString key) const
{
	if (root)
		return root->operator[](key);
	return Null;
}
const JSON &JSON::operator[](int i) const
{
	if (root)
		return root->operator[](i);
	return Null;
}
int JSON::length() const
{
	if (root)
		return root->length();
	return 0;
}
const QString JSON::toString() const
{
	if (root)
		return root->toString();
	return NULL;
}
double JSON::toNumber() const
{
	if (root)
		return root->toNumber();
	return 0.0;
}
bool JSON::toBoolean() const
{
	if (root)
		return root->toBoolean();
	return false;
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Agapetes grandiflora Hook.f.

### Remarks
null


text:
/* DOES THIS HELP AUTOSIZING? */
.inputs {
	height: auto !important;
	font-family: Verdana;
}

/*.inputs .tabTitle {*/
/*	background-color: #FF4;*/
/*	vertical-align: middle;*/
/*	font-size: 20px;*/
/*	font-weight: bold;*/
/*	color: darkred;*/
/*}*/

/*.inputs .tabTitle .tabTitleIcon {*/
/*	background-image: url(../../../plugins/admin/images/input-24.png);*/
/*	text-indent: 28px;*/
/*	background-repeat: no-repeat;*/
/*	width: 150px;*/
/*	text-align: center !important;*/
/*	vertical-align: middle;*/
/*}*/

.inputs .label {
	text-align:	center !important;
	font-weight: bolder;
	font-size: 18px;
	color: darkblue;
	font-style: oblique;
	height: 20px;
	vertical-align: bottom !important;
	/*background-color: #FF4;*/
	background-color: #EEE;
}

.inputs .label .paramTypes {
	line-height: 20px !important;
	height: 40px !important;
}

/* NB: THIS IS NEEDED FOR THE BUTTON CSS BELOW TO WORK! */
.inputs table textarea {
	font-family: Verdana;
}
.inputs .addInputButton {
	height: 20px !important;
	width: 115px !important;
	/*margin-left: auto;*/
	margin-right: 0px;

	text-align: center;
	vertical-align: middle;
	-moz-user-select: none;
	font-size: 14px;
	font-family: Verdana;
	font-weight: bolder;
	color: #224;
	background-color: #EEF;

	border: 4px solid #BBB;
	border-bottom-color: #888;
	border-left-color: #888;
}

.inputs .addInputButton:hover {
	border-color: #999;
	border-bottom-color: #555;
	border-left-color: #555;
	background-color : #FF8;
}

.inputs .addInputButton:active {
	border-color: #999;
	border-bottom-color: #555;
	border-left-color: #555;
	background-color : #8F8;
}

.inputs .inputs .name,
.inputs .inputs .type,
.inputs .inputs .value,
.inputs .inputs .argument,
.inputs .inputs .category,
.inputs .inputs .type,
.inputs .inputs .description,
.inputs .inputs .discretion,
.inputs .inputs .paramtype,
.inputs .inputs .format,
.inputs .inputs .args,
.inputs .inputs .params,
.inputs .inputs .paramFunction
{
	height: 20px !important;
	font-size: 14px;
	color: #222;
	text-align: left !important;
	vertical-align: middle !important;
	font-style: oblique;
	font-weight: bolder !important;
	padding-top: 0px;
	/*background-color: #FFF;*/
	/*background-color: #F2F2F2;*/
}

.inputs .inputs name {
	height: 24px !important;
}

.inputs .inputs .type,
.inputs .inputs .discretion,
.inputs .inputs .paramtype {
	font-size: 13px;
	height: 24px !important;
	width: 103px !important;
	padding-top: 0px;
	position: relative;
	left: 4px;
}

.inputs .inputs .format,
.inputs .inputs .args,
.inputs .inputs .params,
.inputs .inputs .paramFunction {
	/*background-color: #EEE;*/
	color: #555;
}

.inputs .invalid ,
.inputs .inputs .description .dijitTextArea .invalid,
.inputs .inputs .discretion .dijitTextArea .invalid
{
	border: 2px solid #F00 !important;
}

.inputs .inputs .default {
	font-style: normal !important;
	font-weight: normal;
	font-size: 12px !important;
	background-color: #DDD !important;
}
.inputs .inputs .default:hover {
	background-color: #DDD !important;
}

/* APPS COMBO */

.inputs .appsCombo,
.inputs .appNamesCombo,
.inputs .paramTypesCombo,
.inputs .dijitMenu li,
.inputs .dijitMenuItem li
{
	text-indent: 10px;
	background-color: #FFD;
}

/* COMBO BOX SELECTED FIELD */
/*.inputs .appsCombo .dijitReset .dijitInputField,*/
/*.inputs .appNamesCombo .dijitReset .dijitInputField {*/
/*	background-color: #FFD;*/
/*}*/

.inputs .appsCombo,
.inputs .appNamesCombo,
.inputs .paramTypesCombo {
	height: auto;
	width: 165px !important;
	color: #000;
	font-size: 14px;
	font-weight: bold;
	text-align: center !important;
	margin-left: auto;
	margin-right: auto;
	background-color: #FFC;
}

.inputs .appNamesCombo {
	color: darkred;
}

/* HIDE VALIDATION ICON AT RIGHT OF COMBO SCROLLBOX */
.inputs .appsCombo .dijitValidationIcon,
.inputs .appNamesCombo .dijitValidationIcon,
.inputs .paramTypesCombo .dijitValidationIcon {
	display: none !important;
}

.inputs .paramTypesCombo {
	font-size: 14px;
	background-color: #FFF !important;
	text-indent: 0px;
	width: 165px !important;
	display: table-cell;
	text-align: center;
	width: 100%;
	font-weight: bold;
	font-family: Verdana;
}

.inputs .paramTypesCombo .option {
	background-color: #FFC !important;
}

/* NOTE: THIS IS NECESSARY FOR THE NEXT RULE TO WORK!!! */
.inputs .appsCombo .dijitReset .dijitMenu li,
.inputs .appsCombo .dijitReset .dijitMenuItem li,
.inputs .appNamesCombo .dijitReset .dijitMenu li,
.inputs .appNamesCombo .dijitReset .dijitMenuItem li,
.inputs .paramTypesCombo .dijitReset .dijitMenu li,
.inputs .paramTypesCombo .dijitReset .dijitMenuItem li
{
	/*color: #0FF !important;*/
}

.inputs .appNamesCombo .dijitReset .dijitMenu li,
.inputs .appNamesCombo .dijitReset .dijitMenuItem li {
	color: darkred;
}

.inputs .dijitMenu li,
.inputs .dijitMenuItem li
{
	color: #224 !important;
	height: 25px;
	background-color: #FFD;
}

.inputs .appNamesCombo .dijitMenu li,
.inputs .appNamesCombo .dijitMenuItem li
{
	color: darkred !important;
}

.inputs .dijitMenu li:hover,
.inputs .dijitMenuItem li:hover
{
	background-color: #DDD;
}

/*/* PARAMETERS COMBO */*/
/**/
/*.inputs .inputsCombo,*/
/*.inputs .dijitMenu li,*/
/*.inputs .dijitMenuItem li*/
/*{*/
/*	text-indent: 10px;*/
/*}*/
/**/
/*.inputs .inputsCombo {*/
/*	text-indent: 10px;*/
/*	height: auto;*/
/*	width: 150px;*/
/*	color: #000;*/
/*	font-size: 15px;*/
/*	font-weight: bold;*/
/*	text-align: center !important;*/
/*	margin-left: auto;*/
/*	margin-right: auto;*/
/*}*/
/**/
/*/* HIDE VALIDATION ICON AT RIGHT OF COMBO SCROLLBOX */*/
/*.inputs .inputsCombo .dijitValidationIcon {*/
/*	/*visibility: hidden !important;*/*/
/*	display: none !important;*/
/*	/*width: 0px !important;*/*/
/*}*/
/**/
/*/* NOTE: THIS IS NECESSARY FOR THE NEXT RULE TO WORK!!! */*/
/*.inputs .inputsCombo .dijitReset .dijitMenu li,*/
/*.inputs .inputsCombo .dijitReset .dijitMenuItem li*/
/*{*/
/*	/*color: #0FF !important;*/*/
/*}*/
/**/
/*.inputs .dijitMenu li,*/
/*.inputs .dijitMenuItem li*/
/*{*/
/*	color: #224 !important;*/
/*	height: 25px;*/
/*}*/
/**/
/*/* NOTE: THIS DOESN'T WORK!!! */*/
/*.inputs .inputsCombo .dijitReset .dijitInputField*/
/*{*/
/*	/*color: #0FF !important;*/*/
/*	text-align: center !important;*/
/*}*/

/* DRAG SOURCE */

.inputs .dragSource .paramtype .default,
.inputs .dragSource .discretion .default
{
	color: #555;
	font-style: italic;
}

.inputs .editInputRow {
	width: 100%;
	height: 20px;
}

.inputs .dragSource
{
	-moz-background-clip:border;
	-moz-background-inline-policy:continuous;
	-moz-background-origin:padding;
	-moz-border-radius-bottomleft:8pt;
	-moz-border-radius-bottomright:8pt;
	-moz-border-radius-topleft:8pt;
	-moz-border-radius-topright:8pt;

	background:#FFFFFF none repeat scroll 0 0;
	border:3px solid #CCCCCC;
	cursor:default;
	padding:1em 0.5em;

	/*margin-top: 5px;*/
	width: 120px;
	height: 260px;
	min-height: 100px;

	text-align: left !important;
	/*color: #339;*/
	/*color: darkred;*/
	/*font-weight: bold;*/

	font-size: 12px;
	border-color: #333;

	/* NEEDED SO THAT SCROLLBAR WILL SHOW */
	display: block !important;
	overflow:auto !important;
}

.inputs .dragSource .name {
	font-size: 14px;
	color: darkred;
	font-weight: bolder;
	text-align: left !important;

	background-image: url(../../../plugins/admin/images/input-18.png);
	text-indent: 22px;
	background-repeat: no-repeat;
	height: 18px;
}

.inputs .dragSource .type,
.inputs .dragSource .paramtype {
	width: 40px;
	font-size: 11px;
	text-align: center !important;
	background-color: #FFF;
}

.inputs .dragSource .type {
	color: darkblue;
}

.inputs .dragSource .paramtype {
	color: darkred;
}

.inputs .dragSource .category,
.inputs .dragSource .value,
.inputs .dragSource .argument {
	color: #222;
	font-size: 11px;
	font-weight: bold;
	text-align: left !important;
	background: #FFF;
}

.inputs .dragSource .description {
	color: #222;
	font-size: 12px;
	font-weight: bold;
	text-align: left !important;
	background: #FFF;
}

.inputs .dragSource .discretion {
	color: blue;
	font-weight: bold;
	font-size: 12px;
	background: none;
}

.inputs .dragSource .format,
.inputs .dragSource .args,
.inputs .dragSource .params,
.inputs .dragSource .paramFunction {
	color: #222;
	font-weight: normal;
	font-size: 10px;
	background-color: #EFEFEF;
}

.inputs .trash {
	-moz-background-clip:border;
	-moz-background-inline-policy:continuous;
	-moz-background-origin:padding;
	-moz-border-radius-bottomleft:8pt;
	-moz-border-radius-bottomright:8pt;
	-moz-border-radius-topleft:8pt;
	-moz-border-radius-topright:8pt;

	background:#FFFFFF none repeat scroll 0 0;
	border:3px solid #CCCCCC;
	cursor:default;
	padding:1em 0.5em;

	margin-top: 5px;
	width: 150px;
	height: 60px;
	text-align: center;
	vertical-align: middle;
}

.inputs .trashIcon {
	height: 100%;
	width: 100px;
	margin-left: auto;
	margin-right: auto;

	background-image: url(../../../plugins/admin/images/trash-60.png);
	background-repeat: no-repeat;
}


text:
<?php

namespace Intahwebz\FlickrGuzzle\DTO;

use Intahwebz\FlickrGuzzle\DataMapper;

class InstitutionList {

	use DataMapper;

	static protected $dataMap = array(
		['institutions', 'institution', 'class' => 'Intahwebz\FlickrGuzzle\DTO\Institution', 'multiple' => 'true'],
	);

	var $institutions = array();
}


text:
package eu.programit.domain;

import java.util.ArrayList;
import java.util.List;

public class Mervyn extends Person {
    @Override
    public String getFirstName() {
        return "Mervyn";
    }

    @Override
    public List<String> getHobbies() {
        List<String> result = new ArrayList<>(2);
        result.add("Voetbal");
        result.add("Gitaar pingelen");
        return result;
    }
}


text:
"""Tests for namespace_config."""

import copy
import types

from absl.testing import absltest
import fiddle as fdl
from fiddle.experimental import namespace_config

class NamespaceConfigTest(absltest.TestCase):

  def test_simple(self):
    cfg = namespace_config.NamespaceConfig()
    cfg.x = 1
    cfg.y = 'abc'
    obj = fdl.build(cfg)
    self.assertIsInstance(obj, types.SimpleNamespace)
    self.assertEqual(1, obj.x)
    self.assertEqual('abc', obj.y)

  def test_initialize_from_dict(self):
    test_dict = {'a': 1, 'b': 'xyz'}
    cfg = namespace_config.NamespaceConfig(**test_dict)
    obj = fdl.build(cfg)
    self.assertIsInstance(obj, types.SimpleNamespace)
    self.assertEqual(1, obj.a)
    self.assertEqual('xyz', obj.b)

  def test_nesting(self):

    def sample_fn(**kwargs):
      return (sample_fn, kwargs)

    cfg = namespace_config.NamespaceConfig()
    cfg.nested = fdl.Config(sample_fn, x='a')
    cfg.nested.y = 123
    cfg.nested.other_dictconfig = namespace_config.NamespaceConfig(
        very_inside='here')
    cfg.other = 321

    obj = fdl.build(cfg)
    self.assertIsInstance(obj, types.SimpleNamespace)
    self.assertIs(sample_fn, obj.nested[0])
    self.assertEqual(321, obj.other)
    self.assertIsInstance(obj.nested[1]['other_dictconfig'],
                          types.SimpleNamespace)
    self.assertEqual('here', obj.nested[1]['other_dictconfig'].very_inside)

  def test_copy(self):
    cfg1 = namespace_config.NamespaceConfig()
    cfg1.x = 1
    cfg1.y = 'abc'
    cfg2 = copy.copy(cfg1)

    with self.subTest('copy_mantains_equality'):
      self.assertEqual(cfg1, cfg2)

    with self.subTest('mutation_on_copy_does_not_affect_original'):
      cfg2.y = 'def'
      self.assertNotEqual(cfg1, cfg2)

  @absltest.skip('Enable this after dropping pyhon 3.7 support')
  def test_key_named_self(self):
    cfg = namespace_config.NamespaceConfig()
    cfg.self = 2
    expected = types.SimpleNamespace()
    expected.self = 2
    self.assertEqual(fdl.build(cfg), expected)

if __name__ == '__main__':
  absltest.main()