text:
static double max_surf_curvature(const GEdge *ge, double u)
{
  double val = 0;
  std::vector<GFace *> faces = ge->faces();
  std::vector<GFace *>::iterator it = faces.begin();
  while(it != faces.end()) {
    SPoint2 par = ge->reparamOnFace((*it), u, 1);
    double cc = (*it)->curvature(par);
    val = std::max(cc, val);
    ++it;
  }
  return val;
}

static double max_edge_curvature(const GVertex *gv)
{
  double val = 0;
  std::vector<GEdge *> const &l_edges = gv->edges();
  for(std::vector<GEdge *>::const_iterator ite = l_edges.begin();
      ite != l_edges.end(); ++ite) {
    GEdge *_myGEdge = *ite;
    Range<double> range = _myGEdge->parBounds(0);
    double cc;
    if(gv == _myGEdge->getBeginVertex())
      cc = _myGEdge->curvature(range.low());
    else
      cc = _myGEdge->curvature(range.high());
    val = std::max(val, cc);
  }
  return val;
}

// the mesh vertex is classified on a model vertex.  we compute the maximum of
// the curvature of model faces surrounding this point if it is classified on a
// model edge, we do the same for all model faces surrounding it if it is on a
// model face, we compute the curvature at this location
static double LC_MVertex_CURV(GEntity *ge, double U, double V)
{
  double Crv = 0;
  switch(ge->dim()) {
  case 0:
    Crv = max_edge_curvature((const GVertex *)ge);
    // Crv = std::max(max_surf_curvature_vertex((const GVertex *)ge), Crv);
    // Crv = max_surf_curvature((const GVertex *)ge);
    break;
  case 1: {
    GEdge *ged = (GEdge *)ge;
    Crv = ged->curvature(U);
    Crv = std::max(Crv, max_surf_curvature(ged, U));
    // printf("%g %d\n",Crv, CTX::instance()->mesh.minCircPoints);
    // Crv = max_surf_curvature(ged, U);
  } break;
  case 2: {
    GFace *gf = (GFace *)ge;
    Crv = gf->curvature(SPoint2(U, V));
  } break;
  }
  double lc =
    Crv > 0 ? 2 * M_PI / Crv / CTX::instance()->mesh.minCircPoints : MAX_LC;
  return lc;
}

SMetric3 max_edge_curvature_metric(const GEdge *ge, double u)
{
  SVector3 t = ge->firstDer(u);
  t.normalize();
  double l_t =
    (2 * M_PI) / (fabs(ge->curvature(u)) * CTX::instance()->mesh.minCircPoints);
  double l_n = 1.e12;
  return buildMetricTangentToCurve(t, l_t, l_n);
}

static SMetric3 metric_based_on_surface_curvature(const GEdge *ge, double u,
                                                  bool iso_surf)
{
  SMetric3 mesh_size(1.e-12);
  std::vector<GFace *> faces = ge->faces();
  std::vector<GFace *>::iterator it = faces.begin();
  // we choose the metric eigenvectors to be the ones
  // related to the edge ...
  SMetric3 curvMetric = max_edge_curvature_metric(ge, u);
  while(it != faces.end()) {
    SPoint2 par = ge->reparamOnFace((*it), u, 1);
    SMetric3 m =
      metric_based_on_surface_curvature(*it, par.x(), par.y(), iso_surf);
    curvMetric = intersection_conserveM1(curvMetric, m);
    ++it;
  }
  return curvMetric;
}

static SMetric3 metric_based_on_surface_curvature(const GVertex *gv,
                                                  bool iso_surf)
{
  SMetric3 mesh_size(1.e-15);
  return mesh_size;
}

SMetric3 LC_MVertex_CURV_ANISO(GEntity *ge, double U, double V)
{
  bool iso_surf = CTX::instance()->mesh.lcFromCurvature == 2;

  switch(ge->dim()) {
  case 0:
    return metric_based_on_surface_curvature((const GVertex *)ge, iso_surf);
  case 1:
    return metric_based_on_surface_curvature((const GEdge *)ge, U, iso_surf);
  case 2:
    return metric_based_on_surface_curvature((const GFace *)ge, U, V, iso_surf);
  }
  Msg::Error("Curvature control impossible to compute for a volume!");
  return SMetric3();
}

// compute the mesh size at a given vertex due to prescribed sizes at
// mesh vertices
static double LC_MVertex_PNTS(GEntity *ge, double U, double V)
{
  switch(ge->dim()) {
  case 0: {
    GVertex *gv = (GVertex *)ge;
    double lc = gv->prescribedMeshSizeAtVertex();
    // FIXME we might want to remove this to make all lc treatment consistent
    if(lc >= MAX_LC) return CTX::instance()->lc / 10.;
    return lc;
  }
  case 1: {
    GEdge *ged = (GEdge *)ge;
    GVertex *v1 = ged->getBeginVertex();
    GVertex *v2 = ged->getEndVertex();
    if(v1 && v2) {
      double lc1 = v1->prescribedMeshSizeAtVertex();
      double lc2 = v2->prescribedMeshSizeAtVertex();
      if(lc1 >= MAX_LC && lc2 >= MAX_LC) {
        // FIXME we might want to remove this to make all lc treatment
        // consistent
        return CTX::instance()->lc / 10.;
      }
      else {
        Range<double> range = ged->parBounds(0);
        double a = (U - range.low()) / (range.high() - range.low());
        return (1 - a) * lc1 + (a)*lc2;
      }
    }
    else
      return MAX_LC;
  }
  default: return MAX_LC;
  }
}

SMetric3 buildMetricTangentToCurve(SVector3 &t, double l_t, double l_n)
{
  if(l_t == 0.0) return SMetric3(1.e-22);
  SVector3 a;
  if(fabs(t(0)) <= fabs(t(1)) && fabs(t(0)) <= fabs(t(2))) {
    a = SVector3(1, 0, 0);
  }
  else if(fabs(t(1)) <= fabs(t(0)) && fabs(t(1)) <= fabs(t(2))) {
    a = SVector3(0, 1, 0);
  }
  else {
    a = SVector3(0, 0, 1);
  }
  SVector3 b = crossprod(t, a);
  SVector3 c = crossprod(b, t);
  b.normalize();
  c.normalize();
  t.normalize();
  SMetric3 Metric(1. / (l_t * l_t), 1. / (l_n * l_n), 1. / (l_n * l_n), t, b,
                  c);
  //  printf("bmttc %g %g %g %g
  //  %g\n",l_t,l_n,Metric(0,0),Metric(0,1),Metric(1,1));
  return Metric;
}

SMetric3 buildMetricTangentToSurface(SVector3 &t1, SVector3 &t2, double l_t1,
                                     double l_t2, double l_n)
{
  t1.normalize();
  t2.normalize();
  SVector3 n = crossprod(t1, t2);
  n.normalize();

  l_t1 = std::max(l_t1, CTX::instance()->mesh.lcMin);
  l_t2 = std::max(l_t2, CTX::instance()->mesh.lcMin);
  l_t1 = std::min(l_t1, CTX::instance()->mesh.lcMax);
  l_t2 = std::min(l_t2, CTX::instance()->mesh.lcMax);
  SMetric3 Metric(1. / (l_t1 * l_t1), 1. / (l_t2 * l_t2), 1. / (l_n * l_n), t1,
                  t2, n);
  return Metric;
}

