auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Node tryToLookupNode(NodeSource nodeSource, int lookUpTimeout, String nodeUrl) { Node node; try { logger.info("Trying to lookup a node to recover: " + nodeUrl); node = nodeSource.lookupNode(nodeUrl, lookUpTimeout); } catch (Exception e) { logger.warn("Node to recover could not be looked up at URL: " + nodeUrl); node = null; } return node; }

Target:
private Node tryToLookupNode(NodeSource nodeSource, int lookUpTimeout, String nodeUrl) { Node node = null; try { logger.info("Trying to lookup node to recover: " + nodeUrl); node = nodeSource.lookupNode(nodeUrl, lookUpTimeout); } catch (Exception e) { logger.warn("Node to recover could not be looked up"); } return node; }
Source:
private JoinEnumerationResult setJoinNodeProperties(JoinNode joinNode) { if (isAtMostScalar(joinNode.getRight(), lookup)) { return createJoinEnumerationResult(joinNode.withDistributionType(REPLICATED)); } if (isAtMostScalar(joinNode.getLeft(), lookup)) { return createJoinEnumerationResult(joinNode.flipChildren().withDistributionType(REPLICATED)); } List<JoinEnumerationResult> possibleJoinNodes = new ArrayList<>(); FeaturesConfig.JoinDistributionType joinDistributionType = getJoinDistributionType(session); if (joinDistributionType.canRepartition() && !joinNode.isCrossJoin()) { possibleJoinNodes.add(createJoinEnumerationResult(joinNode.withDistributionType(PARTITIONED))); possibleJoinNodes.add(createJoinEnumerationResult(joinNode.flipChildren().withDistributionType(PARTITIONED))); } if (joinDistributionType.canReplicate()) { possibleJoinNodes.add(createJoinEnumerationResult(joinNode.withDistributionType(REPLICATED))); possibleJoinNodes.add(createJoinEnumerationResult(joinNode.flipChildren().withDistributionType(REPLICATED))); } if (possibleJoinNodes.stream().anyMatch(UNKNOWN_COST_RESULT::equals)) { return UNKNOWN_COST_RESULT; } return resultComparator.min(possibleJoinNodes); }

Target:
private JoinEnumerationResult setJoinNodeProperties(JoinNode joinNode) { if (isAtMostScalar(joinNode.getRight(), lookup)) { return createJoinEnumerationResult(joinNode.withDistributionType(REPLICATED)); } if (isAtMostScalar(joinNode.getLeft(), lookup)) { return createJoinEnumerationResult(joinNode.flipChildren().withDistributionType(REPLICATED)); } List<JoinEnumerationResult> possibleJoinNodes = new ArrayList<>(); JoinDistributionType joinDistributionType = getJoinDistributionType(session); if (joinDistributionType.canRepartition() && !joinNode.isCrossJoin()) { possibleJoinNodes.add(createJoinEnumerationResult(joinNode.withDistributionType(PARTITIONED))); possibleJoinNodes.add(createJoinEnumerationResult(joinNode.flipChildren().withDistributionType(PARTITIONED))); } if (joinDistributionType.canReplicate()) { possibleJoinNodes.add(createJoinEnumerationResult(joinNode.withDistributionType(REPLICATED))); possibleJoinNodes.add(createJoinEnumerationResult(joinNode.flipChildren().withDistributionType(REPLICATED))); } if (possibleJoinNodes.stream().anyMatch(UNKNOWN_COST_RESULT::equals)) { return UNKNOWN_COST_RESULT; } return resultComparator.min(possibleJoinNodes); }
Source:
public Mono<AmqpReceiveLink> createReceiveLink(String linkName, String entityPath, ReceiveMode receiveMode, String transferEntityPath, MessagingEntityType entityType) { return createReceiveLink(linkName, entityPath, receiveMode, null, transferEntityPath, entityType); }

Target:
public Mono<AmqpReceiveLink> createReceiveLink(String linkName, String entityPath, ReceiveMode receiveMode, String transferEntityPath, MessagingEntityType entityType) { return createSession(entityPath).cast(ServiceBusSession.class) .flatMap(session -> { logger.verbose("Get or create consumer for path: '{}'", entityPath); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(retryOptions); return session.createConsumer(linkName, entityPath, entityType, retryOptions.getTryTimeout(), retryPolicy, receiveMode); }); }
Source:
public void stop() { scheduledExec.shutdownNow(); scheduledExec = null; }

Target:
public void stop() { if (!lifecycleLock.canStop()) { throw new ISE("can't stop."); } log.info("MetadataSegmentView is stopping."); if (isCacheEnabled) { scheduledExec.shutdown(); } log.info("MetadataSegmentView Stopped."); }
Source:
public long deleteHorizonMs() { return loadFullBatch().deleteHorizonMs(); }

Target:
public long deleteHorizonMs() { return RecordBatch.NO_TIMESTAMP; }
Source:
private Map<String, Object> getTaskCompletionRowStats() { Map<String, Object> metrics = Maps.newHashMap(); if (rowIngestionMeters != null) { metrics.put( "buildSegments", rowIngestionMeters.getTotals() ); } return metrics; }

Target:
private Map<String, Object> getTaskCompletionRowStats() { Map<String, Object> metrics = Maps.newHashMap(); metrics.put( RowIngestionMeters.BUILD_SEGMENTS, rowIngestionMeters.getTotals() ); return metrics; }
Source:
public void doNotDeactivateWithoutWritePermissions() throws InvalidIpForApiKeyException, ApiKeyNotFoundException, RevokedApiKeyException, IOException { ApplicationConfiguration configuration = ApplicationConfiguration.defaultConfiguration(); when(configurationFetcher.configurationFor(request)).thenReturn(Maybe.just(configuration)); when(request.getParameter("source")).thenReturn("upcoming.radiotimes.com"); when(request.getParameter("valid_uris")).thenReturn("uri1,uri2,uri3"); controller.unpublishContent(request, response); ArgumentCaptor<AtlasErrorSummary> argument = ArgumentCaptor.forClass( AtlasErrorSummary.class ); verify(modelWriter, atLeast(2)) .writeError(eq(request), eq(response), argument.capture()); assertEquals("403", argument.getValue().statusCode().toString()); assertEquals("API key does not have write permission", argument.getValue().message() ); }

