auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void readLedgerMetadata(final long ledgerId, final GenericCallback<LedgerMetadata> readCb, Watcher watcher) { zk.getData(getLedgerPath(ledgerId), watcher, new DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { if (rc == KeeperException.Code.NONODE.intValue()) { if (LOG.isDebugEnabled()) { LOG.debug("No such ledger: " + ledgerId, KeeperException.create(KeeperException.Code.get(rc), path)); } readCb.operationComplete(BKException.Code.NoSuchLedgerExistsException, null); return; } if (rc != KeeperException.Code.OK.intValue()) { LOG.error("Could not read metadata for ledger: " + ledgerId, KeeperException.create(KeeperException.Code.get(rc), path)); readCb.operationComplete(BKException.Code.ZKException, null); return; } LedgerMetadata metadata; try { <START> metadata = LedgerMetadata.parseConfig(data, new ZkVersion(stat.getVersion()),stat.getCtime()); <END> } catch (IOException e) { LOG.error("Could not parse ledger metadata for ledger: " + ledgerId, e); readCb.operationComplete(BKException.Code.ZKException, null); return; } readCb.operationComplete(BKException.Code.OK, metadata); } }, null); }</code><technical_language>Space comma</technical_language>

Target:
protected void readLedgerMetadata(final long ledgerId, final GenericCallback<LedgerMetadata> readCb, Watcher watcher) { zk.getData(getLedgerPath(ledgerId), watcher, new DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { if (rc == KeeperException.Code.NONODE.intValue()) { if (LOG.isDebugEnabled()) { LOG.debug("No such ledger: " + ledgerId, KeeperException.create(KeeperException.Code.get(rc), path)); } readCb.operationComplete(BKException.Code.NoSuchLedgerExistsException, null); return; } if (rc != KeeperException.Code.OK.intValue()) { LOG.error("Could not read metadata for ledger: " + ledgerId, KeeperException.create(KeeperException.Code.get(rc), path)); readCb.operationComplete(BKException.Code.ZKException, null); return; } if (stat == null) { LOG.error("Could not parse ledger metadata for ledger: " + ledgerId+". Stat object is null"); readCb.operationComplete(BKException.Code.ZKException, null); return; } LedgerMetadata metadata; try { metadata = LedgerMetadata.parseConfig(data, new ZkVersion(stat.getVersion()), Optional.of(stat.getCtime())); } catch (IOException e) { LOG.error("Could not parse ledger metadata for ledger: " + ledgerId, e); readCb.operationComplete(BKException.Code.ZKException, null); return; } readCb.operationComplete(BKException.Code.OK, metadata); } }, null); }
Source:
<code>public static void toJSON(OutputWriter writer, PipelineSelectionResponse pipelineSelectionResponse) { writer.addChildList("selections", pipelineSelectionResponse.getSelectedPipelines().pipelineList()) .add("blacklist", pipelineSelectionResponse.getSelectedPipelines().isBlacklist()) .addChild("pipelines", pipelineGroupsWriter -> { pipelineSelectionResponse.getPipelineConfigs().forEach(pipelineConfigs -> { List<String> pipelineNames = pipelineConfigs .getPipelines().stream() .map(PipelineConfig::getName) <START> .map(CaseInsensitiveString::toString) <END> .collect(Collectors.toList()); if (!pipelineNames.isEmpty()) { pipelineGroupsWriter.addChildList(pipelineConfigs.getGroup(), pipelineNames); } }); }); }</code><technical_language>iter list instead of twice? map(pipeline -> pipeline.getName().toString())</technical_language>

Target:
public static void toJSON(OutputWriter writer, PipelineSelectionResponse pipelineSelectionResponse) { writer.addChildList("selections", pipelineSelectionResponse.getSelectedPipelines().pipelineList()) .add("blacklist", pipelineSelectionResponse.getSelectedPipelines().isBlacklist()) .addChild("pipelines", pipelineGroupsWriter -> { pipelineSelectionResponse.getPipelineConfigs().forEach(pipelineConfigs -> { List<String> pipelineNames = pipelineConfigs .getPipelines().stream() .map(pipelineConfig -> pipelineConfig.getName().toString()) .collect(Collectors.toList()); if (!pipelineNames.isEmpty()) { pipelineGroupsWriter.addChildList(pipelineConfigs.getGroup(), pipelineNames); } }); }); }
Source:
<code>public void testAmendWithPropertyChange() { DiskImage disk = createDiskImage(); disk.setVolumeFormat(VolumeFormat.COW); disk.setQcowCompat(QcowCompat.QCOW2_V2); disk.setDiskAlias("Test"); disk.setDiskDescription("Test_Desc"); when(diskDao.get(diskImageGuid)).thenReturn(disk); disk.setQcowCompat(QcowCompat.QCOW2_V3); disk.setDiskAlias("New Disk Alias"); command.getParameters().setDiskInfo(disk); initializeCommand(); doNothing().when(command).amendDiskImage(); mockVdsCommandSetVolumeDescription(); <START> command.executeVmCommand(); <END> }</code><technical_language>please verify amend function is executed</technical_language>

