auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void clear() { chunkIndex = -1; <START> chunkBlobSize = -1; <END> chunkBlobId = null; chunkException = null; failedAttempts = 0; partitionId = null; attemptedPartitionIds.clear(); maybeUpdateDefunctBufferInfos(); correlationIdToChunkPutRequestInfo.clear(); state = ChunkState.Free; chunkUserMetadata = userMetadata; chunkFreeAtMs = time.milliseconds(); }</code><technical_language>chunkUserMetadata encryptedPerBlobKey cleared too</technical_language>

Target:
void clear() { chunkIndex = -1; chunkBlobSize = -1; chunkBlobId = null; chunkException = null; failedAttempts = 0; partitionId = null; attemptedPartitionIds.clear(); maybeUpdateDefunctBufferInfos(); correlationIdToChunkPutRequestInfo.clear(); chunkUserMetadata = userMetadata; encryptedPerBlobKey = null; chunkFreeAtMs = time.milliseconds(); state = ChunkState.Free; }
Source:
<code>public boolean onConnect() { String dataBaseUri = connectionToolBar.getCmbDataBaseUri().getSelectedItem().toString(); if (!dataBaseUri.isEmpty()) { MultiInputPanel passwordDialog = new MultiInputPanel(I18N.tr("Please set a password")); passwordDialog.addInput("password", I18N.tr("Password"), "", new PasswordType(10)); passwordDialog.addValidation(new MIPValidation() { @Override public String validate(MultiInputPanel mid) { if (mid.getInput("password").isEmpty()) { <START> return I18N.tr("The password cannot be null"); <END> } return null; } }); if (UIFactory.showDialog(passwordDialog)) { try { String passWord = passwordDialog.getInput("password"); String properties = connectionToolBar.getDbProperties().getProperty(dataBaseUri); tableTree = getTableTree(properties.split(","), passWord); jScrollPane.setViewportView(tableTree); return true; } catch (DriverException ex) { JOptionPane.showMessageDialog(jScrollPane, I18N.tr("Cannot connect the database")); LOGGER.error(ex); return false; } catch (SQLException ex) { JOptionPane.showMessageDialog(jScrollPane, I18N.tr("Cannot connect the database")); LOGGER.error(ex); return false; } } } return false; }</code><technical_language>"Empty" "null" in this sentence. way, a password left empty connecting a database</technical_language>

Target:
public boolean onConnect() { String dataBaseUri = connectionToolBar.getCmbDataBaseUri().getSelectedItem().toString(); if (!dataBaseUri.isEmpty()) { MultiInputPanel passwordDialog = new MultiInputPanel(I18N.tr("Please set a password")); passwordDialog.addInput("password", I18N.tr("Password"), "", new PasswordType(10)); passwordDialog.addValidation(new MIPValidation() { @Override public String validate(MultiInputPanel mid) { if (mid.getInput("password").isEmpty()) { return I18N.tr("The password cannot be empty."); } return null; } }); if (UIFactory.showDialog(passwordDialog)) { try { String passWord = passwordDialog.getInput("password"); String properties = connectionToolBar.getDbProperties().getProperty(dataBaseUri); tableTree = getTableTree(properties.split(","), passWord); jScrollPane.setViewportView(tableTree); return true; } catch (DriverException ex) { JOptionPane.showMessageDialog(jScrollPane, I18N.tr("Cannot connect the database")); LOGGER.error(ex); return false; } catch (SQLException ex) { JOptionPane.showMessageDialog(jScrollPane, I18N.tr("Cannot connect the database")); LOGGER.error(ex); return false; } } } return false; }
Source:
<code><START> private static GatewaySenderEventImpl createGatewaySenderEventImpl(int transactionId, <END> boolean isLastEventInTransaction) { GatewaySenderEventImpl event = mock(GatewaySenderEventImpl.class); when(event.getTransactionId()).thenReturn(new TXId(null, transactionId)); when(event.makeHeapCopyIfOffHeap()).thenReturn(event); when(event.isLastEventInTransaction()).thenReturn(isLastEventInTransaction); return event; }</code><technical_language>This method need static</technical_language>

Target:
private GatewaySenderEventImpl createGatewaySenderEventImpl(int transactionId, boolean isLastEventInTransaction) { GatewaySenderEventImpl event = mock(GatewaySenderEventImpl.class); when(event.getTransactionId()).thenReturn(new TXId(null, transactionId)); when(event.makeHeapCopyIfOffHeap()).thenReturn(event); when(event.isLastEventInTransaction()).thenReturn(isLastEventInTransaction); return event; }
Source:
<code>public Response<BlockBlobItem> uploadWithResponse(InputStream data, long length, BlobHTTPHeaders headers, Metadata metadata, BlobAccessConditions accessConditions, Duration timeout, Context context) throws IOException { Objects.requireNonNull(data); Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(data, length, BlockBlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE); Mono<Response<BlockBlobItem>> upload = blockBlobAsyncClient <START> .uploadWithResponse(fbb, length, headers, metadata, accessConditions, context); <END> try { return Utility.blockWithOptionalTimeout(upload, timeout); } catch (UncheckedIOException e) { throw e.getCause(); } }</code><technical_language>want remove subscribeOn here</technical_language>

Target:
public Response<BlockBlobItem> uploadWithResponse(InputStream data, long length, BlobHTTPHeaders headers, Metadata metadata, BlobAccessConditions accessConditions, Duration timeout, Context context) throws IOException { Objects.requireNonNull(data); Flux<ByteBuffer> fbb = Utility.convertStreamToByteBuffer(data, length, BlockBlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE); Mono<Response<BlockBlobItem>> upload = blockBlobAsyncClient .uploadWithResponse(fbb.subscribeOn(Schedulers.elastic()), length, headers, metadata, accessConditions, context); try { return Utility.blockWithOptionalTimeout(upload, timeout); } catch (UncheckedIOException e) { throw e.getCause(); } }
Source:
<code>private String getLabel(final String value) { if (!isMultipleSelect) { return getValue(value); } final StringBuilder sb = new StringBuilder(); final String[] values = value.split(","); <START> for (int i = 0; i < values.length; i++) { <END> if (i == 0) { sb.append(getValue(values[i])); } else { sb.append(",").append(getValue(values[i])); } } return sb.toString(); }</code><technical_language>I code I worried split here</technical_language>