Target:
public void doNotDeactivateWithoutWritePermissions() throws InvalidIpForApiKeyException, ApiKeyNotFoundException, RevokedApiKeyException, IOException { ApplicationConfiguration configuration = ApplicationConfiguration.defaultConfiguration(); when(configurationFetcher.configurationFor(request)).thenReturn(Maybe.just(configuration)); when(request.getParameter("source")).thenReturn("upcoming.radiotimes.com"); when(request.getParameter("valid_uris")).thenReturn("uri1,uri2,uri3"); controller.unpublishContent(request, response); ArgumentCaptor<AtlasErrorSummary> argument = ArgumentCaptor.forClass( AtlasErrorSummary.class ); verify(modelWriter).writeError(eq(request), eq(response), argument.capture()); assertThat("403", is(argument.getValue().statusCode().toString())); assertThat("API key does not have write permission", is(argument.getValue().message()) ); }
Source:
protected void configure() { bind(CacheDeleteHandler.class); bind(CapabilityDefinition.class) .annotatedWith(Exports.named(DELETE_PROJECT)) .to(DeleteProjectCapability.class); bind(DatabaseDeleteHandler.class) .to(registerDatabaseHandler()); bind(FilesystemDeleteHandler.class); install(new RestApiModule() { @Override protected void configure() { delete(PROJECT_KIND) .to(DeleteProject.class); post(PROJECT_KIND) .to(DeleteProject.class); } }); }

Target:
protected void configure() { bind(CacheDeleteHandler.class); bind(CapabilityDefinition.class) .annotatedWith(Exports.named(DELETE_PROJECT)) .to(DeleteProjectCapability.class); bind(DatabaseDeleteHandler.class) .to(registerDatabaseHandler()); bind(FilesystemDeleteHandler.class); install(new RestApiModule() { @Override protected void configure() { delete(PROJECT_KIND) .to(DeleteProject.class); post(PROJECT_KIND, "delete") .to(DeleteProject.class); } }); }
Source:
private ListView.OnItemClickListener getNavDrawerClickListener() { return new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { drawerLayout.closeDrawer(navDrawerList); switch(drawerItemsShowing[position].id) { case SYNC_DRAWER_ITEM_ID: activity.sendFormsOrSync(true); break; case SAVED_FORMS_ITEM_ID: activity.goToFormArchive(false); break; case UPDATE_DRAWER_ITEM_ID: activity.launchUpdateActivity(); break; case ABOUT_CC_DRAWER_ITEM_ID: activity.showAboutCommCareDialog(); break; case SETTINGS_DRAWER_ITEM_ID: activity.createPreferencesMenu(activity); break; case ADVANCED_DRAWER_ITEM_ID: activity.startAdvancedActionsActivity(); break; case CHANGE_LANGUAGE_DRAWER_ITEM_ID: activity.showLocaleChangeMenu(null); break; case LOGOUT_DRAWER_ITEM_ID: activity.userTriggeredLogout(); break; } } }; }

Target:
private ListView.OnItemClickListener getNavDrawerClickListener() { return new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { drawerLayout.closeDrawer(navDrawerList); switch(drawerItemsShowing[position].id) { case SYNC_DRAWER_ITEM_ID: activity.sendFormsOrSync(true); break; case SAVED_FORMS_ITEM_ID: activity.goToFormArchive(false); break; case UPDATE_DRAWER_ITEM_ID: activity.launchUpdateActivity(); break; case ABOUT_CC_DRAWER_ITEM_ID: activity.showAboutCommCareDialog(); break; case SETTINGS_DRAWER_ITEM_ID: HomeScreenBaseActivity.createPreferencesMenu(activity); break; case ADVANCED_DRAWER_ITEM_ID: activity.startAdvancedActionsActivity(); break; case CHANGE_LANGUAGE_DRAWER_ITEM_ID: activity.showLocaleChangeMenu(null); break; case LOGOUT_DRAWER_ITEM_ID: activity.userTriggeredLogout(); break; } } }; }
Source:
private String getIssue(String filename) throws IOException, InterruptedException { String issueId = ""; Path path = Paths.get(filename); if(Files.notExists(path)){ return null; } try (BufferedReader br = Files.newBufferedReader(path)) { String issue; while ((issue = br.readLine()) != null) { issueId = issue; } return issueId.trim().length() > 0 ? issueId : null; } catch (FileNotFoundException e) { return null; } }

Target:
private String getIssue(String filename) throws IOException, InterruptedException { String issueId = ""; Path path = Paths.get(filename); if(Files.notExists(path)){ return null; } try (BufferedReader br = Files.newBufferedReader(path)) { String issue; while ((issue = br.readLine()) != null) { issueId = issue; } return StringUtils.trimToNull(issueId); } catch (FileNotFoundException e) { return null; } }
Source:
private void addCommonModelAttributesAndValidate(HttpServletRequest request, Model model, @SiteParam Site site, @RequestParam("id") String articleId) throws IOException { Map<?, ?> articleMetadata = requestArticleMetadata(articleId); validateArticleVisibility(site, articleMetadata); addCrossPublishedJournals(request, model, site, articleMetadata); model.addAttribute("article", articleMetadata); model.addAttribute("containingLists", getContainingArticleLists(articleId, site)); model.addAttribute("categoryTerms", getCategoryTerms(articleMetadata)); requestAuthors(model, articleId); }

Target:
private Map<?, ?> addCommonModelAttributesAndValidate(HttpServletRequest request, Model model, @SiteParam Site site, @RequestParam("id") String articleId) throws IOException { Map<?, ?> articleMetadata = requestArticleMetadata(articleId); validateArticleVisibility(site, articleMetadata); addCrossPublishedJournals(request, model, site, articleMetadata); model.addAttribute("article", articleMetadata); model.addAttribute("containingLists", getContainingArticleLists(articleId, site)); model.addAttribute("categoryTerms", getCategoryTerms(articleMetadata)); requestAuthors(model, articleId); return articleMetadata; }
Source:
public void init() { if (!initialized) { final ByteBuffer buffer = bufferSupplier.get().duplicate(); final int usedBufferEnd = getUserBufferCapacity(cardinalityWithMissingValue); buffer.position(0); buffer.limit(usedBufferEnd); usedFlagBuffer = buffer.slice(); buffer.position(usedBufferEnd); buffer.limit(buffer.capacity()); valBuffer = buffer.slice(); reset(); initialized = true; } }

