auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean handleUncommittedChanges(final Repository repository, final List<String> files, Shell shell) { CleanupUncomittedChangesDialog cleanupUncomittedChangesDialog = new CleanupUncomittedChangesDialog( shell, UIText.AbstractRebaseCommandHandler_cleanupDialog_title, UIText.AbstractRebaseCommandHandler_cleanupDialog_text, repository, files); cleanupUncomittedChangesDialog.open(); if (cleanupUncomittedChangesDialog.shouldContinue()) { final PullOperationUI outerThis = this; PullOperationUI pullOperationUI = new PullOperationUI( Collections.singleton(repository)) { public void done(IJobChangeEvent event) { outerThis.results.putAll(this.results); int missing = outerThis.tasksToWaitFor.decrementAndGet(); if (missing == 0) outerThis.showResults(); } }; pullOperationUI.start(); return true; } else return false; }

Target:
private void handleUncommittedChanges(final Repository repository, final List<String> files, Shell shell) { CleanupUncomittedChangesDialog cleanupUncomittedChangesDialog = new CleanupUncomittedChangesDialog( shell, UIText.AbstractRebaseCommandHandler_cleanupDialog_title, UIText.AbstractRebaseCommandHandler_cleanupDialog_text, repository, files); cleanupUncomittedChangesDialog.open(); if (cleanupUncomittedChangesDialog.shouldContinue()) { final PullOperationUI parentOperation = this; final PullOperationUI pullOperationUI = new PullOperationUI( Collections.singleton(repository)); tasksToWaitFor.incrementAndGet(); pullOperationUI.start(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { parentOperation.results.putAll(pullOperationUI.results); int missing = parentOperation.tasksToWaitFor.decrementAndGet(); if (missing == 0) parentOperation.showResults(); } }); } }
Source:
public long findPosition(long nOccurrence) { updateCount(); long ret = RankedBitVector.NOT_FOUND; if (nOccurrence > 0) { int findPos = getBlockNumber(nOccurrence); if (findPos < this.positionArray.length) { long pos0 = this.positionArray[findPos]; long leftOccurrences = nOccurrence - (findPos * this.blockSize); if (leftOccurrences == 0) { ret = pos0; } else { for (long index = pos0 + 1; (leftOccurrences > 0) && (index < this.bitVector.size()); index++) { if (this.bitVector.getBit(index) == this.bit) { leftOccurrences--; } if (leftOccurrences == 0) { ret = index; } } } } } return ret; }

