Combine two shapes

@param target The target shape
@param missing The second shape to apply
@param subtract True if we should subtract missing from target, otherwise union
@param start The point to start at
@return The newly created shape
336312
private Shape combineSingle(Shape target, Shape missing, boolean subtract, int start) {
		Shape current = target;
		Shape other = missing;
		int point = start;
		int dir = 1;
		
		Polygon poly = new Polygon();
		boolean first = true;
		
		int loop = 0;
		
		// while we've not reached the same point
		float px = current.getPoint(point)[0];
		float py = current.getPoint(point)[1];
		
		while (!poly.hasVertex(px, py) || (first) || (current != target)) {
			first = false;
			loop++;
			if (loop > MAX_POINTS) {
				break;
			}
			
			// add the current point to the result shape
			poly.addPoint(px,py);
			if (listener != null) {
				listener.pointUsed(px,py);
			}

			// if the line between the current point and the next one intersect the
			// other shape work out where on the other shape and start traversing it's 
			// path instead
			Line line = getLine(current, px, py, rationalPoint(current, point+dir));
			HitResult hit = intersect(other, line);
			
			if (hit != null) {
				Line hitLine = hit.line;
				Vector2f pt = hit.pt;
				px = pt.x;
				py = pt.y;
				
				if (listener != null) {
					listener.pointIntersected(px,py);
				}
				
				if (other.hasVertex(px, py)) {
					point = other.indexOf(pt.x,pt.y);
					dir = 1;
					px = pt.x;
					py = pt.y;
					
					Shape temp = current;
					current = other;
					other = temp;
					continue;
				}
				
				float dx = hitLine.getDX() / hitLine.length();
				float dy = hitLine.getDY() / hitLine.length();
				dx *= EDGE_SCALE;
				dy *= EDGE_SCALE;
				
				if (current.contains(pt.x + dx, pt.y + dy)) {
					// the point is the next one, we need to take the first and traverse
					// the path backwards
					if (subtract) {
						if (current == missing) {
							point = hit.p2;
							dir = -1;
						} else {
							point = hit.p1;
							dir = 1;
						}
					} else {
						if (current == target) {
							point = hit.p2;
							dir = -1;
						} else {
							point = hit.p2;
							dir = -1;
						}
					}
					
					// swap the shapes over, we'll traverse the other one 
					Shape temp = current;
					current = other;
					other = temp;
				} else if (current.contains(pt.x - dx, pt.y - dy)) {
					if (subtract) {
						if (current == target) {
							point = hit.p2;
							dir = -1;
						} else {
							point = hit.p1;
							dir = 1;
						}
					} else {
						if (current == missing) {
							point = hit.p1;
							dir = 1;
						} else {
							point = hit.p1;
							dir = 1;
						}
					}
					
					// swap the shapes over, we'll traverse the other one 
					Shape temp = current;
					current = other;
					other = temp;
				} else {
					// give up
					if (subtract) {
						break;
					} else {
						point = hit.p1;
						dir = 1;
						Shape temp = current;
						current = other;
						other = temp;
						
						point = rationalPoint(current, point+dir);
						px = current.getPoint(point)[0];
						py = current.getPoint(point)[1];
					}
				}
			} else {
				// otherwise just move to the next point in the current shape
				point = rationalPoint(current, point+dir);
				px = current.getPoint(point)[0];
				py = current.getPoint(point)[1];
			}
		}

		poly.addPoint(px,py);
		if (listener != null) {
			listener.pointUsed(px,py);
		}
		
		return poly;
	}
1039822
private Shape createVertex(GeometryEditService editService, GeometryIndex index)
			throws GeometryIndexNotFoundException {
		Geometry geometry = editService.getGeometry();
		Coordinate v = editService.getIndexService().getVertex(geometry, index);
		if (!targetSpace.equals(RenderSpace.WORLD)) {
			v = mapPresenter.getViewPort().getTransformationService().transform(v, RenderSpace.WORLD, targetSpace);
		}
		return new Rectangle(v.getX() - VERTEX_HALF_SIZE, v.getY() - VERTEX_HALF_SIZE, VERTEX_SIZE, VERTEX_SIZE);
	}
