auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void createSecondaryConnections(boolean isRejoin) { int partitionGroupCount = m_clusterSettings.get().hostcount() / (m_configuredReplicationFactor + 1); int localHostId = m_messenger.getHostId(); Set<Integer> peers = Sets.newHashSet(); if (m_configuredReplicationFactor > 0 && partitionGroupCount > 1) { Set<Integer> buddyHostIds = m_cartographer.getBuddyHostIds(localHostId); if (isRejoin) { peers.addAll(buddyHostIds); } else { for (Integer host : buddyHostIds) { if (host > localHostId) { peers.add(host); } } } int maxConnection = m_clusterSettings.get().hostcount() - 1; int existingConnections = buddyHostIds.size() - 1; int numberOfConnections = Math.min( maxConnection, CoreUtils.availableProcessors() / 4); int secondaryConnections = (numberOfConnections - 1) / existingConnections; Integer configNumberOfConnections = Integer.getInteger(SECONDARY_PICONETWORK_THREADS); if (configNumberOfConnections != null) { secondaryConnections = configNumberOfConnections; hostLog.info("Overridden secondary PicoNetwork network thread count:" + configNumberOfConnections); } else { hostLog.info("This node has " + secondaryConnections + " secondary PicoNetwork thread" + ((secondaryConnections > 1) ? "s" :"")); } <START> m_messenger.createAuxiliaryConnections(peers, secondaryConnections); <END> } }</code><technical_language>hostcount is a part of calculation for numberOfConnections. clusters elastically expanded reduced, do need adjust numberOfConnections</technical_language>

Target:
private void createSecondaryConnections(boolean isRejoin) { int partitionGroupCount = m_clusterSettings.get().hostcount() / (m_configuredReplicationFactor + 1); int localHostId = m_messenger.getHostId(); Set<Integer> peers = Sets.newHashSet(); if (m_configuredReplicationFactor > 0 && partitionGroupCount > 1) { Set<Integer> hostIdsWithinGroup = m_cartographer.getHostIdsWithinPartitionGroup(localHostId); if (isRejoin) { peers.addAll(hostIdsWithinGroup); peers.remove(m_messenger.getHostId()); } else { for (Integer host : hostIdsWithinGroup) { if (host > localHostId) { peers.add(host); } } } int connectionsWithoutPG = m_clusterSettings.get().hostcount() - 1; int existingConnectionsWithinPG = hostIdsWithinGroup.size() - 1; int targetConnectionsWithinPG = Math.min( connectionsWithoutPG, CoreUtils.availableProcessors() / 4); int secondaryConnections = (targetConnectionsWithinPG - 1) / existingConnectionsWithinPG; Integer configNumberOfConnections = Integer.getInteger(SECONDARY_PICONETWORK_THREADS); if (configNumberOfConnections != null) { secondaryConnections = configNumberOfConnections; hostLog.info("Overridden secondary PicoNetwork network thread count:" + configNumberOfConnections); } else { hostLog.info("This node has " + secondaryConnections + " secondary PicoNetwork thread" + ((secondaryConnections > 1) ? "s" :"")); } m_messenger.createAuxiliaryConnections(peers, secondaryConnections); } }
Source:
<code><START> private List<Vector> parseRawSmallMatrix(final String rawSmallMatrix) { <END> final List<Vector> matrix = new LinkedList<>(); for (final String row : rawSmallMatrix.split("\n")) { if (row.startsWith("#") || row.length() == 0) { continue; } final String[] split = row.split("\\s+"); final int numColumns = split.length - 1; final Vector rowVector = new DenseVector(numColumns); try { for (int i = 0; i < numColumns; i++) { rowVector.set(i, Double.valueOf(split[i + 1])); } } catch (final NumberFormatException e) { throw new RuntimeException(e); } matrix.add(rowVector); } return matrix; }</code><technical_language>return a complete Matrix</technical_language>

Target:
private Matrix parseRawSmallMatrix(final String rawSmallMatrix) { final List<double[]> rows = new LinkedList<>(); for (final String row : rawSmallMatrix.split(System.getProperty("line.separator"))) { if (row.startsWith("#") || row.length() == 0) { continue; } final String[] split = row.split("\\s+"); final int numColumns = split.length - 1; final double[] rowVector = new double[numColumns]; try { for (int i = 0; i < numColumns; i++) { rowVector[i] = Double.valueOf(split[i + 1]); } } catch (final NumberFormatException e) { throw new RuntimeException(e); } rows.add(rowVector); } final double[][] rawData = new double[rows.size()][]; int index = 0; for (final double[] row : rows) { rawData[index++] = row; } return new DenseMatrix(rawData); }
Source:
<code>public void update() { super.update(); if(worldObj.isRemote) { return; } updateRecipes(); if(power >= getTarget() && getTarget() != 0) { AssemblyRecipe recipe = getActiveRecipe(); extract(recipe.requiredStacks, false); ItemStack stack = recipe.output.copy(); stack.stackSize -= Utils.addToRandomInventoryAround(worldObj, pos, stack); if(stack.stackSize > 0) { stack.stackSize -= Utils.addToRandomInjectableAround(worldObj, pos, null, stack); } InvUtils.dropItemUp(getWorld(), stack, getPos()); power -= getTarget(); activateNextRecipe(); } <START> sendNetworkUpdate(NET_RENDER_DATA); <END> }</code><technical_language>Instead of NET_RENDER_DATA NET_GUI_DATA sendNetworkGuiUpdate send updates recipe + gui players need it</technical_language>

