Calculate the node and edge connected component tables.

@param connection  Connection
@param inputTable  Edges table produced by ST_Graph
@param orientation Orientation string
@return True if the calculation was successful
@throws SQLException
963709
public static boolean getConnectedComponents(Connection connection,
                                                 String inputTable,
                                                 String orientation) throws SQLException {
        KeyedGraph graph = prepareGraph(connection, inputTable, orientation, null,
                VUCent.class, Edge.class);
        if (graph == null) {
            return false;
        }
        final List<Set<VUCent>> componentsList = getConnectedComponents(graph, orientation);

        final TableLocation tableName = TableUtilities.parseInputTable(connection, inputTable);
        final TableLocation nodesName = TableUtilities.suffixTableLocation(tableName, NODE_COMP_SUFFIX);
        final TableLocation edgesName = TableUtilities.suffixTableLocation(tableName, EDGE_COMP_SUFFIX);

        if (storeNodeConnectedComponents(connection, nodesName, edgesName, componentsList)) {
            if (storeEdgeConnectedComponents(connection, tableName, nodesName, edgesName)) {
                return true;
            }
        }
        return false;
    }
456923
public static PreparedStatement createWayMemberTable(Connection connection, String wayMemberTable) throws SQLException {
        try (Statement stmt = connection.createStatement()) {
            StringBuilder sb = new StringBuilder("CREATE TABLE ");
            sb.append(wayMemberTable);
            sb.append("(ID_RELATION BIGINT, ID_WAY BIGINT, ROLE VARCHAR, WAY_ORDER INT);");
            stmt.execute(sb.toString());
        }
        return connection.prepareStatement("INSERT INTO " + wayMemberTable + " VALUES ( ?,?,?,?);");
    }
1240944
public void connect(Connection c) {

        schemaFilter = null;

        if (c == null) {
            return;
        }

        if (cConn != null) {
            try {
                cConn.close();
            } catch (SQLException e) {

                //  Added: (weconsultants@users)
                CommonSwing.errorMessage(e);
            }
        }

        cConn = c;

        // Added: (weconsultants@users) Need to barrow to get the table rowcounts
        rowConn = c;

        try {
            dMeta      = cConn.getMetaData();
            isOracle = (dMeta.getDatabaseProductName().indexOf("Oracle") >= 0);
            sStatement = cConn.createStatement();

            updateAutoCommitBox();

            // Workaround for EXTREME SLOWNESS getting this info from O.
            showIndexDetails = !isOracle;

            Driver driver = DriverManager.getDriver(dMeta.getURL());
            ConnectionSetting newSetting = new ConnectionSetting(
                dMeta.getDatabaseProductName(), driver.getClass().getName(),
                dMeta.getURL(),
                dMeta.getUserName().replaceAll("@localhost", ""), "");
            Hashtable settings =
                ConnectionDialogCommon.loadRecentConnectionSettings();

            ConnectionDialogCommon.addToRecentConnectionSettings(settings,
                    newSetting);
            ConnectionDialogSwing.setConnectionSetting(newSetting);
            refreshTree();
            clearResultPanel();

            if (fMain instanceof JApplet) {
                getAppletContext().showStatus(
                    "JDBC Connection established to a "
                    + dMeta.getDatabaseProductName() + " v. "
                    + dMeta.getDatabaseProductVersion() + " database as '"
                    + dMeta.getUserName() + "'.");
            }
        } catch (SQLException e) {

            //  Added: (weconsultants@users)
            CommonSwing.errorMessage(e);
        } catch (IOException e) {

            //  Added: (weconsultants@users)
            CommonSwing.errorMessage(e);
        } catch (Exception e) {
            CommonSwing.errorMessage(e);
        }
    }
