Creates the {@link QuadBatch} used as the default top-level batch when rendering the scene
graph. This uses {@link UniformQuadBatch} if possible, {@link TriangleBatch} otherwise.
969661
protected QuadBatch createDefaultBatch (GL20 gl) {
    try {
      if (UniformQuadBatch.isLikelyToPerform(gl)) return new UniformQuadBatch(gl);
    } catch (Exception e) {
      // oops, fall through and use a TriangleBatch
    }
    return new TriangleBatch(gl);
  }
169051
private VoltTable[] fastPath(List<QueuedSQL> batch, final boolean finalTask) {
        final int batchSize = batch.size();
        Object[] params = new Object[batchSize];
        long[] fragmentIds = new long[batchSize];
        String[] sqlTexts = new String[batchSize];
        boolean[] isWriteFrag = new boolean[batchSize];
        int[] sqlCRCs = new int[batchSize];
        int succeededFragmentsCount = 0;

        int i = 0;
        for (final QueuedSQL qs : batch) {
            assert (qs.stmt.collector == null);
            fragmentIds[i] = qs.stmt.aggregator.id;
            // use the pre-serialized params if it exists
            params[i] = qs.params;
            sqlTexts[i] = qs.stmt.getText();
            isWriteFrag[i] = !qs.stmt.isReadOnly;
            sqlCRCs[i] = SQLStmtAdHocHelper.getHash(qs.stmt);
            i++;
        }

        VoltTable[] results = null;
        // Before executing the fragments, tell the EE if this batch should be
        // timed.
        getExecutionEngine().setPerFragmentTimingEnabled(m_perCallStats.samplingStmts());
        try {
            FastDeserializer fragResult = m_site.executePlanFragments(batchSize, fragmentIds, null, params,
                    m_determinismHash, sqlTexts, isWriteFrag, sqlCRCs, m_txnState.txnId, m_txnState.m_spHandle,
                    m_txnState.uniqueId, m_isReadOnly, VoltTrace.log(VoltTrace.Category.EE) != null);
            final int totalSize;
            try {
                // read the size of the DR buffer used
                fragResult.readInt();
                // read the complete size of the buffer used
                totalSize = fragResult.readInt();
            } catch (final IOException ex) {
                log.error("Failed to deserialze result table" + ex);
                throw new EEException(ExecutionEngine.ERRORCODE_WRONG_SERIALIZED_BYTES);
            }
            final ByteBuffer rawDataBuff;
            if ((m_batchIndex == 0 && !m_site.usingFallbackBuffer()) || finalTask) {
                // If this is the first or final batch, skip the copy of the
                // underlying byte array
                rawDataBuff = fragResult.buffer();
            } else {
                rawDataBuff = fragResult.readBuffer(totalSize);
            }
            results = TableHelper.convertBackedBufferToTables(rawDataBuff, batchSize);
        } catch (Throwable ex) {
            if (!m_isReadOnly) {
                // roll back the current batch and re-throw the EE exception
                m_site.truncateUndoLog(true, false,
                        m_spBigBatchBeginToken >= 0 ? m_spBigBatchBeginToken : m_site.getLatestUndoToken(),
                        m_txnState.m_spHandle, null);
            }

            throw ex;
        } finally {
            long[] executionTimes = null;
            if (m_perCallStats.samplingStmts()) {
                executionTimes = new long[batchSize];
            }
            succeededFragmentsCount = getExecutionEngine().extractPerFragmentStats(batchSize, executionTimes);

            for (i = 0; i < batchSize; i++) {
                QueuedSQL qs = batch.get(i);
                // No coordinator task for a single partition procedure.
                boolean isCoordinatorTask = false;
                // If all the fragments in this batch are executed successfully,
                // succeededFragmentsCount == batchSize.
                // Otherwise, the fragment whose index equals
                // succeededFragmentsCount is the one that failed.
                boolean failed = i == succeededFragmentsCount;

                m_perCallStats.recordStatementStats(qs.stmt.getStmtName(), isCoordinatorTask, failed,
                        executionTimes == null ? 0 : executionTimes[i], results == null ? null : results[i], qs.params);

                // If this fragment failed, no subsequent fragments will be
                // executed.
                if (failed) {
                    break;
                }
            }
        }
        return results;
    }