// This is the only function that is used by the meshers
double BGM_MeshSize(GEntity *ge, double U, double V, double X, double Y,
                    double Z)
{
  // default lc (mesh size == size of the model)
  double l1 = CTX::instance()->lc;

  if(!ge)
    Msg::Warning("No entity in background mesh size evaluation");

  // lc from points
  double l2 = MAX_LC;
  if(ge && CTX::instance()->mesh.lcFromPoints && ge->dim() < 2)
    l2 = LC_MVertex_PNTS(ge, U, V);

  // lc from curvature
  double l3 = MAX_LC;
  if(ge && CTX::instance()->mesh.lcFromCurvature && ge->dim() < 3)
    l3 = LC_MVertex_CURV(ge, U, V);

  // lc from fields
  double l4 = MAX_LC;
  if(ge){
    FieldManager *fields = ge->model()->getFields();
    if(fields->getBackgroundField() > 0) {
      Field *f = fields->get(fields->getBackgroundField());
      if(f) l4 = (*f)(X, Y, Z, ge);
    }
  }

  // global lc from entity
  double l5 = ge ? ge->getMeshSize() : MAX_LC;

  // take the minimum, then constrain by lcMin and lcMax
  double lc = std::min(std::min(std::min(std::min(l1, l2), l3), l4), l5);
  lc = std::max(lc, CTX::instance()->mesh.lcMin);
  lc = std::min(lc, CTX::instance()->mesh.lcMax);

  if(lc <= 0.) {
    Msg::Error("Wrong mesh element size lc = %g (lcmin = %g, lcmax = %g)", lc,
               CTX::instance()->mesh.lcMin, CTX::instance()->mesh.lcMax);
    lc = l1;
  }

  return lc * CTX::instance()->mesh.lcFactor;
}

// anisotropic version of the background field
SMetric3 BGM_MeshMetric(GEntity *ge, double U, double V, double X, double Y,
                        double Z)
{
  // Metrics based on element size

  // Element size = min. between default lc and lc from point (if applicable),
  // constrained by lcMin and lcMax
  double lc = CTX::instance()->lc;
  if(CTX::instance()->mesh.lcFromPoints && ge->dim() < 2)
    lc = std::min(lc, LC_MVertex_PNTS(ge, U, V));
  lc = std::min(lc, ge->getMeshSize());
  lc = std::max(lc, CTX::instance()->mesh.lcMin);
  lc = std::min(lc, CTX::instance()->mesh.lcMax);
  if(lc <= 0.) {
    Msg::Error("Wrong mesh element size lc = %g (lcmin = %g, lcmax = %g)", lc,
               CTX::instance()->mesh.lcMin, CTX::instance()->mesh.lcMax);
    lc = CTX::instance()->lc;
  }
  SMetric3 m0(1. / (lc * lc));

  // Intersect with metrics from fields if applicable
  FieldManager *fields = ge->model()->getFields();
  SMetric3 m1 = m0;
  if(fields->getBackgroundField() > 0) {
    Field *f = fields->get(fields->getBackgroundField());
    if(f) {
      SMetric3 l4;
      if(!f->isotropic()) {
        (*f)(X, Y, Z, l4, ge);
      }
      else {
        const double L = (*f)(X, Y, Z, ge);
        l4 = SMetric3(1 / (L * L));
      }
      m1 = intersection(l4, m0);
    }
  }

  // Intersect with metrics from curvature if applicable
  SMetric3 m = (CTX::instance()->mesh.lcFromCurvature && ge->dim() < 3) ?
                 intersection(m1, LC_MVertex_CURV_ANISO(ge, U, V)) :
                 m1;

  return m;
}

bool Extend1dMeshIn2dSurfaces()
{
  return CTX::instance()->mesh.lcExtendFromBoundary;
}

bool Extend2dMeshIn3dVolumes()
{
  return CTX::instance()->mesh.lcExtendFromBoundary;
}

SMetric3 max_edge_curvature_metric(const GVertex *gv)
{
  SMetric3 val(1.e-12);
  std::vector<GEdge *> const &l_edges = gv->edges();
  for(std::vector<GEdge *>::const_iterator ite = l_edges.begin();
      ite != l_edges.end(); ++ite) {
    GEdge *_myGEdge = *ite;
    Range<double> range = _myGEdge->parBounds(0);
    SMetric3 cc;
    if(gv == _myGEdge->getBeginVertex()) {
      SVector3 t = _myGEdge->firstDer(range.low());
      t.normalize();
      double l_t = ((2 * M_PI) / (fabs(_myGEdge->curvature(range.low())) *
                                  CTX::instance()->mesh.minCircPoints));
      double l_n = 1.e12;
      cc = buildMetricTangentToCurve(t, l_t, l_n);
    }
    else {
      SVector3 t = _myGEdge->firstDer(range.high());
      t.normalize();
      double l_t = ((2 * M_PI) / (fabs(_myGEdge->curvature(range.high())) *
                                  CTX::instance()->mesh.minCircPoints));
      double l_n = 1.e12;
      cc = buildMetricTangentToCurve(t, l_t, l_n);
    }
    val = intersection(val, cc);
  }
  return val;
}

SMetric3 metric_based_on_surface_curvature(const GFace *gf, double u, double v,
                                           bool surface_isotropic,
                                           double d_normal,
                                           double d_tangent_max)
{
  if(gf->geomType() == GEntity::Plane) return SMetric3(1.e-12);
  double cmax, cmin;
  SVector3 dirMax, dirMin;
  cmax = gf->curvatures(SPoint2(u, v), dirMax, dirMin, cmax, cmin);
  if(cmin == 0) cmin = 1.e-12;
  if(cmax == 0) cmax = 1.e-12;
  double lambda1 =
    ((2 * M_PI) / (fabs(cmin) * CTX::instance()->mesh.minCircPoints));
  double lambda2 =
    ((2 * M_PI) / (fabs(cmax) * CTX::instance()->mesh.minCircPoints));
  SVector3 Z = crossprod(dirMax, dirMin);
  if(surface_isotropic) lambda2 = lambda1 = std::min(lambda2, lambda1);
  dirMin.normalize();
  dirMax.normalize();
  Z.normalize();
  lambda1 = std::max(lambda1, CTX::instance()->mesh.lcMin);
  lambda2 = std::max(lambda2, CTX::instance()->mesh.lcMin);
  lambda1 = std::min(lambda1, CTX::instance()->mesh.lcMax);
  lambda2 = std::min(lambda2, CTX::instance()->mesh.lcMax);
  double lambda3 = std::min(d_normal, CTX::instance()->mesh.lcMax);
  lambda3 = std::max(lambda3, CTX::instance()->mesh.lcMin);
  lambda1 = std::min(lambda1, d_tangent_max);
  lambda2 = std::min(lambda2, d_tangent_max);

  SMetric3 curvMetric(1. / (lambda1 * lambda1), 1. / (lambda2 * lambda2),
                      1. / (lambda3 * lambda3), dirMin, dirMax, Z);
  return curvMetric;
}


text:
//
// Copyright 2015-21 Volker Sorge
//
// Licensed under the Apache on 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @file Specialist computations to deal with embellished fences.
 * @author volker.sorge@gmail.com (Volker Sorge)
 */

import * as DomUtil from '../common/dom_util';
import { SemanticRole, SemanticType } from '../semantic_tree/semantic_meaning';
import { SemanticNode } from '../semantic_tree/semantic_node';

import { AbstractEnrichCase } from './abstract_enrich_case';
import { CaseDoubleScript } from './case_double_script';
import { CaseMultiscripts } from './case_multiscripts';
import { CaseTensor } from './case_tensor';
import * as EnrichMathml from './enrich_mathml';
import { setAttributes, Attribute } from './enrich_attr';

export class CaseEmbellished extends AbstractEnrichCase {
  /**
   * Fenced semantic node.
   */
  public fenced: SemanticNode = null;

  /**
   * Fenced mml node.
   */
  public fencedMml: Element = null;

  /**
   * List of all fenced mml nodes. `fencedMml` is the first.
   */
  public fencedMmlNodes: Element[] = [];

  /**
   * Open Fenced semantic node.
   */
  public ofence: SemanticNode = null;

  /**
   * Open Fenced mml node.
   */
  public ofenceMml: Element = null;

  /**
   * Open Fenced node map.
   */
  public ofenceMap: { [key: number]: Element } = {};

  /**
   * Closed Fenced semantic node.
   */
  public cfence: SemanticNode = null;

  /**
   * Closed Fenced node map.
   */
  public cfenceMml: Element = null;