Target:
private String getLabel(final String value) { if (!isMultipleSelect) { return getValue(value); } final String[] values = value.split(","); return Stream.of(values) .map(s -> getValue(s)) .collect(Collectors.joining(",")); }
Source:
<code>public DB getDatabase() { Object dbNameObject = this.cfg.get( MONGODB_DATABASE ); if ( dbNameObject == null ) { <START> throw new HibernateException( "The property " + MONGODB_DATABASE <END> + " has not been set into the configration file" ); } else { String dbName = (String) dbNameObject; log.tracef( "Retrieve database %1$s", dbName ); if ( !this.mongo.getDatabaseNames().contains( dbName ) ) { throw new HibernateException( "The database called " + dbName + " doesn't exist, check the " + MONGODB_DATABASE + " property" ); } return this.mongo.getDB( dbName ); } }</code><technical_language>exceptions nice, Infinispan module is _log.unableToInitializeInfinispan( e )_ is a significant benefit that: able internationalize error messsages! useful for cases this, people do this mistake often. add extension of org.hibernate.ogm.util.impl.Log interface in mogodb module add messages want</technical_language>

Target:
public DB getDatabase() { Object dbNameObject = this.cfg.get( MONGODB_DATABASE ); if ( dbNameObject == null ) { throw new HibernateException( "The property " + MONGODB_DATABASE + " has not been set into the configration file" ); } else { String dbName = (String) dbNameObject; if ( log.isTraceEnabled() ) { log.tracef( "Retrieve database %1$s", dbName ); } if ( !this.mongo.getDatabaseNames().contains( dbName ) ) { throw new HibernateException( "The database called " + dbName + " doesn't exist, check the " + MONGODB_DATABASE + " property" ); } return this.mongo.getDB( dbName ); } }
Source:
<code>public Hardware apply(HardwareFlavour from) { <START> int MinRamSize = (int) from.hardware().ram(); <END> if (from.hardware().ram() < 1) { MinRamSize = 1; } List<Volume> volumes = new ArrayList<Volume>(); for (HardwareFlavour.Hardware.Hdd hdd : from.hardware().hdds()) { Volume vol = new VolumeBuilder() .bootDevice(hdd.isMain()) .device("hdd") .type(Volume.Type.LOCAL) .size((float) hdd.size()) .build(); volumes.add(vol); } List<Processor> processors = new ArrayList<Processor>(); for (int i = 0; i < from.hardware().vcore(); i++) { Processor proc = new Processor(from.hardware().coresPerProcessor(), 1); processors.add(proc); } final HardwareBuilder builder; builder = new HardwareBuilder() .ids(from.id()) .name(from.name()) .ram(MinRamSize) .volumes(volumes) .processors(ImmutableList.copyOf(processors)); return builder.build(); }</code><technical_language>Start variable name in lowercase</technical_language>

Target:
public Hardware apply(HardwareFlavour from) { double minRamSize = (int) from.hardware().ram(); if (from.hardware().ram() < 1) { minRamSize = 0.5; } List<Volume> volumes = new ArrayList<Volume>(); for (HardwareFlavour.Hardware.Hdd hdd : from.hardware().hdds()) { Volume vol = new VolumeBuilder() .bootDevice(hdd.isMain()) .device("hdd") .type(Volume.Type.LOCAL) .size((float) hdd.size()) .build(); volumes.add(vol); } List<Processor> processors = new ArrayList<Processor>(); for (int i = 0; i < from.hardware().coresPerProcessor(); i++) { Processor proc = new Processor(from.hardware().vcore(), 1d); processors.add(proc); } final HardwareBuilder builder; builder = new HardwareBuilder() .ids(from.id()) .name(from.name()) .ram((int) (minRamSize * 1024)) .volumes(volumes) .processors(ImmutableList.copyOf(processors)); return builder.build(); }
Source:
<code>public void onSaveInstanceState(Bundle outState) { outState.putString(MapParams.ROUTE_ID, mRouteId); outState.putBoolean(MapParams.ZOOM_TO_ROUTE, mZoomToRoute); outState.putBoolean(MapParams.ZOOM_INCLUDE_CLOSEST_VEHICLE, mZoomIncludeClosestVehicle); Location centerLocation = mFragment.getMapView().getMapCenterAsLocation(); outState.putDouble(MapParams.CENTER_LAT, centerLocation.getLatitude()); outState.putDouble(MapParams.CENTER_LON, centerLocation.getLongitude()); outState.putFloat(MapParams.ZOOM, mFragment.getMapView().getZoomLevelAsFloat()); <START> Log.v("save zoomlevel", mFragment.getMapView().getZoomLevelAsFloat() + ""); <END> }</code><technical_language>delete this Log statement - useful in debugging this implementation works correctly</technical_language>

Target:
public void onSaveInstanceState(Bundle outState) { outState.putString(MapParams.ROUTE_ID, mRouteId); outState.putBoolean(MapParams.ZOOM_TO_ROUTE, mZoomToRoute); outState.putBoolean(MapParams.ZOOM_INCLUDE_CLOSEST_VEHICLE, mZoomIncludeClosestVehicle); Location centerLocation = mFragment.getMapView().getMapCenterAsLocation(); outState.putDouble(MapParams.CENTER_LAT, centerLocation.getLatitude()); outState.putDouble(MapParams.CENTER_LON, centerLocation.getLongitude()); outState.putFloat(MapParams.ZOOM, mFragment.getMapView().getZoomLevelAsFloat()); }
Source:
<code>protected Map<String, Pair<String, String>> getSharedLocks() { Map<String, Pair<String, String>> sharedLock = new HashMap<>(); if (vmsForDisk != null) { for (Pair<VM, VmDevice> vmForDisk : vmsForDisk) { sharedLock.put(vmForDisk.getFirst().getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_VM_IS_LOCKED)); } } <START> return sharedLock.isEmpty() ? null : sharedLock; <END> }</code><technical_language>ok, shared locks sufficient need check if entity is template VM, is allowed for templates</technical_language>