344892
function syncBatch(batch, cb) {
    if (batch && batch.length > 0) {
      var mbaasClient = new MBaaSClient(ENVIRONMENT, {
        url: URL.format(PROTOCOL + '://' + HOST),
        accessKey: ACCESS_KEY,
        project: PROJECT,
        app: GUID,
        appApiKey: API_KEY
      });
      // /api/app/:domain/:environment/:projectid/:appid/message/:topic with [] or messages for data (a batch)
      mbaasClient.app.message.sendbatch({
        'host': HOST,
        'environment': ENVIRONMENT,
        'domain': DOMAIN,
        'data': batch,
        'topic': 'fhact' //the only other topic is fhweb which is not longer used
      }, function(err) {
        if (err) {
          return cb(err, {message: 'Error sending message batch to MBaaS', host: HOST, environment: ENVIRONMENT, domain: DOMAIN, topic:'fhact', batch: batch});
        } else {
          return cb(undefined, {message: 'Batch sent to MBaaS'});
        }
      });
    } else {
      return cb(undefined, {message: 'Batch empty...nothing to sync at this time'});
    }
  }
708495
function Quad(gl)
{
    /*
     * the current WebGL drawing context
     *
     * @member {WebGLRenderingContext}
     */
    this.gl = gl;

//    this.textures = new TextureUvs();

    /**
     * An array of vertices
     *
     * @member {Float32Array}
     */
    this.vertices = new Float32Array([
        0,0,
        200,0,
        200,200,
        0,200
    ]);

    /**
     * The Uvs of the quad
     *
     * @member {Float32Array}
     */
    this.uvs = new Float32Array([
        0,0,
        1,0,
        1,1,
        0,1
    ]);

//    var white = (0xFFFFFF >> 16) + (0xFFFFFF & 0xff00) + ((0xFFFFFF & 0xff) << 16) + (1 * 255 << 24);
    //TODO convert this to a 32 unsigned int array
    /**
     * The color components of the triangles
     *
     * @member {Float32Array}
     */
    this.colors = new Float32Array([
        1,1,1,1,
        1,1,1,1,
        1,1,1,1,
        1,1,1,1
    ]);

    /*
     * @member {Uint16Array} An array containing the indices of the vertices
     */
    this.indices = new Uint16Array([
        0, 1, 2, 0, 3, 2
    ]);

    /*
     * @member {WebGLBuffer} The vertex buffer
     */
    this.vertexBuffer = gl.createBuffer();

    /*
     * @member {WebGLBuffer} The index buffer
     */
    this.indexBuffer = gl.createBuffer();

    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, (8 + 8 + 16) * 4, gl.DYNAMIC_DRAW);

    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);

    this.upload();
}
1061334
private int[] convertBatch(int[] batch) {
        int[] conv = new int[batch.length];
        for (int i=0; i<batch.length; i++) {
            conv[i] = sample[batch[i]];
        }
        return conv;
    }
1242126
function( gl, v, renderer ) {

			var unit = renderer.allocTextureUnit();
			gl.uniform1i( this.addr, unit );
			renderer.setTextureCube( v || emptyCubeTexture, unit );

		}
569159
protected synchronized BatchExecutor getBatchExecutor() {
    if (batchExecutor == null) {
      batchExecutor = new BatchExecutor(bigtableConnection.getSession(), hbaseAdapter);
    }
    return batchExecutor;
  }
918390
public int[] sampleBatchWithoutReplacement() {
        int[] batch = new int[batchSize];
        for (int i=0; i<batch.length; i++) {
            if (cur == indices.length) {
                cur = 0;
            }
            if (cur == 0) {
                IntArrays.shuffle(indices);
            }
            batch[i] = indices[cur++];
        }
        return batch;
    }
