auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void initializeGrid() { int xx = FRAME_THICKNESS; for (int x = 0; x < GRID_WIDTH; x++) { int yy = FRAME_THICKNESS; for (int y = 0; y < GRID_WIDTH; y++) { Cell cell = new Cell(0); cell.setCellLocation(xx, yy); grid[x][y] = cell; yy += FRAME_THICKNESS + Cell.getCellWidth(); } xx += FRAME_THICKNESS + Cell.getCellWidth(); } }

Target:
public void initializeGrid() { int frameThicknessX = FRAME_THICKNESS; for (int i = 0; i < GRID_WIDTH; i++) { int frameThicknessY = FRAME_THICKNESS; for (int j = 0; j < GRID_WIDTH; j++) { Cell cell = new Cell(0); cell.setCellLocation(frameThicknessX, frameThicknessY); grid[i][j] = cell; frameThicknessY += FRAME_THICKNESS + Cell.getCellWidth(); } frameThicknessX += FRAME_THICKNESS + Cell.getCellWidth(); } }
Source:
public void associateNeighborStateNotifier(P unwindingContext, BlockPos sourcePos, Block block, BlockPos notifyPos, WorldServer minecraftWorld, PlayerTracker.Type notifier) { final Player player = unwindingContext.getSpongePlayer(); unwindingContext.getOwner().ifPresent(owner -> ((IMixinChunk) minecraftWorld.getChunkFromBlockCoords(notifyPos)).setBlockCreator(notifyPos, owner.getUniqueId())); ((IMixinChunk) minecraftWorld.getChunkFromBlockCoords(notifyPos)).setBlockNotifier(notifyPos, player.getUniqueId()); }

Target:
public void associateNeighborStateNotifier(P unwindingContext, BlockPos sourcePos, Block block, BlockPos notifyPos, WorldServer minecraftWorld, PlayerTracker.Type notifier) { final Player player = unwindingContext.getSpongePlayer(); Chunk chunk = minecraftWorld.getChunkFromBlockCoords(notifyPos); ((IMixinChunk) chunk).setBlockCreator(notifyPos, player.getUniqueId()); ((IMixinChunk) chunk).setBlockNotifier(notifyPos, player.getUniqueId()); }
Source:
private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { List<Message> listAmqpMessages = convertAMQPValueMessageToBrokeredMessage(amqpMessage); List<ServiceBusReceivedMessage> receivedMessageList = new ArrayList<>(); for (Message oneAmqpMessage:listAmqpMessages ) { ServiceBusReceivedMessage serviceBusReceivedMessage = deserializeMessage(oneAmqpMessage); receivedMessageList.add(serviceBusReceivedMessage); } return receivedMessageList; }

Target:
private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { List<Message> listAmqpMessages = convertAmqpValueMessageToBrokeredMessage(amqpMessage); List<ServiceBusReceivedMessage> receivedMessageList = new ArrayList<>(); for (Message oneAmqpMessage:listAmqpMessages) { ServiceBusReceivedMessage serviceBusReceivedMessage = deserializeMessage(oneAmqpMessage); receivedMessageList.add(serviceBusReceivedMessage); } return receivedMessageList; }
Source:
public void playerDamageEvent(EntityDamageEvent event) { if (!(event.getEntity().getType() == EntityType.PLAYER)) return; Player p = (Player) event.getEntity(); if (BetterShardsPlugin.getTransitManager().isPlayerInTransit(p.getUniqueId())) { event.setCancelled(true); } }

Target:
public void playerDamageEvent(EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) { return; } Player p = (Player) event.getEntity(); if (BetterShardsPlugin.getTransitManager().isPlayerInTransit(p.getUniqueId())) { event.setCancelled(true); } }
Source:
public Ipx800Binding() { logger.debug("Ipx800Binding created"); }

Target:
public Ipx800Binding() { }
Source:
private void sendRequest(String addUrl, String query) throws IOException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/xml;charset=" + charset); OutputStream output = null; try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } InputStream response = connection.getInputStream(); if (response != null) { StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = response.read(bytes)) != -1) { sb.append(new String(bytes, 0, len)); } } }

Target:
private void sendRequest(String addUrl, String query) throws IOException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/xml;charset=" + charset); OutputStream output = null; try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { output.close(); } } InputStream response = connection.getInputStream(); if (response != null) { StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = response.read(bytes)) != -1) { sb.append(new String(bytes, 0, len)); } } }
Source:
private IProxyService retrieveProxyService() { final String CORE_NET_BUNDLE = "org.eclipse.core.net"; Bundle bundle = Platform.getBundle(CORE_NET_BUNDLE); while (bundle.getState() != Bundle.ACTIVE) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } ServiceReference ref = bundle.getBundleContext().getServiceReference(IProxyService.class.getName()); if (ref != null) { return (IProxyService) bundle.getBundleContext().getService(ref); } return null; }

Target:
private IProxyService retrieveProxyService() { final String CORE_NET_BUNDLE = "org.eclipse.core.net"; Bundle bundle = Platform.getBundle(CORE_NET_BUNDLE); ServiceReference ref = bundle.getBundleContext().getServiceReference(IProxyService.class.getName()); if (ref != null) { IProxyService proxyService = (IProxyService) bundle.getBundleContext().getService(ref); proxyService.setProxiesEnabled(true); proxyService.setSystemProxiesEnabled(false); return proxyService; } return null; }
Source:
public boolean cleanupManagedDisks(VirtualMachine virtualMachine) { Map<String, URI> deleteJobs = new HashMap<String, URI>(); OSDisk osDisk = virtualMachine.properties().storageProfile().osDisk(); deleteManagedDisk(osDisk.managedDiskParameters(), deleteJobs); for (DataDisk dataDisk : virtualMachine.properties().storageProfile().dataDisks()) { deleteManagedDisk(dataDisk.managedDiskParameters(), deleteJobs); } Set<String> nonDeletedDisks = filterValues(deleteJobs, not(resourceDeleted)).keySet(); if (!nonDeletedDisks.isEmpty()) { logger.warn(">> could not deleteVault disks: %s", Joiner.on(',').join(nonDeletedDisks)); } return nonDeletedDisks.isEmpty(); }