Target:
public void init() { if (!initialized) { final ByteBuffer buffer = bufferSupplier.get(); final int usedFlagBufferEnd = getUsedFlagBufferCapacity(cardinalityWithMissingValue); buffer.position(0); buffer.limit(usedFlagBufferEnd); usedFlagBuffer = buffer.slice(); buffer.position(usedFlagBufferEnd); buffer.limit(buffer.capacity()); valBuffer = buffer.slice(); reset(); initialized = true; } }
Source:
private void addSiblingNode(int indexOfNode) { synchronized (latestBranch) { final long splitTime = treeEnd; assert (indexOfNode < latestBranch.size()); if (indexOfNode == 0) { addNewRootNode(); return; } if (((CoreNode) latestBranch.get(indexOfNode - 1)).getNbChildren() == config.getMaxChildren()) { addSiblingNode(indexOfNode - 1); return; } for (int i = indexOfNode; i < latestBranch.size(); i++) { latestBranch.get(i).closeThisNode(splitTime); treeIO.writeNode(latestBranch.get(i)); CoreNode prevNode = (CoreNode) latestBranch.get(i - 1); HTNode newNode; switch (latestBranch.get(i).getNodeType()) { case CORE: newNode = initNewCoreNode(prevNode.getSequenceNumber(), splitTime + 1); break; case LEAF: newNode = initNewLeafNode(prevNode.getSequenceNumber(), splitTime + 1); break; default: throw new IllegalStateException(); } prevNode.linkNewChild(newNode); latestBranch.set(i, newNode); } } }

Target:
private void addSiblingNode(int indexOfNode) { synchronized (latestBranch) { final long splitTime = treeEnd; if (indexOfNode >= latestBranch.size()) { throw new IllegalStateException(); } if (indexOfNode == 0) { addNewRootNode(); return; } if (((CoreNode) latestBranch.get(indexOfNode - 1)).getNbChildren() == config.getMaxChildren()) { addSiblingNode(indexOfNode - 1); return; } for (int i = indexOfNode; i < latestBranch.size(); i++) { latestBranch.get(i).closeThisNode(splitTime); treeIO.writeNode(latestBranch.get(i)); CoreNode prevNode = (CoreNode) latestBranch.get(i - 1); HTNode newNode; switch (latestBranch.get(i).getNodeType()) { case CORE: newNode = initNewCoreNode(prevNode.getSequenceNumber(), splitTime + 1); break; case LEAF: newNode = initNewLeafNode(prevNode.getSequenceNumber(), splitTime + 1); break; default: throw new IllegalStateException(); } prevNode.linkNewChild(newNode); latestBranch.set(i, newNode); } } }
Source:
public ExternalIdPConfig getIdPConfigByName(String idpName, String tenantDomain) { ExternalIdPConfig externalIdPConfig = null; IdentityProvider idpDO = null; if (log.isDebugEnabled()) { log.debug("Trying to find the IdP for name: " + idpName); } try { IdentityProviderManager idpManager = IdentityProviderManager.getInstance(); idpDO = idpManager.getEnabledIdPByName(idpName, tenantDomain); if (idpDO != null) { if (log.isDebugEnabled()) { log.debug("A registered IdP was found"); } externalIdPConfig = new ExternalIdPConfig(idpDO); } else { if (log.isDebugEnabled()) { log.debug("A registered IdP was not found the given name"); } } } catch (IdentityProviderManagementException e) { log.error("Exception while getting IdP by name", e); } return externalIdPConfig; }

Target:
public ExternalIdPConfig getIdPConfigByName(String idpName, String tenantDomain) throws IdentityProviderManagementException { ExternalIdPConfig externalIdPConfig = null; IdentityProvider idpDO = null; if (log.isDebugEnabled()) { log.debug("Trying to find the IdP for name: " + idpName); } try { IdentityProviderManager idpManager = IdentityProviderManager.getInstance(); idpDO = idpManager.getEnabledIdPByName(idpName, tenantDomain); if (idpDO != null) { if (log.isDebugEnabled()) { log.debug("A registered IdP was found"); } externalIdPConfig = new ExternalIdPConfig(idpDO); } else { if (log.isDebugEnabled()) { log.debug("A registered IdP was not found the given name"); } } } catch (IdentityProviderManagementException e) { throw new IdentityProviderManagementException("Exception while getting IdP by name", e); } return externalIdPConfig; }
Source:
public void generateChunk(CoreChunk chunk, Region chunkRegion) { BaseFacet baseFacet = chunkRegion.getFacet(BaseFacet.class); for (Base base : baseFacet.getBases()) { BlockRegion baseRegion = base.getArea(); BlockRegion flagRegion = base.getFlagArea(); for (Vector3ic baseBlockPosition : baseRegion) { if (chunkRegion.getRegion().contains(baseBlockPosition) && baseBlockPosition.x() > 0) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(baseBlockPosition, new Vector3i()), redBaseStone); } else if (chunkRegion.getRegion().contains(baseBlockPosition)) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(baseBlockPosition, new Vector3i()), blackBaseStone); } } for (Vector3ic flagPosition : flagRegion) { if (chunkRegion.getRegion().contains(flagPosition) && flagPosition.x() > 0) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(flagPosition, new Vector3i()), redFlag); } else if (chunkRegion.getRegion().contains(flagPosition)) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(flagPosition, new Vector3i()), blackFlag); } } } }

Target:
public void generateChunk(CoreChunk chunk, Region chunkRegion) { BaseFacet baseFacet = chunkRegion.getFacet(BaseFacet.class); Vector3i tempPos = new Vector3i(); for (Base base : baseFacet.getBases()) { BlockRegion baseRegion = base.getArea(); BlockRegion flagRegion = base.getFlagArea(); for (Vector3ic baseBlockPosition : baseRegion) { if (chunkRegion.getRegion().contains(baseBlockPosition) && baseBlockPosition.x() > 0) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(baseBlockPosition, tempPos), redBaseStone); } else if (chunkRegion.getRegion().contains(baseBlockPosition)) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(baseBlockPosition, tempPos), blackBaseStone); } } for (Vector3ic flagPosition : flagRegion) { if (chunkRegion.getRegion().contains(flagPosition) && flagPosition.x() > 0) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(flagPosition, tempPos), redFlag); } else if (chunkRegion.getRegion().contains(flagPosition)) { chunk.setBlock(ChunkMath.calcRelativeBlockPos(flagPosition, tempPos), blackFlag); } } } }
Source:
public Journey getJourneyInfo(String dgw) { String apiResponse = getJourneyInfoFromApi(dgw); List<JourneyInfo> infoList = JsonJavaConverter.toJavaList(apiResponse, JourneyInfo[].class); if (infoList == null) { return null; } Collections.sort(infoList, new Comparator<JourneyInfo>() { @Override public int compare(JourneyInfo lhs, JourneyInfo rhs) { if (rhs.getTimestamp() > lhs.getTimestamp()) { return 1; } else { return -1; } } }); String destination = null; String journeyId = null; for (JourneyInfo info : infoList) { if (info.getResourceSpec().equals(RESOURCE_SPEC_DESTINATION)) { destination = info.getValue(); break; } } for (JourneyInfo info : infoList) { if (info.getResourceSpec().equals(RESOURCE_SPEC_JOURNEY_ID)) { journeyId = info.getValue(); break; } } Journey ret = new Journey(destination, journeyId); return ret; }