157072
public Tile tile (float x, float y, float width, float height) {
    final float tileX = x, tileY = y, tileWidth = width, tileHeight = height;
    return new Tile() {
      @Override public Texture texture () { return Texture.this; }
      @Override public float width () { return tileWidth; }
      @Override public float height () { return tileHeight; }
      @Override public float sx () { return tileX/displayWidth; }
      @Override public float sy () { return tileY/displayHeight; }
      @Override public float tx () { return (tileX+tileWidth)/displayHeight; }
      @Override public float ty () { return (tileY+tileWidth)/displayHeight; }
      @Override public void addToBatch (QuadBatch batch, int tint, AffineTransform tx,
                                        float x, float y, float width, float height) {
        batch.addQuad(texture(), tint, tx, x, y, width, height, tileX, tileY, tileWidth, tileHeight);
      }
      @Override public void addToBatch (QuadBatch batch, int tint, AffineTransform tx,
                                        float dx, float dy, float dw, float dh,
                                        float sx, float sy, float sw, float sh) {
        batch.addQuad(texture(), tint, tx, dx, dy, dw, dh, tileX+sx, tileY+sy, sw, sh);
      }
    };
  }
1339073
public static RenderTarget create (Graphics gfx, final Texture tex) {
    GL20 gl = gfx.gl;
    final int fb = gl.glGenFramebuffer();
    if (fb == 0) throw new RuntimeException("Failed to gen framebuffer: " + gl.glGetError());
    gl.glBindFramebuffer(GL_FRAMEBUFFER, fb);
    gl.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex.id, 0);
    gl.checkError("RenderTarget.create");
    return new RenderTarget (gfx) {
      public int id () { return fb; }
      public int width () { return tex.pixelWidth; }
      public int height () { return tex.pixelHeight; }
      public float xscale () { return tex.pixelWidth / tex.displayWidth; }
      public float yscale () { return tex.pixelHeight / tex.displayHeight; }
      public boolean flip () { return false; }
    };
  }