Target:
public boolean cleanupManagedDisks(VirtualMachine virtualMachine) { Map<String, URI> deleteJobs = new HashMap<String, URI>(); OSDisk osDisk = virtualMachine.properties().storageProfile().osDisk(); deleteManagedDisk(osDisk.managedDiskParameters(), deleteJobs); for (DataDisk dataDisk : virtualMachine.properties().storageProfile().dataDisks()) { deleteManagedDisk(dataDisk.managedDiskParameters(), deleteJobs); } Set<String> nonDeletedDisks = filterValues(deleteJobs, not(resourceDeleted)).keySet(); if (!nonDeletedDisks.isEmpty()) { logger.warn(">> could not delete disks: %s", Joiner.on(',').join(nonDeletedDisks)); } return nonDeletedDisks.isEmpty(); }
Source:
private void executeAndCheckSplitPart(int fieldNumber) throws SQLException { int count = 0; String sCell1 = null; String sCell2 = null; ResultSet rs; rs = methodWatcher.executeQuery(String.format("select split_part(e, ' ', %d), e from ", fieldNumber) + tableWatcherB); count = 0; while (rs.next()) { sCell1 = rs.getString(1); sCell2 = rs.getString(2); String splitExpected; if (sCell2 != null) { String sCell2Parts[] = sCell2.split("\\s"); if (fieldNumber > sCell2Parts.length) { splitExpected = null; } else { splitExpected = sCell2Parts[fieldNumber - 1]; } } else { splitExpected = null; } Assert.assertEquals("Wrong result value", sCell1, splitExpected); count++; } Assert.assertEquals("Incorrect row count", 5, count); }

Target:
private void executeAndCheckSplitPart(int fieldNumber) throws SQLException { int count = 0; String sCell1 = null; String sCell2 = null; ResultSet rs; rs = methodWatcher.executeQuery(String.format("select split_part(e, ' ', %d), e from %s", fieldNumber, tableWatcherB)); count = 0; while (rs.next()) { sCell1 = rs.getString(1); sCell2 = rs.getString(2); String splitExpected; if (sCell2 != null) { String sCell2Parts[] = sCell2.split("\\s"); if (fieldNumber > sCell2Parts.length) { splitExpected = null; } else { splitExpected = sCell2Parts[fieldNumber - 1]; } } else { splitExpected = null; } Assert.assertEquals("Wrong result value", sCell1, splitExpected); count++; } Assert.assertEquals("Incorrect row count", 5, count); }
Source:
public ConceptMapMappings evaluate(CodeSystemURI uri, BranchContext context, Options search) { final String preferredDisplay = search.get(OptionKey.DISPLAY, String.class); SnomedDisplayTermType snomedDisplayTermType; try { snomedDisplayTermType = SnomedDisplayTermType.valueOf(preferredDisplay); } catch(Exception e) { snomedDisplayTermType = SnomedDisplayTermType.PT; } SnomedReferenceSetMembers referenceSetMembers = fetchRefsetMembers(uri, context, search, snomedDisplayTermType); return toCollectionResource(referenceSetMembers, uri, context, search, snomedDisplayTermType); }

Target:
public ConceptMapMappings evaluate(CodeSystemURI uri, BranchContext context, Options search) { final String preferredDisplay = search.get(OptionKey.DISPLAY, String.class); final SnomedDisplayTermType snomedDisplayTermType = SnomedDisplayTermType.getEnum(preferredDisplay); SnomedReferenceSetMembers referenceSetMembers = fetchRefsetMembers(uri, context, search, snomedDisplayTermType); return toCollectionResource(referenceSetMembers, uri, context, search, snomedDisplayTermType); }
Source:
@Override public void close(boolean cancel) throws CacheException { try { closeEx(cancel); closedStreamer = true; } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } }

Target:
@Override public void close(boolean cancel) throws CacheException { try { closeEx(cancel); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } }
Source:
public void setup() throws IOException { geometry = GeoFunctions.toSphericalGeography(GeoFunctions.stGeometryFromText(Slices.utf8Slice(loadPolygon("large_polygon.txt")))); geometry500k = GeoFunctions.toSphericalGeography(GeoFunctions.stGeometryFromText(Slices.utf8Slice(createPolygon(9.0, 500000)))); }

Target:
public void setup() throws IOException { geometry = stGeometryFromText(utf8Slice(loadPolygon("large_polygon.txt"))); geometry500k = stGeometryFromText(utf8Slice(createPolygon(500000))); geography = toSphericalGeography(geometry); geography500k = toSphericalGeography(geometry500k); }
Source:
private void startPassiveScanIfNeeded() { LogManager.d(TAG, "Checking to see if we need to start a passive scan"); boolean insideAnyRegion = false; List<Region> regions = new ArrayList<>(mScanState.getMonitoringStatus().regions()); for (Region region : regions) { RegionMonitoringState state = mScanState.getMonitoringStatus().stateOf(region); if (state != null && state.getInside()) { insideAnyRegion = true; } } if (insideAnyRegion) { } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { mScanHelper.startAndroidOBackgroundScan(mScanState.getBeaconParsers()); } else { LogManager.d(TAG, "This is not Android O. No scanning between cycles when using ScanJob"); } }

Target:
private void startPassiveScanIfNeeded() { LogManager.d(TAG, "Checking to see if we need to start a passive scan"); boolean insideAnyRegion = false; List<Region> regions = new ArrayList<>(mScanState.getMonitoringStatus().regions()); for (Region region : regions) { RegionMonitoringState state = mScanState.getMonitoringStatus().stateOf(region); if (state != null && state.getInside()) { insideAnyRegion = true; } } if (insideAnyRegion && mScanState.getRangedRegionState().size() == 0) { LogManager.i(TAG, "We are inside a beacon region. We will not scan between cycles."); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { mScanHelper.startAndroidOBackgroundScan(mScanState.getBeaconParsers()); } else { LogManager.d(TAG, "This is not Android O. No scanning between cycles when using ScanJob"); } } }
Source:
private boolean processNextEvent(LineTcpMeasurementEvent event) { Parser parser = parserCache.get(event.getTableName()); if (null == parser) { parser = new Parser(); try { parser.processFirstEvent(engine, securityContext, event); } catch (CairoException ex) { LOG.info().$(name).$(" could not create parser [name=").$(event.getTableName()).$(", ex=").$(ex.getFlyweightMessage()).$(']').$(); parser.close(); return false; } LOG.info().$(name).$(" created parser [name=").$(event.getTableName()).$(']').$(); parserCache.put(Chars.toString(event.getTableName()).toString(), parser); return true; } else { parser.processEvent(event); return true; } }