Target:
public void update() { super.update(); if(worldObj.isRemote) { return; } updateRecipes(); if(power >= getTarget() && getTarget() != 0) { AssemblyRecipe recipe = getActiveRecipe(); extract(recipe.requiredStacks, false); ItemStack stack = recipe.output.copy(); stack.stackSize -= Utils.addToRandomInventoryAround(worldObj, pos, stack); if(stack.stackSize > 0) { stack.stackSize -= Utils.addToRandomInjectableAround(worldObj, pos, null, stack); } InvUtils.dropItemUp(getWorld(), stack, getPos()); power -= getTarget(); activateNextRecipe(); } sendNetworkGuiUpdate(NET_GUI_DATA); }
Source:
<code>private String buildError(Error error, List<String> branches) { StringBuilder sb = new StringBuilder(); sb.append(error.get()); <START> if(branches.size() > 0) { <END> sb.append("\nIn branch(es): "); } String delimiter = ""; for (String branch : branches) { sb.append(delimiter).append(branch); delimiter = ", "; } return sb.toString(); }</code><technical_language>style-nit space (</technical_language>

Target:
private String buildError(Error error, List<String> branches) { if (branches.isEmpty()) { return error.get(); } StringBuilder sb = new StringBuilder(); if (branches.size() == 1) { sb.append("Branch ").append(branches.get(0)).append(":\n"); sb.append(error.get()); return sb.toString(); } sb.append("Branches"); String delim = " "; for (String branch : branches) { sb.append(delim).append(branch); delim = ", "; } return sb.append(":\n").append(error.get()).toString(); }
Source:
<code>public void putBlock(final String dataType, final int blockId, final Map<Long, Object> data) { if (!typeToBlocks.containsKey(dataType)) { initBlocks(dataType); } final Map<Integer, Block> blocks = typeToBlocks.get(dataType); if (blocks.containsKey(blockId)) { LOG.log(Level.SEVERE, "Block with id {0} already exists.", blockId); <START> throw new RuntimeException(); <END> } final Block block = new Block(); block.putAll(data); blocks.put(blockId, block); }</code><technical_language>out of curiosity, is more comfortable leave a log message throw empty exception, compared throwing Exception messages</technical_language>

Target:
public void putBlock(final String dataType, final int blockId, final Map<Long, Object> data) { if (!typeToBlocks.containsKey(dataType)) { initBlocks(dataType); } final Map<Integer, Block> blocks = typeToBlocks.get(dataType); if (blocks.containsKey(blockId)) { throw new RuntimeException("Block with id " + blockId + " already exists."); } final Block block = new Block(); block.putAll(data); blocks.put(blockId, block); }
Source:
<code>public Response intercept(Chain chain) throws IOException { AsyncTracerTag tracerTag = chain.request().tag(AsyncTracerTag.class); <START> if (tracerTag == null && tracerTag.asyncTracer() == null) { <END> return chain.proceed(chain.request()); } return tracerTag.asyncTracer().withTrace(() -> chain.proceed(chain.request())); }</code><technical_language>I surprised errorprone catch this, I remembered ahve uber's nullaway enabled</technical_language>

Target:
public Response intercept(Chain chain) throws IOException { AsyncTracerTag tracerTag = chain.request().tag(AsyncTracerTag.class); if (tracerTag == null || tracerTag.asyncTracer() == null) { return chain.proceed(chain.request()); } return tracerTag.asyncTracer().withTrace(() -> chain.proceed(chain.request())); }
Source:
<code>public void onMessage(@NonNull MessageType messageType, @NonNull String message) { switch (messageType) { <START> case FLYIN_ERROR: <END> case FLYIN_WARNING: case FLYIN_INFO: this.showInfoMessage(message); break; case ERROR: case WARNING: case INFO: this.showMessageInSitu(message); break; case EMPTY: this.hideMessageInSitu(); break; } }</code><technical_language>Do need start deprecating some of cases if combine them</technical_language>

Target:
public void onMessage(@NonNull MessageType messageType, @NonNull String message) { switch (messageType) { case FLYIN_ERROR: this.showErrorMessage("", message); break; case FLYIN_WARNING: case FLYIN_INFO: this.showInfoMessage(message); break; case ERROR: case WARNING: case INFO: this.showMessageInSitu(message); break; case EMPTY: this.hideMessageInSitu(); break; case DIALOG: this.showErrorDialog(message); } }
Source:
<code>private Settings() { settingsFile = new File("settings.yaml"); loadDescriptions(); try { if (!settingsFile.exists()) { createSettingsFile(); } else { loadSettings(); } } catch (IOException e) { <START> log.log(LogLevel.ERROR, "Error creating setting file settings.cfg!"); <END> } }</code><technical_language>settings.yml <naming</technical_language>

Target:
private Settings() { settingsFile = new File("settings.yml"); loadDescriptions(); try { if (!settingsFile.exists()) { createSettingsFile(); } else { loadSettings(); } } catch (IOException e) { log.log(LogLevel.ERROR, "Error creating setting file settings.cfg!"); } }
Source:
<code>@Test public void testDistinctCount2() { foodmartModelWithOneTile() .query("select count(distinct \"the_year\") as c\n" + "from \"foodmart\".\"sales_fact_1997\"\n" + "join \"foodmart\".\"time_by_day\" using (\"time_id\")\n" + "group by \"the_year\"") .enableMaterializations(true) .explainContains("EnumerableCalc(expr#0..1=[{inputs}], C=[$t1])\n" <START> + " EnumerableAggregate(group=[{0}], C=[COUNT($0)])\n" + " EnumerableAggregate(group=[{0}])\n" <END> + " EnumerableTableScan(table=[[adhoc, m{32, 36}]])") .returnsUnordered("C=1"); }</code><technical_language>This a plan degradation, it</technical_language>

Target:
@Test public void testDistinctCount2() { foodmartModelWithOneTile() .query("select count(distinct \"the_year\") as c\n" + "from \"foodmart\".\"sales_fact_1997\"\n" + "join \"foodmart\".\"time_by_day\" using (\"time_id\")\n" + "group by \"the_year\"") .enableMaterializations(true) .explainContains("EnumerableCalc(expr#0=[{inputs}], expr#1=[IS NOT NULL($t0)], " + "expr#2=[1:BIGINT], expr#3=[0:BIGINT], expr#4=[CASE($t1, $t2, $t3)], C=[$t4])\n" + " EnumerableAggregate(group=[{0}])\n" + " EnumerableTableScan(table=[[adhoc, m{32, 36}]])") .returnsUnordered("C=1"); }
Source:
<code>private Flux<Indexable> invokeReadyTasksAsync(final InvocationContext context) { TaskGroupEntry<TaskItem> readyTaskEntry = super.getNext(); final List<Flux<Indexable>> observables = new ArrayList<>(); while (readyTaskEntry != null) { final TaskGroupEntry<TaskItem> currentEntry = readyTaskEntry; final TaskItem currentTaskItem = currentEntry.data(); if (currentTaskItem instanceof ProxyTaskItem) { observables.add(invokeAfterPostRunAsync(currentEntry, context)); } else { observables.add(invokeTaskAsync(currentEntry, context)); } readyTaskEntry = super.getNext(); } <START> return Flux.mergeOrdered(32, <END> (some, other) -> { if (rootTaskEntry.key().endsWith(some.key())) { return 1; } else { return -1; } }, (Flux<Indexable>[]) observables.toArray(new Flux[0])); }</code><technical_language>is some difference "DelayError" part well. need check a bit processFaultedTaskAsync method</technical_language>

Target:
private Flux<Indexable> invokeReadyTasksAsync(final InvocationContext context) { TaskGroupEntry<TaskItem> readyTaskEntry = super.getNext(); final List<Flux<Indexable>> observables = new ArrayList<>(); while (readyTaskEntry != null) { final TaskGroupEntry<TaskItem> currentEntry = readyTaskEntry; final TaskItem currentTaskItem = currentEntry.data(); if (currentTaskItem instanceof ProxyTaskItem) { observables.add(invokeAfterPostRunAsync(currentEntry, context)); } else { observables.add(invokeTaskAsync(currentEntry, context)); } readyTaskEntry = super.getNext(); } return Flux.mergeOrdered(32, (some, other) -> { if (rootTaskEntry.key().endsWith(some.key())) { if (rootTaskEntry.key().endsWith(other.key())) { return 0; } return 1; } else if (rootTaskEntry.key().endsWith(other.key())) { return -1; } else { return some.key().compareTo(other.key()); } }, (Flux<Indexable>[]) observables.toArray(new Flux[0])); }
Source:
<code>private void postInfoAndPRsActions(PullRequestRef pr, List<Issue> issueReport, int issueThreshold, StashDiffReport diffReport, StashClient stashClient) { boolean canApprovePullrequest = config.canApprovePullRequest(); int issueTotal = issueReport.size(); if (issueTotal >= issueThreshold) { LOGGER.warn("Too many issues detected ({}/{}): Issues cannot be displayed in Diff view", issueTotal, issueThreshold); } else { stashRequestFacade.postSonarQubeReport(pr, issueReport, diffReport, stashClient); } if (config.includeAnalysisOverview()) { stashRequestFacade.postAnalysisOverview(pr, issueThreshold, issueReport, stashClient); } <START> if (canApprovePullrequest && (issueTotal == 0)){ <END> stashRequestFacade.approvePullRequest(pr, stashClient); } else if (canApprovePullrequest && ( (issueTotal != 0)) ) { stashRequestFacade.resetPullRequestApproval(pr, stashClient); } }</code><technical_language>Extra (): if (canApprovePullrequest && issueTotal == 0){</technical_language>

Target:
private void postInfoAndPRsActions(PullRequestRef pr, List<Issue> issueReport, int issueThreshold, StashDiffReport diffReport, StashClient stashClient) { boolean canApprovePullrequest = config.canApprovePullRequest(); int issueTotal = issueReport.size(); if (issueTotal >= issueThreshold) { LOGGER.warn("Too many issues detected ({}/{}): Issues cannot be displayed in Diff view", issueTotal, issueThreshold); } else { stashRequestFacade.postSonarQubeReport(pr, issueReport, diffReport, stashClient); } if (config.includeAnalysisOverview()) { stashRequestFacade.postAnalysisOverview(pr, issueThreshold, issueReport, stashClient); } if (canApprovePullrequest) { if (issueTotal == 0) { stashRequestFacade.approvePullRequest(pr, stashClient); } else { stashRequestFacade.resetPullRequestApproval(pr, stashClient); } } }
Source:
<code>public void searchPayments_ShouldIncludeCaptureLink_whenReturnedFromConnector() { publicAuthMock.mapBearerTokenToAccountId(API_KEY, GATEWAY_ACCOUNT_ID); <START> String SUBMITTED_STATE = "submitted"; <END> String payments = aPaginatedPaymentSearchResult() .withCount(1) .withPage(1) .withTotal(1) .withPayments(aSuccessfulSearchPayment() .withMatchingInProgressState(SUBMITTED_STATE) .withMatchingReference(TEST_REFERENCE) .withNumberOfResults(1) .withCaptureLink() .getResults()) .build(); connectorMock.respondOk_whenSearchCharges(GATEWAY_ACCOUNT_ID, TEST_REFERENCE, null, null, null, null, null, null, null, null, payments ); searchPayments(API_KEY, ImmutableMap.of("reference", TEST_REFERENCE)) .statusCode(200) .contentType(JSON) .body("results[0]._links", hasKey("capture")) .body("results[0]._links.capture.method", is("POST")); }</code><technical_language>This a constant, in regular camelCase SCREAMING_SNAKE_CASE</technical_language>

Target:
public void searchPayments_ShouldIncludeCaptureLink_whenReturnedFromConnector() { publicAuthMock.mapBearerTokenToAccountId(API_KEY, GATEWAY_ACCOUNT_ID); String submittedState = "submitted"; String chargeId = "charge-id"; String payments = aPaginatedPaymentSearchResult() .withCount(1) .withPage(1) .withTotal(1) .withPayments(aSuccessfulSearchPayment() .withChargeId(chargeId) .withMatchingInProgressState(submittedState) .withMatchingReference(TEST_REFERENCE) .withNumberOfResults(1) .withCaptureLink() .getResults()) .build(); connectorMock.respondOk_whenSearchCharges(GATEWAY_ACCOUNT_ID, TEST_REFERENCE, null, null, null, null, null, null, null, null, payments ); searchPayments(API_KEY, ImmutableMap.of("reference", TEST_REFERENCE)) .statusCode(200) .contentType(JSON) .body("results[0]._links", hasKey("capture")) .body("results[0]._links.capture.method", is("POST")) .body("results[0]._links.capture.href", is("<LINK_0>" + chargeId + "/capture")); }
Source:
<code>public synchronized TaskHandle addTask( TaskId taskId, DoubleSupplier utilizationSupplier, int initialSplitConcurrency, Duration splitConcurrencyAdjustFrequency, OptionalInt maxDriversPerTask) { requireNonNull(taskId, "taskId is null"); requireNonNull(utilizationSupplier, "utilizationSupplier is null"); checkArgument(!maxDriversPerTask.isPresent() || maxDriversPerTask.getAsInt() <= maximumNumberOfDriversPerTask, <START> "maxDriversPerTask must not be greater than the system default"); <END> log.debug("Task scheduled " + taskId); TaskHandle taskHandle = new TaskHandle(taskId, waitingSplits, utilizationSupplier, initialSplitConcurrency, splitConcurrencyAdjustFrequency, maxDriversPerTask); tasks.add(taskHandle); return taskHandle; }</code><technical_language>></technical_language>

Target:
public synchronized TaskHandle addTask( TaskId taskId, DoubleSupplier utilizationSupplier, int initialSplitConcurrency, Duration splitConcurrencyAdjustFrequency, OptionalInt maxDriversPerTask) { requireNonNull(taskId, "taskId is null"); requireNonNull(utilizationSupplier, "utilizationSupplier is null"); checkArgument(!maxDriversPerTask.isPresent() || maxDriversPerTask.getAsInt() <= maximumNumberOfDriversPerTask, "maxDriversPerTask cannot be greater than the configured value"); log.debug("Task scheduled " + taskId); TaskHandle taskHandle = new TaskHandle(taskId, waitingSplits, utilizationSupplier, initialSplitConcurrency, splitConcurrencyAdjustFrequency, maxDriversPerTask); tasks.add(taskHandle); return taskHandle; }
Source:
<code>private static IllegalStateException noDispatcherFound(MessageEnvelope envelope) { String id = Identifier.toString(envelope.id()); <START> String msg = format("No dispatcher found for the command (class: `%s` id: `%s`).", <END> envelope.messageClass(), id); throw new IllegalStateException(msg); }</code><technical_language>personally extract format string a separate variable inline 3 parameters of format() call: String msg = format(messageFormat, envelope.messageClass(), id);</technical_language>

Target:
private static IllegalStateException noDispatcherFound(MessageEnvelope envelope) { String id = Identifier.toString(envelope.id()); throw newIllegalStateException( "No dispatcher found for the command (class: `%s` id: `%s`).", envelope.messageClass(), id ); }
Source:
<code>void testResetBeforeStartingPerformsANormalRun() throws Exception { when(mockHandler.supportsReset()).thenReturn(true); final List<String> handled = new CopyOnWriteArrayList<>(); final List<String> handledInRedelivery = new CopyOnWriteArrayList<>(); doAnswer(i -> { EventMessage<?> message = i.getArgument(0); handled.add(message.getIdentifier()); if (ReplayToken.isReplay(message)) { handledInRedelivery.add(message.getIdentifier()); } return null; }).when(mockHandler).handle(any()); testSubject.resetTokens(); testSubject.start(); eventBus.publish(createEvents(4)); assertWithin(1, TimeUnit.SECONDS, () -> assertEquals(4, handled.size())); assertEquals(0, handledInRedelivery.size()); assertFalse(testSubject.processingStatus().get(0).isReplaying()); <START> assertTrue(testSubject.processingStatus().get(0).getReplayPosition().isPresent()); <END> assertFalse(testSubject.processingStatus().get(0).getResetTokenPosition().isPresent()); }</code><technical_language>getReplayPosition getResetTokenPosition return false this point, isReplaying is false too</technical_language>

Target:
void testResetBeforeStartingPerformsANormalRun() throws Exception { when(mockHandler.supportsReset()).thenReturn(true); final List<String> handled = new CopyOnWriteArrayList<>(); final List<String> handledInRedelivery = new CopyOnWriteArrayList<>(); doAnswer(i -> { EventMessage<?> message = i.getArgument(0); handled.add(message.getIdentifier()); if (ReplayToken.isReplay(message)) { handledInRedelivery.add(message.getIdentifier()); } return null; }).when(mockHandler).handle(any()); testSubject.resetTokens(); testSubject.start(); eventBus.publish(createEvents(4)); assertWithin(1, TimeUnit.SECONDS, () -> assertEquals(4, handled.size())); assertEquals(0, handledInRedelivery.size()); assertFalse(testSubject.processingStatus().get(0).isReplaying()); assertFalse(testSubject.processingStatus().get(0).getResetPosition().isPresent()); assertTrue(testSubject.processingStatus().get(0).getCurrentPosition().isPresent()); assertTrue(testSubject.processingStatus().get(0).getCurrentPosition().getAsLong() > 0); }
Source:
<code>public void testImageExtractionHandlesNullImageUris() { AmazonUnboxItem amazonUnboxItem = createAmazonUnboxItem("seasonAsin", ContentType.TVSEASON) .withLargeImageUrl(null) .build(); Series series = (Series) Iterables.getOnlyElement(extractor.extract(amazonUnboxItem)); assertEquals(0, series.getImages().size()); <START> AmazonUnboxItem amazonUnboxItem2 = <END> createAmazonUnboxItem("seasonAsin", ContentType.TVSEASON) .withLargeImageUrl("") .build(); Series series2 = (Series) Iterables.getOnlyElement(extractor.extract(amazonUnboxItem2)); assertEquals(0, series2.getImages().size()); }</code><technical_language>This a separate test. test testing thing</technical_language>

Target:
public void testImageExtractionHandlesNullImageUris() { AmazonUnboxItem amazonUnboxItem = createAmazonUnboxItem("seasonAsin", ContentType.TVSEASON) .withLargeImageUrl(null) .build(); Series series = (Series) Iterables.getOnlyElement(extractor.extract(amazonUnboxItem)); assertEquals(0, series.getImages().size()); }
Source:
<code>public void registerItemModels() { Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Config.itemRing, 0, new ModelResourceLocation(Baubles.MODID + ":ring", "inventory")); <START> ModelBakery.registerItemVariants(Config.itemRing, new ResourceLocation(Baubles.MODID + ":ring")); <END> }</code><technical_language>a new ResourceLocation(Baubles.MODID, "ring") constructor</technical_language>

Target:
public void registerItemModels() { ModelLoader.setCustomModelResourceLocation(Config.itemRing, 0, new ModelResourceLocation("baubles:Ring", "inventory")); }
Source:
<code>private Map<Address, List<Integer>> getMemberPartitions(Collection<Integer> partitions) { Map<Address, List<Integer>> memberPartitions = createHashMap(3); InternalPartitionService partitionService = nodeEngine.getPartitionService(); for (int partition : partitions) { Address owner = partitionService.getPartitionOwnerOrWait(partition); if (!memberPartitions.containsKey(owner)) { <START> memberPartitions.put(owner, new ArrayList<>()); <END> } memberPartitions.get(owner).add(partition); } return memberPartitions; }</code><technical_language>minor: put-if-absent-then-add idiom substituted more succinct memberPartitions.computeIfAbsent(owner, -> new ArrayList<>()).add(partition);</technical_language>

Target:
private Map<Address, List<Integer>> getMemberPartitions(Collection<Integer> partitions) { Map<Address, List<Integer>> memberPartitions = createHashMap(3); InternalPartitionService partitionService = nodeEngine.getPartitionService(); for (int partition : partitions) { Address owner = partitionService.getPartitionOwnerOrWait(partition); memberPartitions.computeIfAbsent(owner, k -> new ArrayList<>()).add(partition); } return memberPartitions; }
Source:
<code>private NQueens readSolution(String resource) throws IOException { <START> Path tempFile = Files.createTempFile("optaplanner-test", "xml"); <END> try (InputStreamReader inputStreamReader = new InputStreamReader(NQueensConstraintProviderTest.class.getResourceAsStream(resource))) { List<String> lines = IOUtils.readLines(inputStreamReader); Files.write(tempFile,lines); final SolutionFileIO<NQueens> solutionFileIO = new XStreamSolutionFileIO<>(NQueens.class); return solutionFileIO.read(tempFile.toFile()); } finally { Files.deleteIfExists(tempFile); } }</code><technical_language>a temporary file for reading test dataset</technical_language>

Target:
private static NQueens readSolution(String resource) throws IOException { try (InputStream inputStream = NQueensConstraintProviderTest.class.getResourceAsStream(resource)) { final XStreamSolutionFileIO<NQueens> solutionFileIO = new XStreamSolutionFileIO<>(NQueens.class); return solutionFileIO.read(inputStream); } }
Source:
<code>public Instance getInstance() { if (mock) return DeprecationUtil.makeMockInstance(instance); if (instance == null) { return HdfsZooInstance.getInstance(); } try { return getConnector().getInstance(); } catch (Exception e) { <START> throw new RuntimeException(e); <END> } }</code><technical_language>here, respect bad exception handling</technical_language>

Target:
public Instance getInstance() { if (instance == null) { return HdfsZooInstance.getInstance(); } try { return getConnector().getInstance(); } catch (AccumuloSecurityException | AccumuloException e) { throw new IllegalStateException(e); } }
Source:
<code>public static int getValue(String text) { <START> if (text == null || text.isEmpty() || text.equals("build")) { END> return BUILD; } if (text.equals("codan")) { return CODAN; } throw new IllegalArgumentException("Unknown context value: " + text); }</code><technical_language>Please remove isEmpty() check. Null check removed too, comparisons null-proof</technical_language>

Target:
public static int getValue(String text) { if ("build".equals(text)) { return BUILD; } if ("codan".equals(text)) { return CODAN; } throw new IllegalArgumentException("Unknown context value: " + text); }
Source:
<code>private void extractFile(File pdfFile, Appendable outFile) throws ParseException { PDDocument pdfDocument = null; try { pdfDocument = this.password == null ? PDDocument.load(pdfFile) : PDDocument.load(pdfFile, this.password); PageIterator pageIterator = getPageIterator(pdfDocument); List<Table> tables = new ArrayList<>(); while (pageIterator.hasNext()) { Page page = pageIterator.next(); if (pageAreas != null) { <START> for (Pair<Integer, Rectangle> areaPair : pageAreas) { <END> tables.addAll(tableExtractor.extractTables(page.getArea(areaPair.getRight(), areaPair.getLeft()))); } } else { tables.addAll(tableExtractor.extractTables(page)); } } writeTables(tables, outFile); } catch (IOException e) { throw new ParseException(e.getMessage()); } finally { try { if (pdfDocument != null) { pdfDocument.close(); } } catch (IOException e) { System.out.println("Error in closing pdf document" + e); } } }</code><technical_language>I here. access Page objects, do conversion this point</technical_language>

Target:
private void extractFile(File pdfFile, Appendable outFile) throws ParseException { PDDocument pdfDocument = null; try { pdfDocument = this.password == null ? PDDocument.load(pdfFile) : PDDocument.load(pdfFile, this.password); PageIterator pageIterator = getPageIterator(pdfDocument); List<Table> tables = new ArrayList<>(); while (pageIterator.hasNext()) { Page page = pageIterator.next(); if (pageAreas != null) { for (Pair<Integer, Rectangle> areaPair : pageAreas) { Rectangle area = areaPair.getRight(); if (areaPair.getLeft() == RELATIVE_AREA_CALCULATION_MODE) { area = new Rectangle((float) (area.getTop() / 100 * page.getHeight()), (float) (area.getLeft() / 100 * page.getWidth()), (float) (area.getWidth() / 100 * page.getWidth()), (float) (area.getHeight() / 100 * page.getHeight())); } tables.addAll(tableExtractor.extractTables(page.getArea(area))); } } else { tables.addAll(tableExtractor.extractTables(page)); } } writeTables(tables, outFile); } catch (IOException e) { throw new ParseException(e.getMessage()); } finally { try { if (pdfDocument != null) { pdfDocument.close(); } } catch (IOException e) { System.out.println("Error in closing pdf document" + e); } } }
Source:
<code>public Session handshake(String[] subProtocols, boolean allowExtensions) throws ProtocolException { WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketURL(httpRequest), getSubProtocolsStr(subProtocols), allowExtensions); <START> WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(httpRequest); <END> return handleHandshake(handshaker, 0); }</code><technical_language>newHandshaker sounds a noun a verb. methods represents actions a verb</technical_language>