Target:
public Journey getJourneyInfo(String dgw) { String apiResponse = getJourneyInfoFromApi(dgw); List<JourneyInfo> infoList = JsonJavaConverter.toJavaList(apiResponse, JourneyInfo[].class); if (infoList == null) { return null; } Collections.sort(infoList, new Comparator<JourneyInfo>() { @Override public int compare(JourneyInfo lhs, JourneyInfo rhs) { if (rhs.getTimestamp() > lhs.getTimestamp()) { return 1; } else { return rhs.getTimestamp() == lhs.getTimestamp() ? 0 : -1; } } }); String destination = null; String journeyId = null; for (JourneyInfo info : infoList) { if (info.getResourceSpec().equals(RESOURCE_SPEC_DESTINATION)) { destination = info.getValue(); break; } } for (JourneyInfo info : infoList) { if (info.getResourceSpec().equals(RESOURCE_SPEC_JOURNEY_ID)) { journeyId = info.getValue(); break; } } Journey ret = new Journey(destination, journeyId); return ret; }
Source:
private String loadResponseFromFile(String resourceName) throws IOException { URL r = getResource(UpdateMetricsResponseHandler.class, resourceName); ByteSource source = new ByteSource() { @Override public InputStream openStream() throws IOException { return r.openStream(); } }; return source.asCharSource(UTF_8).read(); }

Target:
private String loadResponseFromFile(String resourceName) throws IOException { return IOUtils.toString(getClass().getResourceAsStream(resourceName), UTF_8); }
Source:
public long getEntryLastModified() { if (modTimes == null) return 0; Long cutOff = Long.valueOf(super.getEntryLastModified()); SortedSet<Long> head = modTimes.headSet(cutOff, true); return head.isEmpty() ? 0 : head.last().longValue(); }

Target:
public long getEntryLastModified() { if (modTimes == null) return 0; Long cutOff = Long.valueOf(super.getEntryLastModified() + 1); SortedSet<Long> head = modTimes.headSet(cutOff); return head.isEmpty() ? 0 : head.last().longValue(); }
Source:
public void configureSessionTimeout() { HttpSession httpSession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false); if (httpSession != null) { logger.info("jsession: "+httpSession.getId()+" setting the lifespan of the session to " + systemConfig.getLoginSessionTimeout() + " minutes"); httpSession.setMaxInactiveInterval(systemConfig.getLoginSessionTimeout() * 60); } }

Target:
public void configureSessionTimeout() { HttpSession httpSession = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false); if (httpSession != null) { logger.fine("jsession: "+httpSession.getId()+" setting the lifespan of the session to " + systemConfig.getLoginSessionTimeout() + " minutes"); httpSession.setMaxInactiveInterval(systemConfig.getLoginSessionTimeout() * 60); } }
Source:
public void addApplications(List<Map<String, Object>> applicationURLList) { for (Map<String, Object> curURL : applicationURLList) { String value = "value"; try { appService.addApplication(new URI((String) curURL.get(value))); } catch (URISyntaxException use) { LOGGER.warn("Could not add application with url {}, not a valid URL.", curURL.get(value)); } catch (ApplicationServiceException ase) { LOGGER.warn("Could not add application with url due to error.", curURL.get(value), ase); } } }

Target:
public void addApplications(List<Map<String, Object>> applicationURLList) { for (Map<String, Object> curURL : applicationURLList) { String applicationUrl = (String) curURL.get("value"); try { appService.addApplication(new URI(applicationUrl)); } catch (URISyntaxException use) { LOGGER.warn("Could not add application with url {}, not a valid URL.", applicationUrl); LOGGER.debug("Could not add application", use); } catch (ApplicationServiceException ase) { LOGGER.warn( "Could not add application with url due to error {}.", applicationUrl, ase.getMessage()); LOGGER.debug("Could not add application", ase); } } }
Source:
public static void addFileHandler(String fileName) { try { FileHandler fh = new FileHandler(fileName); fh.setFormatter(new SimpleFormatter()); OVIRT_LOGGER.addHandler(fh); } catch (SecurityException | IOException ex) { throw new IllegalArgumentException( String.format("Error accessing log file '%s': '%s'", fileName, ex.getMessage()), ex); } }

Target:
public static void addFileHandler(String fileName) { try { FileHandler fh = new FileHandler(fileName); fh.setFormatter(new SimpleFormatter()); Logger.getLogger("").addHandler(fh); } catch (SecurityException | IOException ex) { throw new IllegalArgumentException( String.format("Error accessing log file '%s': '%s'", fileName, ex.getMessage()), ex); } }
Source:
public String getStatementName(StatementContext statementContext) { final String rawSql = statementContext.getRawSql(); if (rawSql == null || rawSql.length() == 0) { return "sql.empty"; } return null; }

Target:
public String getStatementName(StatementContext statementContext) { final String rawSql = statementContext.getRawSql(); return rawSql == null || rawSql.isEmpty() ? "sql.empty" : null; }
Source:
public static Layout single(int port) { return new TestLayoutBuilder() .addLayoutServer(port) .addSequencer(port) .buildSegment() .buildStripe() .addLogUnit(port) .addToSegment() .addToLayout() .setClusterId(UUID.fromString("00000000-0000-0000-0000-000000000000")) .build(); }