Target:
public long findPosition(long nOccurrence) { updateCount(); if (nOccurrence <= 0) { return RankedBitVector.NOT_FOUND; } int findPos = (int) (nOccurrence / this.blockSize); if (findPos < this.positionArray.length) { long pos0 = this.positionArray[findPos]; long leftOccurrences = nOccurrence - (findPos * this.blockSize); if (leftOccurrences == 0) { return pos0; } for (long index = pos0 + 1; index < this.bitVector.size(); index++) { if (this.bitVector.getBit(index) == this.bit) { leftOccurrences--; } if (leftOccurrences == 0) { return index; } } } return RankedBitVector.NOT_FOUND; }
Source:
private Timestamp parseTimeStamp(String date) { try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS"); Date parsedDate = dateFormat.parse(date); return new java.sql.Timestamp(parsedDate.getTime()); } catch (ParseException e) { e.printStackTrace(); return null; } }

Target:
private Timestamp parseTimeStamp(String date) { try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS"); Date parsedDate = dateFormat.parse(date); return new java.sql.Timestamp(parsedDate.getTime()); } catch (ParseException e) { StatusHandler.log(new Status(IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, e.getMessage(), e)); return null; } }
Source:
private void removeVmsFromCache() { if (dbVm != null && !stable) { proceedVmBeforeDeletion(); boolean migrating = dbVm.getStatus() == VMStatus.MigratingFrom; if (migrating) { handOverVM(dbVm); } else if (dbVm.getStatus() == VMStatus.PoweringDown) { clearVm(VmExitStatus.Normal, String.format("VM %s shutdown complete", dbVm.getName()), VmExitReason.Success); } else { clearVm(VmExitStatus.Error, String.format("Could not find VM %s on host, assuming it went down unexpectedly", dbVm.getName()), VmExitReason.GenericError); } log.info("VM '{}({}) is running in db and not running in VDS '{}'", dbVm.getId(), dbVm.getName(), getVdsManager().getVdsName()); if (!migrating && !rerun && vmsMonitoring.getResourceManager().IsVmInAsyncRunningList(dbVm.getId())) { rerun = true; log.info("add VM '{}' to rerun treatment", dbVm.getName()); } else if (dbVm.isAutoStartup() && !autoVmToRun && (vdsmVm == null || vdsmVm.getVmDynamic().getExitStatus() != VmExitStatus.Normal)) { autoVmToRun = true; log.info("add VM '{}' to HA rerun treatment", dbVm.getName()); } } }

Target:
private void removeVmsFromCache() { if (dbVm != null && !stable) { boolean poweredDown = false; proceedVmBeforeDeletion(); boolean migrating = dbVm.getStatus() == VMStatus.MigratingFrom; if (migrating) { handOverVM(dbVm); } else if (dbVm.getStatus() == VMStatus.PoweringDown) { poweredDown = true; clearVm(VmExitStatus.Normal, String.format("VM %s shutdown complete", dbVm.getName()), VmExitReason.Success); } else { clearVm(VmExitStatus.Error, String.format("Could not find VM %s on host, assuming it went down unexpectedly", dbVm.getName()), VmExitReason.GenericError); } log.info("VM '{}({}) is running in db and not running in VDS '{}'", dbVm.getId(), dbVm.getName(), getVdsManager().getVdsName()); if (!migrating && !rerun && vmsMonitoring.getResourceManager().IsVmInAsyncRunningList(dbVm.getId())) { rerun = true; log.info("add VM '{}' to rerun treatment", dbVm.getName()); } else if (dbVm.isAutoStartup() && !autoVmToRun && (vdsmVm == null || vdsmVm.getVmDynamic().getExitStatus() != VmExitStatus.Normal) && !poweredDown) { autoVmToRun = true; log.info("add VM '{}' to HA rerun treatment", dbVm.getName()); } } }
Source:
public void executeBatch(JSONObject batch) { emitter.evaluateBatch(batch, qry -> enhanceQuery(qry, false), this::executeTask); }

Target:
public void executeBatch(JSONObject batch) { emitter.evaluateBatch(batch, query -> filterOnExecutableTasks(query, false), this::executeTask); }
Source:
public void emailConsentAgreement(Study study, SubpopulationGuid subpopGuid, StudyParticipant participant) { checkNotNull(study); checkNotNull(subpopGuid); checkNotNull(participant); ConsentSignature consentSignature = getConsentSignature(study, subpopGuid, participant.getId()); SharingScope sharingScope = participant.getSharingScope(); Subpopulation subpop = subpopService.getSubpopulation(study.getStudyIdentifier(), subpopGuid); String htmlTemplate = studyConsentService.getActiveConsent(subpop).getDocumentContent(); String participantEmail = subpop.isAutoSendConsentSuppressed() ? null : participant.getEmail(); ConsentEmailProvider consentEmail = new ConsentEmailProvider(study, participant.getTimeZone(), participantEmail, consentSignature, sharingScope, htmlTemplate, consentTemplate); if (!consentEmail.getRecipients().isEmpty()) { sendMailService.sendEmail(consentEmail); } }

Target:
public void emailConsentAgreement(Study study, SubpopulationGuid subpopGuid, StudyParticipant participant) { checkNotNull(study); checkNotNull(subpopGuid); checkNotNull(participant); ConsentSignature consentSignature = getConsentSignature(study, subpopGuid, participant.getId()); SharingScope sharingScope = participant.getSharingScope(); Subpopulation subpop = subpopService.getSubpopulation(study.getStudyIdentifier(), subpopGuid); String htmlTemplate = studyConsentService.getActiveConsent(subpop).getDocumentContent(); ConsentEmailProvider consentEmail = new ConsentEmailProvider(study, participant.getTimeZone(), participant.getEmail(), consentSignature, sharingScope, htmlTemplate, consentTemplate); if (!consentEmail.getRecipients().isEmpty()) { sendMailService.sendEmail(consentEmail); } }
Source:
private <T extends Entity> boolean collisionsImpl$allowEntityCollision(final List<T> listToFill) { if (this.world instanceof WorldServerBridge) { if (!PhaseTracker.getInstance().getCurrentState().isCollision()) { return true; } final PhaseContext<?> phaseContext = PhaseTracker.getInstance().getCurrentContext(); final Object source = phaseContext.getSource(); if (source == null) { return true; } CollisionsCapability capability; if (source instanceof LocatableBlock) { final LocatableBlock locatable = (LocatableBlock) source; final BlockType blockType =locatable.getLocation().getBlockType(); capability = (CollisionsCapability) blockType; } else if (source instanceof CollisionsCapability) { capability = (CollisionsCapability) source; } else { return true; } if (capability.collision$requiresCollisionsCacheRefresh()) { capability.collision$initializeCollisionState(this.world); capability.collision$requiresCollisionsCacheRefresh(false); } return capability.collision$getMaxCollisions() < 0 || listToFill.size() < capability.collision$getMaxCollisions() || listToFill.size() < this.world.getGameRules().getInt("maxEntityCramming"); } return true; }

Target:
private <T extends Entity> boolean collisionsImpl$allowEntityCollision(final List<T> listToFill) { if (this.world instanceof WorldServerBridge) { if (!PhaseTracker.getInstance().getCurrentState().isCollision()) { return true; } final PhaseContext<?> phaseContext = PhaseTracker.getInstance().getCurrentContext(); final Object source = phaseContext.getSource(); if (!(source instanceof CollisionsCapability)) { return true; } final CollisionsCapability capability = (CollisionsCapability) source; if (capability.collision$requiresCollisionsCacheRefresh()) { capability.collision$initializeCollisionState(this.world); capability.collision$requiresCollisionsCacheRefresh(false); } return capability.collision$getMaxCollisions() < 0 || listToFill.size() < capability.collision$getMaxCollisions() || listToFill.size() < this.world.getGameRules().getInt("maxEntityCramming"); } return true; }
Source:
private String mapActionStatus(String status) { if (CoordinatorAction.Status.READY.toString().equals(status)) { return InstancesResult.WorkflowStatus.READY.name(); } else if (CoordinatorAction.Status.WAITING.toString().equals(status) || CoordinatorAction.Status.SUBMITTED.toString().equals(status)) { return InstancesResult.WorkflowStatus.WAITING.name(); } else if (CoordinatorAction.Status.IGNORED.toString().equals(status)) { return InstancesResult.WorkflowStatus.KILLED.name(); } else if (CoordinatorAction.Status.TIMEDOUT.toString().equals(status)) { return InstancesResult.WorkflowStatus.FAILED.name(); } else if (WorkflowJob.Status.PREP.toString().equals(status)) { return InstancesResult.WorkflowStatus.RUNNING.name(); } else { return status; } }

Target:
private String mapActionStatus(String status) { if (CoordinatorAction.Status.READY.toString().equals(status)) { return InstancesResult.WorkflowStatus.READY.name(); } else if (CoordinatorAction.Status.WAITING.toString().equals(status) || CoordinatorAction.Status.SUBMITTED.toString().equals(status)) { return InstancesResult.WorkflowStatus.WAITING.name(); } else if (CoordinatorAction.Status.KILLED.toString().equals(status)) { return InstancesResult.WorkflowStatus.KILLED.name(); } else if (CoordinatorAction.Status.IGNORED.toString().equals(status)) { return InstancesResult.WorkflowStatus.KILLED_OR_IGNORED.name(); } else if (CoordinatorAction.Status.TIMEDOUT.toString().equals(status)) { return InstancesResult.WorkflowStatus.TIMEDOUT.name(); } else if (WorkflowJob.Status.PREP.toString().equals(status)) { return InstancesResult.WorkflowStatus.RUNNING.name(); } else { return status; } }
Source:
private static Details getDetailsForTryCatchFinally(DetailAST ast) { boolean shouldCheckLastRcurly = false; final DetailAST rcurly; final DetailAST lcurly; DetailAST nextToken; final int tokenType = ast.getType(); if (tokenType == TokenTypes.LITERAL_TRY) { if (ast.getFirstChild().getType() == TokenTypes.RESOURCE_SPECIFICATION) { lcurly = ast.getFirstChild().getNextSibling(); } else { lcurly = ast.getFirstChild(); } nextToken = lcurly.getNextSibling(); rcurly = lcurly.getLastChild(); if (nextToken == null) { shouldCheckLastRcurly = true; nextToken = getNextToken(ast); } } else if (tokenType == TokenTypes.LITERAL_CATCH) { nextToken = ast.getNextSibling(); lcurly = ast.getLastChild(); rcurly = lcurly.getLastChild(); if (nextToken == null) { shouldCheckLastRcurly = true; nextToken = getNextToken(ast); } } else { shouldCheckLastRcurly = true; nextToken = getNextToken(ast); lcurly = ast.getFirstChild(); rcurly = lcurly.getLastChild(); } final Details details = new Details(); details.rcurly = rcurly; details.lcurly = lcurly; details.nextToken = nextToken; details.shouldCheckLastRcurly = shouldCheckLastRcurly; return details; }

Target:
private static Details getDetailsForTryCatchFinally(DetailAST ast) { boolean shouldCheckLastRcurly = false; final DetailAST rcurly; final DetailAST lcurly; DetailAST nextToken; final int tokenType = ast.getType(); if (tokenType == TokenTypes.LITERAL_TRY) { if (ast.getFirstChild().getType() == TokenTypes.RESOURCE_SPECIFICATION) { lcurly = ast.getFirstChild().getNextSibling(); } else { lcurly = ast.getFirstChild(); } nextToken = lcurly.getNextSibling(); rcurly = lcurly.getLastChild(); if (nextToken == null) { shouldCheckLastRcurly = true; nextToken = getNextToken(ast); } } else if (tokenType == TokenTypes.LITERAL_CATCH) { nextToken = ast.getNextSibling(); lcurly = ast.getLastChild(); rcurly = lcurly.getLastChild(); if (nextToken == null) { shouldCheckLastRcurly = true; nextToken = getNextToken(ast); } } else { shouldCheckLastRcurly = true; nextToken = getNextToken(ast); lcurly = ast.getFirstChild(); rcurly = lcurly.getLastChild(); } return new Details(lcurly, rcurly, nextToken, shouldCheckLastRcurly); }
Source:
protected static String getEngineSSHPublicKey() { final String keystoreFile = Config.<String>GetValue(ConfigValues.keystoreUrl); final String alias = Config.<String>GetValue(ConfigValues.CertAlias); final char[] password = Config.<String>GetValue(ConfigValues.keystorePass).toCharArray(); InputStream in = null; try { in = new FileInputStream(keystoreFile); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(in, password); final Certificate cert = ks.getCertificate(alias); if (cert == null) { Enumeration<String> aliases = ks.aliases(); log.info("Alias with name '"+alias+"' not found in "+keystoreFile); StringBuilder aliaslist = new StringBuilder(); while(aliases.hasMoreElements()) { if(aliaslist.length() != 0) { aliaslist.append(", "); } aliaslist.append(aliases.nextElement()); } log.info("aliases: " + aliaslist.toString()); throw new KeyStoreException( String.format( "Failed to find certificate store '%1$s' using alias '%2$s'", keystoreFile, alias ) ); } return OpenSSHUtils.getKeyString( cert.getPublicKey(), Config.<String>GetValue(ConfigValues.SSHKeyAlias) ); } catch (Exception e) { throw new RuntimeException( String.format( "Failed to decode own public key from store '%1$s' using alias '%2$s'", keystoreFile, alias ), e ); } finally { Arrays.fill(password, '*'); if (in != null) { try { in.close(); } catch(IOException e) { log.error("Cannot close key store", e); } } } }

Target:
protected static String getEngineSSHPublicKey() { final String keystoreFile = Config.<String>GetValue(ConfigValues.keystoreUrl); final String alias = Config.<String>GetValue(ConfigValues.CertAlias); final char[] password = Config.<String>GetValue(ConfigValues.keystorePass).toCharArray(); InputStream in = null; try { in = new FileInputStream(keystoreFile); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(in, password); final Certificate cert = ks.getCertificate(alias); if (cert == null) { log.info("Alias with name '"+alias+"' not found in "+keystoreFile); log.info("aliases: " + StringUtils.join(EnumerationUtils.toList(ks.aliases()), ',')); throw new KeyStoreException( String.format( "Failed to find certificate store '%1$s' using alias '%2$s'", keystoreFile, alias ) ); } return OpenSSHUtils.getKeyString( cert.getPublicKey(), Config.<String>GetValue(ConfigValues.SSHKeyAlias) ); } catch (Exception e) { throw new RuntimeException( String.format( "Failed to decode own public key from store '%1$s' using alias '%2$s'", keystoreFile, alias ), e ); } finally { Arrays.fill(password, '*'); if (in != null) { try { in.close(); } catch(IOException e) { log.error("Cannot close key store", e); } } } }
Source:
private void bind(SymbolStyleSearchResult symbol, OnSymbolPreviewTapListener onSymbolPreviewTapListener) { ListenableFuture<Bitmap> bitmapFuture = symbol.getSymbol().createSwatchAsync(itemView.getContext(), Color.TRANSPARENT); try { Bitmap bitmap = bitmapFuture.get(); mImageView.setImageBitmap(bitmap); } catch (InterruptedException | ExecutionException e) { logErrorToUser(itemView.getContext(), getString(R.string.error_loading_symbol_bitmap_failed, e.getMessage())); } itemView.setOnClickListener(v -> { onSymbolPreviewTapListener.onSymbolPreviewTap(symbol); }); }

Target:
private void bind(SymbolStyleSearchResult symbol, OnSymbolPreviewTapListener onSymbolPreviewTapListener) { ListenableFuture<Bitmap> bitmapFuture = symbol.getSymbol().createSwatchAsync(itemView.getContext(), Color.TRANSPARENT); try { Bitmap bitmap = bitmapFuture.get(); mImageView.setImageBitmap(bitmap); } catch (InterruptedException | ExecutionException e) { logErrorToUser(itemView.getContext(), getString(R.string.error_loading_symbol_bitmap_failed, e.getMessage())); } itemView.setOnClickListener(v -> onSymbolPreviewTapListener.onSymbolPreviewTap(symbol)); }
Source:
public void testSuccessfullIdx() throws Exception { MatcherAssert.assertThat( new PsAll( Arrays.asList( new PsFake(true), new PsFake(true), new PsFake(true), new PsFake(true) ), Tv.THREE ).enter(new RqFake()).has(), Matchers.is(true) ); }

Target:
public void testSuccessfullIdx() throws Exception { final Pass resulting = new PsFixed( new Identity.Simple("urn:foo:test") ); final RqFake request = new RqFake(); MatcherAssert.assertThat( new PsAll( Arrays.asList( new PsFake(true), new PsFake(true), new PsFake(true), resulting ), Tv.THREE ).enter(request).get().urn(), Matchers.equalTo(resulting.enter(request).get().urn()) ); }
Source:
public Mono<ResponseEntity<Map<SortedEntry, Result>>> getHealth(@RequestParam(name="all", defaultValue="false") boolean all) { final Pair<Map<String, Result>, CheckState> result = controller.runHealthChecks(); return Mono.just(ResponseEntity.status(result.getRight().getHttpStatus()).body(render(all, result.getLeft()))); }

Target:
public Mono<ResponseEntity<Map<SortedEntry, Result>>> getHealth(@RequestParam(name="all", defaultValue="false") boolean all) { final Pair<Map<String, Result>, CheckState> result = controller.runHealthChecks(); return Mono.just(ResponseEntity.status(result.getRight().getHttpStatus()).body(SortedEntry.render(all, result.getLeft()))); }
Source:
private void generateExecutableIndexExpression() throws StandardException{ if (!onExpression) return; assert compiledExpressions.length == expressionList.size(); assert compiledExpressionClassNames.length == expressionList.size(); for (int i = 0; i < expressionList.size(); i++) { ExecutableIndexExpressionClassBuilder ieb = new ExecutableIndexExpressionClassBuilder(getCompilerContext()); MethodBuilder mb = ieb.getExecuteMethod(); expressionList.elementAt(i).expression.generateExpression(ieb, mb); ieb.finishRunExpressionMethod(i + 1); compiledExpressions[i] = new ByteArray(); GeneratedClass gc = ieb.getGeneratedClass(compiledExpressions[i]); compiledExpressionClassNames[i] = gc.getName(); } }

Target:
private void generateExecutableIndexExpression() throws StandardException{ if (!onExpression) return; assert exprBytecode.length == expressionList.size(); assert generatedClassNames.length == expressionList.size(); for (int i = 0; i < expressionList.size(); i++) { ExecutableIndexExpressionClassBuilder ieb = new ExecutableIndexExpressionClassBuilder(getCompilerContext()); MethodBuilder mb = ieb.getExecuteMethod(); expressionList.elementAt(i).expression.generateExpression(ieb, mb); ieb.finishRunExpressionMethod(i + 1); exprBytecode[i] = new ByteArray(); GeneratedClass gc = ieb.getGeneratedClass(exprBytecode[i]); generatedClassNames[i] = gc.getName(); } }
Source:
public CpuVendor getVendor() { final CpuVendor cpuVendor = CpuVendor.fromFlags(privateFlags); if (cpuVendor != null) { return cpuVendor; } throw new RuntimeException("Unknown processor vendor. Flags: " + privateFlags); }

Target:
public CpuVendor getVendor() { return CpuVendor.fromFlags(privateFlags); }
Source:
public static byte[] serializeConfidentialData(OptionSet options, byte[] payload, int realCode) { if (options != null) { if (realCode > 0) { DatagramWriter writer = new DatagramWriter(); writeOptions(writer, options, true, false, realCode); if (payload != null && payload.length > 0) { writePayload(writer, payload); } return writer.toByteArray(); } else { LOGGER.severe(OSExceptionHandler.COAP_CODE_INVALID); throw new IllegalArgumentException(OSExceptionHandler.COAP_CODE_INVALID); } } else { LOGGER.severe(OSExceptionHandler.OPTIONSET_NULL); throw new IllegalArgumentException(OSExceptionHandler.OPTIONSET_NULL); } }

Target:
public static byte[] serializeConfidentialData(OptionSet options, byte[] payload, int realCode) { if (options != null) { DatagramWriter writer = new DatagramWriter(); if (realCode > 0) { OptionSet filteredOptions = OptionJuggle.prepareEoptions(options); writer.write(realCode, CoAP.MessageFormat.CODE_BITS); DataSerializer.serializeOptionsAndPayload(writer, filteredOptions, payload); return writer.toByteArray(); } else { LOGGER.error(Error.COAP_CODE_INVALID); throw new IllegalArgumentException(Error.COAP_CODE_INVALID); } } else { LOGGER.error(Error.OPTIONSET_NULL); throw new NullPointerException(Error.OPTIONSET_NULL); } }
Source:
public void testNoTime() throws IOException { String str = "time:null, before:20170101, after:20120101,timeFormat:YYYYMMDD"; try { BundleFilterTimeRange filter = Configs.decodeObject(BundleFilterTimeRange.class, str); fail("Expected exception: time field is required"); } catch(JsonMappingException jme) { assertThat(jme.getMessage(), containsString("marked as required")); } }

Target:
public void testNoTime() throws IOException { String str = "before:20170101, after:20120101,timeFormat:YYYYMMDD"; BundleFilterTimeRange filter = Configs.decodeObject(BundleFilterTimeRange.class, str); }
Source:
public String getName() { return null; }

Target:
public String getName() { return "Bump"; }
Source:
public DAG<MISTStream, MISTEdge> getOptimizedDAG() { final Set<MISTStream> visited = new HashSet<>(); for (final MISTStream source : dag.getRootVertices()) { final Map<MISTStream, MISTEdge> rootEdges = dag.getEdges(source); visited.add(source); for (final Map.Entry<MISTStream, MISTEdge> entry : rootEdges.entrySet()) { final MISTStream nextVertex = entry.getKey(); optimizing(nextVertex, visited); } } return dag; }

Target:
public DAG<MISTStream, MISTEdge> getOptimizedDAG() { final Set<MISTStream> visited = new HashSet<>(); for (final MISTStream source : dag.getRootVertices()) { final Map<MISTStream, MISTEdge> rootEdges = dag.getEdges(source); visited.add(source); for (final MISTStream nextVertex : rootEdges.keySet()) { optimizeSubDag(nextVertex, visited); } } return dag; }
Source:
public void test_getExpandHorizontal() { boolean defaultFlag = scrolledComposite.getExpandHorizontal(); boolean setFlag = !defaultFlag; scrolledComposite.setExpandHorizontal(setFlag); if (setFlag) assertTrue(scrolledComposite.getExpandHorizontal()); else assertFalse(scrolledComposite.getExpandHorizontal()); setFlag = !setFlag; scrolledComposite.setExpandHorizontal(setFlag); if (setFlag) assertTrue(scrolledComposite.getExpandHorizontal()); else assertFalse(scrolledComposite.getExpandHorizontal()); scrolledComposite.setExpandHorizontal(defaultFlag); }

Target:
public void test_getExpandHorizontal() { boolean defaultFlag = scrolledComposite.getExpandHorizontal(); boolean setFlag = !defaultFlag; scrolledComposite.setExpandHorizontal(setFlag); if (setFlag){ assertTrue(scrolledComposite.getExpandHorizontal()); } else{ assertFalse(scrolledComposite.getExpandHorizontal()); } setFlag = !setFlag; scrolledComposite.setExpandHorizontal(setFlag); if (setFlag){ assertTrue(scrolledComposite.getExpandHorizontal()); } else{ assertFalse(scrolledComposite.getExpandHorizontal()); } scrolledComposite.setExpandHorizontal(defaultFlag); }
Source:
public static ExchangeRate getExchangeRate(final Cursor cursor) { final String currencyCode = cursor .getString(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_CURRENCY_CODE)); final Coin rateCoin = Coin .valueOf(cursor.getLong(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_RATE_COIN))); final Fiat rateFiat = Fiat.valueOf(currencyCode, cursor.getLong(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_RATE_FIAT))); final String source = cursor.getString(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_SOURCE)); ExchangeRate exchangeRate = new ExchangeRate(new org.bitcoinj.utils.ExchangeRate(rateCoin, rateFiat), source); WalletApplication.getInstance().setExchangeRate(exchangeRate); return exchangeRate; }