Target:
private boolean processNextEvent(LineTcpMeasurementEvent event) { Parser parser = parserCache.get(event.getTableName()); if (null == parser) { parser = new Parser(); try { parser.processFirstEvent(engine, securityContext, event); } catch (CairoException ex) { LOG.info().$("could not create parser [jobName=").$(jobName).$(" name=").$(event.getTableName()).$(", ex=").$(ex.getFlyweightMessage()).$(']').$(); parser.close(); return false; } LOG.info().$("created parser [jobName=").$(jobName).$(" name=").$(event.getTableName()).$(']').$(); parserCache.put(Chars.toString(event.getTableName()), parser); } else { parser.processEvent(event); } return true; }
Source:
private int getTimeMultiplier() { int mult; switch(refitClass) { case NO_CHANGE: mult = 0; break; case CLASS_C: mult = 2; break; case CLASS_D: mult = 3; break; case CLASS_E: mult = 4; break; case CLASS_F: mult = 5; break; case CLASS_A: case CLASS_B: default: mult = 1; } if(customJob) { mult *= 2; } return mult; }

Target:
private int getTimeMultiplier() { int mult; switch(refitClass) { case NO_CHANGE: mult = 0; break; case CLASS_C: mult = 2; break; case CLASS_D: mult = 3; break; case CLASS_E: mult = 4; break; case CLASS_F: mult = 5; break; case CLASS_A: case CLASS_B: default: mult = 1; break; } if (customJob) { mult *= 2; } return mult; }
Source:
public void test_setControl() { int number = 5; TabItem[] items = new TabItem[number]; final Button setControlButton = new Button (tabFolder, SWT.None); setControlButton.setText ("test button"); for (int i = 0; i < number; i++) { items[i] = new TabItem(tabFolder, 0); items[i].setControl (setControlButton); assertEquals (items[i].getControl (), setControlButton); } assertEquals (items[number-1].getControl (), setControlButton); }

Target:
public void test_setControl() { int number = 5; TabItem[] items = new TabItem[number]; final Button setControlButton = new Button (tabFolder, SWT.None); setControlButton.setText ("test button"); for (int i = 0; i < number; i++) { items[i] = new TabItem(tabFolder, 0); items[i].setControl (setControlButton); assertEquals (items[i].getControl (), setControlButton); assertTrue(setControlButton.getVisible()); } items[0].setControl (setControlButton); assertEquals (items[0].getControl (), setControlButton); assertTrue(setControlButton.getVisible()); }
Source:
public boolean hasUpdates() { synchronized (m_updates) { if (m_updates.booleanValue()) { return true; } } return false; }

Target:
public boolean hasUpdates() { return m_updates.get(); }
Source:
private Optional<PingableLeader> getSuspectedLeaderOverNetwork(String uuid) { PaxosResponsesWithRemote<PingableLeader, PaxosString> responses = PaxosQuorumChecker.collectUntil( ImmutableList.copyOf(leaderPingExecutors.keySet()), pingableLeader -> new PaxosString(pingableLeader.getUUID()), leaderPingExecutors, Duration.ofMillis(leaderPingResponseWaitMs), state -> state.responses().values().stream().map(PaxosString::get).anyMatch(uuid::equals)); for (Map.Entry<PingableLeader, PaxosString> cacheEntry : responses.responses().entrySet()) { String uuidFromRequest = cacheEntry.getValue().get(); PingableLeader service = uuidToServiceCache.putIfAbsent(uuidFromRequest, cacheEntry.getKey()); throwIfInvalidSetup(service, cacheEntry.getKey(), uuidFromRequest); if (uuid.equals(uuidFromRequest)) { return Optional.of(cacheEntry.getKey()); } } return Optional.empty(); }

Target:
private Optional<PingableLeader> getSuspectedLeaderOverNetwork(String uuid) { PaxosResponsesWithRemote<PingableLeader, PaxosString> responses = PaxosQuorumChecker.collectUntil( otherPingables, pingableLeader -> new PaxosString(pingableLeader.getUUID()), leaderPingExecutors, Duration.ofMillis(leaderPingResponseWaitMs), state -> state.responses().values().stream().map(PaxosString::get).anyMatch(uuid::equals)); for (Map.Entry<PingableLeader, PaxosString> cacheEntry : responses.responses().entrySet()) { String uuidFromRequest = cacheEntry.getValue().get(); PingableLeader service = uuidToServiceCache.putIfAbsent(uuidFromRequest, cacheEntry.getKey()); throwIfInvalidSetup(service, cacheEntry.getKey(), uuidFromRequest); if (uuid.equals(uuidFromRequest)) { return Optional.of(cacheEntry.getKey()); } } return Optional.empty(); }
Source:
public <T extends Enum<?>> T getEnum(final T[] all, final String section, final String subsection, final String name, final T defaultValue) { String value = getString(section, subsection, name); if (value == null) return defaultValue; String n = value.replace(' ', '_'); T trueState = null; T falseState = null; for (T e : all) { if (StringUtils.equalsIgnoreCase(e.name(), n)) return e; else if (StringUtils.equalsIgnoreCase(e.toString(), n)) return e; else if (StringUtils.equalsIgnoreCase(e.name(), "TRUE")) trueState = e; else if (StringUtils.equalsIgnoreCase(e.name(), "FALSE")) falseState = e; } if (trueState != null && falseState != null) { try { return StringUtils.toBoolean(n) ? trueState : falseState; } catch (IllegalArgumentException err) { } } if (subsection != null) throw new IllegalArgumentException(MessageFormat.format(JGitText .get().enumValueNotSupported3, section, name, value)); else throw new IllegalArgumentException(MessageFormat.format(JGitText .get().enumValueNotSupported2, section, name, value)); }