654452
public Shape[] union(Shape target, Shape other) {
		target = target.transform(new Transform());
		other = other.transform(new Transform());
		
		if (!target.intersects(other)) {
			return new Shape[] {target, other};
		}
		
		// handle the case where intersects is true but really we're talking
		// about edge points
		boolean touches = false;
		int buttCount = 0;
		for (int i=0;i<target.getPointCount();i++) {
			if (other.contains(target.getPoint(i)[0], target.getPoint(i)[1])) {
				if (!other.hasVertex(target.getPoint(i)[0], target.getPoint(i)[1])) {
					touches = true;
					break;
				}
			}
			if (other.hasVertex(target.getPoint(i)[0], target.getPoint(i)[1])) {
				buttCount++;
			} 
		}
		for (int i=0;i<other.getPointCount();i++) {
			if (target.contains(other.getPoint(i)[0], other.getPoint(i)[1])) {
				if (!target.hasVertex(other.getPoint(i)[0], other.getPoint(i)[1])) {
					touches = true;
					break;
				}
			}
		}
		
		if ((!touches) && (buttCount < 2)) {
			return new Shape[] {target, other};
		}
		
		// so they are definitely touching, consider the union
		return combine(target, other, false);
	}
1278709
@ExportInstanceMethod
	public static void setShape(PointSymbolizerShapeAndSize instance, String shape) {
		if ("circle".equals(shape)) {
			instance.setShape(PointSymbolizerShapeAndSize.Shape.CIRCLE);
		} else if ("square".equals(shape)) {
			instance.setShape(PointSymbolizerShapeAndSize.Shape.SQUARE);
		} else {
			//default value
			instance.setShape(PointSymbolizerShapeAndSize.Shape.SQUARE);
		}
	}
1075594
public void merge
			(Model target, Model... sources)
	{
		// Empty merged and added elements sets
		mergedElements.clear();
		addedElements.clear();

		// Fill equivalence map with objects from  target model
		Set<BioPAXElement> targetElements = target.getObjects();
		for (BioPAXElement t_bpe : targetElements)
		{
			this.addIntoEquivalanceMap(t_bpe);
		}

		// Try to insert every biopax element in every source one by one
		for (Model source : sources)
		{
			Set<BioPAXElement> sourceElements = source.getObjects();
			for (BioPAXElement bpe : sourceElements)
			{
				insert(target, bpe);
			}
		}
	}
958271
public DoublePoint Subtract(DoublePoint point1, DoublePoint point2) {
        DoublePoint result = new DoublePoint(point1);
        result.Subtract(point2);
        return result;
    }
157775
public static Pair<INDArray, INDArray> mergeFeatures(@NonNull INDArray[] featuresToMerge,
                    INDArray[] featureMasksToMerge) {
        Preconditions.checkNotNull(featuresToMerge[0], "Encountered null feature array when merging");
        int rankFeatures = featuresToMerge[0].rank();

        switch (rankFeatures) {
            case 2:
                return DataSetUtil.merge2d(featuresToMerge, featureMasksToMerge);
            case 3:
                return DataSetUtil.mergeTimeSeries(featuresToMerge, featureMasksToMerge);
            case 4:
                return DataSetUtil.merge4d(featuresToMerge, featureMasksToMerge);
            default:
                throw new IllegalStateException("Cannot merge examples: features rank must be in range 2 to 4"
                                + " inclusive. First example features shape: "
                                + Arrays.toString(featuresToMerge[0].shape()));
        }
    }