Target:
public static ExchangeRate getExchangeRate(final Cursor cursor) { final String currencyCode = cursor .getString(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_CURRENCY_CODE)); final Coin rateCoin = Coin .valueOf(cursor.getLong(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_RATE_COIN))); final Fiat rateFiat = Fiat.valueOf(currencyCode, cursor.getLong(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_RATE_FIAT))); final String source = cursor.getString(cursor.getColumnIndexOrThrow(ExchangeRatesProvider.KEY_SOURCE)); return new ExchangeRate(new org.bitcoinj.utils.ExchangeRate(rateCoin, rateFiat), source); }
Source:
ContainerElementConstraintMappingContext nestedContainerElement(int[] nestedIndexes) { if ( !( configuredType instanceof ParameterizedType ) && !( TypeHelper.isArray( configuredType ) ) ) { throw LOG.getTypeIsNotAParameterizedNorArrayTypeException( configuredType ); } ContainerElementConstraintMappingContextImpl nestedContext = new ContainerElementConstraintMappingContextImpl( typeContext, parent, ConstraintLocation.forTypeArgument( parentLocation, typeParameter, getContainerElementType() ), nestedIndexes[0] ); nestedContainerElementContexts.put( nestedIndexes[0], nestedContext ); if ( nestedIndexes.length > 1 ) { return nestedContext.nestedContainerElement( Arrays.copyOfRange( nestedIndexes, 1, nestedIndexes.length ) ); } else { return nestedContext; } }