Target:
public HandshakeFuture handshake(String[] subProtocols, boolean allowExtensions) { WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketURL(httpRequest), getSubProtocolsCSV(subProtocols), allowExtensions); WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(httpRequest); return handleHandshake(handshaker, 0); }
Source:
<code>public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { if (!canDeclare(owner)) return; for (BuildTriggerConfig config : configs) { <START> List<AbstractProject> projectList = Util.filter(config.getProjectList(owner.getParent(), null), AbstractProject.class); <END> for (AbstractProject project : projectList) ParameterizedDependency.add(owner, project, config, graph); } }</code><technical_language>expecting get Workflow jobs here? If so, I work</technical_language>

Target:
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { if (!canDeclare(owner)) return; for (BuildTriggerConfig config : configs) { List<AbstractProject> projectList = config.getProjectList(owner.getParent(), null); for (AbstractProject project : projectList) { ParameterizedDependency.add(owner, project, config, graph); } } }
Source:
<code><START> public void testGetTopLevelDataTypeWithName(){ <END> final String topLevelType = "tType"; final DataType dataType = mock(DataType.class); final Optional<DataType> type = Optional.of(dataType); doReturn(type).when(manager).findTopLevelDataTypeWithName(topLevelType); final DataType actual = manager.getTopLevelDataTypeWithName(topLevelType); assertEquals(dataType, actual); }</code><technical_language>formatting</technical_language>