  /**
   * Closed Fenced semantic node.
   */
  public cfenceMap: { [key: number]: Element } = {};

  /**
   * List of elements that need to get the parents reset.
   */
  public parentCleanup: Element[] = [];

  /**
   * Applicability test of the case. This method also prevents walking
   * embellished punctuations twice as they might have already been walked as
   * content nodes.
   *
   * @param semantic The semantic node.
   * @returns True if case is applicable.
   */
  public static test(semantic: SemanticNode): boolean {
    return !!(
      semantic.mathmlTree &&
      semantic.fencePointer &&
      // TODO: This needs a cleaner solution at some point.
      !semantic.mathmlTree.getAttribute('data-semantic-type')
    );
  }

  /**
   * Creates an empty semantic node with an associated empty mrow MathML
   * element.
   *
   * @param id The id number of the node.
   * @returns The new empty node.
   */
  private static makeEmptyNode_(id: number): SemanticNode {
    const mrow = DomUtil.createElement('mrow');
    const empty = new SemanticNode(id);
    empty.type = SemanticType.EMPTY;
    empty.mathmlTree = mrow;
    return empty;
  }

  /**
   * Collates the id numbers of the fenced node.
   *
   * @param fence The fence expression.
   * @param ids The list of id numbers.
   */
  private static fencedMap_(
    fence: SemanticNode,
    ids: { [key: number]: Element }
  ) {
    ids[fence.id] = fence.mathmlTree;
    if (!fence.embellished) {
      return;
    }
    CaseEmbellished.fencedMap_(fence.childNodes[0], ids);
  }

  /**
   * @override
   */
  constructor(semantic: SemanticNode) {
    super(semantic);
  }

  /**
   * @override
   */
  public getMathml() {
    this.getFenced_();
    // This is the first fenced node, but there can be more than one!
    this.fencedMml = EnrichMathml.walkTree(this.fenced as SemanticNode);
    this.getFencesMml_();
    if (this.fenced.type === SemanticType.EMPTY && !this.fencedMml.parentNode) {
      // Fenced element is empty and new. Insert it before the closing fence so
      // it can be walked as usual.
      this.fencedMml.setAttribute(Attribute.ADDED, 'true');
      this.cfenceMml.parentNode.insertBefore(this.fencedMml, this.cfenceMml);
    }
    this.getFencedMml_();
    const rewrite = this.rewrite_();
    return rewrite;
  }

  /**
   * Checks if the node is fenced, including vectors, matrices etc.
   *
   * @param node A semantic node.
   * @returns True if the node is a fenced elementd type.
   */
  private fencedElement(node: SemanticNode) {
    return (
      node.type === SemanticType.FENCED ||
      node.type === SemanticType.MATRIX ||
      node.type === SemanticType.VECTOR
    );
  }

  /**
   * Computes the components of the actual fenced node.
   */
  private getFenced_() {
    let currentNode = this.semantic;
    while (!this.fencedElement(currentNode)) {
      currentNode = currentNode.childNodes[0];
    }
    this.fenced = currentNode.childNodes[0];
    this.ofence = currentNode.contentNodes[0];
    this.cfence = currentNode.contentNodes[1];
    CaseEmbellished.fencedMap_(this.ofence, this.ofenceMap);
    CaseEmbellished.fencedMap_(this.cfence, this.cfenceMap);
  }

  /**
   * Retrieve the list of MathMl elements that are fenced.
   */
  private getFencedMml_() {
    let sibling = this.ofenceMml.nextSibling;
    sibling = sibling === this.fencedMml ? sibling : this.fencedMml;
    while (sibling && sibling !== this.cfenceMml) {
      this.fencedMmlNodes.push(sibling as Element);
      sibling = sibling.nextSibling;
    }
  }

  /**
   * Retrieve the actual MathMl element that forms the outermost layer of the
   * fences.
   */
  private getFencesMml_() {
    let currentNode = this.semantic;
    const ofenceIds = Object.keys(this.ofenceMap);
    const cfenceIds = Object.keys(this.cfenceMap);
    while (
      (!this.ofenceMml || !this.cfenceMml) &&
      currentNode !== this.fenced
    ) {
      if (
        ofenceIds.indexOf(currentNode.fencePointer) !== -1 &&
        !this.ofenceMml
      ) {
        this.ofenceMml = currentNode.mathmlTree;
      }
      if (
        cfenceIds.indexOf(currentNode.fencePointer) !== -1 &&
        !this.cfenceMml
      ) {
        this.cfenceMml = currentNode.mathmlTree;
      }
      currentNode = currentNode.childNodes[0];
    }
    if (!this.ofenceMml) {
      this.ofenceMml = this.ofence.mathmlTree;
    }
    if (!this.cfenceMml) {
      this.cfenceMml = this.cfence.mathmlTree;
    }
    if (this.ofenceMml) {
      this.ofenceMml = EnrichMathml.ascendNewNode(this.ofenceMml);
    }
    if (this.cfenceMml) {
      this.cfenceMml = EnrichMathml.ascendNewNode(this.cfenceMml);
    }
  }

  /**
   * Rewrites the MathML node with embellished fences.
   *
   * @returns The new MathML element.
   */
  private rewrite_(): Element {
    let currentNode = this.semantic;
    let result = null;
    const newNode = this.introduceNewLayer_();
    // Sets the basics composition.
    setAttributes(newNode, this.fenced.parent as SemanticNode);

    while (!this.fencedElement(currentNode)) {
      // Outer embellished node is the one with the fence pointer.
      const mml = currentNode.mathmlTree as Element;
      const specialCase = this.specialCase_(currentNode, mml);
      if (specialCase) {
        currentNode = specialCase;
      } else {
        setAttributes(mml, currentNode);
        const mmlChildren = [];
        // The base node is rewritten. Walk the remaining nodes.
        for (let i = 1, child; (child = currentNode.childNodes[i]); i++) {
          mmlChildren.push(EnrichMathml.walkTree(child));
        }
        currentNode = currentNode.childNodes[0];
      }

      // Reordering the nodes in the tree.
      const dummy = DomUtil.createElement('dummy');
      const saveChild = mml.childNodes[0];

      DomUtil.replaceNode(mml, dummy);
      DomUtil.replaceNode(newNode, mml);
      DomUtil.replaceNode(mml.childNodes[0], newNode);
      DomUtil.replaceNode(dummy, saveChild);
      if (!result) {
        result = mml;
      }
    }

    // Walk the actual fences.
    EnrichMathml.walkTree(this.ofence as SemanticNode);
    EnrichMathml.walkTree(this.cfence as SemanticNode);

    this.cleanupParents_();
    return result || newNode;
  }

  /**
   * Treatment of special cases like msubsup and rewritten mmultiscripts.
   *
   * @param semantic The current semantic node.
   * @param mml The MathML node associated with the semantic node.
   * @returns The next semantic node to be rewritten, if
   *     the original semantic node was a special case.
   */
  private specialCase_(semantic: SemanticNode, mml: Element): SemanticNode {
    const mmlTag = DomUtil.tagName(mml);
    let parent = null;
    let caller;
    if (mmlTag === 'MSUBSUP') {
      parent = semantic.childNodes[0];
      caller = CaseDoubleScript;
    } else if (mmlTag === 'MMULTISCRIPTS') {
      if (
        semantic.type === SemanticType.SUPERSCRIPT ||
        semantic.type === SemanticType.SUBSCRIPT
      ) {
        caller = CaseMultiscripts;
      } else if (semantic.type === SemanticType.TENSOR) {
        caller = CaseTensor;
      }
      if (
        caller &&
        semantic.childNodes[0] &&
        semantic.childNodes[0].role === SemanticRole.SUBSUP
      ) {
        parent = semantic.childNodes[0];
      } else {
        parent = semantic;
      }
    }
    if (!parent) {
      return null;
    }
    const base = parent.childNodes[0];
    const empty = CaseEmbellished.makeEmptyNode_(base.id);
    parent.childNodes[0] = empty;
    mml = new caller(semantic).getMathml();
    parent.childNodes[0] = base;
    this.parentCleanup.push(mml);
    return parent.childNodes[0];
  }