Target:
ContainerElementConstraintMappingContext nestedContainerElement(int[] nestedIndexes) { if ( !( configuredType instanceof ParameterizedType ) && !( TypeHelper.isArray( configuredType ) ) ) { throw LOG.getTypeIsNotAParameterizedNorArrayTypeException( configuredType ); } ContainerElementConstraintMappingContextImpl nestedContext = new ContainerElementConstraintMappingContextImpl( typeContext, parentContainerElementTarget, ConstraintLocation.forTypeArgument( parentLocation, typeParameter, getContainerElementType() ), nestedIndexes[0] ); nestedContainerElementContexts.put( nestedIndexes[0], nestedContext ); if ( nestedIndexes.length > 1 ) { return nestedContext.nestedContainerElement( Arrays.copyOfRange( nestedIndexes, 1, nestedIndexes.length ) ); } else { return nestedContext; } }
Source:
protected Quip doTargetableComplimentRequest(Map<String, String> messageMap, SsmlDocumentBuilder builder, QuipMetadata metadata) throws DerpwizardException { if(!messageMap.containsKey("target") || StringUtils.isEmpty(messageMap.get("target"))){ throw new DerpwizardException("<speak>I'm sorry, I didn't understand who you wanted me to compliment.</speak>", "I'm sorry, I didn't understand who you wanted me to compliment.", "Could not determine compliment recipient"); } String target = messageMap.get("target"); target = target.substring(0,1).toUpperCase()+target.substring(1); Queue<String> complimentsUsed = metadata.getComplimentsUsed(); Quip quip = getRandomTargetableQuip(QuipType.COMPLIMENT, complimentsUsed, target); String plaintext = quip.getText(); String ssml = quip.getSsml(); if(quip.isTargetable()){ plaintext = quip.getTargetableText(); ssml = quip.getTargetableSsml(); } builder.setShortFormTextMessage("CompliBot compliment"); builder.setFullTextMessage(plaintext); builder.text(ssml); return quip; }