Target:
public void testAmendWithPropertyChange() { DiskImage oldDisk = createDiskImage(); oldDisk.setVolumeFormat(VolumeFormat.COW); oldDisk.setQcowCompat(QcowCompat.QCOW2_V2); oldDisk.setDiskAlias("Test"); oldDisk.setDiskDescription("Test_Desc"); when(diskDao.get(diskImageGuid)).thenReturn(oldDisk); DiskImage newDisk = DiskImage.copyOf(oldDisk); newDisk.setQcowCompat(QcowCompat.QCOW2_V3); newDisk.setDiskAlias("New Disk Alias"); command.getParameters().setDiskInfo(newDisk); initializeCommand(); doNothing().when(command).amendDiskImage(); mockVdsCommandSetVolumeDescription(); command.executeVmCommand(); verify(command, times(1)).amendDiskImage(); verify(command, times(1)).setVolumeDescription(any(DiskImage.class), any(StorageDomain.class)); }
Source:
<code>public void saveOrder_shouldFailIfAnActiveDrugOrderForTheSameConceptAndDrugNonCodedAndCareSettingExists() throws Exception { executeDataSet("org/openmrs/api/include/OrderServiceTest-nonCodedDrugs.xml"); final Patient patient = patientService.getPatient(2); final Concept nonCodedConcept = conceptService.getConcept(5584); DrugOrder duplicateOrder = (DrugOrder) orderService.getOrder(584); assertTrue(duplicateOrder.isActive()); assertEquals(nonCodedConcept, duplicateOrder.getConcept()); DrugOrder drugOrder = new DrugOrder(); drugOrder.setPatient(patient); <START> drugOrder.setCareSetting(orderService.getCareSetting(1)); <END> drugOrder.setConcept(nonCodedConcept); drugOrder.setDrugNonCoded("non coded drug Crocine"); drugOrder.setEncounter(encounterService.getEncounter(6)); drugOrder.setOrderer(providerService.getProvider(1)); drugOrder.setCareSetting(duplicateOrder.getCareSetting()); drugOrder.setDrug(duplicateOrder.getDrug()); drugOrder.setDose(duplicateOrder.getDose()); drugOrder.setDoseUnits(duplicateOrder.getDoseUnits()); drugOrder.setRoute(duplicateOrder.getRoute()); drugOrder.setFrequency(duplicateOrder.getFrequency()); drugOrder.setQuantity(duplicateOrder.getQuantity()); drugOrder.setQuantityUnits(duplicateOrder.getQuantityUnits()); drugOrder.setNumRefills(duplicateOrder.getNumRefills()); expectedException.expect(APIException.class); expectedException.expectMessage("Cannot have more than one active order for the same orderable and care setting"); orderService.saveOrder(drugOrder, null); }</code><technical_language>copying care setting other fields values existing guarantee</technical_language>

Target:
public void saveOrder_shouldFailIfAnActiveDrugOrderForTheSameConceptAndDrugNonCodedAndCareSettingExists() throws Exception { executeDataSet("org/openmrs/api/include/OrderServiceTest-nonCodedDrugs.xml"); final Concept nonCodedConcept = orderService.getNonCodedDrugConcept(); DrugOrder duplicateOrder = (DrugOrder) orderService.getOrder(584); assertTrue(duplicateOrder.isActive()); assertEquals(nonCodedConcept, duplicateOrder.getConcept()); DrugOrder drugOrder = duplicateOrder.copy(); drugOrder.setDrugNonCoded("non coded drug crocine"); expectedException.expect(APIException.class); expectedException.expectMessage("Cannot have more than one active order for the same orderable and care setting"); orderService.saveOrder(drugOrder, null); }
Source:
<code>private void handleScheduledTask(final ProtocolResponseMessage message) { final ScheduledTask scheduledTask = this.scheduledTaskRepository .findByCorrelationUid(message.getCorrelationUid()); if (scheduledTask == null) { LOGGER.error("Scheduled task for device with correlation uid not found", message.getDeviceIdentification(), message.getCorrelationUid()); return; } if (message.getResult() == ResponseMessageResultType.OK && scheduledTask.getStatus() == ScheduledTaskStatusType.PENDING) { this.domainResponseMessageSender.send(message); } else { if (message.getRetryHeader() != null && message.getRetryHeader().shouldRetry()) { <START> scheduledTask.retryOn(message.getRetryHeader().getScheduledRetryTime()); <END> } else { this.domainResponseMessageSender.send(message); } } this.scheduledTaskRepository.delete(scheduledTask); }</code><technical_language>a scheduled task needs retried is removed line 139. This right</technical_language>

Target:
private void handleScheduledTask(final ProtocolResponseMessage message) { final ScheduledTask scheduledTask = this.scheduledTaskRepository .findByCorrelationUid(message.getCorrelationUid()); if (scheduledTask == null) { LOGGER.error("Scheduled task for device with correlation uid not found", message.getDeviceIdentification(), message.getCorrelationUid()); return; } if (this.messageIsSuccessful(message, scheduledTask)) { this.domainResponseMessageSender.send(message); this.scheduledTaskRepository.delete(scheduledTask); } else { this.handleUnsuccessfulScheduledTask(message, scheduledTask); } }
Source:
<code>private static Set<SequenceSegment> selectReference( final Graph<SequenceSegment> graph, final Sequence reference) { <START> TreeSet<SequenceSegment> segments = new TreeSet<>(); <END> for (SequenceSegment segment : graph.getAllVertices()) { if (segment.getSources().contains(reference)) { segments.add(segment); } } return segments; }</code><technical_language>Set SortedSet variable type</technical_language>

Target:
private static Set<SequenceSegment> selectReference( final Graph<SequenceSegment> graph, final Sequence reference) { Set<SequenceSegment> segments = new TreeSet<>(); for (SequenceSegment segment : graph.getAllVertices()) { if (segment.getSources().contains(reference)) { segments.add(segment); } } return segments; }
Source:
<code>public void get(HttpServletRequest request, ModelMap model) { String currentProfile = Context.getAdministrationService().getGlobalProperty(GlobalProperties.CURRENT_PROFILE); model.addAttribute("currentProfile", currentProfile); model.addAttribute("authorized", authorized()); model = queryParamsToModelAttr(request, model); <START> if(!profileDir.exists()){ <END> model.addAttribute("success", false); model.addAttribute("message", "The Profile Manager directory does not exist. It must reside on " + "/usr/share/buendia/profiles or on a directory specified in openmrs-runtime.properties " + "file under profile_manager.profile_dir directive."); } else { model.addAttribute("profiles", listProfiles()); } }</code><technical_language>Space if ( Space ) {</technical_language>

Target:
public void get(HttpServletRequest request, ModelMap model) { String currentProfile = getCurrentProfile(); model.addAttribute("currentProfile", currentProfile); model.addAttribute("authorized", authorized()); model = queryParamsToModelAttr(request, model); if (!profileDir.exists()) { model.addAttribute("success", false); model.addAttribute("message", "The Profile Manager directory does not exist. It must reside on " + "/usr/share/buendia/profiles or on a directory specified in openmrs-runtime.properties " + "file under profile_manager.profile_dir directive."); } else { model.addAttribute("profiles", listProfiles()); } }
Source:
<code><START> public Rectangle getBounds() { <END> return syncExec(() -> this.widget.getBounds()); }</code><technical_language>Is super class implementation working</technical_language>

Target:
public Rectangle getBounds() { return super.getBounds(); }
Source:
<code>public void GetText() { if (!havePermission) { final SpeechRecognizer me = this; form.runOnUiThread(new Runnable() { @Override public void run() { form.askPermission(Manifest.permission.RECORD_AUDIO, new PermissionResultHandler() { @Override public void HandlePermissionResponse(String permission, boolean granted) { if (granted) { me.havePermission = true; me.GetText(); } else { <START> form.dispatchPermissionDeniedEvent(me, "Start", Manifest.permission.RECORD_AUDIO); <END> } } }); } }); return; } BeforeGettingText(); recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); recognizerIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true); initialize(); speechRecognizerController.addListener(this); speechRecognizerController.start(); }</code><technical_language>Start GetText</technical_language>