Target:
public static Layout single(int port) { return new TestLayoutBuilder() .addLayoutServer(port) .addSequencer(port) .buildSegment() .buildStripe() .addLogUnit(port) .addToSegment() .addToLayout() .setClusterId(Layout.INVALID_CLUSTER_ID) .build(); }
Source:
private static MoPubErrorCode toMoPubErrorCode(final int applovinErrorCode) { if ( applovinErrorCode == AppLovinErrorCodes.NO_FILL ) { return MoPubErrorCode.NETWORK_NO_FILL; } else if ( applovinErrorCode == AppLovinErrorCodes.UNSPECIFIED_ERROR ) { return MoPubErrorCode.NETWORK_INVALID_STATE; } else if ( applovinErrorCode == AppLovinErrorCodes.NO_NETWORK ) { return MoPubErrorCode.NO_CONNECTION; } else if ( applovinErrorCode == AppLovinErrorCodes.FETCH_AD_TIMEOUT ) { return MoPubErrorCode.NETWORK_TIMEOUT; } else { return MoPubErrorCode.UNSPECIFIED; } }

Target:
private static MoPubErrorCode toMoPubErrorCode(final int applovinErrorCode) { if ( applovinErrorCode == AppLovinErrorCodes.NO_FILL ) { return MoPubErrorCode.NETWORK_NO_FILL; } else if ( applovinErrorCode == AppLovinErrorCodes.UNSPECIFIED_ERROR ) { return MoPubErrorCode.UNSPECIFIED; } else if ( applovinErrorCode == AppLovinErrorCodes.NO_NETWORK ) { return MoPubErrorCode.NO_CONNECTION; } else if ( applovinErrorCode == AppLovinErrorCodes.FETCH_AD_TIMEOUT ) { return MoPubErrorCode.NETWORK_TIMEOUT; } else { return MoPubErrorCode.UNSPECIFIED; } }
Source:
public void rejectsInvalidValue() { final String cookiename = "cookiename"; new RsWithCookie(new RsEmpty(), cookiename, "wo\"rks"); }

Target:
public void rejectsInvalidValue() { new RsWithCookie(new RsEmpty(), "cookiename", "wo\"rks"); }
Source:
public static ChangeAddress ofOldAddressToNewAddress(final Address oldAddress, final Address newAddress) { if (oldAddress.getId() == null) { throw new IllegalArgumentException(format("The address %s should have an id.", oldAddress)); } return of(oldAddress.getId(), oldAddress.getKey(), newAddress); }

Target:
public static ChangeAddress ofOldAddressToNewAddress(final Address oldAddress, final Address newAddress) { if (oldAddress.getId() == null && oldAddress.getKey() == null) { throw new IllegalArgumentException(format("The address %s should have an id or a key.", oldAddress)); } if (oldAddress.getId() != null) { return of(oldAddress.getId(), newAddress); } else { return of(newAddress, oldAddress.getKey()); } }
Source:
public List<Double> roundPercentages(List<Double> percentages) { if (percentages == null || percentages.size() == 0) return null; int size = percentages.size(); for (int i = 0; i < size; i++) { double percentage = percentages.get(i); double rounded = roundDouble(percentage); percentages.set(i, rounded); } double delta = 100.0 - percentages.stream().mapToDouble(d -> d).sum(); if (delta > 0.0) { Double lastRule = percentages.get(size - 1) + roundDouble(delta); percentages.set(size - 1, lastRule); } return percentages; }

Target:
List<Double> roundPercentages(List<Double> percentages) { Double[] array = percentages.toArray(new Double[percentages.size()]); double[] rounded = roundPercentages(ArrayUtils.toPrimitive(array)); return Arrays.asList(ArrayUtils.toObject(rounded)); }
Source:
public final int getBucketPosition(final double position) { return modelVar.getBucketCache().bucketPosition(position); }

Target:
public final int getBucketPosition(final double position) { return model.getBucketCache().bucketPercentagePosition(position); }
Source:
protected void toLegacyText(StringBuilder builder) { builder.append(this.selector); }

Target:
protected void toLegacyText(StringBuilder builder) { builder.append( this.selector ); super.toLegacyText( builder ); }
Source:
public synchronized void scheduleReconnect() { logger.debug("{} scheduleReconnect()", logPrefix()); if (!isEventLoopGroupActive()) { logger.debug("isEventLoopGroupActive() == false"); return; } if (commandHandler != null && commandHandler.isClosed()) { logger.debug("Skip reconnect scheduling, CommandHandler is closed"); return; } if ((channel == null || !channel.isActive()) && !isWaitingReconnection) { attempts++; final int attempt = attempts; int timeout = (int) reconnectDelay.getTimeUnit().toMillis(reconnectDelay.createDelay(attempt)); logger.debug("Reconnect attempt {}, delay {}ms", attempt, timeout); isWaitingReconnection = true; timer.newTimeout(it -> { if (!isEventLoopGroupActive()) { logger.debug("isEventLoopGroupActive() == false"); return; } reconnectWorkers.submit(() -> { ConnectionWatchdog.this.run(); return null; }); }, timeout, TimeUnit.MILLISECONDS); } else { logger.debug("{} Skipping scheduleReconnect() because I have an active channel", logPrefix()); } }

Target:
public void scheduleReconnect() { logger.debug("{} scheduleReconnect()", logPrefix()); if (!isEventLoopGroupActive()) { logger.debug("isEventLoopGroupActive() == false"); return; } if (commandHandler != null && commandHandler.isClosed()) { logger.debug("Skip reconnect scheduling, CommandHandler is closed"); return; } if ((channel == null || !channel.isActive()) && !isWaitingReconnection.get()) { if (!isWaitingReconnection.compareAndSet(false, true)) { return; } attempts++; final int attempt = attempts; int timeout = (int) reconnectDelay.getTimeUnit().toMillis(reconnectDelay.createDelay(attempt)); logger.debug("Reconnect attempt {}, delay {}ms", attempt, timeout); this.reconnectScheduleTimeout = timer.newTimeout(it -> { if (!isEventLoopGroupActive()) { logger.debug("isEventLoopGroupActive() == false"); return; } reconnectWorkers.submit(() -> { ConnectionWatchdog.this.run(it); return null; }); }, timeout, TimeUnit.MILLISECONDS); if (!isWaitingReconnection.get()) { reconnectScheduleTimeout = null; } } else { logger.debug("{} Skipping scheduleReconnect() because I have an active channel", logPrefix()); } }
Source:
public IUser getUserByLogin(String login) { List<UserPrivileges> privileges = Arrays.asList(UserPrivileges.READ_PROJECT, UserPrivileges.DOWNLOAD, UserPrivileges.RUN_EXPERIMENT); IUserGroup group = new LocalUserGroup("guest", privileges, 0, 0); IUser user = new LocalUser(1, login, login, login, login, new ArrayList<LocalGeppettoProject>(), group); return user; }