841780
private void initIndices(ResultSet edges) {
        try {
            ResultSetMetaData metaData = edges.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                final String columnName = metaData.getColumnName(i);
                if (columnName.equalsIgnoreCase(START_NODE)) startNodeIndex = i;
                if (columnName.equalsIgnoreCase(END_NODE)) endNodeIndex = i;
                if (columnName.equalsIgnoreCase(EDGE_ID)) edgeIDIndex = i;
                if (columnName.equalsIgnoreCase(edgeOrientationColumnName)) edgeOrientationIndex = i;
                if (columnName.equalsIgnoreCase(weightColumn)) weightColumnIndex = i;
            }
        } catch (SQLException e) {
            LOGGER.error("Problem accessing edge table metadata.", e);
        }
        verifyIndex(startNodeIndex, START_NODE);
        verifyIndex(endNodeIndex, END_NODE);
        verifyIndex(edgeIDIndex, EDGE_ID);
        if (!globalOrientation.equals(GraphFunctionParser.Orientation.UNDIRECTED)) {
            verifyIndex(edgeOrientationIndex, edgeOrientationColumnName);
        }
        if (weightColumn != null) {
            verifyIndex(weightColumnIndex, weightColumn);
        }
    }
1327554
static boolean polygonRelatePolygon_(Polygon polygon_a, Polygon polygon_b,
			double tolerance, String scl, ProgressTracker progress_tracker) {
		RelationalOperationsMatrix relOps = new RelationalOperationsMatrix();
		relOps.resetMatrix_();
		relOps.setPredicates_(scl);
		relOps.setAreaAreaPredicates_();

		Envelope2D env_a = new Envelope2D(), env_b = new Envelope2D();
		polygon_a.queryEnvelope2D(env_a);
		polygon_b.queryEnvelope2D(env_b);

		boolean bRelationKnown = false;
		boolean b_disjoint = RelationalOperations.envelopeDisjointEnvelope_(
				env_a, env_b, tolerance, progress_tracker);

		if (b_disjoint) {
			relOps.areaAreaDisjointPredicates_(polygon_a, polygon_b);
			bRelationKnown = true;
		}

		if (!bRelationKnown) {
			// Quick rasterize test to see whether the the geometries are
			// disjoint, or if one is contained in the other.
			int relation = RelationalOperations
					.tryRasterizedContainsOrDisjoint_(polygon_a, polygon_b,
							tolerance, false);

			if (relation == RelationalOperations.Relation.disjoint) {
				relOps.areaAreaDisjointPredicates_(polygon_a, polygon_b);
				bRelationKnown = true;
			} else if (relation == RelationalOperations.Relation.contains) {
				relOps.areaAreaContainsPredicates_(polygon_b);
				bRelationKnown = true;
			} else if (relation == RelationalOperations.Relation.within) {
				relOps.areaAreaWithinPredicates_(polygon_a);
				bRelationKnown = true;
			}
		}

		if (!bRelationKnown) {
			EditShape edit_shape = new EditShape();
			int geom_a = edit_shape.addGeometry(polygon_a);
			int geom_b = edit_shape.addGeometry(polygon_b);
			relOps.setEditShapeCrackAndCluster_(edit_shape, tolerance,
					progress_tracker);
			relOps.computeMatrixTopoGraphHalfEdges_(geom_a, geom_b);
			relOps.m_topo_graph.removeShape();
		}

		boolean bRelation = relationCompare_(relOps.m_matrix, relOps.m_scl);
		return bRelation;
	}
348342
static boolean polylineRelateMultiPoint_(Polyline polyline_a,
			MultiPoint multipoint_b, double tolerance, String scl,
			ProgressTracker progress_tracker) {
		RelationalOperationsMatrix relOps = new RelationalOperationsMatrix();
		relOps.resetMatrix_();
		relOps.setPredicates_(scl);
		relOps.setLinePointPredicates_();

		Envelope2D env_a = new Envelope2D(), env_b = new Envelope2D();
		polyline_a.queryEnvelope2D(env_a);
		multipoint_b.queryEnvelope2D(env_b);

		boolean bRelationKnown = false;
		boolean b_disjoint = RelationalOperations.envelopeDisjointEnvelope_(
				env_a, env_b, tolerance, progress_tracker);

		if (b_disjoint) {
			relOps.linePointDisjointPredicates_(polyline_a);
			bRelationKnown = true;
		}

		if (!bRelationKnown) {
			// Quick rasterize test to see whether the the geometries are
			// disjoint, or if one is contained in the other.
			int relation = RelationalOperations
					.tryRasterizedContainsOrDisjoint_(polyline_a, multipoint_b,
							tolerance, false);

			if (relation == RelationalOperations.Relation.disjoint) {
				relOps.linePointDisjointPredicates_(polyline_a);
				bRelationKnown = true;
			}
		}

		if (!bRelationKnown) {
			EditShape edit_shape = new EditShape();
			int geom_a = edit_shape.addGeometry(polyline_a);
			int geom_b = edit_shape.addGeometry(multipoint_b);
			relOps.setEditShapeCrackAndCluster_(edit_shape, tolerance,
					progress_tracker);
			relOps.m_cluster_index_a = relOps.m_topo_graph
					.createUserIndexForClusters();
			markClusterEndPoints_(geom_a, relOps.m_topo_graph,
					relOps.m_cluster_index_a);
			relOps.computeMatrixTopoGraphClusters_(geom_a, geom_b);
			relOps.m_topo_graph
					.deleteUserIndexForClusters(relOps.m_cluster_index_a);
			relOps.m_topo_graph.removeShape();
		}

		boolean bRelation = relationCompare_(relOps.m_matrix, relOps.m_scl);
		return bRelation;
	}