Target:
public void testGetTopLevelDataTypeWithName() { final String topLevelType = "tType"; final DataType dataType = mock(DataType.class); final Optional<DataType> type = Optional.of(dataType); doReturn(type).when(manager).findTopLevelDataTypeWithName(topLevelType); final Optional<DataType> actual = manager.getTopLevelDataTypeWithName(topLevelType); assertTrue(actual.isPresent()); assertEquals(dataType, actual.get()); }
Source:
<code>public AxisAlignedBB getSelectedBoundingBox() { double x = tileEntity.getPos().getX(); double y = tileEntity.getPos().getY(); double z = tileEntity.getPos().getZ(); <START> return AxisAlignedBB.fromBounds(x, y, z, x + 1, y + 1, z + 1); <END> }</code><technical_language>Another AABBFactory candidate</technical_language>

Target:
public AxisAlignedBB getSelectedBoundingBox() { return AABBFactory.make().createBoxForTileAt(getPos()).build(); }
Source:
<code>public void open(OpenEvent event) { if (event !=null ) { ISelection selection = event.getSelection(); <START> if (selection !=null && selection instanceof TreeSelection ) { <END> TreeSelection treeSelection = (TreeSelection)selection; Object element = treeSelection.getFirstElement(); if (element !=null && element instanceof DslNode) { DslNode node = (DslNode)element; } } } }</code><technical_language>Redundant null check. if selection is null, selection is instanceof anything</technical_language>