Target:
public IUser getUserByLogin(String login) { IUserGroup group = new LocalUserGroup("guest", getUserPrivileges(), 0, 0); IUser user = new LocalUser(1, login, login, login, login, new ArrayList<LocalGeppettoProject>(), group); return user; }
Source:
public boolean waitForCompletion(long timeoutMillis) throws InterruptedException { boolean res = true; for (EventBundlePipe pipe : pipes) { res = res && pipe.waitForCompletion(timeoutMillis); } return res; }

Target:
public boolean waitForCompletion(long timeoutMillis) throws InterruptedException { boolean res = true; for (EventBundlePipe pipe : pipes) { res = pipe.waitForCompletion(timeoutMillis) && res; } return res; }
Source:
public void testUpdateContainerId() { ServerTemplate serverTemplate = createServerTemplate(); ContainerSpec containerToDeploy = new ContainerSpec(CONTAINER_ID, CONTAINER_NAME, serverTemplate, releaseId, KieContainerStatus.STOPPED, Collections.EMPTY_MAP); mgmtControllerClient.saveContainerSpec(serverTemplate.getId(), containerToDeploy); ContainerSpec containerResponseEntity = mgmtControllerClient.getContainerInfo(kieServerInfo.getServerId(), CONTAINER_ID); checkContainer(containerResponseEntity, KieContainerStatus.STOPPED); assertEquals(CONTAINER_NAME, containerResponseEntity.getContainerName()); containerToDeploy.setId("newID"); try { mgmtControllerClient.updateContainerSpec(serverTemplate.getId(), CONTAINER_ID, containerToDeploy); fail("Container has updated id."); } catch (UnexpectedResponseCodeException e) { assertEquals(404, e.getResponseCode()); KieServerAssert.assertResultContainsString(e.getMessage(), "no container with id newID"); } }

Target:
public void testUpdateContainerId() { ServerTemplate serverTemplate = createServerTemplate(); ContainerSpec containerToDeploy = new ContainerSpec(CONTAINER_ID, CONTAINER_NAME, serverTemplate, releaseId, KieContainerStatus.STOPPED, Collections.EMPTY_MAP); mgmtControllerClient.saveContainerSpec(serverTemplate.getId(), containerToDeploy); ContainerSpec containerResponseEntity = mgmtControllerClient.getContainerInfo(kieServerInfo.getServerId(), CONTAINER_ID); checkContainer(containerResponseEntity, KieContainerStatus.STOPPED); assertEquals(CONTAINER_NAME, containerResponseEntity.getContainerName()); containerToDeploy.setId("newID"); try { mgmtControllerClient.updateContainerSpec(serverTemplate.getId(), CONTAINER_ID, containerToDeploy); fail("Container has updated id."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); KieServerAssert.assertResultContainsString(e.getMessage(), "Cannot update container newID on container " + CONTAINER_ID); } }
Source:
private SAMRecord getNextRecord() { final long startCoordinate = this.stream.getFilePointer(); final SAMRecord next = this.bamRecordCodec.decode(); final long stopCoordinate = this.stream.getFilePointer(); if (HtsgetBAMFileReader.this.mReader != null && next != null) { next.setFileSource(new SAMFileSource( HtsgetBAMFileReader.this.mReader, new BAMFileSpan(new Chunk(startCoordinate, stopCoordinate)))); } return next; }

Target:
private SAMRecord getNextRecord() { final SAMRecord next = this.bamRecordCodec.decode(); if (HtsgetBAMFileReader.this.mReader != null && next != null) { next.setFileSource(new SAMFileSource( HtsgetBAMFileReader.this.mReader, null)); } return next; }
Source:
public String getQuestionSpecificEditFormHtml(int questionNumber) { return FeedbackQuestionFormTemplates.populateTemplate( FeedbackQuestionFormTemplates.CONTRIB_EDIT_FORM, "${questionNumber}", Integer.toString(questionNumber), "${allowingNotSureOrNot}", (isNotSureAllowed) ? "checked=\"checked\"" : "", "${Const.ParamsNames.FEEDBACK_QUESTION_CONTRIBISNOTSUREALLOWED}", Const.ParamsNames.FEEDBACK_QUESTION_CONTRIBISNOTSUREALLOWED); }

Target:
public String getQuestionSpecificEditFormHtml(int questionNumber) { return FeedbackQuestionFormTemplates.populateTemplate( FeedbackQuestionFormTemplates.CONTRIB_EDIT_FORM, "${questionNumber}", Integer.toString(questionNumber), "${isNotSureAllowedChecked}", (isNotSureAllowed) ? "checked=\"checked\"" : "", "${Const.ParamsNames.FEEDBACK_QUESTION_CONTRIBISNOTSUREALLOWED}", Const.ParamsNames.FEEDBACK_QUESTION_CONTRIBISNOTSUREALLOWED); }
Source:
public VdcActionParametersBase(ParametersMap map) { for (Map.Entry<Parameter, Serializable> entry : map.entrySet()) { put(Parameter.getByUuid(entry.getKey().getUuid().toString()), entry.getValue()); } }

Target:
public VdcActionParametersBase(ParametersMap map) { super(map); }
Source:
public void installPluginFromStream(String originalName, InputStream in) throws IOException, PluginInstallException { String fileName = originalName; if (!(fileName.endsWith(".jar") || fileName.endsWith(".js"))) { throw new PluginInstallException( "Can only install files with '.jar' or '.js' extension"); } File tmp = asTemp(in, ".next_" + fileName + "_", ".tmp", pluginsDir); String name = Objects.firstNonNull(getGerritPluginName(tmp), nameOf(fileName)); if (!originalName.equals(name)) { log.warn(String.format("Plugin provides its own name: <%s>," + " use it instead of the input name: <%s>", name, originalName)); } String fileExtension = getExtension(originalName); File dst = new File(pluginsDir, name + fileExtension); synchronized (this) { Plugin active = running.get(name); if (active != null) { name = active.getSrcFile().getName(); log.info(String.format("Replacing plugin %s", active.getName())); File old = new File(pluginsDir, ".last_" + name); old.delete(); active.getSrcFile().renameTo(old); } new File(pluginsDir, name + ".disabled").delete(); tmp.renameTo(dst); try { Plugin plugin = runPlugin(name, dst, active); if (active == null) { log.info(String.format("Installed plugin %s", plugin.getName())); } } catch (PluginInstallException e) { dst.delete(); throw e; } cleanInBackground(); } }