Target:
public <T extends Enum<?>> T getEnum(final T[] all, final String section, final String subsection, final String name, final T defaultValue) { String value = getString(section, subsection, name); if (value == null) return defaultValue; if (defaultValue instanceof FastForwardMode) { return (T) FastForwardMode.valueOf(section, subsection, name, value); } String n = value.replace(' ', '_'); T trueState = null; T falseState = null; for (T e : all) { if (StringUtils.equalsIgnoreCase(e.name(), n)) return e; else if (StringUtils.equalsIgnoreCase(e.toString(), n)) return e; else if (StringUtils.equalsIgnoreCase(e.name(), "TRUE")) trueState = e; else if (StringUtils.equalsIgnoreCase(e.name(), "FALSE")) falseState = e; } if (trueState != null && falseState != null) { try { return StringUtils.toBoolean(n) ? trueState : falseState; } catch (IllegalArgumentException err) { } } if (subsection != null) throw new IllegalArgumentException(MessageFormat.format(JGitText .get().enumValueNotSupported3, section, subsection, name, value)); else throw new IllegalArgumentException(MessageFormat.format(JGitText .get().enumValueNotSupported2, section, name, value)); }
Source:
private OafRel createOafRelObject() { return OafRel.newBuilder().setSource(SOURCE_ID).setTarget(TARGET_ID) .setRelType(irrelevantType).setSubRelType(irrelevantSubtype) .setRelClass("irrelevantRelClass").setChild(false) .build(); }

Target:
private static OafRel createOafRelObject() { return OafRel.newBuilder().setSource(SOURCE_ID).setTarget(TARGET_ID) .setRelType(RelType.resultResult).setSubRelType(SubRelType.provision) .setRelClass("irrelevantRelClass").setChild(false) .build(); }
Source:
public void withdrawFromStudyRemovesDataGroups() { account.setConsentSignatureHistory(SUBPOP_GUID, ImmutableList.of(CONSENT_SIGNATURE)); account.setDataGroups(new HashSet<>(TestConstants.USER_DATA_GROUPS)); when(subpopulation.getDataGroupsAssignedWhileConsented()).thenReturn(TestConstants.USER_DATA_GROUPS); when(subpopService.getSubpopulation(study.getStudyIdentifier(), SUBPOP_GUID)).thenReturn(subpopulation); when(accountDao.getAccount(any())).thenReturn(account); consentService.withdrawFromStudy(study, PARTICIPANT, WITHDRAWAL, WITHDREW_ON); assertTrue(account.getDataGroups().isEmpty()); verify(subpopulation).getDataGroupsAssignedWhileConsented(); verify(subpopulation, never()).getSubstudyIdsAssignedOnConsent(); }

Target:
public void withdrawFromStudyRemovesDataGroups() { account.setConsentSignatureHistory(SUBPOP_GUID, ImmutableList.of(CONSENT_SIGNATURE)); Set<String> dataGroups = new HashSet<>(TestConstants.USER_DATA_GROUPS); dataGroups.add("remainingDataGroup1"); dataGroups.add("remainingDataGroup2"); account.setDataGroups(dataGroups); when(subpopulation.getDataGroupsAssignedWhileConsented()).thenReturn(TestConstants.USER_DATA_GROUPS); when(subpopService.getSubpopulation(study.getStudyIdentifier(), SUBPOP_GUID)).thenReturn(subpopulation); when(accountDao.getAccount(any())).thenReturn(account); consentService.withdrawFromStudy(study, PARTICIPANT, WITHDRAWAL, WITHDREW_ON); assertEquals(ImmutableSet.of("remainingDataGroup1", "remainingDataGroup2"), account.getDataGroups()); verify(subpopulation).getDataGroupsAssignedWhileConsented(); verify(subpopulation, never()).getSubstudyIdsAssignedOnConsent(); }
Source:
public CompletableFuture<KubernetesWorkerNode> requestResource(TaskExecutorProcessSpec taskExecutorProcessSpec) { final KubernetesTaskManagerParameters parameters = createKubernetesTaskManagerParameters(taskExecutorProcessSpec); final KubernetesPod taskManagerPod = KubernetesTaskManagerFactory.buildTaskManagerKubernetesPod(parameters); final String podName = taskManagerPod.getName(); final CompletableFuture<KubernetesWorkerNode> requestResourceFuture = new CompletableFuture<>(); requestResourceFutures.put(podName, requestResourceFuture); log.info("Creating new TaskManager pod with name and resource <{},{}>.", podName, parameters.getTaskManagerMemoryMB(), parameters.getTaskManagerCPU()); final CompletableFuture<Void> createPodFuture = podCreationCoolDown.thenCompose((ignore) -> kubeClient .map(client -> client.createTaskManagerPod(taskManagerPod)) .orElse(CompletableFuture.completedFuture(null))); FutureUtils.assertNoException( createPodFuture.handleAsync((ignore, exception) -> { if (exception != null) { log.warn("Could not create pod {}, exception: {}", podName, exception); tryResetPodCreationCoolDown(); CompletableFuture<KubernetesWorkerNode> future = requestResourceFutures.remove(taskManagerPod.getName()); if (future != null) { future.completeExceptionally(exception); } } else { log.info("Pod is created.", podName); } return null; }, getMainThreadExecutor())); return requestResourceFuture; }