Target:
protected Map<String, Pair<String, String>> getSharedLocks() { if (getDiskImage() == null || getDiskImage().getVmEntityType() == null) { return null; } if (getDiskImage().getVmEntityType().isVmType()) { return getSharedLocksForVmDisk(); } if (getDiskImage().getVmEntityType().isTemplateType()) { return getSharedLocksForTemplateDisk(); } log.warn("No shared locks are taken while sparsifying disk of entity: {}", getDiskImage().getVmEntityType()); return null; }
Source:
<code>public void testResourceSubset() throws InterruptedException { _admin.enableInstance(_clusterName, "localhost_12918", false); Thread.sleep(1000); _admin.enableCluster(_clusterName, false); _admin.enableInstance(_clusterName, "localhost_12918", true); BestPossAndExtViewZkVerifier verifier = new BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName, null, Sets.newHashSet(RESOURCES[1])); boolean result = false; try { result = ClusterStateVerifier.verifyByZkCallback(verifier); Assert.assertTrue(result); } finally { verifier.close(); } String[] args = { "--zkSvr", ZK_ADDR, "--cluster", _clusterName, "--resources", RESOURCES[1] }; result = ClusterStateVerifier.verifyState(args); Assert.assertTrue(result); <START> BestPossAndExtViewZkVerifier verifier1 = new BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName); <END> try { boolean fullResult = verifier1.verify(); Assert.assertFalse(fullResult); } finally { verifier1.close(); } _admin.enableCluster(_clusterName, true); }</code><technical_language>verifier = ..</technical_language>

Target:
public void testResourceSubset() throws InterruptedException { _admin.enableInstance(_clusterName, "localhost_12918", false); Thread.sleep(1000); _admin.enableCluster(_clusterName, false); _admin.enableInstance(_clusterName, "localhost_12918", true); BestPossAndExtViewZkVerifier verifier = new BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName, null, Sets.newHashSet(RESOURCES[1])); boolean result = false; try { result = ClusterStateVerifier.verifyByZkCallback(verifier); Assert.assertTrue(result); } finally { verifier.close(); } String[] args = { "--zkSvr", ZK_ADDR, "--cluster", _clusterName, "--resources", RESOURCES[1] }; result = ClusterStateVerifier.verifyState(args); Assert.assertTrue(result); verifier = new BestPossAndExtViewZkVerifier(ZK_ADDR, _clusterName); try { boolean fullResult = verifier.verify(); Assert.assertFalse(fullResult); } finally { verifier.close(); } _admin.enableCluster(_clusterName, true); }
Source:
<code>public List<String> getSuggestions(CommandSource source, String arguments) throws CommandException { String[] parts = arguments.split(" +", 2); List<String> suggestions = new ArrayList<String>(); if (parts.length == 1) { String incompleteCommand = parts[0].toLowerCase(); synchronized (this) { for (CommandMapping mapping : this.commands.values()) { for (String alias : mapping.getAllAliases()) { if (alias.toLowerCase().startsWith(incompleteCommand)) { suggestions.add(alias); } } } } } else { Optional<CommandMapping> mapping = get(parts[0]); if (mapping.isPresent()) { List<String> subSuggestions = mapping.get().getCallable().getSuggestions(source, parts.length > 1 ? parts[1] : ""); <START> <END> for (String alias : mapping.get().getAllAliases()) { if (alias.equalsIgnoreCase(parts[0])) { Joiner joiner = Joiner.on(' '); for(String suggestion : subSuggestions) { suggestions.add(joiner.join(alias, suggestion)); } break; } } } } return Collections.unmodifiableList(suggestions); }</code><technical_language>This change necessary</technical_language>

Target:
public List<String> getSuggestions(CommandSource source, String arguments) throws CommandException { String[] parts = arguments.split(" +", 2); List<String> suggestions = new ArrayList<String>(); if (parts.length == 1) { String incompleteCommand = parts[0].toLowerCase(); synchronized (this) { for (CommandMapping mapping : this.commands.values()) { if (!mapping.getCallable().testPermission(source)) continue; for (String alias : mapping.getAllAliases()) { if (alias.toLowerCase().startsWith(incompleteCommand)) { suggestions.add(alias); } } } } } else { Optional<CommandMapping> mapping = get(parts[0]); if (mapping.isPresent() && mapping.get().getCallable().testPermission(source)) { List<String> subSuggestions = mapping.get().getCallable().getSuggestions(source, parts.length > 1 ? parts[1] : ""); for (String alias : mapping.get().getAllAliases()) { if (alias.equalsIgnoreCase(parts[0])) { for (String suggestion : subSuggestions) { suggestions.add(SPACE_JOINER.join(alias, suggestion)); } break; } } } } return Collections.unmodifiableList(suggestions); }
Source:
<code>private void addColumnToTranslatingModel( QueryColumn column, QueryModel translatingModel, QueryModel validatingModel ) throws SqlException { if (validatingModel != null) { <START> CharSequence refColumn = Chars.toLowerCase(column.getAst().token); <END> final int dot = Chars.indexOf(refColumn, '.'); getIndexOfTableForColumn(validatingModel, refColumn, dot, column.getAst().position); if (dot != -1 && validatingModel.getJoinModels().size() == 1) { ExpressionNode base = column.getAst(); column.of( column.getAlias(), expressionNodePool.next().of( base.type, base.token.subSequence(dot + 1, base.token.length()), base.precedence, base.position ) ); } } translatingModel.addBottomUpColumn(column); }</code><technical_language>Unnecessary toLowerCase</technical_language>