Target:
public void GetText() { if (!havePermission) { final SpeechRecognizer me = this; form.runOnUiThread(new Runnable() { @Override public void run() { form.askPermission(Manifest.permission.RECORD_AUDIO, new PermissionResultHandler() { @Override public void HandlePermissionResponse(String permission, boolean granted) { if (granted) { me.havePermission = true; me.GetText(); } else { form.dispatchPermissionDeniedEvent(me, "GetText", Manifest.permission.RECORD_AUDIO); } } }); } }); return; } BeforeGettingText(); speechRecognizerController.addListener(this); speechRecognizerController.start(); }
Source:
<code>private void fireExpireEventLifetime(CallbackInfo ci) { try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { <START> Sponge.getCauseStackManager().pushCause(this); <END> ExpireEntityEvent event = SpongeEventFactory.createExpireEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), this); SpongeImpl.postEvent(event); Sponge.getCauseStackManager().popCause(); } }</code><technical_language>push this frame pop manually</technical_language>

Target:
private void fireExpireEventLifetime(CallbackInfo ci) { try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this); ExpireEntityEvent event = SpongeEventFactory.createExpireEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), this); SpongeImpl.postEvent(event); } }
Source:
<code>public DbUser mapRow(ResultSet rs, int rowNum) throws SQLException { DbUser entity = new DbUser(); entity.setDepartment(rs.getString("department")); entity.setDomain(rs.getString("domain")); entity.setEmail(rs.getString("email")); <START> entity.setGroupNames(new HashSet<String>(Arrays.asList(StringUtils.split(rs.getString("groups"))))); <END> entity.setFirstName(rs.getString("name")); entity.setNote(rs.getString("note")); entity.setNote(rs.getString("note")); entity.setRole(rs.getString("role")); entity.setActive(rs.getBoolean("active")); entity.setLastName(rs.getString("surname")); entity.setId(getGuidDefaultEmpty(rs, "user_id")); entity.setLoginName(rs.getString("username")); entity.setAdmin(rs.getBoolean("last_admin_check_status")); entity.setGroupIds(convertToGuidSet(rs.getString("group_ids"), ',')); entity.setExternalId(rs.getString("external_id")); entity.setNamespace(rs.getString("namespace")); return entity; }</code><technical_language>separator is comma more</technical_language>

Target:
public DbUser mapRow(ResultSet rs, int rowNum) throws SQLException { DbUser entity = new DbUser(); entity.setDepartment(rs.getString("department")); entity.setDomain(rs.getString("domain")); entity.setEmail(rs.getString("email")); entity.setGroupNames(new HashSet<String>(Arrays.asList(StringUtils.split(rs.getString("groups"), ",")))); entity.setFirstName(rs.getString("name")); entity.setNote(rs.getString("note")); entity.setNote(rs.getString("note")); entity.setRole(rs.getString("role")); entity.setActive(rs.getBoolean("active")); entity.setLastName(rs.getString("surname")); entity.setId(getGuidDefaultEmpty(rs, "user_id")); entity.setLoginName(rs.getString("username")); entity.setAdmin(rs.getBoolean("last_admin_check_status")); entity.setGroupIds(convertToGuidSet(rs.getString("group_ids"), ',')); entity.setExternalId(rs.getString("external_id")); entity.setNamespace(rs.getString("namespace")); return entity; }
Source:
<code>public void initialise() { find("version", UILabel.class).setText(TerasologyVersion.getInstance().getHumanVersion()); WidgetUtil.trySubscribe(this, "singleplayer", button -> { <START> UIScreenLayer screen = getManager().pushScreen("engine:selectGameScreen"); <END> if (screen instanceof SelectGameScreen) { ((SelectGameScreen) screen).setLoadingAsServer(false); } }); WidgetUtil.trySubscribe(this, "multiplayer", button -> { UIScreenLayer screen = getManager().pushScreen("engine:selectGameScreen"); if (screen instanceof SelectGameScreen) { ((SelectGameScreen) screen).setLoadingAsServer(true); } }); WidgetUtil.trySubscribe(this, "join", button -> getManager().pushScreen("engine:joinGameScreen")); WidgetUtil.trySubscribe(this, "settings", button -> getManager().pushScreen("engine:settingsMenuScreen")); WidgetUtil.trySubscribe(this, "exit", button -> engine.shutdown()); }</code><technical_language>a similar method parameter takes a class argument. returns arbitrary type check unnecessary</technical_language>