392917
@Override
    public int executeBatch()
    {
        if (batchSize > 0)
        {
            boolean nodeAutoIndexingEnabled = indexer.isNodeAutoIndexingEnabled(factory.getConnection());
            boolean relationshipAutoIndexingEnabled = indexer
                    .isRelationshipAutoIndexingEnabled(factory.getConnection());

            BatchInserter inserter = getBatchInserter();
            BatchInserterIndexProvider indexProvider = new LuceneBatchInserterIndexProvider(inserter);

            if (inserter == null)
            {
                log.error("Unable to create instance of BatchInserter. Opertion will fail");
                throw new PersistenceException("Unable to create instance of BatchInserter. Opertion will fail");
            }

            if (resource != null && resource.isActive())
            {
                log.error("Batch Insertion MUST not be executed in a transaction");
                throw new PersistenceException("Batch Insertion MUST not be executed in a transaction");
            }

            Map<Object, Long> pkToNodeIdMap = new HashMap<Object, Long>();
            for (com.impetus.kundera.graph.Node graphNode : nodes)
            {
                if (graphNode.isDirty())
                {
                    graphNode.handlePreEvent();
                    // Delete can not be executed in batch, deleting normally
                    if (graphNode.isInState(RemovedState.class))
                    {
                        delete(graphNode.getData(), graphNode.getEntityId());
                    }
                    else if (graphNode.isUpdate())
                    {
                        // Neo4J allows only batch insertion, follow usual path
                        // for normal updates
                        persist(graphNode);
                    }
                    else
                    {
                        // Insert node
                        Object entity = graphNode.getData();
                        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());
                        Object pk = PropertyAccessorHelper.getId(entity, m);
                        Map<String, Object> nodeProperties = mapper.createNodeProperties(entity, m);
                        long nodeId = inserter.createNode(nodeProperties);
                        pkToNodeIdMap.put(pk, nodeId);

                        // Index Node
                        indexer.indexNodeUsingBatchIndexer(indexProvider, m, nodeId, nodeProperties,
                                nodeAutoIndexingEnabled);

                        // Insert relationships for this particular node
                        if (!getRelationHolders(graphNode).isEmpty())
                        {
                            for (RelationHolder rh : getRelationHolders(graphNode))
                            {
                                // Search Node (to be connected to ) in Neo4J
                                // graph
                                EntityMetadata targetNodeMetadata = KunderaMetadataManager.getEntityMetadata(
                                        kunderaMetadata, rh.getRelationValue().getClass());
                                Object targetNodeKey = PropertyAccessorHelper.getId(rh.getRelationValue(),
                                        targetNodeMetadata);
                                Long targetNodeId = pkToNodeIdMap.get(targetNodeKey);

                                if (targetNodeId != null)
                                {
                                    /**
                                     * Join this node (source node) to target
                                     * node via relationship
                                     */
                                    // Relationship Type
                                    DynamicRelationshipType relType = DynamicRelationshipType.withName(rh
                                            .getRelationName());

                                    // Relationship Properties
                                    Map<String, Object> relationshipProperties = null;
                                    Object relationshipObj = rh.getRelationVia();
                                    if (relationshipObj != null)
                                    {
                                        EntityMetadata relationMetadata = KunderaMetadataManager.getEntityMetadata(
                                                kunderaMetadata, relationshipObj.getClass());

                                        relationshipProperties = mapper.createRelationshipProperties(m,
                                                targetNodeMetadata, relationshipObj);

                                        // Finally insert relationship
                                        long relationshipId = inserter.createRelationship(nodeId, targetNodeId,
                                                relType, relationshipProperties);

                                        // Index this relationship
                                        indexer.indexRelationshipUsingBatchIndexer(indexProvider, relationMetadata,
                                                relationshipId, relationshipProperties, relationshipAutoIndexingEnabled);
                                    }

                                }
                            }
                        }
                    }
                    graphNode.handlePostEvent();
                }
            }

            // Shutdown Batch inserter
            indexProvider.shutdown();
            inserter.shutdown();

            // Restore Graph Database service
            factory.setConnection((GraphDatabaseService) factory.createPoolOrConnection());

            return pkToNodeIdMap.size();
        }
        else
        {
            return 0;
        }

    }
1337163
public static ComputationGraph toComputationGraph(MultiLayerNetwork net) {

        //We rely heavily here on the fact that the topological sort order - and hence the layout of parameters - is
        // by definition the identical for a MLN and "single stack" computation graph. This also has to hold
        // for the updater state...

        ComputationGraphConfiguration.GraphBuilder b = new NeuralNetConfiguration.Builder()
                .dataType(net.getLayerWiseConfigurations().getDataType())
                .graphBuilder();

        MultiLayerConfiguration origConf = net.getLayerWiseConfigurations().clone();


        int layerIdx = 0;
        String lastLayer = "in";
        b.addInputs("in");
        for (NeuralNetConfiguration c : origConf.getConfs()) {
            String currLayer = String.valueOf(layerIdx);

            InputPreProcessor preproc = origConf.getInputPreProcess(layerIdx);
            b.addLayer(currLayer, c.getLayer(), preproc, lastLayer);

            lastLayer = currLayer;
            layerIdx++;
        }
        b.setOutputs(lastLayer);

        ComputationGraphConfiguration conf = b.build();

        ComputationGraph cg = new ComputationGraph(conf);
        cg.init();

        cg.setParams(net.params());

        //Also copy across updater state:
        INDArray updaterState = net.getUpdater().getStateViewArray();
        if (updaterState != null) {
            cg.getUpdater().getUpdaterStateViewArray()
                    .assign(updaterState);
        }

        return cg;
    }