Target:
private void addColumnToTranslatingModel( QueryColumn column, QueryModel translatingModel, QueryModel validatingModel ) throws SqlException { if (validatingModel != null) { CharSequence refColumn = column.getAst().token; final int dot = Chars.indexOf(refColumn, '.'); getIndexOfTableForColumn(validatingModel, refColumn, dot, column.getAst().position); if (dot != -1 && validatingModel.getJoinModels().size() == 1) { ExpressionNode base = column.getAst(); column.of( column.getAlias(), expressionNodePool.next().of( base.type, base.token.subSequence(dot + 1, base.token.length()), base.precedence, base.position ) ); } } translatingModel.addBottomUpColumn(column); }
Source:
<code><START> int getCpuPercentage() { <END> if (System.currentTimeMillis() <= cpuRecordTime + cpuMaxAllowedDelayInMs) { return cpuPercentage; } cpuPercentage = (int) (osBean.getSystemCpuLoad() * 100); cpuRecordTime = System.currentTimeMillis(); logger.trace("CPU percentage: {}", cpuPercentage); return cpuPercentage; }</code><technical_language>Casey's suggestion, class generic method geConsumptionPercentage(HardwareResource resource) throttler call</technical_language>

Target:
private int getCpuPercentage() { if (System.currentTimeMillis() <= cpuLastSampleTime.get() + cpuSamplingPeriodMs) { return cpuPercentage; } cpuPercentage = (int) (osBean.getSystemCpuLoad() * 100); cpuLastSampleTime.set(System.currentTimeMillis()); logger.trace("CPU percentage: {}", cpuPercentage); return cpuPercentage; }
Source:
<code>public void runCommandByXpath( String idTopMenuCommand, String idCommandName, String xpathSubCommandName) { seleniumWebDriverHelper.waitSuccessCondition( driver -> { runCommand(idTopMenuCommand, idCommandName); <START> WaitUtils.sleepQuietly(1); <END> if (seleniumWebDriverHelper.isVisible(By.xpath(xpathSubCommandName))) { seleniumWebDriverHelper.waitAndClick(By.xpath(xpathSubCommandName)); return true; } return false; }, ELEMENT_TIMEOUT_SEC); }</code><technical_language>nice if get rid of WaitUtils.sleepQuietly(1)</technical_language>

Target:
public void runCommandByXpath( String idTopMenuCommand, String idCommandName, String xpathSubCommandName) { seleniumWebDriverHelper.waitSuccessCondition( driver -> { runCommand(idTopMenuCommand, idCommandName); if (isMenuItemVisible(By.xpath(xpathSubCommandName))) { runCommand(By.xpath(xpathSubCommandName)); return true; } return false; }, ELEMENT_TIMEOUT_SEC); }
Source:
<code>public List<CorfuQueueRecord<E>> entryList(CorfuRecordId entriesAfter, int maxEntries) { <START> if (maxEntries <= 0) { <END> throw new IllegalArgumentException("entryList given negative maxEntries"); } if (maxEntries > MAX_INDEX_ENTRIES) { throw new IllegalArgumentException( "entryList can't return more than "+MAX_INDEX_ENTRIES+" entries" ); } List<CorfuQueueRecord<E>> copy = new ArrayList<>( Math.min(corfuTable.size(), maxEntries) ); Comparator<Map.Entry<Long, CorfuQueueRecord<E>>> recordIdComparator = (r1, r2) -> r1.getValue().getRecordId().compareTo(r2.getValue().recordId); int index = 0; for (Map.Entry<Long, CorfuQueueRecord<E>> entry : corfuTable.entryStream() .filter(e -> e.getValue().getRecordId().compareTo(entriesAfter) > 0) .sorted(recordIdComparator).collect(Collectors.toList())) { if (++index >= maxEntries) { break; } copy.add(entry.getValue()); } return copy; }</code><technical_language>put a .limit(maxEntries) .filter() avoid collecting sorting entries ++index. This more efficient</technical_language>