Target:
public void initialise() { find("version", UILabel.class).setText(TerasologyVersion.getInstance().getHumanVersion()); WidgetUtil.trySubscribe(this, "singleplayer", button -> { getManager().pushScreen("engine:selectGameScreen", SelectGameScreen.class).setLoadingAsServer(false); }); WidgetUtil.trySubscribe(this, "multiplayer", button -> { getManager().pushScreen("engine:selectGameScreen", SelectGameScreen.class).setLoadingAsServer(true); }); WidgetUtil.trySubscribe(this, "join", button -> getManager().pushScreen("engine:joinGameScreen")); WidgetUtil.trySubscribe(this, "settings", button -> getManager().pushScreen("engine:settingsMenuScreen")); WidgetUtil.trySubscribe(this, "exit", button -> engine.shutdown()); }
Source:
<code>void writeRegionEntries(List<WAL.Entry> entries) throws IOException { long startTime = System.nanoTime(); WAL.Entry currentWalEntry = null; try { int editsCount = 0; for (WAL.Entry logEntry : entries) { currentWalEntry = logEntry; filterCellByStore(logEntry); if (!logEntry.getEdit().isEmpty()) { writer.append(logEntry); updateRegionMaximumEditLogSeqNum(logEntry); editsCount++; } else { incrementSkippedEdits(1); } } incrementEdits(editsCount); incrementNanoTime(System.nanoTime() - startTime); } catch (IOException e) { e = e instanceof RemoteException ? ((RemoteException) e).unwrapRemoteException() : e; final String errorMsg = <START> "Failed to write log entry " + currentWalEntry.toString() + " to log"; <END> LOG.error(HBaseMarkers.FATAL, errorMsg, e); updateStatusWithMsg(errorMsg); throw e; } }</code><technical_language>Missing null check here</technical_language>

Target:
void writeRegionEntries(List<WAL.Entry> entries) throws IOException { long startTime = System.nanoTime(); int editsCount = 0; for (WAL.Entry logEntry : entries) { filterCellByStore(logEntry); if (!logEntry.getEdit().isEmpty()) { try { writer.append(logEntry); } catch (IOException e) { logAndThrowWriterAppendFailure(logEntry, e); } updateRegionMaximumEditLogSeqNum(logEntry); editsCount++; } else { incrementSkippedEdits(1); } } incrementEdits(editsCount); incrementNanoTime(System.nanoTime() - startTime); }
Source:
<code>public void nextLine() { if (!columns.isEmpty()) { out.print(StringUtils.join(columns, columnSeparator)); <START> out.println(); <END> columns.clear(); } }</code><technical_language>This be: out.print('\n'); println method prints line separator string is defined system property 'line.separator'. This line separator string '\n' (e.g. Windows '\r\n'). of this of ColumnFormatterTest's currently failing Windows tests assume '\n' new line character</technical_language>

Target:
public void nextLine() { if (!columns.isEmpty()) { out.print(StringUtils.join(columns, columnSeparator)); out.print('\n'); columns.clear(); } }
Source:
<code>public void handleRequest(HttpServerExchange exchange) throws Exception { <START> boolean componentsStarted = countdown.tryAwait(COMPONENT_STARTUP_TIMEOUT, TimeUnit.MILLISECONDS); <END> if (componentsStarted) { wrappedHandler.handleRequest(exchange); } else { exchange.setStatusCode(StatusCodes.NOT_FOUND); exchange.endExchange(); } }</code><technical_language>Undertow handlers block. This server hang. Instead requests queued replayed server finishes starting. a 404 is right response if server takes long start</technical_language>

Target:
public void handleRequest(HttpServerExchange exchange) throws Exception { if (started.get()) { wrappedHandler.handleRequest(exchange); } else { Connectors.executeRootHandler(startupFailedHandler, exchange); } }
Source:
<code>private static String extractLicenseName(ExtractedLicenseInfo extractedLicenseInfo) { return !isNullEmptyOrWhitespace(extractedLicenseInfo.getName()) ? extractedLicenseInfo.getName() <START> : extractedLicenseInfo.getLicenseId().replaceAll("LicenseRef-", ""); <END> }</code><technical_language>magic constant</technical_language>

Target:
private static String extractLicenseName(ExtractedLicenseInfo extractedLicenseInfo) { return !isNullEmptyOrWhitespace(extractedLicenseInfo.getName()) ? extractedLicenseInfo.getName() : extractedLicenseInfo.getLicenseId().replaceAll(LICENSE_REF_PREFIX, ""); }
Source:
<code>public void fill(Control control, MouseEvent event, Point pt) { if (getChartViewer().getWindowDuration() != 0) { Chart chart = getChart(); IAxisSet axisSet = chart.getAxisSet(); IAxis xAxis = axisSet.getXAxis(0); double xCoordinate = xAxis.getDataCoordinate(pt.x); ISeries[] series = getChart().getSeriesSet().getSeries(); if ((xCoordinate < 0) || (series.length == 0)) { return; } double[] xS = series[0].getXSeries(); if (xS == null) { return; } int index = Arrays.binarySearch(xS, xCoordinate); index = index >= 0 ? index : -index - 1; int maxLen = 0; for (ISeries serie : series) { if (isValid(index, serie)) { maxLen = Math.max(maxLen, serie.getId().length()); } } TmfCommonXAxisChartViewer viewer = null; ITmfChartTimeProvider timeProvider = getChartViewer(); <START> if(timeProvider instanceof TmfCommonXAxisChartViewer) { <END> viewer = (TmfCommonXAxisChartViewer) timeProvider; } ITmfTimestamp time = TmfTimestamp.fromNanos((long) xCoordinate + getChartViewer().getTimeOffset()); addItem(null, Messages.TmfCommonXLineChartTooltipProvider_time, time.toString(), time.toNanos()); for (ISeries serie : series) { double[] yS = serie.getYSeries(); if (isValid(index, serie)) { String key = serie.getId(); if (viewer != null && Activator.getDefault().getPreferenceStore().getBoolean(ITmfUIPreferences.USE_BROWSER_TOOLTIPS)) { IYAppearance appearance = viewer.getSeriesAppearance(key); key = " <span style=\"color:" + appearance.getColor() + "\">" + key + "</span>"; } addItem(null, key, String.format("%12.2f", yS[index]), null); } } } }</code><technical_language>formatting..</technical_language>