Target:
protected Quip doTargetableComplimentRequest(Map<String, String> messageMap, SsmlDocumentBuilder builder, QuipMetadata metadata) throws DerpwizardException { if(!messageMap.containsKey("target") || StringUtils.isEmpty(messageMap.get("target"))){ return doComplimentRequest(messageMap, builder, metadata); } String target = messageMap.get("target"); if(target.toLowerCase().equals("me")){ return doComplimentRequest(messageMap, builder, metadata); } target = target.substring(0,1).toUpperCase()+target.substring(1); Queue<String> complimentsUsed = metadata.getComplimentsUsed(); Quip quip = getRandomTargetableQuip(QuipType.COMPLIMENT, complimentsUsed, target); String plaintext = quip.getText(); String ssml = quip.getSsml(); if(quip.isTargetable()){ plaintext = quip.getTargetableText(); ssml = quip.getTargetableSsml(); } builder.setShortFormTextMessage("CompliBot compliment"); builder.setFullTextMessage(plaintext); builder.text(ssml); return quip; }
Source:
protected void executeCommand() { try { glusterSyncJob.refreshSelfHealData(cluster); } catch (Exception e) { addCustomValue("ClusterName", cluster.getName()); auditLog(this, AuditLogType.GLUSTER_VOLUME_HEAL_REFRESH_FAILED); setSucceeded(false); } setSucceeded(true); }