1284124
public boolean isConnectionHandleAlive(ConnectionHandle connection) {
		Statement stmt = null;
		boolean result = false;
		boolean logicallyClosed = connection.logicallyClosed.get();
		try {
			connection.logicallyClosed.compareAndSet(true, false); // avoid checks later on if it's marked as closed.
			String testStatement = this.config.getConnectionTestStatement();
			ResultSet rs = null;

			if (testStatement == null) {
				// Make a call to fetch the metadata instead of a dummy query.
				rs = connection.getMetaData().getTables( null, null, KEEPALIVEMETADATA, METADATATABLE );
			} else {
				stmt = connection.createStatement();
				stmt.execute(testStatement);
			}


			if (rs != null) {
				rs.close();
			}

			result = true;
		} catch (SQLException e) {
			// connection must be broken!
			result = false;
		} finally {
			connection.logicallyClosed.set(logicallyClosed);
			connection.setConnectionLastResetInMs(System.currentTimeMillis());
			result = closeStatement(stmt, result);
		}
		return result;
	}
569964
@Override
    public Direction direction(Vertex vertex) {
        for (int i=0;i<getArity();i++) {
            if (it().getVertex(i).equals(vertex)) return EdgeDirection.fromPosition(i);
        }
        throw new IllegalArgumentException("Relation is not incident on vertex");
    }
167706
public static boolean isTableMaterializeViewSource(org.voltdb.catalog.Database database,
                                                       org.voltdb.catalog.Table table)
    {
        CatalogMap<Table> tables = database.getTables();
        for (Table t : tables) {
            Table matsrc = t.getMaterializer();
            if ((matsrc != null) && (matsrc.getRelativeIndex() == table.getRelativeIndex())) {
                return true;
            }
        }
        return false;
    }
1246916
public static ResultSet triangleContouring(Connection connection, String tableName, Value... varArgs) throws SQLException {
        if (connection.getMetaData().getURL().equals(HACK_URL)) {
            return new ExplodeResultSet(connection,tableName, Collections.singletonList(0.0)).getResultSet();
        }
        ExplodeResultSet rowSource = null;
        if(varArgs.length > 3) {
            // First ones may be column names
            if(varArgs[0] instanceof ValueString &&
                    varArgs[1] instanceof ValueString &&
                    varArgs[2] instanceof ValueString) {
                // Use table columns for iso levels
                List<Double> isoLvls = new ArrayList<Double>(varArgs.length - 3);
                for(int idArg = 3; idArg < varArgs.length; idArg++) {
                    isoLvls.add(varArgs[idArg].getDouble());
                }
                rowSource = new ExplodeResultSet(connection,tableName,varArgs[0].getString(), varArgs[1].getString(),
                        varArgs[2].getString(), isoLvls);
            }
        }
        if(rowSource == null) {
            // Use Z
            List<Double> isoLvls = new ArrayList<Double>(varArgs.length);
            for (Value value : varArgs) {
                if (value instanceof ValueArray) {
                    for (Value arrVal : ((ValueArray) value).getList()) {
                        isoLvls.add(arrVal.getDouble());
                    }
                } else {
                    isoLvls.add(value.getDouble());
                }
            }
            rowSource = new ExplodeResultSet(connection,tableName, isoLvls);
        }
        return rowSource.getResultSet();
    }