Target:
public CompletableFuture<KubernetesWorkerNode> requestResource(TaskExecutorProcessSpec taskExecutorProcessSpec) { final KubernetesTaskManagerParameters parameters = createKubernetesTaskManagerParameters(taskExecutorProcessSpec); final KubernetesPod taskManagerPod = KubernetesTaskManagerFactory.buildTaskManagerKubernetesPod(parameters); final String podName = taskManagerPod.getName(); final CompletableFuture<KubernetesWorkerNode> requestResourceFuture = new CompletableFuture<>(); requestResourceFutures.put(podName, requestResourceFuture); log.info("Creating new TaskManager pod with name and resource <{},{}>.", podName, parameters.getTaskManagerMemoryMB(), parameters.getTaskManagerCPU()); final CompletableFuture<Void> createPodFuture = podCreationCoolDown.thenCompose((ignore) -> getKubeClient().createTaskManagerPod(taskManagerPod)); FutureUtils.assertNoException( createPodFuture.handleAsync((ignore, exception) -> { if (exception != null) { log.warn("Could not create pod {}, exception: {}", podName, exception); tryResetPodCreationCoolDown(); CompletableFuture<KubernetesWorkerNode> future = requestResourceFutures.remove(taskManagerPod.getName()); if (future != null) { future.completeExceptionally(exception); } } else { log.info("Pod is created.", podName); } return null; }, getMainThreadExecutor())); return requestResourceFuture; }
Source:
private void resolveIdentityInsertDelayable() { canIdentityInsertBeDelayed = true; if ( getEntityMetamodel().getIdentifierProperty().isIdentifierAssignedByInsert() ) { for ( NonIdentifierAttribute attribute : getEntityMetamodel().getProperties() ) { final Type attributeType = attribute.getType(); if ( attributeType.isAssociationType() ) { if ( attributeType.isEntityType() ) { Class<?> entityClass = attributeType.getReturnedClass(); if ( getMappedClass().equals( entityClass ) ) { canIdentityInsertBeDelayed = false; } } else if ( attributeType.isCollectionType() ) { final CollectionType collection = (CollectionType) attributeType; final CollectionPersister collectionPersister = getFactory().getMetamodel().collectionPersister( collection.getRole() ); if ( collectionPersister.isInverse() ) { final EntityPersister entityPersister = collectionPersister.getOwnerEntityPersister(); if ( collectionPersister.getOwnerEntityPersister().equals( this ) ) { final QueryableCollection queryableCollection = (QueryableCollection) collectionPersister; final IdentifierGenerator identifierGenerator = queryableCollection.getElementPersister().getIdentifierGenerator(); if ( ( identifierGenerator instanceof ForeignGenerator ) || ( identifierGenerator instanceof SequenceStyleGenerator ) ) { canIdentityInsertBeDelayed = false; } } } } } } } }

Target:
private void resolveIdentityInsertDelayable() { canIdentityInsertBeDelayed = true; if ( getEntityMetamodel().getIdentifierProperty().isIdentifierAssignedByInsert() ) { for ( NonIdentifierAttribute attribute : getEntityMetamodel().getProperties() ) { if ( isTypeSelfReferencing( attribute.getType() ) ) { canIdentityInsertBeDelayed = false; } } } }
Source:
public void testConvert() throws Exception { LjubesicPandzicStemmer stemmer = new LjubesicPandzicStemmer(); assert stemmer.stemWord("abdominalni").equals("abdominaln"); assert stemmer.stemWord("абдоминалне").equals("abdominaln"); assert stemmer.stemWord("zabave").equals("zabav"); assert stemmer.stemWord("забавама").equals("zabav"); assert stemmer.stemWord("Ћаф").equals("Ćaf"); assert stemmer.stemWord("жућкастосмеђим").equals("žućkastosmeđ"); assert stemmer.stemWord("јужночешком").equals("južnočešk"); assert stemmer.stemWord("ђуричковић").equals("đuričković"); assert stemmer.stemWord("βικιπαίδεια").equals("βικιπαίδεια"); assert stemmer.stemWord("ვიკიპედია").equals("ვიკიპედია"); assert stemmer.stemWord("위키백과").equals("위키백과"); }

Target:
public void testConvert() throws Exception { LjubesicPandzicStemmer stemmer = new LjubesicPandzicStemmer(); assertEquals(stemmer.stemWord("abdominalni"), "abdominaln"); assertEquals(stemmer.stemWord("абдоминалне"), "abdominaln"); assertEquals(stemmer.stemWord("zabave"), "zabav"); assertEquals(stemmer.stemWord("забавама"), "zabav"); assertEquals(stemmer.stemWord("Ћаф"), "Ćaf"); assertEquals(stemmer.stemWord("жућкастосмеђим"), "žućkastosmeđ"); assertEquals(stemmer.stemWord("јужночешком"), "južnočešk"); assertEquals(stemmer.stemWord("ђуричковић"), "đuričković"); assertEquals(stemmer.stemWord("βικιπαίδεια"), "βικιπαίδεια"); assertEquals(stemmer.stemWord("ვიკიპედია"), "ვიკიპედია"); assertEquals(stemmer.stemWord("위키백과"), "위키백과"); }
Source:
public void visitToken(DetailAST ast) { final DetailAST whitespaceFollowedAst = getWhitespaceFollowedNode(ast); if (!ignoreWhitespaceAfter(whitespaceFollowedAst)) { final int whitespaceColumnNo = getPositionAfter(whitespaceFollowedAst); final int whitespaceLineNo = whitespaceFollowedAst.getLineNo(); if (hasTrailingWhitespace(ast, whitespaceColumnNo, whitespaceLineNo)) { log(ast, MSG_KEY, whitespaceFollowedAst.getText()); } } }

Target:
public void visitToken(DetailAST ast) { final DetailAST whitespaceFollowedAst = getWhitespaceFollowedNode(ast); if (shouldCheckWhitespaceAfter(whitespaceFollowedAst)) { final int whitespaceColumnNo = getPositionAfter(whitespaceFollowedAst); final int whitespaceLineNo = whitespaceFollowedAst.getLineNo(); if (hasTrailingWhitespace(ast, whitespaceColumnNo, whitespaceLineNo)) { log(ast, MSG_KEY, whitespaceFollowedAst.getText()); } } }
Source:
public static CopyState create(@Nullable Package targetPackage, Progress progress) { return new AutoValue_CopyState( targetPackage, progress, newArrayList(), newHashMap(), newHashMap(), newHashMap(), newHashMap(), newHashMap()); }

Target:
public static CopyState create(@Nullable Package targetPackage, Progress progress) { return new CopyState(targetPackage, progress); }
Source:
protected VdcReturnValueBase connectStorage() { VdcReturnValueBase result = null; String connectionId = getStorageDomain().getStorage(); StorageServerConnections connection = getStorageServerConnectionDAO().get(connectionId); result = Backend.getInstance().runInternalAction(VdcActionType.ConnectStorageToVds, new StorageServerConnectionParametersBase(connection, getParameters().getVdsId())); return result; }

Target:
protected Pair<Boolean, Integer> connectStorage() { String connectionId = getStorageDomain().getStorage(); StorageServerConnections connection = getStorageServerConnectionDAO().get(connectionId); java.util.HashMap<String, String> result = (java.util.HashMap<String, String>) runVdsCommand( VDSCommandType.ConnectStorageServer, new StorageServerConnectionManagementVDSParameters(getParameters().getVdsId(), Guid.Empty, connection.getstorage_type(), new java.util.ArrayList<StorageServerConnections>(java.util.Arrays .asList(new StorageServerConnections[] { connection })))) .getReturnValue(); return new Pair<Boolean, Integer>(StorageHelperDirector.getInstance() .getItem(connection.getstorage_type()) .isConnectSucceeded(result, Arrays.asList(connection)), Integer.parseInt(result.values().iterator().next())); }
Source:
public boolean hasNext() { if (buf == null) { request(1); buf = take(); } if (buf.isOnError()) { throw Exceptions.propagate(buf.getThrowable()); } return !buf.isOnCompleted(); }