946780
public static ExecutionGraph buildGraph(
			@Nullable ExecutionGraph prior,
			JobGraph jobGraph,
			Configuration jobManagerConfig,
			ScheduledExecutorService futureExecutor,
			Executor ioExecutor,
			SlotProvider slotProvider,
			ClassLoader classLoader,
			CheckpointRecoveryFactory recoveryFactory,
			Time rpcTimeout,
			RestartStrategy restartStrategy,
			MetricGroup metrics,
			BlobWriter blobWriter,
			Time allocationTimeout,
			Logger log)
		throws JobExecutionException, JobException {

		checkNotNull(jobGraph, "job graph cannot be null");

		final String jobName = jobGraph.getName();
		final JobID jobId = jobGraph.getJobID();

		final FailoverStrategy.Factory failoverStrategy =
				FailoverStrategyLoader.loadFailoverStrategy(jobManagerConfig, log);

		final JobInformation jobInformation = new JobInformation(
			jobId,
			jobName,
			jobGraph.getSerializedExecutionConfig(),
			jobGraph.getJobConfiguration(),
			jobGraph.getUserJarBlobKeys(),
			jobGraph.getClasspaths());

		// create a new execution graph, if none exists so far
		final ExecutionGraph executionGraph;
		try {
			executionGraph = (prior != null) ? prior :
				new ExecutionGraph(
					jobInformation,
					futureExecutor,
					ioExecutor,
					rpcTimeout,
					restartStrategy,
					failoverStrategy,
					slotProvider,
					classLoader,
					blobWriter,
					allocationTimeout);
		} catch (IOException e) {
			throw new JobException("Could not create the ExecutionGraph.", e);
		}

		// set the basic properties

		executionGraph.setScheduleMode(jobGraph.getScheduleMode());
		executionGraph.setQueuedSchedulingAllowed(jobGraph.getAllowQueuedScheduling());

		try {
			executionGraph.setJsonPlan(JsonPlanGenerator.generatePlan(jobGraph));
		}
		catch (Throwable t) {
			log.warn("Cannot create JSON plan for job", t);
			// give the graph an empty plan
			executionGraph.setJsonPlan("{}");
		}

		// initialize the vertices that have a master initialization hook
		// file output formats create directories here, input formats create splits

		final long initMasterStart = System.nanoTime();
		log.info("Running initialization on master for job {} ({}).", jobName, jobId);

		for (JobVertex vertex : jobGraph.getVertices()) {
			String executableClass = vertex.getInvokableClassName();
			if (executableClass == null || executableClass.isEmpty()) {
				throw new JobSubmissionException(jobId,
						"The vertex " + vertex.getID() + " (" + vertex.getName() + ") has no invokable class.");
			}

			try {
				vertex.initializeOnMaster(classLoader);
			}
			catch (Throwable t) {
					throw new JobExecutionException(jobId,
							"Cannot initialize task '" + vertex.getName() + "': " + t.getMessage(), t);
			}
		}

		log.info("Successfully ran initialization on master in {} ms.",
				(System.nanoTime() - initMasterStart) / 1_000_000);

		// topologically sort the job vertices and attach the graph to the existing one
		List<JobVertex> sortedTopology = jobGraph.getVerticesSortedTopologicallyFromSources();
		if (log.isDebugEnabled()) {
			log.debug("Adding {} vertices from job graph {} ({}).", sortedTopology.size(), jobName, jobId);
		}
		executionGraph.attachJobGraph(sortedTopology);

		if (log.isDebugEnabled()) {
			log.debug("Successfully created execution graph from job graph {} ({}).", jobName, jobId);
		}

		// configure the state checkpointing
		JobCheckpointingSettings snapshotSettings = jobGraph.getCheckpointingSettings();
		if (snapshotSettings != null) {
			List<ExecutionJobVertex> triggerVertices =
					idToVertex(snapshotSettings.getVerticesToTrigger(), executionGraph);

			List<ExecutionJobVertex> ackVertices =
					idToVertex(snapshotSettings.getVerticesToAcknowledge(), executionGraph);

			List<ExecutionJobVertex> confirmVertices =
					idToVertex(snapshotSettings.getVerticesToConfirm(), executionGraph);

			CompletedCheckpointStore completedCheckpoints;
			CheckpointIDCounter checkpointIdCounter;
			try {
				int maxNumberOfCheckpointsToRetain = jobManagerConfig.getInteger(
						CheckpointingOptions.MAX_RETAINED_CHECKPOINTS);

				if (maxNumberOfCheckpointsToRetain <= 0) {
					// warning and use 1 as the default value if the setting in
					// state.checkpoints.max-retained-checkpoints is not greater than 0.
					log.warn("The setting for '{} : {}' is invalid. Using default value of {}",
							CheckpointingOptions.MAX_RETAINED_CHECKPOINTS.key(),
							maxNumberOfCheckpointsToRetain,
							CheckpointingOptions.MAX_RETAINED_CHECKPOINTS.defaultValue());

					maxNumberOfCheckpointsToRetain = CheckpointingOptions.MAX_RETAINED_CHECKPOINTS.defaultValue();
				}

				completedCheckpoints = recoveryFactory.createCheckpointStore(jobId, maxNumberOfCheckpointsToRetain, classLoader);
				checkpointIdCounter = recoveryFactory.createCheckpointIDCounter(jobId);
			}
			catch (Exception e) {
				throw new JobExecutionException(jobId, "Failed to initialize high-availability checkpoint handler", e);
			}

			// Maximum number of remembered checkpoints
			int historySize = jobManagerConfig.getInteger(WebOptions.CHECKPOINTS_HISTORY_SIZE);

			CheckpointStatsTracker checkpointStatsTracker = new CheckpointStatsTracker(
					historySize,
					ackVertices,
					snapshotSettings.getCheckpointCoordinatorConfiguration(),
					metrics);

			// load the state backend from the application settings
			final StateBackend applicationConfiguredBackend;
			final SerializedValue<StateBackend> serializedAppConfigured = snapshotSettings.getDefaultStateBackend();

			if (serializedAppConfigured == null) {
				applicationConfiguredBackend = null;
			}
			else {
				try {
					applicationConfiguredBackend = serializedAppConfigured.deserializeValue(classLoader);
				} catch (IOException | ClassNotFoundException e) {
					throw new JobExecutionException(jobId,
							"Could not deserialize application-defined state backend.", e);
				}
			}

			final StateBackend rootBackend;
			try {
				rootBackend = StateBackendLoader.fromApplicationOrConfigOrDefault(
						applicationConfiguredBackend, jobManagerConfig, classLoader, log);
			}
			catch (IllegalConfigurationException | IOException | DynamicCodeLoadingException e) {
				throw new JobExecutionException(jobId, "Could not instantiate configured state backend", e);
			}

			// instantiate the user-defined checkpoint hooks

			final SerializedValue<MasterTriggerRestoreHook.Factory[]> serializedHooks = snapshotSettings.getMasterHooks();
			final List<MasterTriggerRestoreHook<?>> hooks;

			if (serializedHooks == null) {
				hooks = Collections.emptyList();
			}
			else {
				final MasterTriggerRestoreHook.Factory[] hookFactories;
				try {
					hookFactories = serializedHooks.deserializeValue(classLoader);
				}
				catch (IOException | ClassNotFoundException e) {
					throw new JobExecutionException(jobId, "Could not instantiate user-defined checkpoint hooks", e);
				}

				final Thread thread = Thread.currentThread();
				final ClassLoader originalClassLoader = thread.getContextClassLoader();
				thread.setContextClassLoader(classLoader);

				try {
					hooks = new ArrayList<>(hookFactories.length);
					for (MasterTriggerRestoreHook.Factory factory : hookFactories) {
						hooks.add(MasterHooks.wrapHook(factory.create(), classLoader));
					}
				}
				finally {
					thread.setContextClassLoader(originalClassLoader);
				}
			}

			final CheckpointCoordinatorConfiguration chkConfig = snapshotSettings.getCheckpointCoordinatorConfiguration();

			executionGraph.enableCheckpointing(
				chkConfig.getCheckpointInterval(),
				chkConfig.getCheckpointTimeout(),
				chkConfig.getMinPauseBetweenCheckpoints(),
				chkConfig.getMaxConcurrentCheckpoints(),
				chkConfig.getCheckpointRetentionPolicy(),
				triggerVertices,
				ackVertices,
				confirmVertices,
				hooks,
				checkpointIdCounter,
				completedCheckpoints,
				rootBackend,
				checkpointStatsTracker);
		}

		// create all the metrics for the Execution Graph

		metrics.gauge(RestartTimeGauge.METRIC_NAME, new RestartTimeGauge(executionGraph));
		metrics.gauge(DownTimeGauge.METRIC_NAME, new DownTimeGauge(executionGraph));
		metrics.gauge(UpTimeGauge.METRIC_NAME, new UpTimeGauge(executionGraph));
		metrics.gauge(NumberOfFullRestartsGauge.METRIC_NAME, new NumberOfFullRestartsGauge(executionGraph));

		executionGraph.getFailoverStrategy().registerMetrics(metrics);

		return executionGraph;
	}