Target:
public void installPluginFromStream(String originalName, InputStream in) throws IOException, PluginInstallException { String fileName = originalName; if (!(fileName.endsWith(".jar") || fileName.endsWith(".js"))) { fileName += ".jar"; } File tmp = asTemp(in, ".next_" + fileName + "_", ".tmp", pluginsDir); String name = Objects.firstNonNull(getGerritPluginName(tmp), nameOf(fileName)); if (!originalName.equals(name)) { log.warn(String.format("Plugin provides its own name: <%s>," + " use it instead of the input name: <%s>", name, originalName)); } String fileExtension = getExtension(originalName); File dst = new File(pluginsDir, name + fileExtension); synchronized (this) { Plugin active = running.get(name); if (active != null) { fileName = active.getSrcFile().getName(); log.info(String.format("Replacing plugin %s", active.getName())); File old = new File(pluginsDir, ".last_" + fileName); old.delete(); active.getSrcFile().renameTo(old); } new File(pluginsDir, fileName + ".disabled").delete(); tmp.renameTo(dst); try { Plugin plugin = runPlugin(name, dst, active); if (active == null) { log.info(String.format("Installed plugin %s", plugin.getName())); } } catch (PluginInstallException e) { dst.delete(); throw e; } cleanInBackground(); } }
Source:
void receiveMessageAndCompleteFailLockLost(MessagingEntityType entityType, boolean isSessionEnabled) { if (!isSessionEnabled) return; setSenderAndReceiver(entityType, isSessionEnabled); int maxMessages = 1; final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final Stream<ServiceBusReceivedMessage> messages = receiver.receive(maxMessages, TIMEOUT) .stream() .map(ServiceBusReceivedMessageContext::getMessage); final AtomicInteger receivedMessageCount = new AtomicInteger(); messages.forEach(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); Mono.empty().delaySubscription(MESSAGE_LOCK_EXPIRED_TIME).block(); try { receiver.complete(receivedMessage); assertFalse(true, "Complete should have failed because of lock token expired."); } catch (Exception ex) { assertTrue( ex instanceof AmqpException); AmqpErrorCondition lockErrorCondition; if (isSessionEnabled) { lockErrorCondition = AmqpErrorCondition.fromString("com.microsoft:session-cannot-be-locked"); } else { lockErrorCondition = AmqpErrorCondition.fromString("com.microsoft:message-lock-lost"); } assertTrue((((AmqpException)ex).getErrorCondition() == lockErrorCondition)); } messagesPending.decrementAndGet(); receivedMessageCount.incrementAndGet(); }); assertEquals(maxMessages, receivedMessageCount.get()); }

Target:
void receiveMessageAndCompleteFailLockLost(MessagingEntityType entityType, boolean isSessionEnabled) { if (!isSessionEnabled) return; setSenderAndReceiver(entityType, isSessionEnabled); int maxMessages = 1; final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final Stream<ServiceBusReceivedMessage> messages = receiver.receive(maxMessages, TIMEOUT) .stream() .map(ServiceBusReceivedMessageContext::getMessage); final AtomicInteger receivedMessageCount = new AtomicInteger(); messages.forEach(receivedMessage -> { assertMessageEquals(receivedMessage, messageId, isSessionEnabled); Mono.empty().delaySubscription(MESSAGE_LOCK_EXPIRED_TIME).block(); try { receiver.complete(receivedMessage); assertFalse(true, "Complete should have failed because of lock token expired."); } catch (Exception ex) { assertTrue( ex instanceof AmqpException); AmqpErrorCondition lockErrorCondition; if (isSessionEnabled) { lockErrorCondition = AmqpErrorCondition.fromString("com.microsoft:session-cannot-be-locked"); } else { lockErrorCondition = AmqpErrorCondition.fromString("com.microsoft:message-lock-lost"); } assertTrue((((AmqpException)ex).getErrorCondition() == lockErrorCondition)); } receivedMessageCount.incrementAndGet(); }); assertEquals(maxMessages, receivedMessageCount.get()); }
Source:
public Optional<AggStats> getSingleStat(final Long accountId, final DeviceId deviceId, final DateTime dateLocal) { Response<ImmutableList<AggStats>> response = getBatchStatsBetweenLocalDate(accountId, deviceId, dateLocal, dateLocal); if (response.status != Response.Status.SUCCESS || response.exception.isPresent()) { LOGGER.debug("action=get-single-stat response_stats={} response_exception={} accountId={} senseId={} dateLocal={}", response.status.toString(), response.exception.toString(), accountId, deviceId.externalDeviceId, dateLocal.toString()); return Optional.absent(); } if (response.data.isEmpty()) { LOGGER.trace("action=get-single-stat response_data=empty accountId={} senseId={} dateLocal={}", accountId, deviceId.externalDeviceId, dateLocal.toString()); return Optional.absent(); } Optional<AggStats> aggStatsOptional = Optional.of(response.data.get(0)); return aggStatsOptional; }

Target:
public Optional<AggStats> getSingleStat(final Long accountId, final DeviceId deviceId, final DateTime dateLocal) { final Response<ImmutableList<AggStats>> response = getBatchStatsBetweenLocalDate(accountId, deviceId, dateLocal, dateLocal); if (response.status != Response.Status.SUCCESS || response.exception.isPresent()) { LOGGER.debug("action=get-single-stat response_stats={} response_exception={} accountId={} senseId={} dateLocal={}", response.status.toString(), response.exception.toString(), accountId, deviceId.externalDeviceId, dateLocal.toString()); return Optional.absent(); } if (response.data.isEmpty()) { LOGGER.trace("action=get-single-stat response_data=empty accountId={} senseId={} dateLocal={}", accountId, deviceId.externalDeviceId, dateLocal.toString()); return Optional.absent(); } final Optional<AggStats> aggStatsOptional = Optional.of(response.data.get(0)); return aggStatsOptional; }
Source:
public void removeSegment(final DataSegment segment, final DataSegmentChangeCallback callback) { try { announcer.unannounceSegment(segment); segmentsToDelete.add(segment); log.info("Completely removing [%s] in [%,d] millis", segment.getIdentifier(), config.getDropSegmentDelayMillis()); exec.schedule( new Runnable() { @Override public void run() { try { synchronized (lock) { if (segmentsToDelete.remove(segment)) { File parentPath = segmentManager.getSegmentLocation(segment); segmentManager.dropSegment(segment); File segmentInfoCacheFile = new File(parentPath, "info.json"); if (!segmentInfoCacheFile.delete()) { log.warn("Unable to delete segmentInfoCacheFile[%s]", segmentInfoCacheFile); } } } } catch (Exception e) { log.makeAlert(e, "Failed to remove segment! Possible resource leak!") .addData("segment", segment) .emit(); } } }, config.getDropSegmentDelayMillis(), TimeUnit.MILLISECONDS ); } catch (Exception e) { log.makeAlert(e, "Failed to remove segment") .addData("segment", segment) .emit(); } finally { callback.execute(); } }