Target:
public boolean hasNext() { if (buf == null) { buf = take(); received++; if (received >= LIMIT) { request(received); received = 0; } } if (buf.isOnError()) { throw Exceptions.propagate(buf.getThrowable()); } return !buf.isOnCompleted(); }
Source:
public static void main(String[] args) throws Exception { DotNetAPIGenerator dnapi = new DotNetAPIGenerator("../zap-api-dotnet/src/OWASPZAPDotNetAPI/OWASPZAPDotNetAPI/Generated", true); dnapi.generateCSharpFiles(ApiGeneratorUtils.getAllImplementors()); }

Target:
public static void main(String[] args) throws Exception { DotNetAPIGenerator dnapi = new DotNetAPIGenerator("../zap-api-dotnet/src/OWASPZAPDotNetAPI/OWASPZAPDotNetAPI/Generated", false); dnapi.generateCSharpFiles(ApiGeneratorUtils.getAllImplementors()); }
Source:
public ScriptEntryData getScriptEntryData() { return new BukkitScriptEntryData(event != null ? EntityTag.getPlayerFrom(event.getPlayer()) : null, null); }

Target:
public ScriptEntryData getScriptEntryData() { return new BukkitScriptEntryData(EntityTag.getPlayerFrom(event.getPlayer()), null); }
Source:
private void finishInternal() { if (m_leasedThread.get() != null) { return; } if (!isDone()) { return; } if (!m_finished.compareAndSet(false, true)) { return; } finished(); }

Target:
private void finishInternal() { if (m_leasedThread != null) { return; } if (!isDone()) { return; } if (!m_finished.compareAndSet(false, true)) { return; } finished(); }
Source:
public DictionaryConnection openConnection(DataCleanerConfiguration configuration) { final SortedSet<String> connectionValueSet = new TreeSet<>(Comparator.comparingInt(String::length).reversed().thenComparing(String::compareTo)); connectionValueSet.addAll(_valueSet); return new DictionaryConnection() { SortedSet<String> _values = connectionValueSet; @Override public Iterator<String> getAllValues() { return _values.iterator(); } @Override public boolean containsValue(String value) { if (value == null) { return false; } if (!_caseSensitive) { value = value.toLowerCase(); } return _values.contains(value); } @Override public void close() { } }; }

Target:
public DictionaryConnection openConnection(DataCleanerConfiguration configuration) { return new DictionaryConnection() { @Override public Iterator<String> getAllValues() { return _valueSet.iterator(); } @Override public Iterator<String> getLengthSortedValues() { final SortedSet<String> connectionValueSet = new TreeSet<>(Comparator.comparingInt(String::length).reversed().thenComparing(String::compareTo)); connectionValueSet.addAll(_valueSet); return connectionValueSet.iterator(); } @Override public boolean containsValue(String value) { if (value == null) { return false; } if (!_caseSensitive) { value = value.toLowerCase(); } return _valueSet.contains(value); } @Override public void close() { } }; }
Source:
Mono<PollResponse<PhoneNumberSearch>>> createSearchPollOperation() { return pollingContext -> getSearchById(pollingContext.getActivationResponse().getValue().getSearchId()) .flatMap(getSearchResponse -> { if (getSearchResponse.getStatus().equals(SearchStatus.SUCCESS)) { return Mono.just(new PollResponse<>( LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, getSearchResponse)); } if (getSearchResponse.getStatus().equals(SearchStatus.EXPIRED)) { return Mono.just(new PollResponse<>( LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, getSearchResponse)); } if (getSearchResponse.getStatus().equals(SearchStatus.CANCELLED)) { return Mono.just(new PollResponse<>( LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, getSearchResponse)); } if (getSearchResponse.getStatus().equals(SearchStatus.RESERVED)) { return Mono.just(new PollResponse<>( LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, getSearchResponse)); } if (getSearchResponse.getStatus().equals(SearchStatus.ERROR)) { return Mono.just(new PollResponse<>( LongRunningOperationStatus.FAILED, getSearchResponse)); } return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, getSearchResponse)); }); }

Target:
createSearchPollOperation() { return pollingContext -> getSearchById(pollingContext.getLatestResponse().getValue().getSearchId()) .flatMap(getSearchResponse -> { SearchStatus status = getSearchResponse.getStatus(); if (status.equals(SearchStatus.EXPIRED) || status.equals(SearchStatus.CANCELLED) || status.equals(SearchStatus.RESERVED)) { return Mono.just(new PollResponse<>( LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, getSearchResponse)); } if (status.equals(SearchStatus.ERROR)) { return Mono.just(new PollResponse<>( LongRunningOperationStatus.FAILED, getSearchResponse)); } return Mono.just(new PollResponse<>(LongRunningOperationStatus.IN_PROGRESS, getSearchResponse)); }); }
Source:
public long addUnknownDevice(String uniqueId) { Device device = new Device(); String defaultGroupName = Context.getConfig().getString("database.registerUnknown.defaultGroup", "NOTDEFINED"); device.setName(uniqueId); device.setUniqueId(uniqueId); device.setCategory(Context.getConfig().getString("database.registerUnknown.defaultCategory", "default")); if (!defaultGroupName.equals("NOTDEFINED")) { Group defaultGroup = Context.getDeviceManager().getGroupByName(defaultGroupName); if (defaultGroup != null) { device.setGroupId(defaultGroup.getId()); } } try { Context.getDeviceManager().addDevice(device); Log.info("Automatically registered device " + uniqueId); return device.getId(); } catch (SQLException e) { Log.warning(e); return 0; } }