Target:
public List<CorfuQueueRecord<E>> entryList(CorfuRecordId entriesAfter, int maxEntries) { if (maxEntries <= 0) { throw new IllegalArgumentException("entryList can't take zero or negative maxEntries"); } log.trace("entryList: "+maxEntries+" entries after:"+entriesAfter); List<CorfuQueueRecord<E>> copy = new ArrayList<>( Math.min(corfuTable.size(), maxEntries) ); Comparator<Map.Entry<Long, CorfuQueueRecord<E>>> recordIdComparator = (r1, r2) -> r1.getValue().getRecordId().compareTo(r2.getValue().recordId); for (Map.Entry<Long, CorfuQueueRecord<E>> entry : corfuTable.entryStream() .filter(e -> e.getValue().getRecordId().compareTo(entriesAfter) > 0) .limit(maxEntries) .sorted(recordIdComparator).collect(Collectors.toList())) { copy.add(entry.getValue()); } return copy; }
Source:
<code>public boolean reserve(long size) throws IllegalArgumentException { if (size < 0) { throw new IllegalArgumentException("Reservation size cannot be negative"); } while (true) { OffHeapResourceState currentState = state.get(); OffHeapResourceState newState = currentState.reserve(size); <START> if (newState.getUsed() > newState.getCapacity()) { <END> return false; } if (state.compareAndSet(currentState, newState)) { stateUpdated(newState); return true; } } }</code><technical_language>nice like: if (newState.overflows()) { move logic OffHeapResourceState object fields there</technical_language>

Target:
public boolean reserve(long size) throws IllegalArgumentException { if (size < 0) { throw new IllegalArgumentException("Reservation size cannot be negative"); } while (true) { OffHeapResourceState currentState = state.get(); OffHeapResourceState newState = currentState.reserve(size); if (newState.isOverflowed()) { return false; } if (state.compareAndSet(currentState, newState)) { stateUpdated(newState); return true; } } }
Source:
<code>public static void setup() throws Exception { <START> System.setProperty("com.ibm.jsse2.overrideDefaultTLS", "true"); <END> }</code><technical_language>good set this property if IBM JDK is in use</technical_language>

Target:
public static void setup() throws Exception { if (Utils.IBM_JDK) { defaultTSLValue = System.setProperty(IBM_JSSE2_DEFAULT_TSL, "true"); } }
Source:
<code>public void closed( BoltConnection connection ) { String id = connection.id(); try { <START> CompletableFuture currentFuture = activeWorkItems.remove( id ); <END> if ( currentFuture != null ) { currentFuture.cancel( true ); } } finally { activeConnections.remove( id ); } }</code><technical_language>CompletableFuture<Boolean> avoid raw types</technical_language>

Target:
public void closed( BoltConnection connection ) { String id = connection.id(); try { CompletableFuture<Boolean> currentFuture = activeWorkItems.remove( id ); if ( currentFuture != null ) { currentFuture.cancel( true ); } } finally { activeConnections.remove( id ); } }
Source:
<code>private List<Project> filterProjectsWithIndices(Set<Project> projects) { List<String> patterns = new ArrayList<>(projects.size()); for (Project project : projects) { String indexPattern = kibanaUtils.formatIndexPattern(project); patterns.add(indexPattern); } LOGGER.trace("Evaluating indexPattern for existing index.", patterns.size()); Set<Project> result = new HashSet<>(projects.size()); SearchResponse response = pluginClient.search(patterns.toArray(new String[]{}), ArrayUtils.EMPTY_STRING_ARRAY, 1000, false); for (SearchHit hit : response.getHits().getHits()){ LOGGER.trace("Evaluating index {}", hit.getIndex()); Project project = kibanaUtils.getProjectFromIndex(hit.getIndex()); LOGGER.trace("Found index for project {}", project); <START> result.add(project); <END> } return new ArrayList<>(result); }</code><technical_language>response.getHits() return null? If so, need guard NPE</technical_language>

Target:
private List<Project> filterProjectsWithIndices(Set<Project> projects) { List<String> patterns = new ArrayList<>(projects.size()); for (Project project : projects) { String indexPattern = kibanaUtils.formatIndexPattern(project); patterns.add(indexPattern); } LOGGER.trace("Evaluating indexPattern for existing index.", patterns.size()); Set<Project> result = new HashSet<>(projects.size()); SearchResponse response = pluginClient.search(patterns.toArray(new String[]{}), ArrayUtils.EMPTY_STRING_ARRAY, 1000, false); if (response.getHits() == null ) { LOGGER.warn("Searching for indexPatterns returned a response with a null hits (e.g. response.getHits())"); return Collections.emptyList(); } for (SearchHit hit : response.getHits().getHits()){ LOGGER.trace("Evaluating index {}", hit.getIndex()); Project project = kibanaUtils.getProjectFromIndex(hit.getIndex()); LOGGER.trace("Found index for project {}", project); result.add(project); } return new ArrayList<>(result); }
Source:
<code>public void locate() throws Exception { MultiBranchImpl stuff = r.createProject(MultiBranchImpl.class, "stuff"); stuff.getSourcesList().add(new BranchSource(new SingleSCMSource(null, "dev/flow", new NullSCM()))); stuff.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); showComputation(stuff); <START> FreeStyleProject master = r.jenkins.getItemByFullName("stuff/dev%2fflow", FreeStyleProject.class); <END> assertNotNull(master); assertEquals(r.jenkins.getRootPath().child("workspace/stuff_dev_flow-L5GKER67QGVMJ2UD3JCSGKEV2ACON2O4VO4RNUZ27HGUY32SYVXQ"), r.jenkins.getWorkspaceFor(master)); DumbSlave slave = r.createOnlineSlave(); assertEquals(slave.getWorkspaceRoot().child("stuff_dev_flow-L5GKER67QGVMJ2UD3JCSGKEV2ACON2O4VO4RNUZ27HGUY32SYVXQ"), slave.getWorkspaceFor(master)); FreeStyleProject unrelated = r.createFreeStyleProject("100% crazy"); assertEquals(r.jenkins.getRootPath().child("workspace/100% crazy"), r.jenkins.getWorkspaceFor(unrelated)); }</code><technical_language>%2F %2f</technical_language>

Target:
public void locate() throws Exception { MultiBranchImpl stuff = r.createProject(MultiBranchImpl.class, "stuff"); stuff.getSourcesList().add(new BranchSource(new SingleSCMSource(null, "dev/flow", new NullSCM()))); stuff.scheduleBuild2(0).getFuture().get(); r.waitUntilNoActivity(); showComputation(stuff); FreeStyleProject master = r.jenkins.getItemByFullName("stuff/dev%2Fflow", FreeStyleProject.class); assertNotNull(master); assertEquals(r.jenkins.getRootPath().child("workspace/stuff_dev_flow-L5GKER67QGVMJ2UD3JCSGKEV2ACON2O4VO4RNUZ27HGUY32SYVXQ"), r.jenkins.getWorkspaceFor(master)); DumbSlave slave = r.createOnlineSlave(); assertEquals(slave.getWorkspaceRoot().child("stuff_dev_flow-L5GKER67QGVMJ2UD3JCSGKEV2ACON2O4VO4RNUZ27HGUY32SYVXQ"), slave.getWorkspaceFor(master)); FreeStyleProject unrelated = r.createFreeStyleProject("100% crazy"); assertEquals(r.jenkins.getRootPath().child("workspace/100% crazy"), r.jenkins.getWorkspaceFor(unrelated)); }
Source:
<code>public View getView(int position, View convertView, ViewGroup parent) { if (appList != null) { View view; if (convertView == null) { view = inflater.inflate(R.layout.kiosk_app_drawer, null); } else { view = convertView; } Holder holder = new Holder(); holder.appName = (TextView) view.findViewById(R.id.name); holder.appIcon = (ImageView) view.findViewById(R.id.icon); PackageManager pm = context.getPackageManager(); String packageName = appList.get(position); if (packageName.equals(NEW_APP)) { holder.appName.setText(NEW_APP); holder.appIcon.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_download)); } else { ApplicationInfo applicationInfo = null; try { applicationInfo = pm.getApplicationInfo(packageName, 0); } catch (PackageManager.NameNotFoundException e) { <START> e.printStackTrace(); <END> } holder.appName.setText(pm.getApplicationLabel(applicationInfo).toString()); try { holder.appIcon.setImageDrawable(pm.getApplicationIcon(packageName)); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } return view; } else { return null; } }</code><technical_language>print stack trace, log.e instead</technical_language>