1339440
@Override
	public double execute(Geometry geom1, Geometry geom2,
			ProgressTracker progressTracker) {
		if (null == geom1 || null == geom2) {
			throw new IllegalArgumentException();
		}

		Geometry geometryA = geom1;
		Geometry geometryB = geom2;

		if (geometryA.isEmpty() || geometryB.isEmpty())
			return NumberUtils.TheNaN;		

		Polygon polygonA;
		Polygon polygonB;
		MultiPoint multiPointA;
		MultiPoint multiPointB;

		// if geometryA is an envelope use a polygon instead (if geom1 was
		// folded, then geometryA will already be a polygon)
		// if geometryA is a point use a multipoint instead
		Geometry.Type gtA = geometryA.getType();
		Geometry.Type gtB = geometryB.getType();
		if (gtA == Geometry.Type.Point) {
			if (gtB == Geometry.Type.Point) {
				return Point2D.distance(((Point)geometryA).getXY(), ((Point)geometryB).getXY());
			}
			else if (gtB == Geometry.Type.Envelope) {
				Envelope2D envB = new Envelope2D();
				geometryB.queryEnvelope2D(envB);
				return envB.distance(((Point)geometryA).getXY());
			}
			
			multiPointA = new MultiPoint();
			multiPointA.add((Point) geometryA);
			geometryA = multiPointA;
		} else if (gtA == Geometry.Type.Envelope) {
			if (gtB == Geometry.Type.Envelope) {
				Envelope2D envA = new Envelope2D();
				geometryA.queryEnvelope2D(envA);
				Envelope2D envB = new Envelope2D();
				geometryB.queryEnvelope2D(envB);
				return envB.distance(envA);
			}
			polygonA = new Polygon();
			polygonA.addEnvelope((Envelope) geometryA, false);
			geometryA = polygonA;
		}

		// if geom_2 is an envelope use a polygon instead
		// if geom_2 is a point use a multipoint instead
		if (gtB == Geometry.Type.Point) {
			multiPointB = new MultiPoint();
			multiPointB.add((Point) geometryB);
			geometryB = multiPointB;
		} else if (gtB == Geometry.Type.Envelope) {
			polygonB = new Polygon();
			polygonB.addEnvelope((Envelope) geometryB, false);
			geometryB = polygonB;
		}

		DistanceCalculator distanceCalculator = new DistanceCalculator(
				progressTracker);
		double distance = distanceCalculator.calculate(geometryA, geometryB);
		return distance;
	}
892182
@CheckReturnValue
  public ScannerSupplier plus(ScannerSupplier other) {
    HashBiMap<String, BugCheckerInfo> combinedAllChecks = HashBiMap.create(this.getAllChecks());
    other
        .getAllChecks()
        .forEach(
            (k, v) -> {
              BugCheckerInfo existing = combinedAllChecks.putIfAbsent(k, v);
              if (existing != null
                  && !existing.checkerClass().getName().contentEquals(v.checkerClass().getName())) {
                throw new IllegalArgumentException(
                    String.format(
                        "Cannot combine scanner suppliers with different implementations of"
                            + " '%s': %s, %s",
                        k, v.checkerClass().getName(), existing.checkerClass().getName()));
              }
            });
    HashMap<String, SeverityLevel> combinedSeverities = new LinkedHashMap<>(this.severities());
    other
        .severities()
        .forEach(
            (k, v) -> {
              SeverityLevel existing = combinedSeverities.putIfAbsent(k, v);
              if (existing != null && !existing.equals(v)) {
                throw new IllegalArgumentException(
                    String.format(
                        "Cannot combine scanner suppliers with different severities for"
                            + " '%s': %s, %s",
                        k, v, existing));
              }
            });
    ImmutableSet<String> disabled =
        Sets.difference(combinedAllChecks.keySet(), Sets.union(enabled(), other.enabled()))
            .immutableCopy();
    ErrorProneFlags combinedFlags = this.getFlags().plus(other.getFlags());
    return new ScannerSupplierImpl(
        ImmutableBiMap.copyOf(combinedAllChecks),
        ImmutableMap.copyOf(combinedSeverities),
        disabled,
        combinedFlags);
  }
1105152
public void merge(ClusteringFeature x) {
		assert (this.sumPoints.length == x.sumPoints.length);
		this.numPoints += x.numPoints;
		super.setWeight(this.numPoints);
		for (int i = 0; i < this.sumPoints.length; i++) {
			this.sumPoints[i] += x.sumPoints[i];
		}
		this.sumSquaredLength += x.sumSquaredLength;
	}