Target:
public void removeSegment(final DataSegment segment, final DataSegmentChangeCallback callback) { try { announcer.unannounceSegment(segment); segmentsToDelete.add(segment); log.info("Completely removing [%s] in [%,d] millis", segment.getIdentifier(), config.getDropSegmentDelayMillis()); exec.schedule( new Runnable() { @Override public void run() { try { synchronized (lock) { File segmentToRemove = segmentManager.getSegmentFiles(segment); if (segmentsToDelete.remove(segment)) { segmentManager.dropSegment(segment); File segmentInfoCacheFile = new File(segmentToRemove, SEGMENT_CACHE_FILENAME); if (!segmentInfoCacheFile.delete()) { log.warn("Unable to delete segmentInfoCacheFile[%s]", segmentInfoCacheFile); } } } } catch (Exception e) { log.makeAlert(e, "Failed to remove segment! Possible resource leak!") .addData("segment", segment) .emit(); } } }, config.getDropSegmentDelayMillis(), TimeUnit.MILLISECONDS ); } catch (Exception e) { log.makeAlert(e, "Failed to remove segment") .addData("segment", segment) .emit(); } finally { callback.execute(); } }
Source:
private void ensureWritableBytes(int minWritableBytes) { int neededBufferSize = bufferPosition + minWritableBytes; if (neededBufferSize <= slice.length()) { return; } if (slice.length() >= maxBufferSize) { flushBufferToOutputStream(); return; } int newBufferSize = min(max(slice.length() * 2, minWritableBytes), maxBufferSize); if (neededBufferSize <= newBufferSize) { byte[] previousBuffer = buffer; buffer = new byte[newBufferSize]; System.arraycopy(previousBuffer, 0, buffer, 0, bufferPosition); } else { flushBufferToOutputStream(); buffer = new byte[newBufferSize]; } slice = wrappedBuffer(buffer); }

Target:
private void ensureWritableBytes(int minWritableBytes) { int neededBufferSize = bufferPosition + minWritableBytes; if (neededBufferSize <= slice.length()) { return; } if (slice.length() >= maxBufferSize) { flushBufferToOutputStream(); return; } int newBufferSize = min(max(slice.length() * 2, minWritableBytes), maxBufferSize); if (neededBufferSize <= newBufferSize) { byte[] previousBuffer = buffer; buffer = new byte[newBufferSize]; slice = wrappedBuffer(buffer); System.arraycopy(previousBuffer, 0, buffer, 0, bufferPosition); } else { flushBufferToOutputStream(); buffer = new byte[newBufferSize]; slice = wrappedBuffer(buffer); } }
Source:
private void composeBuckFile(Path cacheDir) { ImmutableList.Builder<Rule> rulesBuilder = new ImmutableList.Builder<>(); if (dependencies != null) { rulesBuilder.add( new Prebuilt() .prebuiltType(RuleType.PREBUILT_JAR.getProperties().get(0)) .prebuilt(TRANSFORM_JAR) .ruleType(RuleType.PREBUILT_JAR.getBuckName()) .name(TRANSFORM_JAR)); rulesBuilder.add( new JvmBinaryRule() .excludes(Collections.singleton(BINARY_EXCLUDES)) .deps(dependencies) .ruleType(RuleType.JAVA_BINARY.getBuckName()) .name(OKBUCK_TRANSFORM_TARGET_NAME) .defaultVisibility()); } rulesBuilder.addAll( configFileToPathMap .values() .stream() .sorted() .map(configFileName -> new ExportFile().name(configFileName)) .collect(Collectors.toList())); List<Rule> rules = rulesBuilder.build(); File buckFile = cacheDir.resolve(OkBuckGradlePlugin.BUCK).toFile(); Multimap<String, String> loadStatements = LoadStatementsUtil.getLoadStatements(rules, okbuckExt); FileUtil.writeToBuckFile(loadStatements, rulesBuilder.build(), buckFile); }

Target:
private void composeBuckFile(Path cacheDir) { ImmutableList.Builder<Rule> rulesBuilder = new ImmutableList.Builder<>(); if (dependencies != null) { rulesBuilder .add( new Prebuilt() .prebuiltType(RuleType.PREBUILT_JAR.getProperties().get(0)) .prebuilt(TRANSFORM_JAR) .ruleType(RuleType.PREBUILT_JAR.getBuckName()) .name(TRANSFORM_JAR)) .add( new JvmBinaryRule() .excludes(Collections.singleton(BINARY_EXCLUDES)) .deps(dependencies) .ruleType(RuleType.JAVA_BINARY.getBuckName()) .name(OKBUCK_TRANSFORM_TARGET_NAME) .defaultVisibility()); } rulesBuilder.addAll( configFileToPathMap .values() .stream() .sorted() .map(configFileName -> new ExportFile().name(configFileName)) .collect(Collectors.toList())); List<Rule> rules = rulesBuilder.build(); File buckFile = cacheDir.resolve(OkBuckGradlePlugin.BUCK).toFile(); Multimap<String, String> loadStatements = LoadStatementsUtil.getLoadStatements(rules, okbuckExt); FileUtil.writeToBuckFile(loadStatements, rules, buckFile); }
Source:
void setDeltaAttempted(boolean deltaAttempted) { if (deltaAttempted) flags |= DELTA_ATTEMPTED; else flags &= DELTA_ATTEMPTED; }

Target:
void setDeltaAttempted(boolean deltaAttempted) { if (deltaAttempted) flags |= DELTA_ATTEMPTED; else flags &= ~DELTA_ATTEMPTED; }