Target:
public View getView(int position, View convertView, ViewGroup parent) { if (appList != null) { View view; if (convertView == null) { view = inflater.inflate(R.layout.kiosk_app_drawer, null); } else { view = convertView; } Holder holder = new Holder(); holder.appName = (TextView) view.findViewById(R.id.name); holder.appIcon = (ImageView) view.findViewById(R.id.icon); PackageManager pm = context.getPackageManager(); String packageName = appList.get(position); if (packageName.equals(NEW_APP)) { holder.appName.setText(NEW_APP); holder.appIcon.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_download)); } else { ApplicationInfo applicationInfo = null; try { applicationInfo = pm.getApplicationInfo(packageName, 0); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG,"Package name not found", e); } holder.appName.setText(pm.getApplicationLabel(applicationInfo).toString()); try { holder.appIcon.setImageDrawable(pm.getApplicationIcon(packageName)); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG,"Package name not found", e); } } return view; } else { return null; } }
Source:
<code>public void initFileSystem() { try { <START> fileSystem = ioService.newFileSystem(spaces.resolveFileSystemURI(SpacesAPIImpl.Scheme.DEFAULT, <END> SpacesAPI.DEFAULT_SPACE, "security"), new HashMap<String, Object>() {{ put("init", Boolean.TRUE); put("internal", Boolean.TRUE); }}); } catch (FileSystemAlreadyExistsException e) { fileSystem = ioService.getFileSystem(spaces.resolveFileSystemURI(SpacesAPIImpl.Scheme.DEFAULT, SpacesAPI.DEFAULT_SPACE, "security")); } this.root = fileSystem.getRootDirectories().iterator().next(); }</code><technical_language>SpacesAPI.Scheme instead of SpacesAPIImpl.Scheme</technical_language>

Target:
public void initFileSystem() { try { fileSystem = ioService.newFileSystem(spaces.resolveFileSystemURI(SpacesAPI.Scheme.DEFAULT, SpacesAPI.DEFAULT_SPACE, "security"), new HashMap<String, Object>() {{ put("init", Boolean.TRUE); put("internal", Boolean.TRUE); }}); } catch (FileSystemAlreadyExistsException e) { fileSystem = ioService.getFileSystem(spaces.resolveFileSystemURI(SpacesAPI.Scheme.DEFAULT, SpacesAPI.DEFAULT_SPACE, "security")); } this.root = fileSystem.getRootDirectories().iterator().next(); }
Source:
<code>public static ClassName bestGuess(String classNameString) { List<String> names = new ArrayList<>(); int p = 0; while (p < classNameString.length() && Character.isLowerCase(classNameString.charAt(p))) { p = classNameString.indexOf('.', p) + 1; checkArgument(p != 0, "couldn't make a guess for %s", classNameString); } names.add(p != 0 ? classNameString.substring(0, p - 1) : ""); for (String part : classNameString.substring(p).split("\\.", -1)) { <START> checkArgument(!part.isEmpty() && Character.isUpperCase(part.charAt(0)), <END> "couldn't make a guess for %s", classNameString); names.add(part); } checkArgument(names.size() >= 2, "couldn't make a guess for %s", classNameString); return new ClassName(names); }</code><technical_language>part.codePointAt(0)</technical_language>

Target:
public static ClassName bestGuess(String classNameString) { List<String> names = new ArrayList<>(); int p = 0; while (p < classNameString.length() && Character.isLowerCase(classNameString.codePointAt(p))) { p = classNameString.indexOf('.', p) + 1; checkArgument(p != 0, "couldn't make a guess for %s", classNameString); } names.add(p != 0 ? classNameString.substring(0, p - 1) : ""); for (String part : classNameString.substring(p).split("\\.", -1)) { checkArgument(!part.isEmpty() && Character.isUpperCase(part.codePointAt(0)), "couldn't make a guess for %s", classNameString); names.add(part); } checkArgument(names.size() >= 2, "couldn't make a guess for %s", classNameString); return new ClassName(names); }
Source:
<code>public void release( T obj ) { LocalSlot<T> localSlot = puddle.get(); <START> if ( localSlot.release( obj ) ) <END> { } else { pool.release( obj ); } }</code><technical_language>if ( !localSlot.release( obj ) ) { // Fall delegate pool pool.release( obj ); }</technical_language>

Target:
public void release( T obj ) { LocalSlot<T> localSlot = puddle.get(); if ( !localSlot.release( obj ) ) { pool.release( obj ); } }
Source:
<code>public void assertionFailureGivesActiveDetails() { TestSubscriber<String> ts = new TestSubscriber<String>(); ts.onNext("a"); ts.onNext("b"); ts.onNext("c"); ts.onError(new TestException("forced failure")); try { ts.assertValues("1", "2"); fail(); } catch (AssertionError expected) { assertEquals("Number of items does not match. Provided: 2 Actual: 3.\n" + "Provided values: [1, 2]\n" + <START> "Actual values: [a, b, c] (0 completions) (+1 errors)", <END> expected.getMessage() ); Throwable ex = expected.getCause(); assertEquals(TestException.class, ex.getClass()); assertEquals("forced failure", ex.getMessage()); } }</code><technical_language>In case of long Actual values: number of completions errors visible enough for developer, move new line</technical_language>

Target:
public void assertionFailureGivesActiveDetails() { TestSubscriber<String> ts = new TestSubscriber<String>(); ts.onNext("a"); ts.onNext("b"); ts.onNext("c"); ts.onError(new TestException("forced failure")); try { ts.assertValues("1", "2"); fail(); } catch (AssertionError expected) { assertEquals("Number of items does not match. Provided: 2 Actual: 3.\n" + "Provided values: [1, 2]\n" + "Actual values: [a, b, c]\n (0 completions) (+1 error)", expected.getMessage() ); Throwable ex = expected.getCause(); assertEquals(TestException.class, ex.getClass()); assertEquals("forced failure", ex.getMessage()); } }
Source:
<code>public void handleSetMbusUserKeyByChannelResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType responseMessageResultType, final OsgpException exception) { LOGGER.info("handleSetMbusUserKeyByChannelResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = responseMessageResultType; if (exception != null) { LOGGER.error("Set M-Bus User Key By Channel Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } <START> this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() <END> .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleSetMbusUserKeyByChannelResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType responseMessageResultType, final OsgpException exception) { LOGGER.info("handleSetMbusUserKeyByChannelResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = responseMessageResultType; if (exception != null) { LOGGER.error("Set M-Bus User Key By Channel Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send(responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>protected ByteBuffer filterChunkToRange(ByteBuffer buf) { if (options.getBlobOptions.getRange() == null) { return buf; } if (resolvedByteRange.getRangeSize() == 0) { buf.position(0); buf.limit(0); } else { long relativeOffset = offset; <START> if (options.getBlobOptions.getBlobSegment() != -1) { <END> relativeOffset = 0; } long startOffsetInThisChunk = chunkIndex == 0 ? resolvedByteRange.getStartOffset() - relativeOffset : 0; long endOffsetInThisChunkExclusive = chunkIndex == (numChunksTotal - 1) ? resolvedByteRange.getEndOffset() - relativeOffset + 1 : chunkSize; buf.position((int) startOffsetInThisChunk); buf.limit((int) endOffsetInThisChunkExclusive); } return buf.slice(); }</code><technical_language>constant, alternatively add utility method GetBlobOptions.hasBlobSegment()</technical_language>

Target:
protected ByteBuffer filterChunkToRange(ByteBuffer buf) { if (options.getBlobOptions.getRange() == null) { return buf; } if (resolvedByteRange.getRangeSize() == 0) { buf.position(0); buf.limit(0); } else { long relativeOffset = offset; if (options.getBlobOptions.hasBlobSegmentIdx()) { relativeOffset = 0; } long startOffsetInThisChunk = chunkIndex == 0 ? resolvedByteRange.getStartOffset() - relativeOffset : 0; long endOffsetInThisChunkExclusive = chunkIndex == (numChunksTotal - 1) ? resolvedByteRange.getEndOffset() - relativeOffset + 1 : chunkSize; buf.position((int) startOffsetInThisChunk); buf.limit((int) endOffsetInThisChunkExclusive); } return buf.slice(); }
Source:
<code>public void onMapReady(GoogleMap googleMap) { mMap = googleMap; <START> if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { <END> finish(); } mMap.setMyLocationEnabled(false); mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { @Override public void onMapLongClick(LatLng latLng) { placeNewGeofence(latLng); } }); }</code><technical_language>move this repeated permission-related code some common helper, a static method in ListExamplesActivity</technical_language>

Target:
public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if (!ListExamplesActivity.checkLocationPermissions(this)) { finish(); return; } mMap.setMyLocationEnabled(false); mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { @Override public void onMapLongClick(LatLng latLng) { placeNewGeofence(latLng); } }); }
Source:
<code>public boolean onPrepareOptionsMenu(Menu menu) { <START> menu.getItem(0).setEnabled(savedPagesList.getCount() > 0); <END> return super.onPrepareOptionsMenu(menu); }</code><technical_language>findId well</technical_language>