Target:
public long addUnknownDevice(String uniqueId) { Device device = new Device(); device.setName(uniqueId); device.setUniqueId(uniqueId); device.setCategory(Context.getConfig().getString("database.registerUnknown.defaultCategory")); long defaultGroupId = Context.getConfig().getLong("database.registerUnknown.defaultGroupId"); if (defaultGroupId != 0) { device.setGroupId(defaultGroupId); } try { Context.getDeviceManager().addDevice(device); Log.info("Automatically registered device " + uniqueId); return device.getId(); } catch (SQLException e) { Log.warning(e); return 0; } }
Source:
private IFile findBuildFile(IContainer parent) { String[] names = AntUtil.getKnownBuildfileNames(); if (names == null) { return null; } IContainer lparent = parent; IResource file = null; while (file == null || file.getType() != IResource.FILE) { for (String string : names) { file = lparent.findMember(string); if (file != null && file.getType() == IResource.FILE) { break; } } lparent = lparent.getParent(); if (lparent == null) { return null; } } return (IFile) file; }

Target:
private IFile findBuildFile(IContainer parent) { String[] names = AntUtil.getKnownBuildfileNames(); if (names == null) { return null; } IContainer lparent = parent; IResource file = null; while (file == null || file.getType() != IResource.FILE) { for (String name : names) { file = lparent.findMember(name); if (file != null && file.getType() == IResource.FILE) { break; } } lparent = lparent.getParent(); if (lparent == null) { return null; } } return (IFile) file; }
Source:
public void removeAddress(LinkAddress address) throws IOException { try { mService.removeAddressFromTunnelInterface(mResourceId, address); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } }

Target:
public void removeAddress(LinkAddress address) { try { mService.removeAddressFromTunnelInterface(mResourceId, address); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } }
Source:
private void removeListeners() { if (restoreToSavePointListener != null) { restoreToSavePointListener.unregister(); restoreToSavePointListener.dispose(); restoreToSavePointListener = null; } if (this.saveSessionListener != null) { this.saveSessionListener.unregister(); this.saveSessionListener = null; } }

Target:
private void removeListeners() { if (restoreToSavePointListener != null) { restoreToSavePointListener.dispose(); restoreToSavePointListener = null; } if (this.saveSessionListener != null) { this.saveSessionListener.unregister(); this.saveSessionListener = null; } }
Source:
private void fillInUnsetIpConfigs() { getParameters().getNetworkAttachments().stream().forEach(networkAttachment -> { if (networkAttachment.getIpConfiguration() == null) { IpConfiguration ipConfiguration = NetworkUtils.createDefaultIpConfiguration(); networkAttachment.setIpConfiguration(ipConfiguration); } }); }

Target:
private void fillInUnsetIpConfigs() { getParameters().getNetworkAttachments() .stream() .filter(attachment -> attachment.getIpConfiguration() == null) .forEach(attachment -> attachment.setIpConfiguration(NetworkUtils.createDefaultIpConfiguration())); }
Source:
public Subscriber<? super T> call(Subscriber<? super T> child) { final SerializedSubscriber<T> s = new SerializedSubscriber<T>(child); final AtomicReference<Object> value = new AtomicReference<Object>(EMPTY_TOKEN); final AtomicReference<Subscription> main = new AtomicReference<Subscription>(); final Subscriber<U> samplerSub = new Subscriber<U>() { @Override public void onNext(U t) { Object localValue = value.getAndSet(EMPTY_TOKEN); if (localValue != EMPTY_TOKEN) { @SuppressWarnings("unchecked") T v = (T)localValue; s.onNext(v); } } @Override public void onError(Throwable e) { main.get().unsubscribe(); s.onError(e); } @Override public void onCompleted() { main.get().unsubscribe(); s.onCompleted(); } }; Subscriber<T> result = new Subscriber<T>() { @Override public void onNext(T t) { value.set(t); } @Override public void onError(Throwable e) { samplerSub.unsubscribe(); s.onError(e); } @Override public void onCompleted() { samplerSub.unsubscribe(); s.onCompleted(); } }; main.lazySet(result); child.add(result); child.add(samplerSub); sampler.unsafeSubscribe(samplerSub); return result; }

Target:
public Subscriber<? super T> call(Subscriber<? super T> child) { final SerializedSubscriber<T> s = new SerializedSubscriber<T>(child); final AtomicReference<Object> value = new AtomicReference<Object>(EMPTY_TOKEN); final AtomicReference<Subscription> main = new AtomicReference<Subscription>(); final Subscriber<U> samplerSub = new Subscriber<U>() { @Override public void onNext(U t) { Object localValue = value.getAndSet(EMPTY_TOKEN); if (localValue != EMPTY_TOKEN) { @SuppressWarnings("unchecked") T v = (T)localValue; s.onNext(v); } } @Override public void onError(Throwable e) { s.onError(e); main.get().unsubscribe(); } @Override public void onCompleted() { s.onCompleted(); main.get().unsubscribe(); } }; Subscriber<T> result = new Subscriber<T>() { @Override public void onNext(T t) { value.set(t); } @Override public void onError(Throwable e) { s.onError(e); samplerSub.unsubscribe(); } @Override public void onCompleted() { s.onCompleted(); samplerSub.unsubscribe(); } }; main.lazySet(result); child.add(result); child.add(samplerSub); sampler.unsafeSubscribe(samplerSub); return result; }
Source:
public Journal getPublicationJournal(Article article) { String eissn = article.geteIssn(); Journal journal = null; if (eissn == null) { log.warn("eIssn not set for article"); } else { journal = (Journal) DataAccessUtils.uniqueResult((List<?>) hibernateTemplate.findByCriteria(journalCriteria().add(Restrictions.eq("eIssn", eissn)))); if (journal == null) { String msg = "XML contained eIssn that was not matched to a journal: " + eissn; throw new RestClientException(msg, HttpStatus.BAD_REQUEST); } } return journal; }

Target:
public Journal getPublicationJournal(Article article) { String eissn = article.geteIssn(); if (eissn == null) { String msg = "eIssn not set for article: " + article.getDoi(); throw new RestClientException(msg, HttpStatus.BAD_REQUEST); } else { Journal journal = (Journal) DataAccessUtils.uniqueResult((List<?>) hibernateTemplate.findByCriteria(journalCriteria().add(Restrictions.eq("eIssn", eissn)))); if (journal == null) { String msg = "XML contained eIssn that was not matched to a journal: " + eissn; throw new RestClientException(msg, HttpStatus.BAD_REQUEST); } return journal; } }
Source:
protected ReferencedEnvelope getBoundsInternal(Query query) throws IOException { Filter f = query.getFilter(); if (f != null && f.equals(Filter.INCLUDE)) { try { return new ReferencedEnvelope( CRS.transform(mbtiles.loadMetaData().getBounds(), DEFAULT_CRS)); } catch (TransformException e) { throw new RuntimeException("Unable to retrieve bounds from mbtiles metadata", e); } } else { return null; } }