  /**
   * Introduces a new layer if necessary before rewriting the fence.
   *
   * @returns The node representing the active layer.
   */
  private introduceNewLayer_(): Element {
    const fullOfence = this.fullFence(this.ofenceMml);
    const fullCfence = this.fullFence(this.cfenceMml);
    // Introduce a definite new layer.
    let newNode = DomUtil.createElement('mrow');
    DomUtil.replaceNode(this.fencedMml as Element, newNode);
    this.fencedMmlNodes.forEach((node) => newNode.appendChild(node));
    newNode.insertBefore(fullOfence, this.fencedMml);
    newNode.appendChild(fullCfence);
    // The case of top element math.
    if (!newNode.parentNode) {
      const mrow = DomUtil.createElement('mrow');
      while (newNode.childNodes.length > 0) {
        mrow.appendChild(newNode.childNodes[0]);
      }
      newNode.appendChild(mrow);
      newNode = mrow;
    }
    return newNode;
  }

  /**
   * Retrieves the original embellished fence for the given fence.
   *
   * @param fence A simple fence.
   * @returns The embellished version of that fence. Can be the fence
   *     itself if it was not embellished.
   */
  private fullFence(fence: Element): Element {
    const parent = this.fencedMml.parentNode;
    let currentFence = fence;
    while (currentFence.parentNode && currentFence.parentNode !== parent) {
      currentFence = currentFence.parentNode as Element;
    }
    return currentFence as Element;
  }