Target:
public void open(OpenEvent event) { if (event !=null ) { ISelection selection = event.getSelection(); if (selection instanceof TreeSelection ) { TreeSelection treeSelection = (TreeSelection)selection; Object element = treeSelection.getFirstElement(); if (element instanceof DslNode) { DslNode node = (DslNode)element; ICProject project = node.getProject(); IFile file = project.getProject().getFile("CallHierarchy_test.java"); IWorkbenchPage page= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart().getSite().getPage(); IEditorInput input = new FileEditorInput(file); IEditorDescriptor desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(input.getName()); UIJob ui = new UIJob("Open File") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { try { String editorId = null; if (desc == null || desc.isOpenExternal()) { editorId = "org.eclipse.ui.DefaultTextEditor"; } else { editorId = desc.getId(); } IEditorPart editor = page.openEditor(input, editorId); IMarker fMarker = file.createMarker(IMarker.TEXT); HashMap<String, Object> map = new HashMap<String, Object>(); map.put(IMarker.LINE_NUMBER, 3); fMarker.setAttributes(map); IDE.gotoMarker(editor,fMarker); } catch (PartInitException e) { e.printStackTrace(); } catch (CoreException e) { e.printStackTrace(); } return new Status(IStatus.OK, CTestPlugin.PLUGIN_ID, ""); } }; ui.schedule(); } } } }
Source:
<code>public void assignPartitionKeys(Collection<Partition<AbstractSinglePortHDHTWriter<EVENT>>> partitions, InputPort<?> inputPort) { if (partitions.isEmpty()) { throw new IllegalArgumentException("partitions collection cannot be empty"); } <START> LOG.info("Totoal number of buckets = {}, Partitions = {}", numberOfBuckets, partitions.size()); <END> int partitionBits = (Integer.numberOfLeadingZeros(0) - Integer.numberOfLeadingZeros(numberOfBuckets - 1)); int partitionMask = 0; if (partitionBits > 0) { partitionMask = -1 >>> (Integer.numberOfLeadingZeros(-1)) - partitionBits; } Iterator<Partition<AbstractSinglePortHDHTWriter<EVENT>>> iterator = partitions.iterator(); for (int i = 0; i <= partitionMask; i++) { Partition<?> p; if (iterator.hasNext()) { p = iterator.next(); } else { iterator = partitions.iterator(); p = iterator.next(); } PartitionKeys pks = p.getPartitionKeys().get(inputPort); if (pks == null) { p.getPartitionKeys().put(inputPort, new PartitionKeys(partitionMask, Sets.newHashSet(i))); } else { pks.partitions.add(i); } } }</code><technical_language>typo</technical_language>