Target:
public void fill(Control control, MouseEvent event, Point pt) { if (getChartViewer().getWindowDuration() != 0) { Chart chart = getChart(); IAxisSet axisSet = chart.getAxisSet(); IAxis xAxis = axisSet.getXAxis(0); double xCoordinate = xAxis.getDataCoordinate(pt.x); ISeries[] series = getChart().getSeriesSet().getSeries(); if ((xCoordinate < 0) || (series.length == 0)) { return; } double[] xS = series[0].getXSeries(); if (xS == null) { return; } int index = Arrays.binarySearch(xS, xCoordinate); index = index >= 0 ? index : -index - 1; int maxLen = 0; for (ISeries serie : series) { if (isValid(index, serie)) { maxLen = Math.max(maxLen, serie.getId().length()); } } TmfCommonXAxisChartViewer viewer = null; ITmfChartTimeProvider timeProvider = getChartViewer(); if (timeProvider instanceof TmfCommonXAxisChartViewer) { viewer = (TmfCommonXAxisChartViewer) timeProvider; } ITmfTimestamp time = TmfTimestamp.fromNanos((long) xCoordinate + getChartViewer().getTimeOffset()); addItem(null, Messages.TmfCommonXLineChartTooltipProvider_time, time.toString(), time.toNanos()); for (ISeries serie : series) { double[] yS = serie.getYSeries(); if (isValid(index, serie)) { String key = serie.getId(); if (key != null && viewer != null && Activator.getDefault().getPreferenceStore().getBoolean(ITmfUIPreferences.USE_BROWSER_TOOLTIPS)) { IYAppearance appearance = viewer.getSeriesAppearance(key); key = String.format(HTML_COLOR_TOOLTIP, appearance.getColor(), key); } addItem(null, key, String.format("%12.2f", yS[index]), null); } } } }
Source:
<code>public boolean doesMatchUserAttribute(NamingEnumeration<SearchResult> answer, Map<String, String> ldap_user_attribute_map) { boolean matches = false; StringBuffer logString = new StringBuffer(); try { if (answer.hasMore()) { SearchResult s = answer.next(); logString.append(s.getName() + "---- Users current university LDAP attributes: "); Attributes attrs = s.getAttributes(); for (String attributeName : ldap_user_attribute_map.keySet()) { String expectedValue = ldap_user_attribute_map.get(attributeName); logString.append(attrs.get(attributeName) + " ----"); if (attrs.get(attributeName) != null && attrs.get(attributeName).contains(expectedValue)) { matches = true; break; } } } } catch (Exception e) { <START> System.out.println("\nUnexpected exception when iterating over user attributes"); <END> System.out.println(e.toString()); e.printStackTrace(); } if(!matches){ log.error("No matching LDAP attributes in active directory " + logString.toString()); } return matches; }</code><technical_language>logger? This is produce a log entry context</technical_language>

Target:
public boolean doesMatchUserAttribute(NamingEnumeration<SearchResult> answer, Map<String, String> ldap_user_attribute_map) { boolean matches = false; StringBuffer logString = new StringBuffer(); try { if (answer.hasMore()) { SearchResult s = answer.next(); logString.append(s.getName() + "---- Users current university LDAP attributes: "); Attributes attrs = s.getAttributes(); for (String attributeName : ldap_user_attribute_map.keySet()) { String expectedValue = ldap_user_attribute_map.get(attributeName); logString.append(attrs.get(attributeName) + " ----"); if (attrs.get(attributeName) != null && attrs.get(attributeName).contains(expectedValue)) { matches = true; break; } } } } catch (Exception e) { LOG.error("Unexpected exception when iterating over user attributes", e); } if(!matches){ LOG.error("No matching LDAP attributes in active directory " + logString.toString()); } return matches; }
Source:
<code>private boolean upgradeNineTen(SQLiteDatabase db) { <START> db.beginTransaction(); <END> try { if (multipleInstalledAppRecords()) { throw new MigrationException(true); } SqlStorage<FormRecordV1> oldStorage = new SqlStorage<>( FormRecord.STORAGE_KEY, FormRecordV1.class, new ConcreteAndroidDbHelper(c, db)); String appId = getInstalledAppRecord().getApplicationId(); Vector<FormRecord> upgradedRecords = new Vector<>(); for (FormRecordV1 oldRecord : oldStorage) { FormRecord newRecord = new FormRecord( oldRecord.getInstanceURIString(), oldRecord.getStatus(), oldRecord.getFormNamespace(), oldRecord.getAesKey(), oldRecord.getInstanceID(), oldRecord.lastModified(), appId); newRecord.setID(oldRecord.getID()); upgradedRecords.add(newRecord); } db.execSQL(DatabaseAppOpenHelper.addColumnToTable( FormRecord.STORAGE_KEY, FormRecord.META_APP_ID, "TEXT")); SqlStorage<FormRecord> newStorage = new SqlStorage<>( FormRecord.STORAGE_KEY, FormRecord.class, new ConcreteAndroidDbHelper(c, db)); for (FormRecord r : upgradedRecords) { newStorage.write(r); } db.setTransactionSuccessful(); return true; } finally { db.endTransaction(); } }</code><technical_language>This potentially a long time. request more time commcare service connector app time out connect db (I fixture migration code this)</technical_language>

Target:
private boolean upgradeNineTen(SQLiteDatabase db) { CommCareApplication._().setCustomServiceBindTimeout(60 * 5 * 1000); db.beginTransaction(); try { if (multipleInstalledAppRecords()) { deleteExistingFormRecordsAndWarnUser(c, db); addAppIdColumnToTable(db); db.setTransactionSuccessful(); return true; } SqlStorage<FormRecordV1> oldStorage = new SqlStorage<>( FormRecord.STORAGE_KEY, FormRecordV1.class, new ConcreteAndroidDbHelper(c, db)); String appId = getInstalledAppRecord().getApplicationId(); Vector<FormRecord> upgradedRecords = new Vector<>(); for (FormRecordV1 oldRecord : oldStorage) { FormRecord newRecord = new FormRecord( oldRecord.getInstanceURIString(), oldRecord.getStatus(), oldRecord.getFormNamespace(), oldRecord.getAesKey(), oldRecord.getInstanceID(), oldRecord.lastModified(), appId); newRecord.setID(oldRecord.getID()); upgradedRecords.add(newRecord); } addAppIdColumnToTable(db); SqlStorage<FormRecord> newStorage = new SqlStorage<>( FormRecord.STORAGE_KEY, FormRecord.class, new ConcreteAndroidDbHelper(c, db)); for (FormRecord r : upgradedRecords) { newStorage.write(r); } db.setTransactionSuccessful(); return true; } finally { db.endTransaction(); } }
Source:
<code>public void testLaunchAppPackageParametersWithConfigPackage() throws Exception { ApexCli.LaunchCommandLineInfo commandLineInfo = getLaunchCommandLineInfo(new String[]{"-exactMatch", "-conf", configFile.getAbsolutePath(), appFile.getAbsolutePath(), "MyFirstApplication"}); commandLineInfo.args = new String[1]; <START> commandLineInfo.args[0] = "MyFirstApplication"; <END> String[] args = cli.getLaunchAppPackageArgs(ap, cp, commandLineInfo, null); commandLineInfo = getLaunchCommandLineInfo(args); StringBuilder sb = new StringBuilder(); for (String f : ap.getClassPath()) { if (sb.length() != 0) { sb.append(","); } sb.append(ap.tempDirectory()).append(File.separatorChar).append(f); } for (String f : cp.getClassPath()) { if (sb.length() != 0) { sb.append(","); } sb.append(cp.tempDirectory()).append(File.separatorChar).append(f); } Assert.assertEquals(sb.toString(), commandLineInfo.libjars); sb.setLength(0); for (String f : cp.getFiles()) { if (sb.length() != 0) { sb.append(","); } sb.append(cp.tempDirectory()).append(File.separatorChar).append(f); } Assert.assertEquals(sb.toString(), commandLineInfo.files); }</code><technical_language>Please notation new String[]{ "item1", "item2", ... } instead of element assignment this</technical_language>