403852
public void updateRectangle(Point a, Point b, Symbol symbol) {
        int xfrom = (a.x < b.x) ? a.x : b.x;
        int xto = (a.x > b.x) ? a.x : b.x;
        int yfrom = (a.y < b.y) ? a.y : b.y;
        int yto = (a.y > b.y) ? a.y : b.y;
        for (int x = xfrom; x <= xto; x++) {
            for (int y = yfrom; y <= yto; y++) {
                updateLocation(new Point(x, y), symbol);
            }
        }
    }
390642
public final void setShape(@NonNull final PreviewShape shape) {
        Condition.INSTANCE.ensureNotNull(shape, "The shape may not be null");
        this.shape = shape;
    }
239065
@Deprecated
    public static <T> BiRecordGetter<T, RuntimeException> createBiRecordGetterByTargetClass(final Class<? extends T> targetClass) {
        if (Object[].class.isAssignableFrom(targetClass)) {
            return new BiRecordGetter<T, RuntimeException>() {
                @Override
                public T apply(ResultSet rs, List<String> columnLabelList) throws SQLException {
                    final int columnCount = columnLabelList.size();
                    final Object[] a = Array.newInstance(targetClass.getComponentType(), columnCount);

                    for (int i = 0; i < columnCount; i++) {
                        a[i] = JdbcUtil.getColumnValue(rs, i + 1);
                    }

                    return (T) a;
                }
            };
        } else if (List.class.isAssignableFrom(targetClass)) {
            return new BiRecordGetter<T, RuntimeException>() {

                private final boolean isListOrArrayList = targetClass.equals(List.class) || targetClass.equals(ArrayList.class);

                @Override
                public T apply(ResultSet rs, List<String> columnLabelList) throws SQLException {
                    final int columnCount = columnLabelList.size();
                    final List<Object> c = isListOrArrayList ? new ArrayList<Object>(columnCount) : (List<Object>) N.newInstance(targetClass);

                    for (int i = 0; i < columnCount; i++) {
                        c.add(JdbcUtil.getColumnValue(rs, i + 1));
                    }

                    return (T) c;
                }
            };
        } else if (Map.class.isAssignableFrom(targetClass)) {
            return new BiRecordGetter<T, RuntimeException>() {
                private final boolean isMapOrHashMap = targetClass.equals(Map.class) || targetClass.equals(HashMap.class);
                private final boolean isLinkedHashMap = targetClass.equals(LinkedHashMap.class);

                @Override
                public T apply(ResultSet rs, List<String> columnLabelList) throws SQLException {
                    final int columnCount = columnLabelList.size();
                    final Map<String, Object> m = isMapOrHashMap ? new HashMap<String, Object>(columnCount)
                            : (isLinkedHashMap ? new LinkedHashMap<String, Object>(columnCount) : (Map<String, Object>) N.newInstance(targetClass));

                    for (int i = 0; i < columnCount; i++) {
                        m.put(columnLabelList.get(i), JdbcUtil.getColumnValue(rs, i + 1));
                    }

                    return (T) m;
                }
            };
        } else if (N.isEntity(targetClass)) {
            return new BiRecordGetter<T, RuntimeException>() {
                private final boolean isDirtyMarker = N.isDirtyMarker(targetClass);
                private volatile String[] columnLabels = null;
                private volatile Method[] propSetters;
                private volatile Type<?>[] columnTypes = null;

                @Override
                public T apply(ResultSet rs, List<String> columnLabelList) throws SQLException {
                    final int columnCount = columnLabelList.size();

                    String[] columnLabels = this.columnLabels;
                    Method[] propSetters = this.propSetters;
                    Type<?>[] columnTypes = this.columnTypes;

                    if (columnLabels == null) {
                        columnLabels = columnLabelList.toArray(new String[columnLabelList.size()]);
                        this.columnLabels = columnLabels;
                    }

                    if (columnTypes == null || propSetters == null) {
                        final EntityInfo entityInfo = ParserUtil.getEntityInfo(targetClass);
                        final Map<String, String> column2FieldNameMap = getField2ColumnNameMap(targetClass);

                        propSetters = new Method[columnCount];
                        columnTypes = new Type[columnCount];

                        for (int i = 0; i < columnCount; i++) {
                            propSetters[i] = ClassUtil.getPropSetMethod(targetClass, columnLabels[i]);

                            if (propSetters[i] == null) {
                                String fieldName = column2FieldNameMap.get(columnLabels[i]);

                                if (N.isNullOrEmpty(fieldName)) {
                                    fieldName = column2FieldNameMap.get(columnLabels[i].toLowerCase());
                                }

                                if (N.notNullOrEmpty(fieldName)) {
                                    propSetters[i] = ClassUtil.getPropSetMethod(targetClass, fieldName);
                                }
                            }

                            if (propSetters[i] == null) {
                                columnLabels[i] = null;
                                throw new IllegalArgumentException(
                                        "No property in class: " + ClassUtil.getCanonicalClassName(targetClass) + " mapping to column: " + columnLabels[i]);
                            } else {
                                columnTypes[i] = entityInfo.getPropInfo(columnLabels[i]).type;
                            }
                        }

                        this.propSetters = propSetters;
                        this.columnTypes = columnTypes;
                    }

                    final Object entity = N.newInstance(targetClass);

                    for (int i = 0; i < columnCount; i++) {
                        if (columnLabels[i] == null) {
                            continue;
                        }

                        ClassUtil.setPropValue(entity, propSetters[i], columnTypes[i].get(rs, i + 1));
                    }

                    if (isDirtyMarker) {
                        ((DirtyMarker) entity).markDirty(false);
                    }

                    return (T) entity;
                }
            };
        } else {
            throw new IllegalArgumentException(targetClass.getCanonicalName() + " is not an Array/List/Map/Entity class");
        }
    }