Target:
public void assignPartitionKeys(Collection<Partition<AbstractSinglePortHDHTWriter<EVENT>>> partitions, InputPort<?> inputPort) { if (partitions.isEmpty()) { throw new IllegalArgumentException("partitions collection cannot be empty"); } LOG.info("Total number of buckets = {}, Partitions = {}", numberOfBuckets, partitions.size()); int partitionMask = setPartitionMask(); Iterator<Partition<AbstractSinglePortHDHTWriter<EVENT>>> iterator = partitions.iterator(); for (int i = 0; i <= partitionMask; i++) { Partition<?> p; if (iterator.hasNext()) { p = iterator.next(); } else { iterator = partitions.iterator(); p = iterator.next(); } PartitionKeys pks = p.getPartitionKeys().get(inputPort); if (pks == null) { p.getPartitionKeys().put(inputPort, new PartitionKeys(partitionMask, Sets.newHashSet(i))); } else { pks.partitions.add(i); } } }
Source:
<code>public void uploadAvatar(String file) { File fileCheck = new File("." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ImagesForUploadTests" + File.separator + file); if (!fileCheck.isFile()) { try { throw new Exception("the file doesn't exist"); } catch (Exception e) { e.printStackTrace(); } } uplaodInput.sendKeys(fileCheck.getAbsoluteFile().toString()); <START> PageObjectLogging.log("typeInFileToUploadPath", "type file "+file+" to upload it", true, driver); <END> }</code><technical_language>speces "+" :)</technical_language>

Target:
public void uploadAvatar(String file) { File fileCheck = new File("." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ImagesForUploadTests" + File.separator + file); if (!fileCheck.isFile()) { try { throw new Exception("the file doesn't exist"); } catch (Exception e) { e.printStackTrace(); } } uploadInput.sendKeys(fileCheck.getAbsoluteFile().toString()); PageObjectLogging.log("typeInFileToUploadPath", "type file " + file + " to upload it", true, driver); }
Source:
<code>public void should_generate_yaml() throws Exception { RestxSpec testCase = restxSpecLoader.load( "restx/tests/restx_test_case_example_1.yaml"); String actual = testCase.toString(); System.out.println("actual = " + actual); <START> assertThat(replaceNewLine(actual)).isEqualTo(replaceNewLine(Resources.toString( <END> Resources.getResource("restx/tests/expected_restx_case_example_1.yaml"), Charsets.UTF_8))); }</code><technical_language>Is worth replacing new lines *both* sides ? (sounds useless is, I missing something)</technical_language>

Target:
public void should_generate_yaml() throws Exception { RestxSpec testCase = restxSpecLoader.load( "restx/tests/restx_test_case_example_1.yaml"); String actual = testCase.toString(); assertThat(actual).isEqualTo(Resources.toString( Resources.getResource("restx/tests/expected_restx_case_example_1.yaml"), Charsets.UTF_8)); }
Source:
<code>public void testENG16879() throws Exception { String ddl = "CREATE TABLE without_ttl migrate to target foo (i int NOT NULL, j FLOAT, ts TIMESTAMP);\n"; setup(ddl); try { m_client.callProcedure("@AdHoc", "MIGRATE FROM without_ttl WHERE NOT MIGRATING() \n" + "AND without_ttl.i < (SELECT MIN(i) FROM without_ttl \n" + <START> "WHERE FLOOR(without_ttl.j) <> without_ttl.j ORDER BY NULL, without_ttl.i);"); <END> } catch (ProcCallException e) { assertTrue(e.getMessage().contains("Expression is too complicated")); } finally { teardownSystem(); } }</code><technical_language>Need fail("Expected fail DML") calling AdHoc</technical_language>

Target:
public void testENG16879() throws Exception { String ddl = "CREATE TABLE without_ttl migrate to target foo (i int NOT NULL, j FLOAT, ts TIMESTAMP);\n"; setup(ddl); try { m_client.callProcedure("@AdHoc", "MIGRATE FROM without_ttl WHERE NOT MIGRATING() \n" + "AND without_ttl.i < (SELECT MIN(i) FROM without_ttl \n" + "WHERE FLOOR(without_ttl.j) <> without_ttl.j ORDER BY NULL, without_ttl.i);"); fail("Hsql parser should fail when parsing this sql query."); } catch (ProcCallException e) { assertTrue(e.getMessage().contains("Expression is too complicated")); } finally { teardownSystem(); } }
Source:
<code>void afterGroupNumChanged() { numberOfGroupsInput = numGroups.getText().toString().trim(); <START> boolean isInputValid = isInputValid(); <END> if (numGroups.isFocused() && isInputValid && autocomplete.isChecked()) { namesPerGroup.setText(getMatchingNumber(numberOfGroupsInput)); } dialog.getActionButton(DialogAction.POSITIVE).setEnabled(isInputValid); maybeShowUnevenGroupsWarning(); }</code><technical_language>feedback above. logic follows: 1. Parse out input 2. if autocomplete is turned act 3. Turn action button on/off</technical_language>

Target:
void afterGroupNumChanged() { String numberOfGroupsInput = numGroups.getText().toString().trim(); boolean isInputValid = isInputValid(numberOfGroupsInput); if (numGroups.isFocused() && isInputValid && autocomplete.isChecked()) { namesPerGroup.setText(getMatchingNumber(numberOfGroupsInput)); } dialog.getActionButton(DialogAction.POSITIVE).setEnabled(isInputValid); maybeShowUnevenGroupsWarning(); }
Source:
<code>public void reset() { size = 0; buckets = Math.min(tableArenaSize / bucketSize, INITIAL_BUCKETS); if (buckets < 1) { throw new IAE( "Not enough capacity for even one row! Need[%,d] but have[%,d].", bucketSize + Ints.BYTES, buffer.capacity() ); } maxSize = Math.max(1, (int) (buckets * MAX_LOAD_FACTOR)); for (int i = 0; i < buckets; i++) { buffer.put(i * bucketSize, (byte) 0); <START> } <END> final ByteBuffer bufferDup = buffer.duplicate(); bufferDup.position(0); bufferDup.limit(buckets * bucketSize); tableBuffer = bufferDup.slice(); tableStart = 0; keySerde.reset(); }</code><technical_language>consider allocating a x MB byte[] repeatedly call put(byte[]) method zero fill ByteBuffer? I faster fast enough initialize ByteBuffer "growing" avoided</technical_language>

Target:
public void reset() { size = 0; buckets = Math.min(tableArenaSize / bucketSize, initialBuckets); maxSize = maxSizeForBuckets(buckets); if (buckets < 1) { throw new IAE( "Not enough capacity for even one row! Need[%,d] but have[%,d].", bucketSize + Ints.BYTES, buffer.capacity() ); } tableStart = tableArenaSize - buckets * bucketSize; int nextBuckets = buckets * 2; while (true) { final int nextTableStart = tableStart - nextBuckets * bucketSize; if (nextTableStart > tableArenaSize / 2) { tableStart = nextTableStart; nextBuckets = nextBuckets * 2; } else { break; } } if (tableStart < tableArenaSize / 2) { tableStart = 0; } final ByteBuffer bufferDup = buffer.duplicate(); bufferDup.position(tableStart); bufferDup.limit(tableStart + buckets * bucketSize); tableBuffer = bufferDup.slice(); for (int i = 0; i < buckets; i++) { tableBuffer.put(i * bucketSize, (byte) 0); } keySerde.reset(); }
Source:
<code>private Supplier<StorageStatement> storeStatementSupplier( NeoStores neoStores ) { Supplier<IndexReaderFactory> indexReaderFactory = () -> new IndexReaderFactory.Caching( indexingService ); LockService lockService = takePropertyReadLocks ? this.lockService : NO_LOCK_SERVICE; return new Supplier<StorageStatement>() { @Override public StorageStatement get() { return new StoreStatement( neoStores, indexReaderFactory, labelScanStore::newReader, lockService, allocateCommandCreationContext() ); } <START> }; <END> }</code><technical_language>need expand lambda</technical_language>

Target:
private Supplier<StorageStatement> storeStatementSupplier( NeoStores neoStores ) { Supplier<IndexReaderFactory> indexReaderFactory = () -> new IndexReaderFactory.Caching( indexingService ); LockService lockService = takePropertyReadLocks ? this.lockService : NO_LOCK_SERVICE; return () -> new StoreStatement( neoStores, indexReaderFactory, labelScanStore::newReader, lockService, allocateCommandCreationContext() ); }
Source:
<code>private InternalCacheEntry<WrappedBytes, WrappedBytes> peekOrGet(WrappedBytes k, boolean peek) { int hashCode = k.hashCode(); int lockOffset = getLockOffset(hashCode); Lock lock = locks.getLockWithOffset(lockOffset).readLock(); lock.lock(); try { checkDeallocation(); InternalCacheEntry<WrappedBytes, WrappedBytes> value = lockedPeekOrGet(memoryLookup, k, hashCode, peek); if (value == null && oldMemoryLookup != null) { <START> value = lockedPeekOrGet(oldMemoryLookup, k, hashCode, peek); <END> } return value; } finally { lock.unlock(); } }</code><technical_language>cheaper check pendingBlocks do a single lookup</technical_language>

Target:
private InternalCacheEntry<WrappedBytes, WrappedBytes> peekOrGet(WrappedBytes k, boolean peek) { int hashCode = k.hashCode(); int lockOffset = getLockOffset(hashCode); Lock lock = locks.getLockWithOffset(lockOffset).readLock(); lock.lock(); try { checkDeallocation(); MemoryAddressHash memoryLookup; if (pendingBlocks != null && pendingBlocks.contains(lockOffset)) { memoryLookup = this.oldMemoryLookup; } else { memoryLookup = this.memoryLookup; } return lockedPeekOrGet(memoryLookup, k, hashCode, peek); } finally { lock.unlock(); } }
Source:
<code>public void testIncludeCipherEmpty() throws Exception { <START> String keyStorePath = new File(getResource("test.keystore").toURI()).getAbsolutePath(); <END> String keyStorePassword = "airlift"; HttpServerConfig config = new HttpServerConfig() .setHttpsEnabled(true) .setHttpsPort(0) .setKeystorePath(keyStorePath) .setKeystorePassword(keyStorePassword) .setHttpsIncludedCipherSuites(" , "); NodeInfo nodeInfo = new NodeInfo("test"); HttpServerInfo httpServerInfo = new HttpServerInfo(config, nodeInfo); HttpServer server = createServer(nodeInfo, httpServerInfo, config); try { server.start(); URI httpsUri = httpServerInfo.getHttpsUri(); HttpClient httpClient = createClient(new String[] {}, new String[] {"TLS_RSA_WITH_AES_128_CBC_SHA"}, keyStorePath, keyStorePassword); httpClient.GET(httpsUri); } finally { server.stop(); } }</code><technical_language>This is duplicated</technical_language>

Target:
public void testIncludeCipherEmpty() throws Exception { HttpServerConfig config = new HttpServerConfig() .setHttpsEnabled(true) .setHttpsPort(0) .setKeystorePath(KEY_STORE_PATH) .setKeystorePassword(KEY_STORE_PASSWORD) .setHttpsIncludedCipherSuites(" , "); NodeInfo nodeInfo = new NodeInfo("test"); HttpServerInfo httpServerInfo = new HttpServerInfo(config, nodeInfo); HttpServer server = createServer(nodeInfo, httpServerInfo, config); try { server.start(); URI httpsUri = httpServerInfo.getHttpsUri(); HttpClient httpClient = createClientIncludeCiphers(CIPHER_1); httpClient.GET(httpsUri); httpClient = createClientIncludeCiphers(CIPHER_2); httpClient.GET(httpsUri); httpClient = createClientIncludeCiphers(CIPHER_3); httpClient.GET(httpsUri); } finally { server.stop(); } }
Source:
<code>public Pointer convertToNumpy(INDArray array) { LongPointer size = new LongPointer(1); Pointer header = NativeOpsHolder .getInstance().getDeviceNativeOps() .numpyHeaderForNd4j( array.data().pointer(), array.shapeInfoDataBuffer().pointer(), array.data().getElementSize() ,size); header.capacity(size.get()); header.position(0); <START> BytePointer bytePointer = new BytePointer((int) (size.get() + (array.data().getElementSize() * array.data().length()))); <END> BytePointer headerCast = new BytePointer(header); int pos = 0; bytePointer.position(pos); Pointer.memcpy(bytePointer,headerCast,headerCast.capacity()); pos += (headerCast.capacity() - 1); bytePointer.position(pos); Nd4j.getAffinityManager().ensureLocation(array, AffinityManager.Location.HOST); Pointer.memcpy(bytePointer,array.data().pointer(),(array.data().getElementSize() * array.data().length())); bytePointer.position(0); return bytePointer; }</code><technical_language>looked numpy versios header changed</technical_language>

Target:
public Pointer convertToNumpy(INDArray array) { val size = new LongPointer(1); Pointer header = NativeOpsHolder .getInstance().getDeviceNativeOps() .numpyHeaderForNd4j( array.data().pointer(), array.shapeInfoDataBuffer().pointer(), array.data().getElementSize() ,size); val headerSize = size.get() - 1; header.capacity(headerSize); header.position(0); BytePointer bytePointer = new BytePointer((int) (headerSize + (array.data().getElementSize() * array.data().length()))); BytePointer headerCast = new BytePointer(header); val indexer = ByteIndexer.create(headerCast); int pos = 0; bytePointer.position(pos); Pointer.memcpy(bytePointer, headerCast,headerCast.capacity()); pos += (headerCast.capacity()); bytePointer.position(pos); Nd4j.getAffinityManager().ensureLocation(array, AffinityManager.Location.HOST); Pointer.memcpy(bytePointer,array.data().pointer(),(array.data().getElementSize() * array.data().length())); bytePointer.position(0); return bytePointer; }