Target:
protected void executeCommand() { try { glusterSyncJob.refreshSelfHealData(cluster); } catch (Exception e) { log.error("Error while refreshing Gluster self heal data of cluster '{}': {}", cluster.getName(), e.getMessage()); addCustomValue("ClusterName", cluster.getName()); auditLog(this, AuditLogType.GLUSTER_VOLUME_HEAL_REFRESH_FAILED); setSucceeded(false); } setSucceeded(true); }
Source:
public static void output(Type elementType, ArrayAggregationState state, BlockBuilder out) { if (state.isEmpty()) { out.appendNull(); } else { BlockBuilder entryBuilder = out.beginBlockEntry(); state.forEach((block, position) -> { if (entryBuilder.getRetainedSizeInBytes() > MAX_ARRAY_SIZE) { throw new PrestoException(EXCEEDED_MAX_ARRAY_SIZE, format("Array size (%s) exceeds the maximum array size (%s)", entryBuilder.getRetainedSizeInBytes(), MAX_ARRAY_SIZE)); } elementType.appendTo(block, position, entryBuilder); }); out.closeEntry(); } }

Target:
public static void output(Type elementType, ArrayAggregationState state, BlockBuilder out) { if (state.isEmpty()) { out.appendNull(); } else { BlockBuilder entryBuilder = out.beginBlockEntry(); state.forEach((block, position) -> { elementType.appendTo(block, position, entryBuilder); if (entryBuilder.getRetainedSizeInBytes() > MAX_ENTRY_RETAINED_SIZE_IN_BYTES) { throw new PrestoException(CELL_TOO_LARGE, format( "Array size %s bytes exceeds the maximum supported array size %s", new DataSize(entryBuilder.getRetainedSizeInBytes(), BYTE).toString(), new DataSize(MAX_ENTRY_RETAINED_SIZE_IN_BYTES, BYTE).toString())); } }); out.closeEntry(); } }
Source:
public ConfigBag putAll(Map flags) { for (Object eo: flags.entrySet()) { Map.Entry e = (Map.Entry)eo; boolean isNew = !config.containsKey(e.getKey()); boolean isUsed = !isNew && unusedConfig.containsKey(e.getKey()); config.put(e.getKey(), e.getValue()); if (isNew || !isUsed) unusedConfig.put(e.getKey(), e.getValue()); } return this; }

Target:
public ConfigBag putAll(Map flags) { for (Object eo: flags.entrySet()) { Map.Entry e = (Map.Entry)eo; boolean isNew = !config.containsKey(e.getKey()); boolean isUsed = !isNew && !unusedConfig.containsKey(e.getKey()); config.put(e.getKey(), e.getValue()); if (!isUsed) unusedConfig.put(e.getKey(), e.getValue()); } return this; }
Source:
private static double computeSphericalExcess(Polygon polygon, int start, int end) { if (polygon.getPoint(end - 1).equals(polygon.getPoint(start))) { end = end - 1; } if (end - start < 3) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Polygon is not valid: a loop contains less then 3 vertices."); } Point point = new Point(); polygon.getPoint(end - 1, point); SphericalExcessCalculator calculator = new SphericalExcessCalculator(point); for (int i = start; i < end; i++) { polygon.getPoint(i, point); calculator.add(point); } return calculator.getSphericalExcess(); }

Target:
private static double computeSphericalExcess(Polygon polygon, int start, int end) { if (polygon.getPoint(end - 1).equals(polygon.getPoint(start))) { end = end - 1; } if (end - start < 3) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Polygon is not valid: a loop contains less then 3 vertices."); } Point point = new Point(); polygon.getPoint(end - 1, point); SphericalExcessCalculator calculator = new SphericalExcessCalculator(point); for (int i = start; i < end; i++) { polygon.getPoint(i, point); calculator.add(point); } return calculator.computeSphericalExcess(); }
Source:
public void performHaResevationCheck() { log.debug("HA Reservation check timer entered."); List<VDSGroup> clusters = DbFacade.getInstance().getVdsGroupDao().getAll(); if (clusters != null) { HaReservationHandling haReservationHandling = new HaReservationHandling(); for (VDSGroup cluster : clusters) { if (cluster.supportsHaReservation()) { List<VDS> returnedFailedHosts = new ArrayList<VDS>(); boolean status = haReservationHandling.checkHaReservationStatusForCluster(cluster, returnedFailedHosts); if (!status) { AuditLogableBase logable = new AuditLogableBase(); logable.setVdsGroupId(cluster.getId()); logable.addCustomValue("ClusterName", cluster.getName()); String failedHostsStr = StringUtils.join(Entities.objectNames(returnedFailedHosts), ", "); logable.addCustomValue("Hosts", failedHostsStr); AlertDirector.Alert(logable, AuditLogType.CLUSTER_ALERT_HA_RESERVATION); log.infoFormat("Cluster: {0} fail to pass HA reservation check.", cluster.getName()); } boolean oldStatus = clusterId2isHaReservationSafe.containsKey(cluster.getId()) ? clusterId2isHaReservationSafe.get(cluster.getId()) : true; clusterId2isHaReservationSafe.put(cluster.getId(), status); if (!oldStatus && status) { AuditLogableBase logable = new AuditLogableBase(); logable.setVdsGroupId(cluster.getId()); logable.addCustomValue("ClusterName", cluster.getName()); AlertDirector.Alert(logable, AuditLogType.CLUSTER_ALERT_HA_RESERVATION_DOWN); log.infoFormat("Cluster: {0} pass HA reservation check.", cluster.getName()); } } } } log.debug("HA Reservation check timer finished."); }

Target:
public void performHaResevationCheck() { log.debug("HA Reservation check timer entered."); List<VDSGroup> clusters = DbFacade.getInstance().getVdsGroupDao().getAll(); if (clusters != null) { HaReservationHandling haReservationHandling = new HaReservationHandling(); for (VDSGroup cluster : clusters) { if (cluster.supportsHaReservation()) { List<VDS> returnedFailedHosts = new ArrayList<VDS>(); boolean clusterHaStatus = haReservationHandling.checkHaReservationStatusForCluster(cluster, returnedFailedHosts); if (!clusterHaStatus) { AuditLogableBase logable = new AuditLogableBase(); logable.setVdsGroupId(cluster.getId()); logable.addCustomValue("ClusterName", cluster.getName()); String failedHostsStr = StringUtils.join(Entities.objectNames(returnedFailedHosts), ", "); logable.addCustomValue("Hosts", failedHostsStr); AlertDirector.Alert(logable, AuditLogType.CLUSTER_ALERT_HA_RESERVATION); log.infoFormat("Cluster: {0} fail to pass HA reservation check.", cluster.getName()); } boolean clusterHaStatusFromPreviousCycle = clusterId2isHaReservationSafe.containsKey(cluster.getId()) ? clusterId2isHaReservationSafe.get(cluster.getId()) : true; clusterId2isHaReservationSafe.put(cluster.getId(), clusterHaStatus); if (!clusterHaStatusFromPreviousCycle && clusterHaStatus) { AuditLogableBase logable = new AuditLogableBase(); logable.setVdsGroupId(cluster.getId()); logable.addCustomValue("ClusterName", cluster.getName()); AlertDirector.Alert(logable, AuditLogType.CLUSTER_ALERT_HA_RESERVATION_DOWN); } } } } log.debug("HA Reservation check timer finished."); }
Source:
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (applicationContext instanceof AbstractApplicationContext) { ((AbstractApplicationContext) applicationContext).setId(this.containerMetadata.getId()); } this.context = applicationContext; }

Target:
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; }
Source:
private void matchIndexesToNode( NodeRecord record, CheckerEngine<NodeRecord, ConsistencyReport.NodeConsistencyReport> engine, RecordAccess records, Collection<PropertyRecord> propertyRecs ) { Set<Long> labels = NodeLabelReader.getListOfLabels( record, records, engine ); PrimitiveIntObjectMap<PropertyBlock> nodePropertyMap = null; for ( IndexRule indexRule : indexes.onlineRules() ) { int[] labelIds = indexRule.schema().getEntityTokenIds(); if ( Arrays.stream( labelIds ).asLongStream().anyMatch( labels::contains ) ) { if ( nodePropertyMap == null ) { nodePropertyMap = properties( propertyReader.propertyBlocks( propertyRecs ) ); } int[] indexPropertyIds = indexRule.schema().getPropertyIds(); if ( nodeHasSchemaProperties( nodePropertyMap, indexPropertyIds ) ) { Value[] values = getPropertyValues( nodePropertyMap, indexPropertyIds ); try ( IndexReader reader = indexes.accessorFor( indexRule ).newReader() ) { long nodeId = record.getId(); if ( indexRule.canSupportUniqueConstraint() ) { verifyNodeCorrectlyIndexedUniquely( nodeId, values, engine, indexRule, reader ); } else { long count = reader.countIndexedNodes( nodeId, values ); reportIncorrectIndexCount( values, engine, indexRule, count ); } } } } } }