727752
public static void createTables( Connection connection ) throws IOException, SQLException {
        StringBuilder sB = new StringBuilder();
        sB.append("CREATE TABLE ");
        sB.append(TABLE_NOTES);
        sB.append(" (");
        sB.append(NotesTableFields.COLUMN_ID.getFieldName());
        sB.append(" INTEGER PRIMARY KEY, ");
        sB.append(NotesTableFields.COLUMN_LON.getFieldName()).append(" REAL NOT NULL, ");
        sB.append(NotesTableFields.COLUMN_LAT.getFieldName()).append(" REAL NOT NULL,");
        sB.append(NotesTableFields.COLUMN_ALTIM.getFieldName()).append(" REAL NOT NULL,");
        sB.append(NotesTableFields.COLUMN_TS.getFieldName()).append(" DATE NOT NULL,");
        sB.append(NotesTableFields.COLUMN_DESCRIPTION.getFieldName()).append(" TEXT, ");
        sB.append(NotesTableFields.COLUMN_TEXT.getFieldName()).append(" TEXT NOT NULL, ");
        sB.append(NotesTableFields.COLUMN_FORM.getFieldName()).append(" CLOB, ");
        sB.append(NotesTableFields.COLUMN_STYLE.getFieldName()).append(" TEXT,");
        sB.append(NotesTableFields.COLUMN_ISDIRTY.getFieldName()).append(" INTEGER");
        sB.append(");");
        String CREATE_TABLE_NOTES = sB.toString();

        sB = new StringBuilder();
        sB.append("CREATE INDEX notes_ts_idx ON ");
        sB.append(TABLE_NOTES);
        sB.append(" ( ");
        sB.append(NotesTableFields.COLUMN_TS.getFieldName());
        sB.append(" );");
        String CREATE_INDEX_NOTES_TS = sB.toString();

        sB = new StringBuilder();
        sB.append("CREATE INDEX notes_x_by_y_idx ON ");
        sB.append(TABLE_NOTES);
        sB.append(" ( ");
        sB.append(NotesTableFields.COLUMN_LON.getFieldName());
        sB.append(", ");
        sB.append(NotesTableFields.COLUMN_LAT.getFieldName());
        sB.append(" );");
        String CREATE_INDEX_NOTES_X_BY_Y = sB.toString();

        sB = new StringBuilder();
        sB.append("CREATE INDEX notes_isdirty_idx ON ");
        sB.append(TABLE_NOTES);
        sB.append(" ( ");
        sB.append(NotesTableFields.COLUMN_ISDIRTY.getFieldName());
        sB.append(" );");
        String CREATE_INDEX_NOTES_ISDIRTY = sB.toString();

        try (Statement statement = connection.createStatement()) {
            statement.setQueryTimeout(30); // set timeout to 30 sec.

            statement.executeUpdate(CREATE_TABLE_NOTES);
            statement.executeUpdate(CREATE_INDEX_NOTES_TS);
            statement.executeUpdate(CREATE_INDEX_NOTES_X_BY_Y);
            statement.executeUpdate(CREATE_INDEX_NOTES_ISDIRTY);
        } catch (Exception e) {
            throw new IOException(e.getLocalizedMessage());
        }
    }
595432
private boolean connected(NodeCursor start, long end, int[][] typedDirections) {
        try (RelationshipTraversalCursor relationship = ktx.cursors().allocateRelationshipTraversalCursor()) {
            start.allRelationships(relationship);
            while (relationship.next()) {
                if (relationship.neighbourNodeReference() ==end) {
                    if (typedDirections==null) {
                        return true;
                    } else {
                        int direction = relationship.targetNodeReference() == end ? 0 : 1 ;
                        int[] types = typedDirections[direction];
                        if (arrayContains(types, relationship.type())) return true;
                    }
                }
            }
        }
        return false;
    }
588174
public <T> void addColumn(Connection connection, Attribute<T, ?> attribute) {
        addColumn(connection, attribute, true);
    }