694583
static Matcher combineAdjacentStart(Matcher matcher) {
    if (matcher instanceof SeqMatcher) {
      List<Matcher> matchers = matcher.<SeqMatcher>as().matchers();
      if (!matchers.isEmpty() && matchers.get(0) instanceof StartMatcher) {
        List<Matcher> ms = new ArrayList<>();
        ms.add(StartMatcher.INSTANCE);
        int pos = 0;
        for (Matcher m : matchers) {
          if (m instanceof StartMatcher) {
            ++pos;
          } else {
            break;
          }
        }
        ms.addAll(matchers.subList(pos, matchers.size()));
        return SeqMatcher.create(ms);
      }
    }
    return matcher;
  }
1001381
private void merge(final GeometryFunction callback) {
		GeometryOperationService operationService = new GeometryOperationServiceImpl();
		UnionInfo unionInfo = new UnionInfo();
		unionInfo.setUsePrecisionAsBuffer(true);
		unionInfo.setPrecision(precision);
		operationService.union(geometries, unionInfo, new Callback<Geometry, Throwable>() {

			public void onSuccess(Geometry result) {
				callback.execute(result);
			}

			public void onFailure(Throwable reason) {
				reason.printStackTrace();
			}
		});
	}
513698
public static Map<String, MergedVertex> getMergedVertexes(Shape shape)
	{
		Map<String, MergedVertex> mergedVertexes = new HashMap<>();

		for (Face f : shape.getFaces())
		{
			for (Vertex v : f.getVertexes())
			{
				MergedVertex mv = mergedVertexes.get(v.baseName());
				if (mv == null)
				{
					mv = new MergedVertex(v);
					mergedVertexes.put(v.baseName(), mv);
				}
				else
					mv.addVertex(v);
			}

		}

		return mergedVertexes;

	}
1019094
static Matcher combineCharSeqAfterStartsWith(Matcher matcher) {
    if (matcher instanceof SeqMatcher) {
      List<Matcher> matchers = matcher.<SeqMatcher>as().matchers();
      if (matchers.size() >= 2
          && matchers.get(0) instanceof StartsWithMatcher
          && matchers.get(1) instanceof CharSeqMatcher) {
        List<Matcher> ms = new ArrayList<>();
        String prefix = matchers.get(0).<StartsWithMatcher>as().pattern()
            + matchers.get(1).<CharSeqMatcher>as().pattern();
        ms.add(new StartsWithMatcher(prefix));
        ms.addAll(matchers.subList(2, matchers.size()));
        return SeqMatcher.create(ms);
      } else {
        return matcher;
      }
    }
    return matcher;
  }