Target:
public void testLaunchAppPackageParametersWithConfigPackage() throws Exception { ApexCli.LaunchCommandLineInfo commandLineInfo = ApexCli .getLaunchCommandLineInfo(new String[]{"-exactMatch", "-conf", configFile.getAbsolutePath(), appFile.getAbsolutePath(), "MyFirstApplication"}); commandLineInfo.args = new String[] {"MyFirstApplication"}; String[] args = cli.getLaunchAppPackageArgs(ap, cp, commandLineInfo, null); commandLineInfo = ApexCli.getLaunchCommandLineInfo(args); StringBuilder sb = new StringBuilder(); for (String f : ap.getClassPath()) { if (sb.length() != 0) { sb.append(","); } sb.append(ap.tempDirectory()).append(File.separatorChar).append(f); } for (String f : cp.getClassPath()) { if (sb.length() != 0) { sb.append(","); } sb.append(cp.tempDirectory()).append(File.separatorChar).append(f); } Assert.assertEquals(sb.toString(), commandLineInfo.libjars); sb.setLength(0); for (String f : cp.getFiles()) { if (sb.length() != 0) { sb.append(","); } sb.append(cp.tempDirectory()).append(File.separatorChar).append(f); } Assert.assertEquals(sb.toString(), commandLineInfo.files); }
Source:
<code>public static List<String> splitStatements(String expression) { <START> StringTokenizer tokenizer = new StringTokenizer(expression, SQL_SPECIAL_CHARS + BEELINE_SPECIAL_CHARS, true); <END> List<String> statements = new ArrayList<>(); String statement = ""; while (tokenizer.hasMoreElements()) { String token = (String) tokenizer.nextElement(); switch (token) { case ";": if (isValidStatement(statement)) { statements.add(statement.trim()); } statement = ""; break; case "-": statement += token; if (START_OF_COMMENT_PATTERN.matcher(statement).matches()) { statement += readUntilEndOfLine(tokenizer); } break; case "\"": case "'": statement += readQuoted(tokenizer, token); break; case "!": if (statement.trim().isEmpty()) { statement += token; statement += readUntilEndOfLine(tokenizer); if (isValidStatement(statement)) { statements.add(statement.trim()); } statement = ""; break; } default: statement += token; } } if (isValidStatement(statement)) { statements.add(statement); } return statements; }</code><technical_language>Beeline leaked a general statement splitter class. Is this avoided</technical_language>

Target:
public static List<String> splitStatements(String expression) { StringTokenizer tokenizer = new StringTokenizer(expression, SQL_SPECIAL_CHARS + BEELINE_SPECIAL_CHARS, true); List<String> statements = new ArrayList<>(); String statement = ""; while (tokenizer.hasMoreElements()) { String token = (String) tokenizer.nextElement(); switch (token) { case ";": if (isValidStatement(statement)) { statements.add(statement.trim()); } statement = ""; break; case "-": statement += token; if (START_OF_COMMENT_PATTERN.matcher(statement).matches()) { statement += readUntilEndOfLine(tokenizer); } break; case "\"": case "'": statement += readQuoted(tokenizer, token); break; case "!": if (statement.trim().isEmpty()) { statement += token; statement += readUntilEndOfLine(tokenizer); if (isValidStatement(statement)) { statements.add(statement.trim()); } statement = ""; break; } default: statement += token; } } if (isValidStatement(statement)) { statements.add(statement.trim()); } return statements; }
Source:
<code>public synchronized Map<RecipientId, Long> remove(long timestamp) { Map<RecipientId, Long> receipts = cache.remove(timestamp); Log.i(TAG, this+""); Log.i(TAG, String.format(Locale.US, "Checking early receipts (%d): %d", timestamp, receipts == null ? 0 : receipts.size())); <START> return receipts != null ? receipts : Collections.emptyMap(); <END> }</code><technical_language>If making null case immutable, do for non-null case consistent ideally get some earlier detection of potential bugs. want wrap recipients Collections.unmodifiableMap</technical_language>

Target:
public synchronized Map<RecipientId, Long> remove(long timestamp) { Map<RecipientId, Long> receipts = cache.remove(timestamp); return receipts != null ? Collections.unmodifiableMap(receipts) : Collections.emptyMap(); }
Source:
<code>private void computeNextStartPosition(List<CellTsPairInfo> results, boolean scannedSingleRow) { if (results.size() < sqlRowLimit) { if (scannedSingleRow) { byte[] nextRow = RangeRequests.getNextStartRowUnlessTerminal(false, startRowInclusive); if (nextRow == null) { reachedEnd = true; } else { <START> startRowInclusive = nextRow; <END> startColInclusive = PtBytes.EMPTY_BYTE_ARRAY; startTsInclusive = null; cellTsPairsAlreadyExaminedInCurrentRow = 0L; } } else { reachedEnd = true; } } else { CellTsPairInfo lastResult = Iterables.getLast(results); Preconditions.checkState(lastResult.ts != Long.MAX_VALUE); startRowInclusive = lastResult.rowName; startColInclusive = lastResult.colName; startTsInclusive = lastResult.ts + 1; } }</code><technical_language>fields tightly. Consider extracting a Token class cover startRowInclusive, startColInclusive, startTsInclusive, reachedEnd, cellTsPairsAlreadyExaminedInCurrentRow</technical_language>