604839
private void connectArcToPort(SbgnPDNode lPort, Port vPort)
    {
        //Iterate over the edges of l level port
        for  (Object e: (lPort.getEdges()))
        {
            //Ignore rigid edges
            if(((LEdge)e).type.equals("rigid edge"))
                continue;

            //Determine the if vPort is source or target
            Arc arc = idToArcs.get(((LEdge)e).label);
            if( lPort.label.equals(((LEdge)e).getSource().label ))
            {
                arc.setSource(vPort);
            }
            else if ( lPort.label.equals(((LEdge)e).getTarget().label ) )
            {
                arc.setTarget(vPort);
            }
        }
    }
405839
private void setSchemaOnConnection(Connection connection) throws SQLException {
		logger.finest("Entering " + CLASSNAME +".setSchemaOnConnection()");

		String dbProductName = connection.getMetaData().getDatabaseProductName();
		if (!"Oracle".equals(dbProductName) && !"Microsoft SQL Server".equals(dbProductName)) {
			PreparedStatement ps = null;
			if ("MySQL".equals(dbProductName)) {
				ps = connection.prepareStatement("USE " + schema);
			} else {
				ps = connection.prepareStatement("SET SCHEMA ?");
				ps.setString(1, schema);
			}
			ps.executeUpdate(); 
			ps.close();
		}

		logger.finest("Exiting " + CLASSNAME +".setSchemaOnConnection()");
	}
851718
public void process(List<ChessboardCorner> corners ) {
		this.corners = corners;

		// reset internal data structures
		vertexes.reset();
		edges.reset();
		clusters.reset();

		// Create a vertex for each corner
		for (int idx = 0; idx < corners.size(); idx++) {
			Vertex v = vertexes.grow();
			v.reset();
			v.index = idx;
		}

		// Initialize nearest-neighbor search.
		nn.setPoints(corners,true);

		// Connect corners to each other based on relative distance on orientation
		for (int i = 0; i < corners.size(); i++) {
			findVertexNeighbors(vertexes.get(i),corners);
		}

		// If more than one vertex's are near each other, pick one and remove the others
		handleAmbiguousVertexes(corners);
//		printDualGraph();

		// Prune connections which are not mutual
		for (int i = 0; i < vertexes.size; i++) {
			Vertex v = vertexes.get(i);
			v.pruneNonMutal(EdgeType.PARALLEL);
			v.pruneNonMutal(EdgeType.PERPENDICULAR);
		}
//		printDualGraph();

		// Select the final 2 to 4 connections from perpendicular set
		// each pair of adjacent perpendicular edge needs to have a matching parallel edge between them
		// Use each perpendicular edge as a seed and select the best one
		for (int idx = 0; idx < vertexes.size(); idx++) {
			selectConnections(vertexes.get(idx));
		}
//		printConnectionGraph();

		// Connects must be mutual to be accepted. Keep track of vertexes which were modified
		dirtyVertexes.clear();
		for (int i = 0; i < vertexes.size; i++) {
			Vertex v = vertexes.get(i);
			int before = v.connections.size();
			v.pruneNonMutal(EdgeType.CONNECTION);
			if( before != v.connections.size() ) {
				dirtyVertexes.add(v);
				v.marked = true;
			}
		}

//		printConnectionGraph();
		// attempt to recover from poorly made decisions in the past from the greedy algorithm
		repairVertexes();

		// Prune non-mutual edges again. Only need to consider dirty edges since it makes sure that the new
		// set of connections is a super set of the old
		for (int i = 0; i < dirtyVertexes.size(); i++) {
			dirtyVertexes.get(i).pruneNonMutal(EdgeType.CONNECTION);
			dirtyVertexes.get(i).marked = false;
		}

		// Final clean up to return just valid grids
		disconnectInvalidVertices();

		// Name says it all
		convertToOutput(corners);
	}
594820
protected void validateFetchOrientation(FetchOrientation orientation,
      EnumSet<FetchOrientation> supportedOrientations) throws HiveSQLException {
    if (!supportedOrientations.contains(orientation)) {
      throw new HiveSQLException("The fetch type " + orientation.toString() +
          " is not supported for this resultset", "HY106");
    }
  }