Target:
public boolean onPrepareOptionsMenu(Menu menu) { menu.findItem(R.id.menu_clear_all_saved_pages).setEnabled(savedPagesList.getCount() > 0); return super.onPrepareOptionsMenu(menu); }
Source:
<code>public byte exitStatus() { return results.isEmpty() || (runtimeOptions.isWip() ? max(results, SEVERITY).isOkWip(runtimeOptions.isStrict()) : <START> max(results, SEVERITY).isOk(runtimeOptions.isStrict())) ? 0x0 : ERRORS; <END> }</code><technical_language>if statements here. [guard clauses](<LINK_0> handle empty case wip case. I this fail is test case passes test case failed</technical_language>

Target:
public byte exitStatus() { if (results.isEmpty()) { return DEFAULT; } if (runtimeOptions.isWip()) { return min(results, SEVERITY).is(Result.Type.PASSED) ? ERRORS : DEFAULT; } return max(results, SEVERITY).isOk(runtimeOptions.isStrict()) ? DEFAULT : ERRORS; }
Source:
<code>public static <C extends ReadableByteChannel & SuspendableReadChannel> int readBlocking(C channel, ByteBuffer buffer, long time, TimeUnit unit) throws IOException { int res = channel.read(buffer); if (res != 0) { return res; } long startTimeNanos = System.nanoTime(); long timeoutNanos = unit.toNanos(time); long remainingNanos; while (res == 0 && buffer.hasRemaining() <START> && (remainingNanos = timeoutNanos - (System.nanoTime() - startTimeNanos)) > 0) { <END> channel.awaitReadable(remainingNanos, TimeUnit.NANOSECONDS); res = channel.read(buffer); } return res; }</code><technical_language>This structure System.nanoTime called in short succession intervening wait. preferred call nanoTime start, immediately waiting</technical_language>

Target:
public static <C extends ReadableByteChannel & SuspendableReadChannel> int readBlocking(C channel, ByteBuffer buffer, long time, TimeUnit unit) throws IOException { int res = channel.read(buffer); if (res != 0) { return res; } long remaining = unit.toNanos(time); long now = System.nanoTime(); while (buffer.hasRemaining() && remaining > 0) { channel.awaitReadable(remaining, TimeUnit.NANOSECONDS); res = channel.read(buffer); if (res != 0) { return res; } remaining -= Math.max(-now + (now = System.nanoTime()), 0L); } return res; }
Source:
<code>public void procreate() { if (getSpouseID() != null && getSpouse() == null) { setSpouseID(null); } if (!isDeployed()) { if (getAge(campaign.getCalendar()) > 13 && getAge(campaign.getCalendar()) < 51) { if (getSpouse() == null && campaign.getCampaignOptions().useUnofficialProcreationNoRelationship()) { if (Compute.randomInt(100000) < 2) { GregorianCalendar tCal = (GregorianCalendar) campaign.getCalendar().clone(); tCal.add(GregorianCalendar.DAY_OF_YEAR, 40*7); setDueDate(tCal); campaign.addReport(getHyperlinkedName()+" has conceived"); if (campaign.getCampaignOptions().logConception()) { addLogEntry(campaign.getDate(), "Has conceived"); } } } else if (getSpouse() != null) { if (getSpouse().isActive() && !getSpouse().isDeployed() && getSpouse().getAge(campaign.getCalendar()) > 13) { <START> if (Compute.randomInt(10000) < 200) { <END> GregorianCalendar tCal = (GregorianCalendar) campaign.getCalendar().clone(); tCal.add(GregorianCalendar.DAY_OF_YEAR, 40*7); setDueDate(tCal); campaign.addReport(getHyperlinkedName()+" has conceived"); if (campaign.getCampaignOptions().logConception()) { addLogEntry(campaign.getDate(), "Has conceived"); } } } } } } }</code><technical_language>So, other change in percentage line for procreation, this good</technical_language>

Target:
public void procreate() { if (getSpouseID() != null && getSpouse() == null) { setSpouseID(null); } if (!isDeployed()) { if (getAge(campaign.getCalendar()) > 13 && getAge(campaign.getCalendar()) < 51) { if (getSpouse() == null && campaign.getCampaignOptions().useUnofficialProcreationNoRelationship()) { if (Compute.randomInt(100000) < 2) { GregorianCalendar tCal = (GregorianCalendar) campaign.getCalendar().clone(); tCal.add(GregorianCalendar.DAY_OF_YEAR, 40*7); setDueDate(tCal); campaign.addReport(getHyperlinkedName()+" has conceived"); if (campaign.getCampaignOptions().logConception()) { addLogEntry(campaign.getDate(), "Has conceived"); } } } else if (getSpouse() != null) { if (getSpouse().isActive() && !getSpouse().isDeployed() && getSpouse().getAge(campaign.getCalendar()) > 13) { if (Compute.randomInt(10000) < 2) { GregorianCalendar tCal = (GregorianCalendar) campaign.getCalendar().clone(); tCal.add(GregorianCalendar.DAY_OF_YEAR, 40*7); setDueDate(tCal); campaign.addReport(getHyperlinkedName()+" has conceived"); if (campaign.getCampaignOptions().logConception()) { addLogEntry(campaign.getDate(), "Has conceived"); } } } } } } }
Source:
<code>public void shouldShowAllMusicsAsHTTP() { MockHttpResult mockHttpResult = new MockHttpResult(); controller = new MusicController(dao, userInfo, mockHttpResult, validator, musics); when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.showAllMusicsAsHTTP(); assertEquals("<p class=\"content\">"+ Arrays.asList(music).toString()+"</p>", mockHttpResult.getBody()); <START> } <END></code><technical_language>If want, change hamcrest too. method Matchers.is compare if objects equals</technical_language>

Target:
public void shouldShowAllMusicsAsHTTP() { MockHttpResult mockHttpResult = new MockHttpResult(); controller = new MusicController(dao, userInfo, mockHttpResult, validator, musics); when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.showAllMusicsAsHTTP(); assertThat(mockHttpResult.getBody(), is("<p class=\"content\">"+ Arrays.asList(music).toString()+"</p>")); }
Source:
<code>public void run() { fFilterDialog.update(fTimeGraphViewer.getControl().getShell(), this, fTimeGraphViewer); fFilterDialog.open(); <START> fFilterDialog.getShell().setSize(400, 400); <END> }</code><technical_language>set size. Layout managers handle creation of right size. However, set minimum size (setMinimumSize()) prevent users dialog small</technical_language>

Target:
public void run() { fFilterDialog.update(fTimeGraphViewer.getControl().getShell(), this, fTimeGraphViewer); fFilterDialog.open(); fFilterDialog.getShell().setSize(SHELL_SIZE, SHELL_SIZE); }
Source:
<code>private void authenticateCheck(String username, String password) { if (NetworkUtils.hasNetwork()) { RestApi restApi = RestServiceBuilder.createService(RestApi.class, username, password); Call<Session> call = restApi.getSession(); call.enqueue(new Callback<Session>() { @Override public void onResponse(Call<Session> call, Response<Session> response) { if (response.isSuccessful()) { Session session = response.body(); if (session.isAuthenticated()) { Log.e("Service Task ", "user authenticated"); } else { Log.e("Service Task ", "User Credentials Changed"); <START> if(isForeground(ApplicationConstants.PACKAGE_NAME)){ <END> Intent broadcastIntent = new Intent(); broadcastIntent.setAction(ApplicationConstants.BroadcastActions.AUTHENTICATION_CHECK_BROADCAST_ACTION); sendBroadcast(broadcastIntent); }else{ OpenMRSDBOpenHelper.getInstance().closeDatabases(); mOpenMRS.clearUserPreferencesData(); mOpenMRS.clearCurrentLoggedInUserInfo(); } } } else { ToastUtil.error("Error in AuthenticateCheckService Response"); } } @Override public void onFailure(Call<Session> call, Throwable t) { ToastUtil.error("Error in AuthenticateCheckService"); } }); } else { Log.e("Service Task ", "No Network"); } }</code><technical_language>Format this file Android Studio's formatter</technical_language>

Target:
private void authenticateCheck(String username, String password) { if (NetworkUtils.hasNetwork()) { RestApi restApi = RestServiceBuilder.createService(RestApi.class, username, password); Call<Session> call = restApi.getSession(); call.enqueue(new Callback<Session>() { @Override public void onResponse(Call<Session> call, Response<Session> response) { if (response.isSuccessful()) { Session session = response.body(); if (session.isAuthenticated()) { Log.e("Service Task ", "user authenticated"); } else { Log.e("Service Task ", "User Credentials Changed"); if (isForeground(OpenMRS.getInstance().getPackageName())) { Intent broadcastIntent = new Intent(); broadcastIntent.setAction(ApplicationConstants.BroadcastActions.AUTHENTICATION_CHECK_BROADCAST_ACTION); sendBroadcast(broadcastIntent); } else { OpenMRSDBOpenHelper.getInstance().closeDatabases(); mOpenMRS.clearUserPreferencesData(); mOpenMRS.clearCurrentLoggedInUserInfo(); } } } else { ToastUtil.error("Error in AuthenticateCheckService Response"); } } @Override public void onFailure(Call<Session> call, Throwable t) { ToastUtil.error("Error in AuthenticateCheckService"); } }); } else { Log.e("Service Task ", "No Network"); } }