Target:
private CellTsPairToken computeNextStartPosition(List<CellTsPairInfo> results, boolean scannedSingleRow) { if (results.size() < sqlRowLimit) { if (scannedSingleRow) { byte[] nextRow = RangeRequests.getNextStartRowUnlessTerminal(false, token.startRowInclusive()); if (nextRow == null) { return CellTsPairToken.end(); } else { cellTsPairsAlreadyExaminedInCurrentRow = 0L; return CellTsPairToken.startRow(nextRow); } } else { return CellTsPairToken.end(); } } else { CellTsPairInfo lastResult = Iterables.getLast(results); return CellTsPairToken.continueRow(lastResult); } }
Source:
<code>private void setUser(String userKey) { new Thread(() -> { UserProfile cachedProfile = Caches.UserProfileCache.getInstance().get(userKey); <START> if (cachedProfile == null) { <END> try { Caches.UserProfileCache.getInstance().put( userKey, JsonUserProfileDecoder.decodeUserProfile( Json.createReader(MapillaryURL.APIv3.getUser(userKey).openStream()).readObject() ) ); } catch (IOException var4) { Logging.log(Logging.LEVEL_WARN, "Error when downloading user profile for user key '" + userKey + "'!", var4); } } this.user = Caches.UserProfileCache.getInstance().get(userKey); }, "userProfileDownload_" + userKey).start(); }</code><technical_language>run ./gradlew spotlessApply -- pretty tab spacing is wrong (BTW, I personally prefer 4 spaces for tabs, this project is standardized 2 spaces for tabs)</technical_language>

Target:
private void setUser(String userKey) { if (userKey != null) { MainApplication.worker.submit(() -> { UserProfile cachedProfile = Caches.UserProfileCache.getInstance().get(userKey); if (cachedProfile == null) { try { Caches.UserProfileCache.getInstance().put( userKey, JsonUserProfileDecoder.decodeUserProfile( Json.createReader(MapillaryURL.APIv3.getUser(userKey).openStream()).readObject() ) ); } catch (IOException var4) { Logging.log(Logging.LEVEL_WARN, "Error when downloading user profile for user key '" + userKey + "'!", var4); } } this.user = Caches.UserProfileCache.getInstance().get(userKey); }, "userProfileDownload_" + userKey); } else { this.user = null; } }
Source:
<code>public void onAdd(SolApplication solApplication) { mapDrawer = solApplication.getGame().getMapDrawer(); mapDrawer.setToggled(true); UiVerticalListLayout verticalListLayout = new UiVerticalListLayout(); cancelButton = new UiTextButton() .setDisplayName("Cancel") .setTriggerKey(solApplication.getOptions().getKeyClose()) .setOnReleaseAction(uiElement -> { mapDrawer.setToggled(false); SolApplication.changeScreen(solApplication.getGame().getScreens().mainGameScreen); }); UiHeadlessButton alternateCancelKeyButton = new UiHeadlessButton() .setTriggerKey(solApplication.getOptions().getKeyMap()) .setOnReleaseAction(uiElement -> { <START> cancelButton.maybeFlashPressed(solApplication.getOptions().getKeyClose()); <END> }); zoomOutButton = new UiTextButton() .setDisplayName("Zoom out") .setOnReleaseAction(uiElement -> { mapDrawer.changeZoom(false); }) .setTriggerKey(solApplication.getOptions().getKeyZoomOut()); zoomInButton = new UiTextButton() .setDisplayName("Zoom in") .setOnReleaseAction(uiElement -> { mapDrawer.changeZoom(true); }) .setTriggerKey(solApplication.getOptions().getKeyZoomIn()); verticalListLayout.addElement(cancelButton); verticalListLayout.addElement(zoomInButton); verticalListLayout.addElement(zoomOutButton); verticalListLayout.addElement(alternateCancelKeyButton); rootUiElement = new UiRelativeLayout().addElement(verticalListLayout, UI_POSITION_RIGHT, -UiTextButton.DEFAULT_BUTTON_WIDTH / 2, 0); SolApplication.getInputManager().changeScreen(this); }</code><technical_language>I indentation is incorrect (one space missing)</technical_language>