Target:
private void matchIndexesToNode( NodeRecord record, CheckerEngine<NodeRecord, ConsistencyReport.NodeConsistencyReport> engine, RecordAccess records, Collection<PropertyRecord> propertyRecs ) { LongSet labels = NodeLabelReader.getListOfLabels( record, records, engine ); IntObjectMap<PropertyBlock> nodePropertyMap = null; for ( StoreIndexDescriptor indexRule : indexes.onlineRules() ) { int[] labelIds = indexRule.schema().getEntityTokenIds(); if ( Arrays.stream( labelIds ).asLongStream().anyMatch( labels::contains ) ) { if ( nodePropertyMap == null ) { nodePropertyMap = properties( propertyReader.propertyBlocks( propertyRecs ) ); } int[] indexPropertyIds = indexRule.schema().getPropertyIds(); if ( nodeHasSchemaProperties( nodePropertyMap, indexPropertyIds ) ) { Value[] values = getPropertyValues( nodePropertyMap, indexPropertyIds ); try ( IndexReader reader = indexes.accessorFor( indexRule ).newReader() ) { long nodeId = record.getId(); if ( indexRule.canSupportUniqueConstraint() ) { verifyNodeCorrectlyIndexedUniquely( nodeId, values, engine, indexRule, reader ); } else { long count = reader.countIndexedNodes( nodeId, values ); reportIncorrectIndexCount( values, engine, indexRule, count ); } } } } } }
Source:
public void testTextMaxWidth(){ assertEquals(10, testLayerDefault.getTextMaxWidth().intValue()); assertEquals(16, testLayerDefault.getTextSize().intValue()); assertEquals(160, testLayerDefault.getTextMaxWidth().intValue() * testLayerDefault.getTextSize().intValue()); assertEquals(5, testLayer.getTextMaxWidth().intValue()); assertEquals(20, testLayer.getTextSize().intValue()); assertEquals(100, testLayer.getTextMaxWidth().intValue() * testLayer.getTextSize().intValue()); }

Target:
public void testTextMaxWidth(){ assertEquals(160, testLayerDefault.getTextMaxWidth().intValue() * testLayerDefault.getTextSize().intValue()); assertEquals(100, testLayer.getTextMaxWidth().intValue() * testLayer.getTextSize().intValue()); }
Source:
public Utf8InputStreamReader(final InputStream input) { super(input, Charset.forName(Utf8InputStreamReader.ENCODING)); }

Target:
public Utf8InputStreamReader(final InputStream input) { super(input, StandardCharsets.UTF_8); }
Source:
public static int getFooterCount(Properties schema) { return getIntegerValue(schema, "skip.footer.line.count", "0"); }

Target:
public static int getFooterCount(Properties schema) { return getPositiveIntegerValue(schema, "skip.footer.line.count", "0"); }
Source:
public void testExecuteQueryNotSupported() { setup(ExpectedError.NOT_SUPPORTED); getQuery().executeQueryCommand(); Map<String, LldpInfo> returnValue = getQuery().getQueryReturnValue().getReturnValue(); assertTrue(returnValue == null); }

Target:
public void testExecuteQueryNotSupported() { setup(ExpectedError.NOT_SUPPORTED); getQuery().executeQueryCommand(); Map<String, LldpInfo> returnValue = getQuery().getQueryReturnValue().getReturnValue(); assertEquals(returnValue, null); }
Source:
public void testCreateAndBulkLoadTable() throws SQLException { String tblName = QueryUtils.DFLT_SCHEMA + ".\"PersonTbl\""; execute(conn, "create table " + tblName + " (id int primary key, age int, firstName varchar(30), lastName varchar(30))"); int updatesCnt = stmt.executeUpdate( "copy from '" + BULKLOAD_TWO_LINES_CSV_FILE + "' into " + tblName + "(_key, age, firstName, lastName)" + " format csv"); assertEquals(2, updatesCnt); checkCacheContents(tblName, true, 2); }