  /**
   * Sets the correct parent pointer for MathML nodes treated and collated in
   * the special cases. In particular we set the parent of the first child of a
   * node to the parent of the remaining children.
   */
  private cleanupParents_() {
    this.parentCleanup.forEach(function (x) {
      const parent = (x.childNodes[1] as Element).getAttribute(
        Attribute.PARENT
      );
      (x.childNodes[0] as Element).setAttribute(Attribute.PARENT, parent);
    });
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.araqne.logdb.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 테이블 설정을 표현합니다.
 *
 * @author xeraph@eediom.com
 *
 */
public class TableSchemaInfo {
	private String name;

	private int id;

	private StorageEngineConfig primaryStorage;

	private StorageEngineConfig replicaStorage;

	private List<StorageEngineConfig> secondaryStorages = new ArrayList<StorageEngineConfig>();

	private List<FieldInfo> fieldDefinitions;

	private Map<String, String> metadata = new HashMap<String, String>();

	public TableSchemaInfo() {
	}

	/**
	 * @param name
	 *            테이블 이름
	 * @param type
	 *            주 스토리지 엔진 타입
	 */
	public TableSchemaInfo(String name, String type) {
		this.name = name;
		this.primaryStorage = new StorageEngineConfig(type);
	}

	@Deprecated
	public TableSchemaInfo(String name, Map<String, String> metadata) {
		this.name = name;
		this.metadata = metadata;
	}

	public TableSchemaInfo clone() {
		TableSchemaInfo c = new TableSchemaInfo();
		c.setName(name);
		c.setId(id);
		c.setPrimaryStorage(primaryStorage.clone());

		if (replicaStorage != null)
			c.setReplicaStorage(replicaStorage.clone());

		List<StorageEngineConfig> l = new ArrayList<StorageEngineConfig>();
		for (StorageEngineConfig s : secondaryStorages)
			l.add(s.clone());

		c.setSecondaryStorages(l);

		c.setFieldDefinitions(cloneFieldDefinitions(fieldDefinitions));
		if (metadata != null)
			c.setMetadata(new HashMap<String, String>(metadata));

		return c;
	}

	private List<FieldInfo> cloneFieldDefinitions(List<FieldInfo> l) {
		if (l == null)
			return null;

		List<FieldInfo> cloned = new ArrayList<FieldInfo>();
		for (FieldInfo d : l)
			cloned.add(FieldInfo.parse(d.toString()));
		return cloned;
	}

	/**
	 * 테이블 이름을 반환합니다.
	 *
	 * @return 테이블 이름
	 */
	public String getName() {
		return name;
	}

	/**
	 * 테이블 이름을 설정합니다.
	 *
	 * @param name
	 *            테이블 이름
	 */
	public void setName(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public StorageEngineConfig getPrimaryStorage() {
		return primaryStorage;
	}

	public void setPrimaryStorage(StorageEngineConfig primaryStorage) {
		this.primaryStorage = primaryStorage;
	}

	public StorageEngineConfig getReplicaStorage() {
		return replicaStorage;
	}

	public void setReplicaStorage(StorageEngineConfig replicaStorage) {
		this.replicaStorage = replicaStorage;
	}

	public List<StorageEngineConfig> getSecondaryStorages() {
		return secondaryStorages;
	}

	public void setSecondaryStorages(List<StorageEngineConfig> secondaryStorages) {
		this.secondaryStorages = secondaryStorages;
	}

	/**
	 * 테이블 메타데이터를 반환합니다.
	 *
	 * @return 테이블 메타데이터
	 */
	public Map<String, String> getMetadata() {
		return metadata;
	}

	/**
	 * 테이블 메타데이터를 설정합니다.
	 *
	 * @param metadata
	 *            테이블 메타데이터
	 */
	public void setMetadata(Map<String, String> metadata) {
		this.metadata = metadata;
	}

	/**
	 * 스키마를 구성하는 필드 정의 목록을 반환합니다.
	 *
	 * @return 필드 정의 목록
	 */
	public List<FieldInfo> getFieldDefinitions() {
		return fieldDefinitions;
	}

	/**
	 * 스키마를 구성하는 필드 정의 목록을 설정합니다.
	 *
	 * @param fieldDefinitions
	 *            필드 정의 목록
	 */
	public void setFieldDefinitions(List<FieldInfo> fieldDefinitions) {
		this.fieldDefinitions = fieldDefinitions;
	}

	public Map<String, Object> toMap() {
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("table", name);
		m.put("id", id);
		m.put("type", primaryStorage.getType());
		m.put("base_path", primaryStorage.getBasePath());
		m.put("primary_configs", serialize(primaryStorage));
		m.put("replica_configs", serialize(replicaStorage));
		m.put("metadata", metadata);

		return m;
	}

	private Map<String, Object> serialize(StorageEngineConfig c) {
		if (c == null)
			return null;

		Map<String, Object> m = new HashMap<String, Object>();
		for (TableConfig t : c.getConfigs()) {
			if (t.getValues().size() <= 1)
				m.put(t.getKey(), t.getValue());
			else
				m.put(t.getKey(), t.getValues());
		}

		return m;
	}

	@Override
	public String toString() {
		String replica = "";
		if (replicaStorage != null)
			replica = ", replica={" + replicaStorage + "}";

		String m = "";
		if (metadata != null && !metadata.isEmpty())
			m = ", metadata=" + metadata;

		return "name=" + name + ", primary={" + primaryStorage + "}" + replica + m;
	}
}


text:
package de.craften.craftenlauncher.exception;

public class CraftenDownloadException extends CraftenLogicException {
    public CraftenDownloadException(String message) {
        super(message);
    }

    public CraftenDownloadException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
$(function(){
  mapApp.init();
  mapApp.addMarkers('startups');
  mapApp.addMarkers('workspaces');
  $('.add-place-to-form').on('click', mapApp.captureLatLng);
  $('#form-new-startup').on('submit', mapApp.postStartup);
});

var mapApp = mapApp || {};

mapApp.captureLatLng = function(){
  event.preventDefault();

  var $form = $(this).parent();
  var type  = $form.attr("id").replace("form-new-", "");
  console.log(type)

  for (i in mapApp.place) {
    $form.find("#" + i + "-" + type).val(mapApp.place[i]);
    if (i === "geometry") {
      $form.find("#latitude-" + type).val(mapApp.place[i].location.lat());
      $form.find("#longitude-" + type).val(mapApp.place[i].location.lng());
    }
  }
  // $form.find("#headquarters-startup").val(mapApp.place[formatted_address]);
  // $form.find("#address-workspace").val(mapApp.place[formatted_address]);
}

mapApp.addMarkers = function(markerType){
  ajaxRequest("get", "/api/" + markerType, null, function(data){
    $.each(data[markerType], function(index, marker){
      mapApp.addMarkerWithTimeout(marker, markerType, index * 200);

      var twitterHTML = '';
      if(marker.twitter) {
        twitterHTML = 'Twitter';
      }
      var dataHTML   = '';
      var singleHTML = '';
      var itemsForShow = ['twitter', 'facebook', 'website'];

      $.each(marker, function(key, value) {
        if (itemsForShow.indexOf(key) > -1){
          if (value){
            singleHTML =
            '
' +
              ''
            '
'
            dataHTML = dataHTML + singleHTML;
          }
        }
      });

      var address   = marker.address ? marker.address : marker.headquarters;
      var telephone = marker.telephone ? marker.telephone : marker.phone;

      var markerHTML =
      '
' +
        '
' +
          '
' +
            '
' + marker.name + '
' +
            '
'+ address + '
' +
            '
'+ telephone + '
' +
            '
'+
            dataHTML +
            '
' +
          '
' +
          '
' +
            '' + marker.name + '\'s Twitter feed' +
            '
Here are tweets from ' + marker.name + ' account!
' +
          '
' +
        '
' +
      '
';

      $("#results").append(markerHTML);
    })
  });
}

mapApp.removeAllMarkers = function(){

}

mapApp.postPlace = function(){
  event.preventDefault();

  var data   = $(this).serialize();
  var method = $(this).attr("method");
  var url    = '/api' + $(this).attr("action");

  ajaxRequest(method, url, data, function(){
    console.log("Added place init")
  });
}

mapApp.init = function(){

  var mapStyle = [
  {
    "featureType": "administrative",
    "elementType": "labels.text.fill",
    "stylers": [
    {
      "color": "#444444"
    }
    ]
  },
  {
    "featureType": "administrative",
    "elementType": "labels.icon",
    "stylers": [
    {
      "saturation": "15"
    },
    {
      "visibility": "off"
    }
    ]
  },
  {
    "featureType": "administrative.locality",
    "elementType": "geometry",
    "stylers": [
    {
      "visibility": "off"
    }
    ]
  },
  {
    "featureType": "administrative.locality",
    "elementType": "labels.icon",
    "stylers": [
    {
      "visibility": "off"
    }
    ]
  },
  {
    "featureType": "landscape",
    "elementType": "all",
    "stylers": [
    {
      "color": "#f6f6f6"
    }
    ]
  },
  {
    "featureType": "poi",
    "elementType": "all",
    "stylers": [
    {
      "visibility": "off"
    }
    ]
  },
  {
    "featureType": "road",
    "elementType": "all",
    "stylers": [
    {
      "saturation": -100
    },
    {
      "lightness": 45
    }
    ]
  },
  {
    "featureType": "road.highway",
    "elementType": "all",
    "stylers": [
    {
      "visibility": "simplified"
    }
    ]
  },
  {
    "featureType": "road.arterial",
    "elementType": "labels.icon",
    "stylers": [
    {
      "visibility": "off"
    }
    ]
  },
  {
    "featureType": "transit",
    "elementType": "all",
    "stylers": [
    {
      "visibility": "off"
    }
    ]
  },
  {
    "featureType": "water",
    "elementType": "all",
    "stylers": [
    {
      "color": "#00bc66"
    },
    {
      "visibility": "on"
    }
    ]
  }
  ];

  mapApp.canvas = document.getElementById('googleMap');
  mapApp.center = new google.maps.LatLng(51.507904, -0.127466)
  mapApp.mapOptions = {
    zoom:        13,
    styles:      mapStyle,
    scrollwheel: false,
    center:      mapApp.center,
    mapTypeId:   google.maps.MapTypeId.ROADMAP
  };

  this.map = new google.maps.Map(mapApp.canvas, mapApp.mapOptions);

  mapApp.markers = [];

  // Icons for markers
  mapApp.icons = {
    workspaces: 'http://i.imgur.com/1VZp3yo.png',
    startups:   'http://i.imgur.com/IAWepkj.png',
    mains:      'http://i.imgur.com/beye5l3.png'
  }

  mapApp.setupAutocompleteFields();

  google.maps.event.addDomListener(window, 'resize', function(){
    mapApp.map.setCenter(mapApp.center);
  });

  // All search boxes have the class .search-box
  // When you click or focus back into the box, empty it
  $('.search-box').on('click', function(){
    $(this).val('');
  })
  $('.search-box').on('focus', function(){
    $(this).val('');
  })

}

mapApp.setupAutocompleteFields = function(){
  var fields = ["startup-search-box", "workspace-search-box", "main-search-box"];

  $.each(fields, function(index, field) {
    var autocomplete = new google.maps.places.Autocomplete(document.getElementById(field));

    google.maps.event.addListener(autocomplete, 'place_changed', function(){

      mapApp.place = autocomplete.getPlace();
      console.log(mapApp.place);
      var icon = mapApp.icons[field.split("-")[0]+"s"];

      if(icon === 'mains'){
        mapApp.map.setCenter(mapApp.place.geometry.location);
        return;
      }

      var marker = new google.maps.Marker({
        map:       mapApp.map,
        icon:      icon,
        animation: google.maps.Animation.DROP,
        title:     mapApp.place.name,
        position:  mapApp.place.geometry.location
      });

      var contentHTML =
      '
' +
        '
'+ marker.title +'
' +
        '
For more information, click here
' +
      '
';

      var infoWindow = new google.maps.InfoWindow({
        content: contentHTML
      });
      marker.addListener('click', function(){
        infoWindow.open(mapApp.map, marker);
      });

      // Recenter the map onto the newStartup position
      mapApp.map.setCenter(mapApp.place.geometry.location);
    });
  })
}

mapApp.clearMarkers = function() {
  for (var i = 0; i < mapApp.markers.length; i++) {
    mapApp.markers[i].setMap(null);
  }
  mapApp.markers = [];
}

mapApp.addInfoWindowToMarker = function(marker, markerType, id){
  var contentHTML =
  '
' +
    '
'+ marker.title +'
' +
    '
CLICK HERE FOR MORE INFORMATION
'+
  '
';

  var infoWindow = new google.maps.InfoWindow({
    content: contentHTML
  });
  marker.addListener('click', function(){
    infoWindow.open(mapApp.map, marker);
  });
  return marker;
}

mapApp.addMarkerWithTimeout = function(marker, markerType, timeout) {
  window.setTimeout(function() {
    var position = new google.maps.LatLng(marker.latitude, marker.longitude);
    var gmMarker = new google.maps.Marker({
      map:       mapApp.map,
      icon:      mapApp.icons[markerType],
      animation: google.maps.Animation.DROP,
      title:     marker.name,
      position:  position
    });
    mapApp.markers.push(mapApp.addInfoWindowToMarker(gmMarker, markerType, marker._id), timeout);
  });
}


text:
package com.gzlk.android.isp.model.common;

import android.os.Parcel;
import android.os.Parcelable;

import com.amap.api.location.AMapLocation;
import com.gzlk.android.isp.R;
import com.gzlk.android.isp.etc.Utils;
import com.gzlk.android.isp.helper.StringHelper;
import com.gzlk.android.isp.model.BaseModel;

import java.util.Locale;

/**
 * 功能描述:地图定位内容

 * 创建作者:Hsiang Leekwok

 * 创建时间:2017/04/23 18:21

 * 作者邮箱:xiang.l.g@gmail.com

 * 最新版本:Version: 1.0.0

 * 修改时间:2017/04/23 18:21

 * 修改人员:

 * 修改备注:

 */

public class HLKLocation extends BaseModel implements Parcelable {

    private String time;
    private String address;
    private String country;
    private String countryCode;
    private String province;
    private String city;
    private String cityCode;
    private String district;
    private String street;
    private String streetNumber;
    private String describe;
    private double latitude;
    private double longitude;
    private double altitude;
    private float radius;
    private float direction;

    protected HLKLocation(Parcel in) {
        time = in.readString();
        address = in.readString();
        country = in.readString();
        countryCode = in.readString();
        province = in.readString();
        city = in.readString();
        cityCode = in.readString();
        district = in.readString();
        street = in.readString();
        streetNumber = in.readString();
        describe = in.readString();
        latitude = in.readDouble();
        longitude = in.readDouble();
        altitude = in.readDouble();
        radius = in.readFloat();
        direction = in.readFloat();
    }

    public static final Creator<HLKLocation> CREATOR = new Creator<HLKLocation>() {
        @Override
        public HLKLocation createFromParcel(Parcel in) {
            return new HLKLocation(in);
        }

        @Override
        public HLKLocation[] newArray(int size) {
            return new HLKLocation[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(time);
        dest.writeString(address);
        dest.writeString(country);
        dest.writeString(countryCode);
        dest.writeString(province);
        dest.writeString(city);
        dest.writeString(cityCode);
        dest.writeString(district);
        dest.writeString(street);
        dest.writeString(streetNumber);
        dest.writeDouble(latitude);
        dest.writeDouble(longitude);
        dest.writeDouble(altitude);
        dest.writeFloat(radius);
        dest.writeDouble(direction);
    }

    public HLKLocation() {
    }

    public HLKLocation(AMapLocation location) {
        latitude = 0.0;
        longitude = 0.0;
        altitude = 0.0;
        if (null == location) return;
        time = Utils.format(StringHelper.getString(R.string.ui_base_text_date_time_format), location.getTime());
        if (!Double.isNaN(location.getLatitude())) {
            latitude = location.getLatitude();
        }
        if (!Double.isNaN(location.getLongitude())) {
            longitude = location.getLongitude();
        }
        if (!Double.isNaN(location.getAltitude())) {
            altitude = location.getAltitude();
        }
        country = location.getCountry();
        province = location.getProvince();
        city = location.getCity();
        cityCode = location.getCityCode();
        district = location.getDistrict();
        street = location.getStreet();
        streetNumber = location.getStreetNum();
        address = location.getAddress();
        describe = location.getDescription();
    }

    @Override
    public String toString() {
        return String.format(Locale.getDefault(), "%s %s %s %s %s %s %s\n%s",
                country, province, city, district, street,
                streetNumber, describe, address);
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCountryCode() {
        return countryCode;
    }

    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    public String getDistrict() {
        return district;
    }

    public void setDistrict(String district) {
        this.district = district;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getStreetNumber() {
        return streetNumber;
    }

    public void setStreetNumber(String streetNumber) {
        this.streetNumber = streetNumber;
    }

    public void setDescribe(String describe) {
        this.describe = describe;
    }

    public String getDescribe() {
        return this.describe;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public double getAltitude() {
        return altitude;
    }

    public void setAltitude(double altitude) {
        this.altitude = altitude;
    }

    public float getRadius() {
        return radius;
    }

    public void setRadius(float radius) {
        this.radius = radius;
    }

    public float getDirection() {
        return direction;
    }

    public void setDirection(float direction) {
        this.direction = direction;
    }

}


text:
/**
 *
 */
/**
 * @author Administrator
 *
 */
package com.charmyin.cmstudio.basic.authorize.service;


text:
"use strict";

import 'seedrandom';
import paper from 'paper';
import Generator from './Generator';
let createBranch = Symbol();

export default class Tree extends Generator {

    constructor(options) {
        var path = getShape(options);

        super(path, new paper.Point(0, options.default.length/2));

        this.options = options;
        this.random = new Math.seedrandom();
        this.maxLength = 0;
    }

    create(props={point: new paper.Point(), angle: 0, scale: 1}) {
        return this[createBranch](props, 0).then((group) => {
            this.group = group;
        });
    }

    prerender() {
        var maxDuration = (this.maxLength / (1 / 0.35));
        var normalizedDuration = maxDuration / this.maxLength;
        paper.project.layers[0].visible = false;
        var list = [];
        for(var i = 0; i <= maxDuration; i+=(1/30)) {
            renderBranch(i, normalizedDuration, this.group);
            var item = this.group.rasterize();
            list.push(item);
            item.remove();
        }

        setTimeout(function() {
            paper.project.layers[0].visible = true;
            global.animationFrame.add(function(step) {
                paper.project.layers[0].removeChildren();
                paper.project.layers[0].addChild(list[Math.round((list.length-1) * (step))]);
            }, Math.round(maxDuration * 1000) / 2);
        }, 1);
    }

    [createBranch](props, scaleBefore) {
        scaleBefore += props.scale;
        this.maxLength = Math.max(this.maxLength, scaleBefore);

        return new Promise((resolve) => {
            let group = new paper.Group([super.next(props)]);
            group.remove();
            group.firstChild.absoluteLength = scaleBefore;
            group.firstChild.relativeLength = props.scale;

            if(props.scale > 0.10) {
                resolve(Promise.all([
                    this[createBranch](prepare(props, this.options, this.random), scaleBefore),
                    this[createBranch](prepare(props, this.options, this.random), scaleBefore)
                ]).then(function(result) {
                    group.addChildren(result);
                    return group;
                }));
            }
            resolve(group);
        });
    }
}

function renderBranch(time, normDuration, group) {
    var symbol = group.firstChild;
    var maxTime = normDuration * symbol.absoluteLength;
    var minTime = normDuration * (symbol.absoluteLength - symbol.relativeLength);
    var step = (time - minTime) / (maxTime - minTime);
    step = Math.min(Math.max(step, 0), 1);

    var scale = (step * (symbol.relativeLength / symbol.currentScale)) || 0.0001;
    symbol.currentScale /= 1 / scale;
    symbol.scale(scale);
    symbol.pivot = symbol.currentOrigin;
    symbol.position = symbol.currentPosition;

    if(time > maxTime) {
        while((symbol = symbol.nextSibling) !== null) {
            renderBranch(time, normDuration, symbol);
        }
    }
}

function prepare(props, options, random) {
    return {
        point: props.point.subtract(new paper.Point(0,options.default.length).rotate(props.angle).multiply(props.scale)),
        angle: props.angle + (random() * (-options.default.angle.min + options.default.angle.max) + options.default.angle.min),
        scale: props.scale - (random() * (props.scale / 2))
    };
}

function getShape(options) {
    return new paper.Path(Object.assign({
        segments: [
            new paper.Point(),
            new paper.Point(0,options.default.length),
        ],
        strokeWidth: options.default.width
    }, options.style));
}


text:
Developed by
Zulfinjuliant - Sysfotech's Crew


text:
package org.switchyard.component.common.knowledge.persistence;

import java.util.Collections;
import java.util.Map;

import javax.persistence.Cache;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnitUtil;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.metamodel.Metamodel;

/** NoopEntityManagerFactory.
 *
 * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. */
public class NoopEntityManagerFactory implements EntityManagerFactory {

    private boolean _open = true;

    @Override
    public EntityManager createEntityManager() {
        return null;
    }

    @Override
    @SuppressWarnings("rawtypes")
    public EntityManager createEntityManager(Map map) {
        return null;
    }

    @Override
    public CriteriaBuilder getCriteriaBuilder() {
        return null;
    }

    @Override
    public Metamodel getMetamodel() {
        return null;
    }

    @Override
    public boolean isOpen() {
        return _open;
    }

    @Override
    public void close() {
        _open = false;
    }

    @Override
    public Map<String, Object> getProperties() {
        return Collections.emptyMap();
    }

    @Override
    public Cache getCache() {
        return null;
    }

    @Override
    public PersistenceUnitUtil getPersistenceUnitUtil() {
        return null;
    }

}


text:
import json
import os
import shutil
import tempfile
from unittest import mock

from toscaparser.common import exception
from toscaparser.utils.gettextutils import _
import translator.shell as shell
from translator.tests.base import TestCase

class ShellTest(TestCase):
    tosca_helloworld = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        "data/tosca_helloworld.yaml")
    template_file = '--template-file=' + tosca_helloworld
    template_type = '--template-type=tosca'
    template_validation = "--validate-only"
    failure_msg = _('The program raised an exception unexpectedly.')

    def test_invalid_file_value(self):
        error = self.assertRaises(ValueError,
                                  shell.main, ('--template-file=template.txt',
                                               self.template_type))
        err_msg = _('The path template.txt is not a valid file or URL.')
        self.assertEqual(err_msg, str(error))

    def test_invalid_type_value(self):
        self.assertRaises(SystemExit, shell.main,
                          (self.template_file, '--template-type=xyz'))

    def test_invalid_parameters(self):
        self.assertRaises(ValueError, shell.main,
                          (self.template_file, self.template_type,
                           '--parameters=key'))

    def test_valid_template(self):
        shell.main([self.template_file, self.template_type])

    def test_valid_template_without_type(self):
        try:
            shell.main([self.template_file])
        except Exception:
            self.fail(self.failure_msg)

    def test_valid_template_with_parameters(self):
        tosca_single_instance_wordpress = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "data/tosca_single_instance_wordpress.yaml")
        parameters = '--parameters="cpus=2;db_name=wpdb;db_user=test;'\
                     'db_port=2000;db_root_pwd=fun2test;db_pwd=fun2test"'
        template = '--template-file=' + tosca_single_instance_wordpress
        try:
            shell.main([template, self.template_type, parameters])
        except Exception:
            self.fail(self.failure_msg)

    def test_validate_only(self):
        try:
            shell.main([self.template_file, self.template_type,
                        self.template_validation])
        except Exception:
            self.fail(self.failure_msg)

        template = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "data/tosca_helloworld_invalid.yaml")
        invalid_template = '--template-file=' + template
        self.assertRaises(exception.ValidationError, shell.main,
                          [invalid_template, self.template_type,
                           self.template_validation])

    def test_output_file(self):
        temp_dir = tempfile.mkdtemp()
        temp_file = "/test_translation_output.txt"
        output_file = "--output-file=" + temp_dir + temp_file
        try:
            shell.main([self.template_file, self.template_type, output_file])
        except Exception:
            self.fail(self.failure_msg)
        finally:
            if temp_dir:
                shutil.rmtree(temp_dir)
                self.assertTrue(temp_dir is None or
                                not os.path.exists(temp_dir))

    @mock.patch('uuid.uuid4')
    @mock.patch.object(shell.TranslatorShell, '_create_stack')
    @mock.patch('keystoneauth1.loading.load_auth_from_argparse_arguments')
    @mock.patch('keystoneauth1.loading.load_session_from_argparse_arguments')
    @mock.patch('translator.common.flavors.get_flavors')
    @mock.patch('translator.common.images.get_images')
    def test_template_deploy(self, mock_populate_image_dict,
                             mock_flavor_dict,
                             mock_keystone_session,
                             mock_keystone_auth,
                             mock_client,
                             mock_uuid):
        mock_uuid.return_value = 'abcXXX-abcXXX'
        mock_flavor_dict.return_value = {
            'm1.medium': {'mem_size': 4096, 'disk_size': 40, 'num_cpus': 2}
        }
        mock_populate_image_dict.return_value = {
            "rhel-6.5-test-image": {
                "version": "6.5",
                "architecture": "x86_64",
                "distribution": "RHEL",
                "type": "Linux"
            }
        }

        try:
            data = {
                'outputs': {},
                'heat_template_version': '2013-05-23',
                'description': 'Template for deploying a single server '
                               'with predefined properties.\n',
                'parameters': {},
                'resources': {
                    'my_server': {
                        'type': 'OS::Nova::Server',
                        'properties': {
                            'flavor': 'm1.medium',
                            'user_data_format': 'SOFTWARE_CONFIG',
                            'image': 'rhel-6.5-test-image'
                        }
                    }
                }
            }

            mock_heat_res = {
                "stacks": [
                    {
                        "id": "d648ad27-fb9c-44d1-b293-646ea6c4f8da",
                        "stack_status": "CREATE_IN_PROGRESS",
                    }
                ]
            }

            class mock_response(object):
                def __init__(self, status_code, _content):
                    self.status_code = status_code
                    self._content = _content

            mock_response_obj = mock_response(201, json.dumps(mock_heat_res))
            mock_client.return_value = mock_response_obj
            shell.main([self.template_file, self.template_type, "--deploy"])
            args, kwargs = mock_client.call_args
            self.assertEqual(kwargs["stack_name"],
                             'heat_tosca_helloworld_abcXXX')
            self.assertEqual(kwargs["template"], data)
        except Exception as e:
            self.fail(e)


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

namespace Coffee.UIEffects
{
    /// <summary>
    /// Abstract effect base for UI.
    /// </summary>
    [DisallowMultipleComponent]
    public abstract class BaseMaterialEffect : BaseMeshEffect, IParameterTexture, IMaterialModifier
    {
        protected static readonly Hash128 k_InvalidHash = new Hash128();
        protected static readonly List<UIVertex> s_TempVerts = new List<UIVertex>();
        private static readonly StringBuilder s_StringBuilder = new StringBuilder();

        Hash128 _effectMaterialHash;

        /// <summary>
        /// Gets or sets the parameter index.
        /// </summary>
        public int parameterIndex { get; set; }

        /// <summary>
        /// Gets the parameter texture.
        /// </summary>
        public virtual ParameterTexture paramTex
        {
            get { return null; }
        }

        /// <summary>
        /// Mark the vertices as dirty.
        /// </summary>
        public void SetMaterialDirty()
        {
            connector.SetMaterialDirty(graphic);

            foreach (var effect in syncEffects)
            {
                effect.SetMaterialDirty();
            }
        }

        public virtual Hash128 GetMaterialHash(Material baseMaterial)
        {
            return k_InvalidHash;
        }

        public Material GetModifiedMaterial(Material baseMaterial)
        {
            return GetModifiedMaterial(baseMaterial, graphic);
        }

        public virtual Material GetModifiedMaterial(Material baseMaterial, Graphic graphic)
        {
            if (!isActiveAndEnabled) return baseMaterial;

            var oldHash = _effectMaterialHash;
            _effectMaterialHash = GetMaterialHash(baseMaterial);
            var modifiedMaterial = baseMaterial;
            if (_effectMaterialHash.isValid)
            {
                modifiedMaterial = MaterialCache.Register(baseMaterial, _effectMaterialHash, ModifyMaterial, graphic);
            }

            MaterialCache.Unregister(oldHash);

            return modifiedMaterial;
        }

        // protected bool isTMProMobile (Material material)
        // {
        // 	return material && material.shader && material.shader.name.StartsWith ("TextMeshPro/Mobile/", StringComparison.Ordinal);
        // }

        public virtual void ModifyMaterial(Material newMaterial, Graphic graphic)
        {
            if (isActiveAndEnabled && paramTex != null)
                paramTex.RegisterMaterial(newMaterial);
        }

        protected void SetShaderVariants(Material newMaterial, params object[] variants)
        {
            // Set shader keywords as variants
            var keywords = variants.Where(x => 0 < (int) x)
                .Select(x => x.ToString().ToUpper())
                .Concat(newMaterial.shaderKeywords)
                .Distinct()
                .ToArray();
            newMaterial.shaderKeywords = keywords;

            // Add variant name
            s_StringBuilder.Length = 0;
            s_StringBuilder.Append(Path.GetFileName(newMaterial.shader.name));
            foreach (var keyword in keywords)
            {
                s_StringBuilder.Append("-");
                s_StringBuilder.Append(keyword);
            }

            newMaterial.name = s_StringBuilder.ToString();
        }

#if UNITY_EDITOR
        protected override void Reset()
        {
            if (!isActiveAndEnabled) return;
            SetMaterialDirty();
            SetVerticesDirty();
            SetEffectParamsDirty();
        }

        protected override void OnValidate()
        {
            if (!isActiveAndEnabled) return;
            SetVerticesDirty();
            SetEffectParamsDirty();
        }
#endif

        /// <summary>
        /// This function is called when the object becomes enabled and active.
        /// </summary>
        protected override void OnEnable()
        {
            if (paramTex != null)
            {
                paramTex.Register(this);
            }

            SetVerticesDirty();
            SetMaterialDirty();
            SetEffectParamsDirty();

            // foreach (var mr in GetComponentsInChildren<UIEffectMaterialResolver> ())
            // {
            // 	mr.GetComponent<Graphic> ().SetMaterialDirty ();
            // 	mr.GetComponent<Graphic> ().SetVerticesDirty ();
            // }
        }

        /// <summary>
        /// This function is called when the behaviour becomes disabled () or inactive.
        /// </summary>
        protected override void OnDisable()
        {
            SetVerticesDirty();
            SetMaterialDirty();

            if (paramTex != null)
            {
                paramTex.Unregister(this);
            }

            MaterialCache.Unregister(_effectMaterialHash);
            _effectMaterialHash = k_InvalidHash;
        }

        // protected override void OnDidApplyAnimationProperties()
        // {
        //     SetEffectParamsDirty();
        // }

        // protected override void OnTextChanged (UnityEngine.Object obj)
        // {
        // 	base.OnTextChanged (obj);
        //
        //
        // 	foreach (var sm in GetComponentsInChildren<TMPro.TMP_SubMeshUI> ())
        // 	{
        // 		if(!sm.GetComponent<UIEffectMaterialResolver>())
        // 		{
        // 			var mr = sm.gameObject.AddComponent<UIEffectMaterialResolver> ();
        //
        // 			targetGraphic.SetAllDirty ();
        // 			//targetGraphic.SetVerticesDirty ();
        //
        // 			//mr.GetComponent<Graphic> ().SetMaterialDirty ();
        // 			//mr.GetComponent<Graphic> ().SetVerticesDirty ();
        //
        //
        // 		}
        // 	}
        // }
    }
}


text:
package org.ansj.util;

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

import org.ansj.domain.Nature;
import org.ansj.domain.Term;
import org.ansj.domain.TermNatures;
import org.ansj.library.NatureLibrary;
import org.ansj.library.company.CompanyAttrLibrary;
import org.ansj.recognition.ForeignPersonRecognition;

/**
 * term的操作类
 *
 * @author ansj
 *
 */
public class TermUtil {

	/**
	 * 将两个term合并为一个全新的term
	 *
	 * @param termNatures
	 * @return
	 */
	public static Term makeNewTermNum(Term from, Term to, TermNatures termNatures) {
		Term term = new Term(from.getName() + to.getName(), from.getOffe(), termNatures);
		term.termNatures().numAttr = from.termNatures().numAttr;
		TermUtil.termLink(term, to.to());
		TermUtil.termLink(term.from(), term);
		return term;
	}

	public static void termLink(Term from, Term to) {
		if (from == null || to == null)
			return;
		from.setTo(to);
		to.setFrom(from);
	}

	/**
	 * 将一个term插入到链表中的对应位置中,应该是词长由大到小
	 *
	 * @param terms
	 * @param term
	 */
	public static void insertTerm(Term[] terms, Term term) {
		Term temp = terms[term.getOffe()];
		//插入到最右面
		Term last = temp ;
		while((temp = temp.next())!=null){
			last = temp ;
		}
		last.setNext(term) ;
	}

	public static void insertTermNum(Term[] terms, Term term) {
		// TODO Auto-generated method stub
		terms[term.getOffe()] = term;

	}

	public static void insertTerm(Term[] terms, List<Term> tempList, TermNatures nr) {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		int offe = tempList.get(0).getOffe();
		for (Term term : tempList) {
			sb.append(term.getName());
			terms[term.getOffe()] = null;
		}
		Term term = new Term(sb.toString(), offe, TermNatures.NR);
		insertTermNum(terms, term);
	}

	protected static Term setToAndfrom(Term to, Term from) {
		// TODO Auto-generated method stub
		from.setTo(to);
		to.setFrom(from);
		return from;
	}

	private static final HashMap<String, int[]> companyMap = CompanyAttrLibrary.getCompanyMap();

	/**
	 * 得到细颗粒度的分词,并且确定词性
	 *
	 * @return 返回是null说明已经是最细颗粒度
	 */
	public static void parseNature(Term term) {
		if (!Nature.NW.equals(term.natrue())) {
			return;
		}

		String name = term.getName();

		if (name.length() <= 3) {
			return;
		}

		// 是否是外国人名
		if (ForeignPersonRecognition.isFName(name)) {
			term.setNature(NatureLibrary.getNature("nrf"));
			return;
		}

		List<Term> subTerm = term.getSubTerm();

		// 判断是否是机构名
		term.setSubTerm(subTerm);
		Term first = subTerm.get(0);
		Term last = subTerm.get(subTerm.size() - 1);
		int[] is = companyMap.get(first.getName());
		int all = 0;

		is = companyMap.get(last.getName());
		if (is != null) {
			all += is[1];
		}

		if (all > 1000) {
			term.setNature(NatureLibrary.getNature("nt"));
			return;
		}
	}

	/**
	 * 从from到to生成subterm
	 *
	 * @param terms
	 * @param from
	 * @param to
	 * @return
	 */
	public static List<Term> getSubTerm(Term from, Term to) {
		// TODO Auto-generated method stub
		List<Term> subTerm = new ArrayList<Term>(3);

		while ((from = from.to()) != to) {
			subTerm.add(from);
		}

		return subTerm;
	}

}


text:
var assert                  = require('assert');
var _                       = require('lodash');
var Backbone                = require('backbone');
var proxyquire              = require('proxyquire');
var stopListeningForChanges = require('../lib/stopListeningForChanges');

describe('stopListeningForChanges', function () {

  it('should stop listen for `change` and `sync` on models', function () {

    var user = new Backbone.Model({ name: 'Chris' });

    var component = {
      models: {
        user: user
      }
    };

    var modelKey;
    var listenForChanges = proxyquire('../lib/listenForChanges', {
      './handleModelUpdate': function (key) {
        modelKey = key;
      }
    });

    listenForChanges.call(component);

    user.trigger('change');
    assert.strictEqual(modelKey, 'user');

    modelKey = undefined;
    stopListeningForChanges.call(component);
    user.trigger('change');
    assert(_.isUndefined(modelKey));

    user.trigger('sync');
    assert(_.isUndefined(modelKey));

  });

  it('should stop listening for `change`, `add`, `remove`, and `sync` on collections', function () {

    var users = new Backbone.Collection([{ name: 'Chris' }, { name: 'Steph' }]);

    var component = {
      collections: {
        users: users
      }
    };

    var collectionKey;
    var listenForChanges = proxyquire('../lib/listenForChanges', {
      './handleCollectionUpdate': function (key) {
        collectionKey = key;
      }
    });

    listenForChanges.call(component);

    users.trigger('change');
    assert.strictEqual(collectionKey, 'users');

    collectionKey = undefined;
    users.trigger('sync');
    assert.strictEqual(collectionKey, 'users');

    collectionKey = undefined;
    users.trigger('add');
    assert.strictEqual(collectionKey, 'users');

    collectionKey = undefined;
    users.trigger('remove');
    assert.strictEqual(collectionKey, 'users');

    stopListeningForChanges.call(component);

    collectionKey = undefined;
    users.trigger('change');
    assert(_.isUndefined(collectionKey));

    collectionKey = undefined;
    users.trigger('sync');
    assert(_.isUndefined(collectionKey));

    collectionKey = undefined;
    users.trigger('add');
    assert(_.isUndefined(collectionKey));

    collectionKey = undefined;
    users.trigger('remove');
    assert(_.isUndefined(collectionKey));

  });

});