Target:
protected ReferencedEnvelope getBoundsInternal(Query query) throws IOException { Filter f = query.getFilter(); if (f == null || f.equals(Filter.INCLUDE)) { try { return new ReferencedEnvelope( CRS.transform(mbtiles.loadMetaData().getBounds(), DEFAULT_CRS)); } catch (TransformException e) { throw new RuntimeException("Unable to retrieve bounds from mbtiles metadata", e); } } else { return null; } }
Source:
private void reconstructMasterDomainNotInSync(final Guid storagePoolId, final Guid masterDomainId, final String exceptionMessage, final String logMessage) { ((EventQueue) EjbUtils.findBean(BeanType.EVENTQUEUE_MANAGER, BeanProxyType.LOCAL)).submitEventSync(new Event(_storagePoolId, masterDomainId, EventType.RECONSTRUCT), new Callable<EventResult>() { @Override public EventResult call() { EventResult result = null; log.warnFormat(logMessage); AuditLogableBase logable = new AuditLogableBase(mCurrentVdsId); logable.setStorageDomainId(masterDomainId); AuditLogDirector.log(logable, AuditLogType.SYSTEM_MASTER_DOMAIN_NOT_IN_SYNC); result = ResourceManager.getInstance() .getEventListener() .masterDomainNotOperational(masterDomainId, storagePoolId); return result; } }); throw new IRSNoMasterDomainException(exceptionMessage); }

Target:
private void reconstructMasterDomainNotInSync(final Guid storagePoolId, final Guid masterDomainId, final String exceptionMessage, final String logMessage) { ((EventQueue) EjbUtils.findBean(BeanType.EVENTQUEUE_MANAGER, BeanProxyType.LOCAL)).submitEventSync(new Event(_storagePoolId, masterDomainId, null, EventType.RECONSTRUCT), new Callable<EventResult>() { @Override public EventResult call() { EventResult result = null; log.warnFormat(logMessage); AuditLogableBase logable = new AuditLogableBase(mCurrentVdsId); logable.setStorageDomainId(masterDomainId); AuditLogDirector.log(logable, AuditLogType.SYSTEM_MASTER_DOMAIN_NOT_IN_SYNC); result = ResourceManager.getInstance() .getEventListener() .masterDomainNotOperational(masterDomainId, storagePoolId); return result; } }); throw new IRSNoMasterDomainException(exceptionMessage); }
Source:
public FunctionSignatureProto getProto() { FunctionSignatureProto.Builder builder = FunctionSignatureProto.newBuilder(); builder.setType(functionType); builder.setName(name); List inputList = new ArrayList<>(); inputList.addAll(Arrays.asList(paramTypes)); builder.addAllParameterTypes(inputList); builder.setReturnType(returnType); return builder.build(); }

Target:
public FunctionSignatureProto getProto() { FunctionSignatureProto.Builder builder = FunctionSignatureProto.newBuilder(); builder.setType(functionType); builder.setName(name); builder.addAllParameterTypes(Arrays.asList(paramTypes)); builder.setReturnType(returnType); return builder.build(); }
Source:
private Object[] _reqForTemplate(JSONObject m, ArrayList<String> flds, JSONObject t) { ArrayList<String> a = new ArrayList<>(); ArrayList<String> b = new ArrayList<>(); for (String f : flds) { a.add("ankiflag"); b.add(""); } Object[] data; Long mid = m.getLong("id"); int ord = t.getInt("ord"); String packedFields = Utils.joinFields(a.toArray(new String[a.size()])); data = new Object[] {1L, 1L, mid, 1L, ord, "", packedFields, 0}; String full = mCol._renderQA(data).get("q"); packedFields = Utils.joinFields(b.toArray(new String[b.size()])); data = new Object[] {1L, 1L, mid, 1L, ord, "", packedFields, 0}; String empty = mCol._renderQA(data).get("q"); if (full.equals(empty)) { return new Object[] { "none", new JSONArray(), new JSONArray() }; } String type = "all"; JSONArray req = new JSONArray(); ArrayList<String> tmp = new ArrayList<>(); for (int i = 0; i < flds.size(); i++) { tmp.clear(); tmp.addAll(a); tmp.set(i, ""); data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()])); if (!mCol._renderQA(data).get("q").contains("ankiflag")) { req.put(i); } } if (req.length() > 0) { return new Object[] { type, req }; } type = "any"; req = new JSONArray(); for (int i = 0; i < flds.size(); i++) { tmp.clear(); tmp.addAll(b); tmp.set(i, "1"); data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()])); if (!mCol._renderQA(data).get("q").equals(empty)) { req.put(i); } } return new Object[] { type, req }; }

Target:
private Object[] _reqForTemplate(JSONObject m, ArrayList<String> flds, JSONObject t) { int nbFields = flds.size(); String[] a = new String[nbFields]; String[] b = new String[nbFields]; Arrays.fill(a, "ankiflag"); Arrays.fill(b, ""); Long mid = m.getLong("id"); int ord = t.getInt("ord"); String full = mCol._renderQA(1L, mid, 1L, ord, "", a, 0).get("q"); String empty = mCol._renderQA(1L, mid, 1L, ord, "", b, 0).get("q"); if (full.equals(empty)) { return new Object[] { "none", new JSONArray(), new JSONArray() }; } String type = "all"; JSONArray req = new JSONArray(); for (int i = 0; i < flds.size(); i++) { a[i] = ""; if (!mCol._renderQA(1L, mid, 1L, ord, "", a, 0).get("q").contains("ankiflag")) { req.put(i); } a[i] = "ankiflag"; } if (req.length() > 0) { return new Object[] { type, req }; } type = "any"; req = new JSONArray(); for (int i = 0; i < flds.size(); i++) { b[i] = "1"; if (!mCol._renderQA(1L, mid, 1L, ord, "", b, 0).get("q").equals(empty)) { req.put(i); } b[i] = ""; } return new Object[] { type, req }; }