526824
@NotNull
  public BatchRes postBatch(@NotNull final BatchReq batchReq) throws IOException {
    return doWork(auth -> doRequest(auth, new JsonPost<>(batchReq, BatchRes.class), AuthHelper.join(auth.getHref(), PATH_BATCH)), batchReq.getOperation());
  }
1357497
function render(gl, width, height, dt, batch, shader) {
    time+=dt
    
    //switching textures is free, and doesn't update any buffers
    if (time > 1000) {
        batch.texture = batch.texture === tex2 ? tex : tex2
        time = 0
    }

    //draw our static vertex data
    batch.bind(shader)
    batch.draw()
    batch.unbind()
}
740212
protected void getBatch(int batchSize){

//      if (numCalls == 0) {
//        for (int i = 0; i < 1538*\15; i++) {
//          randGenerator.nextInt(this.dataDimension());
//        }
//      }
//      numCalls++;

    if (thisBatch == null || thisBatch.length != batchSize){
      thisBatch = new int[batchSize];
    }

    //-----------------------------
    //RANDOM WITH REPLACEMENT
    //-----------------------------
    if (sampleMethod.equals(SamplingMethod.RandomWithReplacement)){
      for(int i = 0; i<batchSize;i++){
        thisBatch[i] = randGenerator.nextInt(this.dataDimension());        //Just generate a random index
//        System.err.println("numCalls = "+(numCalls++));
      }
      //-----------------------------
      //ORDERED
      //-----------------------------
    }else if(sampleMethod.equals(SamplingMethod.Ordered)){
      for(int i = 0; i<batchSize;i++){
        thisBatch[i] = (curElement + i) % this.dataDimension() ;          //Take the next batchSize points in order
      }
      curElement = (curElement + batchSize) % this.dataDimension();       //watch out for overflow

      //-----------------------------
      //RANDOM WITHOUT REPLACEMENT
      //-----------------------------
    }else if(sampleMethod.equals(SamplingMethod.RandomWithoutReplacement)){
      //Declare the indices array if needed.
      if (allIndices == null || allIndices.size()!= this.dataDimension()){

        allIndices = new ArrayList<Integer>();
        for(int i=0;i<this.dataDimension();i++){
          allIndices.add(i);
        }
        Collections.shuffle(allIndices,randGenerator);
      }

      for(int i = 0; i<batchSize;i++){
        thisBatch[i] = allIndices.get((curElement + i) % allIndices.size());  //Grab the next batchSize indices
      }

      if (curElement + batchSize > this.dataDimension()){
        Collections.shuffle(Arrays.asList(allIndices),randGenerator);                   //Shuffle if we got to the end of the list
      }

      //watch out for overflow
      curElement = (curElement + batchSize) % allIndices.size();          //Rollover


    }else{
      System.err.println("NO SAMPLING METHOD SELECTED");
      System.exit(1);
    }


  }
1193075
@WithBridgeMethods(value = SQLDeleteClause.class, castRequired =  true)
    public C addBatch() {
        batches.add(metadata);
        metadata = new DefaultQueryMetadata();
        metadata.addJoin(JoinType.DEFAULT, entity);
        metadata.setValidatingVisitor(validatingVisitor);
        return (C) this;
    }