Target:
public void onAdd(SolApplication solApplication) { mapDrawer = solApplication.getGame().getMapDrawer(); mapDrawer.setToggled(true); UiVerticalListLayout verticalListLayout = new UiVerticalListLayout(); cancelButton = new UiTextButton() .setDisplayName("Cancel") .setTriggerKey(solApplication.getOptions().getKeyClose()) .setOnReleaseAction(uiElement -> { mapDrawer.setToggled(false); SolApplication.changeScreen(solApplication.getGame().getScreens().mainGameScreen); }); UiHeadlessButton alternateCancelKeyButton = new UiHeadlessButton() .setTriggerKey(solApplication.getOptions().getKeyMap()) .setOnReleaseAction(uiElement -> cancelButton.maybeFlashPressed(solApplication.getOptions().getKeyClose())); zoomOutButton = new UiTextButton() .setDisplayName("Zoom out") .setOnReleaseAction(uiElement -> mapDrawer.changeZoom(false)) .setTriggerKey(solApplication.getOptions().getKeyZoomOut()); zoomInButton = new UiTextButton() .setDisplayName("Zoom in") .setOnReleaseAction(uiElement -> mapDrawer.changeZoom(true)) .setTriggerKey(solApplication.getOptions().getKeyZoomIn()); verticalListLayout.addElement(cancelButton); verticalListLayout.addElement(zoomInButton); verticalListLayout.addElement(zoomOutButton); verticalListLayout.addElement(alternateCancelKeyButton); rootUiElement = new UiRelativeLayout().addElement(verticalListLayout, UI_POSITION_RIGHT, -UiTextButton.DEFAULT_BUTTON_WIDTH / 2, 0); SolApplication.getInputManager().changeScreen(this); }
Source:
<code>public void updated(Dictionary<String, ?> config) throws ConfigurationException { <START> logger.debug("update() method is called!"); <END> if (config != null) { String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } String newPort = (String) config.get("port"); if (StringUtils.isNotBlank(newPort) && !newPort.equals(port)) { port = newPort; setProperlyConfigured(true); } } }</code><technical_language>please remove this generic log statement decrease level trace</technical_language>

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { logger.trace("update() method is called!"); if (config != null) { String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } String newPort = (String) config.get("port"); if (StringUtils.isNotBlank(newPort) && !newPort.equals(port)) { port = newPort; setProperlyConfigured(true); } } }
Source:
<code>TabletGoalState getGoalState(TabletLocationState tls, MergeInfo mergeInfo) { KeyExtent extent = tls.extent; TabletGoalState state = getSystemGoalState(tls); if (state == TabletGoalState.HOSTED) { if (tls.current != null && serversToShutdown.contains(tls.current)) { return TabletGoalState.SUSPENDED; } if (mergeInfo.getExtent() != null) { final boolean overlaps = mergeInfo.overlaps(extent); <START> if (overlaps && log.isDebugEnabled()) { <END> log.debug("mergeInfo overlaps: {}", extent, overlaps); } else if (log.isTraceEnabled()) { log.trace("mergeInfo overlaps: {}", extent, overlaps); } if (overlaps) { switch (mergeInfo.getState()) { case NONE: case COMPLETE: break; case STARTED: case SPLITTING: return TabletGoalState.HOSTED; case WAITING_FOR_CHOPPED: if (tls.getState(tserverSet.getCurrentServers()).equals(TabletState.HOSTED)) { if (tls.chopped) return TabletGoalState.UNASSIGNED; } else { if (tls.chopped && tls.walogs.isEmpty()) return TabletGoalState.UNASSIGNED; } return TabletGoalState.HOSTED; case WAITING_FOR_OFFLINE: case MERGING: return TabletGoalState.UNASSIGNED; } } } state = getTableGoalState(extent); if (state == TabletGoalState.HOSTED) { TServerInstance dest = migrations.get(extent); if (dest != null && tls.current != null && !dest.equals(tls.current)) { return TabletGoalState.UNASSIGNED; } } } return state; }</code><technical_language>slf4j checks if level is enabled, need part of conditional. time need do check is if work prepare log message avoid. case here, format string mechanism. suggestion if (overlaps) { Also, this is if condition below... combine this if/else below</technical_language>

Target:
TabletGoalState getGoalState(TabletLocationState tls, MergeInfo mergeInfo) { KeyExtent extent = tls.extent; TabletGoalState state = getSystemGoalState(tls); if (state == TabletGoalState.HOSTED) { if (tls.current != null && serversToShutdown.contains(tls.current)) { return TabletGoalState.SUSPENDED; } if (mergeInfo.getExtent() != null) { final boolean overlaps = mergeInfo.overlaps(extent); if (overlaps) { log.debug("mergeInfo overlaps: true", extent); switch (mergeInfo.getState()) { case NONE: case COMPLETE: break; case STARTED: case SPLITTING: return TabletGoalState.HOSTED; case WAITING_FOR_CHOPPED: if (tls.getState(tserverSet.getCurrentServers()).equals(TabletState.HOSTED)) { if (tls.chopped) return TabletGoalState.UNASSIGNED; } else { if (tls.chopped && tls.walogs.isEmpty()) return TabletGoalState.UNASSIGNED; } return TabletGoalState.HOSTED; case WAITING_FOR_OFFLINE: case MERGING: return TabletGoalState.UNASSIGNED; } } else { log.trace("mergeInfo overlaps: false", extent); } } state = getTableGoalState(extent); if (state == TabletGoalState.HOSTED) { TServerInstance dest = migrations.get(extent); if (dest != null && tls.current != null && !dest.equals(tls.current)) { return TabletGoalState.UNASSIGNED; } } } return state; }
Source:
<code>private void updateTimezoneForCourse(CourseAttributes course) { List<FeedbackSessionAttributes> sessions = logic.getFeedbackSessionsForCourse(course.getId()); String timeZone = sessions.isEmpty() ? Const.DEFAULT_TIMEZONE : getTimeZoneId(sessions.get(0).getTimeZone()); if (isPreview) { System.out.println("Course " + course.getId() + " to be set to " + timeZone + "."); return; } try { course.setTimeZone(timeZone); logic.updateCourse(course); <START> System.out.println("Course + " + course.getId() + " timezone successfully set to " + timeZone + "."); <END> } catch (InvalidParametersException | EntityDoesNotExistException e) { System.out.println("Failed to set timezone for course + " + course.getId() + "."); e.printStackTrace(); } }</code><technical_language>Is + in "Course + " intended? removed</technical_language>

Target:
private void updateTimezoneForCourse(CourseAttributes course) { List<FeedbackSessionAttributes> sessions = logic.getFeedbackSessionsForCourse(course.getId()); String timeZone = sessions.isEmpty() ? Const.DEFAULT_TIMEZONE : getTimeZoneId(sessions.get(0).getTimeZone()); if (isPreview) { System.out.println("Course " + course.getId() + " timezone to be set to " + timeZone + "."); return; } try { course.setTimeZone(timeZone); logic.updateCourse(course); System.out.println("Course " + course.getId() + " timezone successfully set to " + timeZone + "."); } catch (InvalidParametersException | EntityDoesNotExistException e) { System.out.println("Failed to set timezone for course " + course.getId() + "."); e.printStackTrace(); } }
Source:
<code>public BayesNetHmmModelDAODynamoDB(final AmazonDynamoDB dynamoDBClient, final String tableName){ this.dynamoDBClient = dynamoDBClient; this.tableName = tableName; <START> mapper.registerModule(new GuavaModule()); <END> mapper.registerModule(new GuavaExtrasModule()); mapper.registerModule(new JodaModule()); }</code><technical_language>Is this used</technical_language>

Target:
public BayesNetHmmModelDAODynamoDB(final AmazonDynamoDB dynamoDBClient, final String tableName){ this.dynamoDBClient = dynamoDBClient; this.tableName = tableName; }