Target:
public void testCreateAndBulkLoadTable() throws SQLException { String tblName = QueryUtils.DFLT_SCHEMA + ".\"PersonTbl\""; execute(conn, "create table " + tblName + " (id int primary key, age int, firstName varchar(30), lastName varchar(30))"); try { int updatesCnt = stmt.executeUpdate( "copy from '" + BULKLOAD_TWO_LINES_CSV_FILE + "' into " + tblName + "(_key, age, firstName, lastName)" + " format csv"); assertEquals(2, updatesCnt); checkCacheContents(tblName, true, 2); } finally { execute(conn, "drop table " + tblName); } }
Source:
private MetadataStrategy getMetadataStrategy(final RepositoryPath repositoryPath) { MavenRepositoryConfiguration repositoryConfiguration = (MavenRepositoryConfiguration) repositoryPath.getRepository().getRepositoryConfiguration(); if (repositoryConfiguration == null) { return checksumMetadataStrategy; } MetadataStrategyEnum configuredStrategy = MetadataStrategyEnum.ofStrategy(repositoryConfiguration.getMetadataStrategy()); if (MetadataStrategyEnum.REFRESH.equals(configuredStrategy)) { return refreshMetadataStrategy; } else { return checksumMetadataStrategy; } }

Target:
private MetadataExpirationStrategy getMetadataStrategy(final RepositoryPath repositoryPath) { MavenRepositoryConfiguration repositoryConfiguration = (MavenRepositoryConfiguration) repositoryPath.getRepository().getRepositoryConfiguration(); String strategy = Optional.ofNullable(repositoryConfiguration) .map(MavenRepositoryConfiguration::getMetadataExpirationStrategy) .orElse(null); if (MetadataExpirationStrategyType.REFRESH == MetadataExpirationStrategyType.ofStrategy(strategy)) { return refreshMetadataStrategy; } return checksumMetadataExpirationStrategy; }
Source:
private List<StagingFileInfo> computeFileNamesForMissingBuckets( ConnectorSession session, Table table, HiveStorageFormat storageFormat, Path targetPath, String filePrefix, int bucketCount, PartitionUpdate partitionUpdate) { if (partitionUpdate.getStagingFileInfos().size() == bucketCount) { return ImmutableList.of(); } HdfsContext hdfsContext = new HdfsContext(session, table.getDatabaseName(), table.getTableName()); JobConf conf = toJobConf(hdfsEnvironment.getConfiguration(hdfsContext, targetPath)); String fileExtension = HiveWriterFactory.getFileExtension(conf, fromHiveStorageFormat(storageFormat)); Set<String> targetFileNames = ImmutableSet.copyOf( partitionUpdate.getStagingFileInfos().stream() .map(StagingFileInfo::getTargetFileName) .collect(toImmutableSet())); ImmutableList.Builder<StagingFileInfo> missingFileNamesBuilder = ImmutableList.builder(); for (int i = 0; i < bucketCount; i++) { String targetFileName = HiveWriterFactory.computeBucketedFileName(filePrefix, i) + fileExtension; if (!targetFileNames.contains(targetFileName)) { missingFileNamesBuilder.add(new StagingFileInfo(targetFileName, targetFileName)); } } List<StagingFileInfo> missingStagingFileInfos = missingFileNamesBuilder.build(); verify(targetFileNames.size() + missingStagingFileInfos.size() == bucketCount); return missingStagingFileInfos; }

Target:
private List<String> computeFileNamesForMissingBuckets( ConnectorSession session, Table table, HiveStorageFormat storageFormat, Path targetPath, String filePrefix, int bucketCount, PartitionUpdate partitionUpdate) { if (partitionUpdate.getFileWriteInfos().size() == bucketCount) { return ImmutableList.of(); } HdfsContext hdfsContext = new HdfsContext(session, table.getDatabaseName(), table.getTableName()); JobConf conf = toJobConf(hdfsEnvironment.getConfiguration(hdfsContext, targetPath)); String fileExtension = HiveWriterFactory.getFileExtension(conf, fromHiveStorageFormat(storageFormat)); Set<String> targetFileNames = ImmutableSet.copyOf(getTargetFileNames(partitionUpdate.getFileWriteInfos())); ImmutableList.Builder<String> missingFileNamesBuilder = ImmutableList.builder(); for (int i = 0; i < bucketCount; i++) { String targetFileName = HiveWriterFactory.computeBucketedFileName(filePrefix, i) + fileExtension; if (!targetFileNames.contains(targetFileName)) { missingFileNamesBuilder.add(targetFileName); } } List<String> missingFileNames = missingFileNamesBuilder.build(); verify(targetFileNames.size() + missingFileNames.size() == bucketCount); return missingFileNames; }
Source:
private String applyRestrictions(@NonNull String string, int maxChars) { if (string.length() > maxChars) { return string.substring(0, maxChars); } string = string.replaceAll("[:\\-\\s]", "_").replaceAll("__", "_"); return string; }

Target:
private String applyRestrictions(@NonNull String string, int maxChars) { string = truncateString(string, maxChars); string = string.replaceAll("[:\\-\\s]+", "_"); return string; }
Source:
public void setContent(String contents) { this.nameplateContent = Strings.nullToEmpty(contents); }

Target:
public void setContent(String contents) { this.nameplateContent = contents; }
Source:
public File source() { if (expression != null) { return null; } else { return new File(parameters.get(0)); } }

Target:
public Source source() { if (expression != null) { return Sources.fromCommandLine("-e"); } else { return Sources.fromFile(parameters.get(0)); } }
Source:
public static UnweightedDoubleReservoirSample deserialize(SliceInput input) { int count = input.readInt(); int maxSamples = input.readInt(); double[] samples = new double[maxSamples]; input.readBytes( Slices.wrappedDoubleArray(samples), Math.min(count, samples.length) * SizeOf.SIZE_OF_DOUBLE); return new UnweightedDoubleReservoirSample(count, samples); }

Target:
public static UnweightedDoubleReservoirSample deserialize(SliceInput input) { int seenCount = input.readInt(); int maxSamples = input.readInt(); double[] samples = new double[maxSamples]; input.readBytes(Slices.wrappedDoubleArray(samples), Math.min(seenCount, samples.length) * SizeOf.SIZE_OF_DOUBLE); return new UnweightedDoubleReservoirSample(seenCount, samples); }