auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void openConnectionAsync() throws IOException { throwable.set(null); if (loginUrl != null && userName != null && password != null) { JSONObject json = new JSONObject(); try { json.put("userName", userName); json.put("password", password); } catch (JSONException ex) { throw new RuntimeException(ex); } <START> client.preparePost(loginUrl).setHeader("Content-Type", "application/json").setBody(json.toString()) <END> .execute(new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { List<Cookie> cookies = response.getCookies(); BoundRequestBuilder brb = client.prepareGet(uri.toString()); if (cookies != null) { for (Cookie cookie : cookies) { brb.addCookie(cookie); } } connection = brb .execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new PubSubWebSocket()).build()) .get(); return response; } }); } else { client.prepareGet(uri.toString()).execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener( new PubSubWebSocket() { @Override public void onOpen(WebSocket ws) { connection = ws; super.onOpen(ws); } }) .build() ); } }</code><technical_language>Consider introducing local variable</technical_language>

Target:
public void openConnectionAsync() throws IOException { throwable.set(null); if (loginUrl != null && userName != null && password != null) { JSONObject json = new JSONObject(); try { json.put("userName", userName); json.put("password", password); } catch (JSONException ex) { throw new RuntimeException(ex); } client.preparePost(loginUrl).setHeader("Content-Type", "application/json").setBody(json.toString()) .execute(new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { List<Cookie> cookies = response.getCookies(); BoundRequestBuilder brb = client.prepareGet(uri.toString()); if (cookies != null) { for (Cookie cookie : cookies) { brb.addCookie(cookie); } } connection = brb.execute(new WebSocketUpgradeHandler.Builder().addWebSocketListener(new PubSubWebSocket()).build()) .get(); return response; } }); } else { final WebSocketUpgradeHandler.Builder socketUpgradeBuilder = new WebSocketUpgradeHandler.Builder().addWebSocketListener(new PubSubWebSocket() { @Override public void onOpen(WebSocket ws) { connection = ws; super.onOpen(ws); } }); client.prepareGet(uri.toString()).execute(socketUpgradeBuilder.build()); } }
Source:
<code>public void executeAndTrigger(Set<String> tables, String sql, Object... args) { execute(sql, args); <START> sendTableTrigger(Collections.unmodifiableSet(tables)); <END> }</code><technical_language>need wrap unmodifiable downstream of is internal. If wanted defensive need a copy of collection ends hurting single-table overload builds a singleton set a copy made</technical_language>

Target:
public void executeAndTrigger(Set<String> tables, String sql, Object... args) { execute(sql, args); sendTableTrigger(tables); }
Source:
<code>private void finishInitialization() { String value = property.getValue(); <START> if (value.equals("None") && !choices.containsValue(value)) { <END> property.setValue(""); } }</code><technical_language>a bit concerned this legacy code here. In theory, a component called selectable this reset it</technical_language>

Target:
private void finishInitialization() { String value = property.getValue(); if (value == choices.getValueAtIndex(0)) { property.setValue(""); } }
Source:
<code>public OkHttpNetworkFetcher(OkHttpClient okHttpClient) { mCallFactory = okHttpClient; <START> mCancellationExecutor = okHttpClient.dispatcher().executorService(); <END> }</code><technical_language>Instead of setting both, call this(okHttpClient, okHttpClient.dispatcher().executorService())</technical_language>

Target:
public OkHttpNetworkFetcher(OkHttpClient okHttpClient) { this(okHttpClient, okHttpClient.dispatcher().executorService()); }
Source:
<code>private @Nullable OutputElementStyle getElementStyle(ITimeEvent event) { OutputElementStyle elementStyle; if (fTimeGraphProvider instanceof IStylePresentationProvider) { IStylePresentationProvider provider = (IStylePresentationProvider) fTimeGraphProvider; elementStyle = provider.getElementStyle(event); if (elementStyle == null) { return null; } if (elementStyle.getParentKey() == null && elementStyle.getStyleValues().isEmpty()) { return elementStyle; } return new OutputElementStyle(elementStyle.getParentKey(), applyEventStyleProperties(new HashMap<>(elementStyle.getStyleValues()), event)); } <START> int colorIdx = fTimeGraphProvider.getStateTableIndex(event); <END> if (colorIdx == ITimeGraphPresentationProvider.INVISIBLE) { return null; } if (colorIdx == ITimeGraphPresentationProvider.TRANSPARENT) { return new OutputElementStyle(null, new HashMap<>()); } @NonNull Map<@NonNull String, @NonNull Object> styleMap = StylePropertiesUtils.updateEventStyleProperties(fTimeGraphProvider.getEventStyle(event)); return new OutputElementStyle(null, applyEventStyleProperties(styleMap, event)); }</code><technical_language>common method is backward-compatible enough for markers. presentation provider returns state table index INVISIBLE TRANSPARENT handle MarkerEvent, return early MarkerEvent color, some code expects fillColor() returned getEventStyle(). common method skip state table index for MarkerEvent</technical_language>

Target:
private @Nullable OutputElementStyle getElementStyle(ITimeEvent event) { OutputElementStyle elementStyle; if (fTimeGraphProvider instanceof IStylePresentationProvider) { IStylePresentationProvider provider = (IStylePresentationProvider) fTimeGraphProvider; elementStyle = provider.getElementStyle(event); if (elementStyle == null) { return null; } if (elementStyle.getParentKey() == null && elementStyle.getStyleValues().isEmpty()) { return elementStyle; } return new OutputElementStyle(elementStyle.getParentKey(), applyEventStyleProperties(new HashMap<>(elementStyle.getStyleValues()), event)); } if (!(event instanceof MarkerEvent)) { int colorIdx = fTimeGraphProvider.getStateTableIndex(event); if (colorIdx == ITimeGraphPresentationProvider.INVISIBLE) { return null; } if (colorIdx == ITimeGraphPresentationProvider.TRANSPARENT) { return new OutputElementStyle(null, new HashMap<>()); } } @NonNull Map<@NonNull String, @NonNull Object> styleMap = StylePropertiesUtils.updateEventStyleProperties(fTimeGraphProvider.getEventStyle(event)); return new OutputElementStyle(null, applyEventStyleProperties(styleMap, event)); }
Source:
<code>public StateReport getReport(String domain) { StateReport report = new StateReport(domain); report = new StateReport(ReportConstants.CAT); report.setStartTime(new Date(m_startTime)); report.setEndTime(new Date(m_startTime + MINUTE * 60 - 1)); report.getMachines().clear(); String ip = NetworkInterfaceManager.INSTANCE.getLocalHostAddress(); Machine machine = report.findOrCreateMachine(ip); buildStateInfo(machine); StateReport startReport = m_reportManager.getHourlyReport(getStartTime(), ReportConstants.CAT, true); <START> for(String key:machine.getProcessDomains().keySet()){ <END> machine.getProcessDomains().get(key).getIps().addAll(startReport.findOrCreateMachine(ip).getProcessDomains().get(key).getIps()); } return report; }</code><technical_language>problem. Map.Entry instead</technical_language>

Target:
public StateReport getReport(String domain) { StateReport report = new StateReport(domain); report = new StateReport(ReportConstants.CAT); report.setStartTime(new Date(m_startTime)); report.setEndTime(new Date(m_startTime + MINUTE * 60 - 1)); report.getMachines().clear(); String ip = NetworkInterfaceManager.INSTANCE.getLocalHostAddress(); Machine machine = report.findOrCreateMachine(ip); buildStateInfo(machine); StateReport startReport = m_reportManager.getHourlyReport(getStartTime(), ReportConstants.CAT, true); Map<String, ProcessDomain> processDomains = startReport.findOrCreateMachine(ip).getProcessDomains(); for(Map.Entry<String, ProcessDomain> entry:machine.getProcessDomains().entrySet()){ entry.getValue().getIps().addAll(processDomains.get(entry.getKey()).getIps()); } return report; }
Source:
<code>public void executeFix(final String endpointId) throws DotDataException, DotSecurityException { DotConnect dc = new DotConnect(); final String getResultsQuery = new StringBuilder("SELECT ") .append(getIntegrityType().getFirstDisplayColumnLabel()) .append(", local_identifier, remote_identifier, local_working_inode, remote_working_inode, local_live_inode, remote_live_inode, language_id FROM ") .append(getIntegrityType().getResultsTableName()).append(" WHERE endpoint_id = ?") .toString(); dc.setSQL(getResultsQuery); dc.addParam(endpointId); List<Map<String, Object>> results = dc.loadObjectResults(); Map<String, Integer> versionCount = new HashMap<String, Integer>(); for (Map<String, Object> result : results) { final String oldIdentifier = (String) result.get("local_identifier"); final Integer counter = versionCount.get(oldIdentifier); if (counter == null) { versionCount.put(oldIdentifier, 1); } else { versionCount.put(oldIdentifier, counter + 1); } } for (Map<String, Object> result : results) { final String oldIdentifier = (String) result.get("local_identifier"); int counter = versionCount.get(oldIdentifier); boolean isTheLastConflict = counter == 1 ? true : false; try{ fixContentletConflicts(result, Structure.STRUCTURE_TYPE_FILEASSET, isTheLastConflict); } catch(IOException e){ <START> throw new DotDataException(e.getMessage(),e); <END> } if (!isTheLastConflict) { versionCount.put(oldIdentifier, counter - 1); } } }</code><technical_language>is re-throwing a DotDataException, a good alternative do this <LINK_0> instead (please scroll up, github handle line ref diff view well). Surround line try catch DotDataException rethrow. prevent changing signature of generateNewContentlet, moveInodeFolder fixContentletConflicts result</technical_language>

Target:
public void executeFix(final String endpointId) throws DotDataException, DotSecurityException { DotConnect dc = new DotConnect(); final String getResultsQuery = new StringBuilder("SELECT ") .append(getIntegrityType().getFirstDisplayColumnLabel()) .append(", local_identifier, remote_identifier, local_working_inode, remote_working_inode, local_live_inode, remote_live_inode, language_id FROM ") .append(getIntegrityType().getResultsTableName()).append(" WHERE endpoint_id = ?") .toString(); dc.setSQL(getResultsQuery); dc.addParam(endpointId); List<Map<String, Object>> results = dc.loadObjectResults(); Map<String, Integer> versionCount = new HashMap<String, Integer>(); for (Map<String, Object> result : results) { final String oldIdentifier = (String) result.get("local_identifier"); final Integer counter = versionCount.get(oldIdentifier); if (counter == null) { versionCount.put(oldIdentifier, 1); } else { versionCount.put(oldIdentifier, counter + 1); } } for (Map<String, Object> result : results) { final String oldIdentifier = (String) result.get("local_identifier"); int counter = versionCount.get(oldIdentifier); boolean isTheLastConflict = counter == 1 ? true : false; fixContentletConflicts(result, Structure.STRUCTURE_TYPE_FILEASSET, isTheLastConflict); if (!isTheLastConflict) { versionCount.put(oldIdentifier, counter - 1); } } }
Source:
<code>public Void call() throws Exception { ReviewDb db = sysInjector.getInstance(ReviewDb.class); GitRepositoryManager mgr = sysInjector.getInstance(GitRepositoryManager.class); repo = mgr.openRepository(project); try { Map<String, Ref> refs = repo.getAllRefs(); <START> for (Change c : db.changes().all()) { <END> Ref r = refs.get(c.currentPatchSetId().toRefName()); if (r != null) { byId.put(r.getObjectId(), new ChangeData(c)); } } walk(); } finally { repo.close(); RepositoryCache.close(repo); } return null; }</code><technical_language>load change? Filter project? load this list *once* Reindex process reuse in thread</technical_language>

Target:
public Void call() throws Exception { ReviewDb db = sysInjector.getInstance(ReviewDb.class); GitRepositoryManager mgr = sysInjector.getInstance(GitRepositoryManager.class); repo = mgr.openRepository(project); try { Map<String, Ref> refs = repo.getAllRefs(); for (Change c : db.changes().byProject(project)) { Ref r = refs.get(c.currentPatchSetId().toRefName()); if (r != null) { byId.put(r.getObjectId(), new ChangeData(c)); } } walk(); } finally { repo.close(); RepositoryCache.close(repo); } return null; }
Source:
<code>public void tearDown() throws Exception { <START> File credDir = new File("."); <END> File file = new File(credDir, JKS_FILE_NAME); file.delete(); file = new File(credDir, "." + JKS_FILE_NAME + ".crc"); file.delete(); }</code><technical_language>define credDir public static final String CRED_DIR reused in tearDown testResolveAlias? Thanks</technical_language>

Target:
public void tearDown() throws Exception { File file = new File(credDir, JKS_FILE_NAME); file.delete(); file = new File(credDir, "." + JKS_FILE_NAME + ".crc"); file.delete(); }
Source:
<code>long verifyDigestAndReturnLac(ByteBuf dataReceived) throws BKDigestMatchException{ if ((LAC_METADATA_LENGTH + macCodeLength) > dataReceived.readableBytes()) { logger.error("Data received is smaller than the minimum for this digest type." + " Either the packet it corrupt, or the wrong digest is configured. " + " Digest type: {}, Packet Length: {}", this.getClass().getName(), dataReceived.readableBytes()); throw new BKDigestMatchException(); } update(dataReceived.slice(0, LAC_METADATA_LENGTH)); int offset = LAC_METADATA_LENGTH + macCodeLength; <START> update(dataReceived.slice(offset, dataReceived.readableBytes() - offset)); <END> ByteBuf digest = PooledByteBufAllocator.DEFAULT.buffer(macCodeLength); try { populateValueAndReset(digest); if (digest.compareTo(dataReceived.slice(LAC_METADATA_LENGTH, macCodeLength)) != 0) { logger.error("Mac mismatch for ledger-id LAC: " + ledgerId); throw new BKDigestMatchException(); } } finally { digest.release(); } long actualLedgerId = dataReceived.readLong(); long lac = dataReceived.readLong(); if (actualLedgerId != ledgerId) { logger.error("Ledger-id mismatch in authenticated message, expected: " + ledgerId + " , actual: " + actualLedgerId); throw new BKDigestMatchException(); } return lac; }</code><technical_language>this from? original code a single update for LAC metadata header. This is including a payload in checksum, I thought payload for this type of message, this unneeded noop</technical_language>

Target:
long verifyDigestAndReturnLac(ByteBuf dataReceived) throws BKDigestMatchException{ if ((LAC_METADATA_LENGTH + macCodeLength) > dataReceived.readableBytes()) { logger.error("Data received is smaller than the minimum for this digest type." + " Either the packet it corrupt, or the wrong digest is configured. " + " Digest type: {}, Packet Length: {}", this.getClass().getName(), dataReceived.readableBytes()); throw new BKDigestMatchException(); } update(dataReceived.slice(0, LAC_METADATA_LENGTH)); ByteBuf digest = PooledByteBufAllocator.DEFAULT.buffer(macCodeLength); try { populateValueAndReset(digest); if (digest.compareTo(dataReceived.slice(LAC_METADATA_LENGTH, macCodeLength)) != 0) { logger.error("Mac mismatch for ledger-id LAC: " + ledgerId); throw new BKDigestMatchException(); } } finally { digest.release(); } long actualLedgerId = dataReceived.readLong(); long lac = dataReceived.readLong(); if (actualLedgerId != ledgerId) { logger.error("Ledger-id mismatch in authenticated message, expected: " + ledgerId + " , actual: " + actualLedgerId); throw new BKDigestMatchException(); } return lac; }
Source:
<code>protected boolean uploadCertificate(String certificate, String certificateName, long hostId) { SetupDirectDownloadCertificateCommand cmd = new SetupDirectDownloadCertificateCommand(certificate, certificateName); Answer answer = agentManager.easySend(hostId, cmd); if (answer == null || !answer.getResult()) { String msg = "Certificate " + certificateName + " could not be added to host " + hostId; if (answer != null) { msg += " due to: " + answer.getDetails(); } <START> s_logger.info(msg); <END> return false; } s_logger.info("Certificate " + certificateName + " successfully uploaded to host: " + hostId); return true; }</code><technical_language>is error, right</technical_language>

Target:
protected boolean uploadCertificate(String certificate, String certificateName, long hostId) { SetupDirectDownloadCertificateCommand cmd = new SetupDirectDownloadCertificateCommand(certificate, certificateName); Answer answer = agentManager.easySend(hostId, cmd); if (answer == null || !answer.getResult()) { String msg = "Certificate " + certificateName + " could not be added to host " + hostId; if (answer != null) { msg += " due to: " + answer.getDetails(); } s_logger.error(msg); return false; } s_logger.info("Certificate " + certificateName + " successfully uploaded to host: " + hostId); return true; }
Source:
<code>private Sequence remove(final Sequence[] args) throws XPathException { final AbstractMapType map = (AbstractMapType) args[0].itemAt(0); <START> AtomicValue[] keys = new AtomicValue[args[1].getItemCount()]; <END> for (int i = 0; i < keys.length; i++) { keys[i] = (AtomicValue) args[1].itemAt(i); } return map.remove(keys); }</code><technical_language>replaced nice lambda/collector expression</technical_language>

Target:
private Sequence remove(final Sequence[] args) throws XPathException { final AbstractMapType map = (AbstractMapType) args[0].itemAt(0); final int length = args[1].getItemCount(); final AtomicValue[] keys = new AtomicValue[length]; for (int i = 0; i < length; i++) { keys[i] = (AtomicValue) args[1].itemAt(i); } return map.remove(keys); }
Source:
<code>public void signalProcessInstances(List<Long> processInstanceIds) { if (view.getSignalRefText() == null || view.getSignalRefText().isEmpty()) { view.setHelpText(constants.Signal_Name_Required()); return; } for (Long processInstanceId : processInstanceIds) { view.displayNotification(constants.Signaling_Process_Instance() + " (" + constants.Id() + " = " + processInstanceId + ") " + constants.Signal() + " = " + view.getSignalRefText() + " - " + constants.Signal_Data() + " = " + view.getEventText()); } processService.call((Void v) -> { processInstancesUpdatedEvent.fire(new ProcessInstancesUpdateEvent(0L)); <START> bulkActionPerformedEvent.fire(new BulkActionPerformedEvent()); <END> placeManager.closePlace(place); } ).signalProcessInstances(serverTemplateId, Arrays.asList(deploymentId), processInstanceIds, view.getSignalRefText(), view.getEventText()); }</code><technical_language>.. I consider this affecting task bulk actions due class name ... ProcessInstanceSignalPresenter is part in task bulk actions</technical_language>

Target:
public void signalProcessInstances(List<Long> processInstanceIds) { if (view.getSignalRefText() == null || view.getSignalRefText().isEmpty()) { view.setHelpText(constants.Signal_Name_Required()); return; } for (Long processInstanceId : processInstanceIds) { view.displayNotification(constants.Signaling_Process_Instance() + " (" + constants.Id() + " = " + processInstanceId + ") " + constants.Signal() + " = " + view.getSignalRefText() + " - " + constants.Signal_Data() + " = " + view.getEventText()); } processService.call((Void v) -> { processInstancesUpdatedEvent.fire(new ProcessInstancesUpdateEvent(0L)); deselectAllItemsEvent.fire(new DeselectAllItemsEvent()); placeManager.closePlace(place); } ).signalProcessInstances(serverTemplateId, Arrays.asList(deploymentId), processInstanceIds, view.getSignalRefText(), view.getEventText()); }
Source:
<code>private Map<Cell, Value> getRowsAllColumns(final TableReference tableRef, final Iterable<byte[]> rows, final long timestamp) { if (Iterables.isEmpty(rows)) { return ImmutableMap.of(); } Map<Cell, Value> toReturn = new HashMap<>(); <START> for (List<byte[]> part : Iterables.partition(rows, PARTITION_SIZE)) { <END> toReturn.putAll(run(ctx -> { Select<? extends Record> query = getLatestTimestampQueryAllColumns( ctx, tableRef, ImmutableList.copyOf(part), timestamp); Result<? extends Record> records = fetchValues(ctx, tableRef, query); Map<Cell, Value> results = Maps.newHashMapWithExpectedSize(records.size()); for (Record record : records) { results.put( Cell.create(record.getValue(A_ROW_NAME), record.getValue(A_COL_NAME)), Value.create(record.getValue(A_VALUE), record.getValue(A_TIMESTAMP))); } return results; })); } return toReturn; }</code><technical_language>A confused - this is called getRows(), guarantees iterable passed in this method PARTITION_SIZE elements. Do intend batchSizeForReads here? If this is intended read PARTITION_SIZE need this partition all, run single toReturn.putAll(run(...)) call once</technical_language>

Target:
private Map<Cell, Value> getRowsAllColumns(final TableReference tableRef, final Iterable<byte[]> rows, final long timestamp) { if (Iterables.isEmpty(rows)) { return ImmutableMap.of(); } return run(ctx -> { Select<? extends Record> query = getLatestTimestampQueryAllColumns( ctx, tableRef, ImmutableList.copyOf(rows), timestamp); Result<? extends Record> records = fetchValues(ctx, tableRef, query); Map<Cell, Value> results = Maps.newHashMapWithExpectedSize(records.size()); for (Record record : records) { results.put( Cell.create(record.getValue(A_ROW_NAME), record.getValue(A_COL_NAME)), Value.create(record.getValue(A_VALUE), record.getValue(A_TIMESTAMP))); } return results; }); }
Source:
<code>private static ArrayList<ArrayList<String>> findCliqueCover(Graph graph, int bestSize, String tabs) { <START> verboseLog(tabs+"findCliqueCover up to "+bestSize+", "+graph.toString()); <END> for (int i=0; i<graph.verts.length; i++) { if (i >= bestSize-1) { verboseLog(tabs+"giving up"); return null; } String v0 = graph.verts[i]; if (!graph.edges.get(v0).isEmpty()) { verboseLog(tabs+"Selected vertex "+v0); String v1 = graph.edges.get(v0).iterator().next(); ArrayList<ArrayList<String>> bestCover0 = findCliqueCover(graph.ntract(v0,v1), bestSize, tabs+"----"); int bestSize0 = bestCover0 == null ? bestSize : bestCover0.size(); graph.removeEdge(v0,v1); ArrayList<ArrayList<String>> bestCover1 = findCliqueCover(graph, bestSize0, tabs+" "); graph.addEdge(v0,v1); if (bestCover1 != null) { return bestCover1; } else { if (bestCover0 != null) { bestCover0.get(i).add(v1); } return bestCover0; } } } verboseLog(tabs+"done, "+graph.verts.length); ArrayList<ArrayList<String>> bestCover = new ArrayList<>(); for (int i=0; i<graph.verts.length; i++) { ArrayList<String> singleton = new ArrayList<>(); singleton.add(graph.verts[i]); bestCover.add(singleton); } return bestCover; }</code><technical_language>some Checkstyle violations for whitespace</technical_language>

Target:
private static ArrayList<ArrayList<String>> findCliqueCover(Graph graph, int bestSize, String tabs) { verboseLog(tabs + "findCliqueCover up to " + bestSize + ", " + graph.toString()); for (int i = 0; i < graph.size(); i++) { if (i >= bestSize - 1) { verboseLog(tabs + "giving up"); return null; } String v0 = graph.getVert(i); if (!graph.getEdges(v0).isEmpty()) { verboseLog(tabs + "Selected vertex " + v0); String v1 = graph.getEdges(v0).iterator().next(); ArrayList<ArrayList<String>> bestCover0 = findCliqueCover(graph.ntract(v0, v1), bestSize, tabs + "----"); int bestSize0 = bestCover0 == null ? bestSize : bestCover0.size(); graph.removeEdge(v0, v1); ArrayList<ArrayList<String>> bestCover1 = findCliqueCover(graph, bestSize0, tabs + " "); graph.addEdge(v0, v1); if (bestCover1 != null) { return bestCover1; } else { if (bestCover0 != null) { bestCover0.get(i).add(v1); } return bestCover0; } } } verboseLog(tabs + "done, " + graph.size()); ArrayList<ArrayList<String>> bestCover = new ArrayList<>(); for (int i = 0; i < graph.size(); i++) { ArrayList<String> singleton = new ArrayList<>(); singleton.add(graph.getVert(i)); bestCover.add(singleton); } return bestCover; }
Source:
<code>public ValidationResult canRebalance(GlusterVolumeEntity volumeEntity) { int replicaCount = 0; List<GlusterBrickEntity> bricks = volumeEntity.getBricks(); if (volumeEntity.getVolumeType() == GlusterVolumeType.DISTRIBUTE) { replicaCount = 1; } else if (volumeEntity.getVolumeType() == GlusterVolumeType.DISTRIBUTED_REPLICATE) { <START> replicaCount = volumeEntity.getReplicaCount(); <END> } int i = 0, j = 0; while (i < bricks.size()) { for (j = 0; j < replicaCount; j++) { if (bricks.get(i + j).isOnline()) { i = i + replicaCount; break; } } if (j == replicaCount) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_ONE_OR_MORE_BRICKS_ARE_DOWN); } } return ValidationResult.VALID; }</code><technical_language>DISTRIBUTED_STRIPED_REPLICATE</technical_language>

Target:
public ValidationResult canRebalance(GlusterVolumeEntity volumeEntity) { int replicaCount = 0; List<GlusterBrickEntity> bricks = volumeEntity.getBricks(); if (volumeEntity.getVolumeType().isReplicatedType()) { replicaCount = volumeEntity.getReplicaCount(); } else { replicaCount = 1; } int brickIndex = 0, replicaIndex = 0; while (brickIndex < bricks.size()) { for (replicaIndex = 0; replicaIndex < replicaCount; replicaIndex++) { if (bricks.get(brickIndex + replicaIndex).isOnline()) { brickIndex = brickIndex + replicaCount; break; } } if (replicaIndex == replicaCount) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_ONE_OR_MORE_BRICKS_ARE_DOWN); } } return ValidationResult.VALID; }
Source:
<code>public void editDomain(ActionEvent event) { UpdateDomain updateDomain = new UpdateDomain(); updateDomain.setDomain(selectedDomain); try { directService.updateDomain(updateDomain); selectedDomain = null; refreshDomains(); <START> } catch (CreateDomainException domainException) { <END> FacesContext.getCurrentInstance().validationFailed(); FacesContext.getCurrentInstance().addMessage("domainEditErrors", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Can not update domain: " + domainException.getLocalizedMessage(), "")); LOG.error("Error updating domain: " + domainException.getMessage()); } }</code><technical_language>If this Exception for Create Modify, rename more "DomainDaoException" "DomainTxException"</technical_language>

Target:
public void editDomain(ActionEvent event) { UpdateDomain updateDomain = new UpdateDomain(); updateDomain.setDomain(selectedDomain); try { directService.updateDomain(updateDomain); selectedDomain = null; refreshDomains(); } catch (DomainException domainException) { FacesContext.getCurrentInstance().validationFailed(); FacesContext.getCurrentInstance().addMessage("domainEditErrors", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Can not update domain: " + domainException.getLocalizedMessage(), "")); LOG.error("Error updating domain: " + domainException.getMessage()); } }
Source:
<code><START> public String toQueryString() { <END> HashMap<String, String> parameters = new HashMap<String, String>(); if (transferToId != null) { parameters.put("transferTo", transferToId.toString()); if (transferSheets != null) { parameters.put("transferSheets", transferSheets.toString()); } } if (removeFromSharing != null) { parameters.put("removeFromSharing", removeFromSharing.toString()); } return QueryUtil.generateUrl(null, parameters); }</code><technical_language>similar methods in other objects. modify generateUrl() ignore null values. This manually check null of field in object is generateUrl. This simplify this method to: HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("transferTo", transferToId); parameters.put("transferSheets", transferSheets); parameters.put("removeFromSharing", removeFromSharing); return QueryUtil.generateUrl(null, parameters);</technical_language>

Target:
public String toQueryString() { HashMap<String, Object> parameters = new HashMap<String, Object>(); parameters.put("transferTo", transferToId); parameters.put("transferSheets", transferSheets); parameters.put("removeFromSharing", removeFromSharing); return QueryUtil.generateUrl(null, parameters); }
Source:
<code>public @NonNull Map<@NonNull String, @NonNull String> getProperties() { Map<@NonNull String, @NonNull String> properties = new HashMap<>(); StateSystemBackendType backend = getBackendType(); properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesBackend), NonNullUtils.checkNotNull(backend.name())); switch (backend) { case FULL: case PARTIAL: File htFile = getSsFile(); if (htFile != null) { if (htFile.exists()) { properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesFileSize), <START> NonNullUtils.checkNotNull(FileUtils.byteCountToDisplaySize(htFile.length()))); <END> } else { properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesFileSize), NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesAnalysisNotExecuted)); } } break; case INMEM: case NULL: default: break; } return properties; }</code><technical_language>byteCountToDisplaySize return null. Add external annotation</technical_language>

Target:
public @NonNull Map<@NonNull String, @NonNull String> getProperties() { Map<@NonNull String, @NonNull String> properties = new HashMap<>(); StateSystemBackendType backend = getBackendType(); properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesBackend), NonNullUtils.checkNotNull(backend.name())); switch (backend) { case FULL: case PARTIAL: File htFile = getSsFile(); if (htFile != null) { if (htFile.exists()) { properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesFileSize), FileUtils.byteCountToDisplaySize(htFile.length())); } else { properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesFileSize), NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesAnalysisNotExecuted)); } } break; case INMEM: case NULL: default: break; } return properties; }
Source:
<code>public void testInsertNewFieldIfDataTypeIsStructureWhenDataTypeIsStructure() { <START> <END> final DataType dataType = mock(DataType.class); when(dataTypeSelectComponent.getValue()).thenReturn(structure); when(dataType.getSubDataTypes()).thenReturn(emptyList()); doReturn(dataType).when(listItem).getDataType(); doNothing().when(listItem).insertNestedField(); listItem.insertNewFieldIfDataTypeIsStructure(); verify(listItem).insertNestedField(); }</code><technical_language>please update method name. I name **IfDataTypeIsStructure** **WhenDataTypeIsStructure**</technical_language>

Target:
public void testInsertNewFieldIfDataTypeIsStructureWhenDataTypeIsStructure() { final DataType dataType = mock(DataType.class); final String hash = "hash"; when(dataTypeSelectComponent.getValue()).thenReturn(structure); when(dataType.getSubDataTypes()).thenReturn(emptyList()); doReturn(dataType).when(listItem).getDataType(); doNothing().when(listItem).insertNestedField(); listItem.insertNewFieldIfDataTypeIsStructure(hash); verify(dataTypeList).insertNestedField(hash); }
Source:
<code>public static String getResultObjectName() { <START> return "snapshot"; <END> }</code><technical_language>Possibly a final string ApiConstants</technical_language>

Target:
public static String getResultObjectName() { return ApiConstants.SNAPSHOT; }
Source:
<code>public void update(SolGame game) { float life = 0; Hero hero = game.getHero(); float ts = game.getTimeStep(); if (hero.isDead() || DIRECT_CAM_CONTROL) { applyInput(game); <START> life = hero.getLife(); <END> } else { myPos.set(hero.getPosition()); life = hero.getLife(); } if (life < myPrevHeroLife) { float shakeDiff = .1f * MAX_SHAKE * (myPrevHeroLife - life); myShake = SolMath.approach(myShake, MAX_SHAKE, shakeDiff); } else { myShake = SolMath.approach(myShake, 0, SHAKE_DAMP * ts); } myPrevHeroLife = life; Vector2 pos = SolMath.fromAl(SolMath.rnd(180), myShake); pos.add(myPos); applyPos(pos.x, pos.y); SolMath.free(pos); float desiredAngle = myCamRotStrategy.getRotation(myPos, game); float rotSpd = CAM_ROT_SPD * ts; myAngle = SolMath.approachAngle(myAngle, desiredAngle, rotSpd); applyAngle(); updateMap(game); }</code><technical_language>do life = .. in directCam deadHero condition? Originally done if hero null. Bigger question: do need maintain a life variable way? Also, in case decide necessary this statement, notice is repeated in if else - means condition</technical_language>

Target:
public void update(SolGame game) { float life = 0; Hero hero = game.getHero(); float ts = game.getTimeStep(); life = hero.getLife(); if (hero.isDead() || DIRECT_CAM_CONTROL) { applyInput(game); } else { Vector2 heroPos = hero.getHull().getBody().getWorldCenter(); if (myZoom * VIEWPORT_HEIGHT < heroPos.dst(myPos)) { myPos.set(heroPos); game.getObjMan().resetDelays(); } else { Vector2 moveDiff = SolMath.getVec(hero.getSpd()); moveDiff.scl(ts); myPos.add(moveDiff); SolMath.free(moveDiff); float moveSpd = MOVE_SPD * ts; myPos.x = SolMath.approach(myPos.x, heroPos.x, moveSpd); myPos.y = SolMath.approach(myPos.y, heroPos.y, moveSpd); } } if (life < myPrevHeroLife) { float shakeDiff = .1f * MAX_SHAKE * (myPrevHeroLife - life); myShake = SolMath.approach(myShake, MAX_SHAKE, shakeDiff); } else { myShake = SolMath.approach(myShake, 0, SHAKE_DAMP * ts); } myPrevHeroLife = life; Vector2 pos = SolMath.fromAl(SolMath.rnd(180), myShake); pos.add(myPos); applyPos(pos.x, pos.y); SolMath.free(pos); float desiredAngle = myCamRotStrategy.getRotation(myPos, game); float rotSpd = CAM_ROT_SPD * ts; myAngle = SolMath.approachAngle(myAngle, desiredAngle, rotSpd); applyAngle(); updateMap(game); }
Source:
<code>private void initCommandExecutor() { if (!cmdExecutorInitialized) { synchronized(LOCK) { if (!cmdExecutorInitialized) { for (CommandEntity cmdEntity : coco.getCommandsWithCallBackEnabled()) { if (!cmdEntity.isCallBackNotified()) { switch(cmdEntity.getCommandStatus()) { case ACTIVE_SYNC: coco.retrieveCommand(cmdEntity.getId()).setCommandStatus(CommandStatus.FAILED_RESTARTED); break; case REJECTED: case NOT_STARTED: executeAsyncCommand(cmdEntity.getCommandType(), cmdEntity.getActionParameters()); <START> break; <END> default: addToCallBackMap(cmdEntity); } } } cmdExecutorInitialized = true; } } } }</code><technical_language>want execute REJECTED/NOT_STARTED command engine startup, if 2 hours restart engine? of case: host run a VM ran this infra, command start engine is stopped started hour - startup try run VM, if SPM selected, user try run VM asking operation fails I is try execute commands in case. do for special cases HA VMs</technical_language>

Target:
private void initCommandExecutor() { if (!cmdExecutorInitialized) { synchronized(LOCK) { if (!cmdExecutorInitialized) { for (CommandEntity cmdEntity : coco.getCommandsWithCallBackEnabled()) { switch(cmdEntity.getCommandStatus()) { case ACTIVE_SYNC: case NOT_STARTED: coco.retrieveCommand(cmdEntity.getId()).setCommandStatus(CommandStatus.FAILED_RESTARTED); break; default: addToCallBackMap(cmdEntity); break; } } cmdExecutorInitialized = true; } } } }
Source:
<code>public MessageBuilder appendCustomMessage() { AbstractProject<?, ?> project = build.getProject(); String customMessage = Util.fixEmpty(project.getProperty(SlackNotifier.SlackJobProperty.class) .getCustomMessage()); Map<String, String> buildVariables = new HashMap(); buildVariables.putAll(build.getBuildVariables()); try { buildVariables.putAll(build.getEnvironment(new LogTaskListener(logger, INFO))); } catch (IOException e) { logger.log(SEVERE, e.getMessage(), e); } catch (InterruptedException e) { logger.log(SEVERE, e.getMessage(), e); } message.append("\n"); <START> message.append(replaceMacro(customMessage, new VariableResolver.ByMap<String>(buildVariables))); <END> return this; }</code><technical_language>EnvVars expand() ? <LINK_0> If I understand correctly, allow usage of Environment Variables</technical_language>

Target:
public MessageBuilder appendCustomMessage() { AbstractProject<?, ?> project = build.getProject(); String customMessage = Util.fixEmpty(project.getProperty(SlackNotifier.SlackJobProperty.class) .getCustomMessage()); EnvVars envVars = new EnvVars(); try { envVars = build.getEnvironment(new LogTaskListener(logger, INFO)); } catch (IOException e) { logger.log(SEVERE, e.getMessage(), e); } catch (InterruptedException e) { logger.log(SEVERE, e.getMessage(), e); } message.append("\n"); message.append(envVars.expand(customMessage)); return this; }
Source:
<code>public void onErrorNull() { FlowableProcessor<T> p = create(); try { p.onError(null); fail("No NullPointerException thrown"); } catch (NullPointerException ex) { assertEquals("onError called with null. Null values are generally not allowed in 2.x operators and sources.", ex.getMessage()); } <START> p.test().assertEmpty().cancel();; <END> }</code><technical_language>;; (and in other places in this PR)</technical_language>

Target:
public void onErrorNull() { FlowableProcessor<T> p = create(); try { p.onError(null); fail("No NullPointerException thrown"); } catch (NullPointerException ex) { assertEquals("onError called with null. Null values are generally not allowed in 2.x operators and sources.", ex.getMessage()); } p.test().assertEmpty().cancel(); }
Source:
<code>protected void service(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { if (req.getQueryString() == null || req.getQueryString().isEmpty()) { rsp.sendRedirect(req.getContextPath() + "/"); return; } final Map<String, String> params = getParameters(req); if (deniedActions.contains(params.get("a"))) { rsp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String name = params.get("p"); if (name == null) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (name.endsWith(".git")) { name = name.substring(0, name.length() - 4); } final ProjectControl project; try { final Project.NameKey nameKey = new Project.NameKey(name); project = projectControl.validateFor(nameKey); <START> if (project.areAllRefsVisible()) { <END> throw new NoSuchProjectException(nameKey); } } catch (NoSuchProjectException e) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final Repository repo; try { repo = repoManager.openRepository(name); } catch (RepositoryNotFoundException e) { getServletContext().log("Cannot open repository", e); rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } rsp.setHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"); rsp.setHeader("Pragma", "no-cache"); rsp.setHeader("Cache-Control", "no-cache, must-revalidate"); exec(req, rsp, project, repo); }</code><technical_language>this backwards? :-)</technical_language>

Target:
protected void service(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { if (req.getQueryString() == null || req.getQueryString().isEmpty()) { rsp.sendRedirect(req.getContextPath() + "/"); return; } final Map<String, String> params = getParameters(req); if (deniedActions.contains(params.get("a"))) { rsp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String name = params.get("p"); if (name == null) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (name.endsWith(".git")) { name = name.substring(0, name.length() - 4); } final ProjectControl project; try { final Project.NameKey nameKey = new Project.NameKey(name); project = projectControl.validateFor(nameKey); if (!project.isAllRefsVisible()) { throw new NoSuchProjectException(nameKey); } } catch (NoSuchProjectException e) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final Repository repo; try { repo = repoManager.openRepository(name); } catch (RepositoryNotFoundException e) { getServletContext().log("Cannot open repository", e); rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } rsp.setHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT"); rsp.setHeader("Pragma", "no-cache"); rsp.setHeader("Cache-Control", "no-cache, must-revalidate"); exec(req, rsp, project, repo); }
Source:
<code>public void assertIsPackagePrivate(AssertionInfo info, Class<?> actual) { assertNotNull(info, actual); if ((Modifier.isPublic(actual.getModifiers()) || Modifier.isProtected(actual.getModifiers()) <START> || Modifier.isPrivate(actual.getModifiers()))) { <END> throw failures.failure(info, shouldBePackagePrivate(actual)); } }</code><technical_language>extract actual.getModifiers() a local variable</technical_language>

Target:
public void assertIsPackagePrivate(AssertionInfo info, Class<?> actual) { assertNotNull(info, actual); final int modifiers = actual.getModifiers(); if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers) || Modifier.isPrivate(modifiers)) { throw failures.failure(info, shouldBePackagePrivate(actual)); } }
Source:
<code>private static boolean isPositiveInteger(final String str) { if (str == null || str.isEmpty()) { return false; } <START> if (str.charAt(0) == '0') { <END> return false; } for (int i = 0; i < str.length(); i++) { final char c = str.charAt(i); if (c < '0' || c > '9') { return false; } } return true; }</code><technical_language>This treat '0' a string. need add a && str.length() > 1</technical_language>

Target:
static boolean isPositiveInteger(final String str) { if (str == null || str.isEmpty()) { return false; } if (str.charAt(0) == '0' && str.length() > 1) { return false; } for (int i = 0; i < str.length(); i++) { final char c = str.charAt(i); if (c < '0' || c > '9') { return false; } } return true; }
Source:
<code>public AnalogValue(int rawValue, int type) { <START> if (type < 1 || type > 21) { <END> measureType = TACmiMeasureType.UNSUPPORTED; value = new BigDecimal(rawValue); logger.warn("Got unsupported measure type {}, value is {}", type, rawValue); } else { measureType = TACmiMeasureType.fromInt(type); value = new BigDecimal(rawValue).movePointLeft(factors[type]); logger.debug("Got measure: type {}, raw value {}, converted: {}, {}", type, rawValue, measureType.name(), value); } }</code><technical_language>1 21 static final constants TACmiMeasureType enum</technical_language>

Target:
public AnalogValue(int rawValue, int type) { measureType = TACmiMeasureType.fromInt(type); value = new BigDecimal(rawValue).movePointLeft(measureType.getScale()); if (measureType.equals(TACmiMeasureType.UNSUPPORTED)) { logger.warn("Unsupported measure type {}, value is {}", type, value); } else { logger.debug("Got measure: type {}, raw value {}, converted: {}, {}", type, rawValue, measureType.name(), value); } }
Source:
<code>public void serializeCollectionsSingletonList() { ManageNetworkClustersParameters params = new ManageNetworkClustersParameters( Collections.singletonList(new NetworkCluster( <START> Guid.createGuidFromString("f455686a-79cc-11e6-8c65-54ee755c6cc7"), <END> Guid.createGuidFromString("f970c5f6-79cc-11e6-bc8f-54ee755c6cc7"), NetworkStatus.NON_OPERATIONAL, false, false, false, false, false))); JsonObjectSerializer serializer = new JsonObjectSerializer(); String json = serializer.serialize(params); assertTrue(json.length() > 0); ManageNetworkClustersParameters deserializedParams = new JsonObjectDeserializer().deserialize( json, ManageNetworkClustersParameters.class); assertEquals(params.getExecutionReason(), deserializedParams.getExecutionReason()); }</code><technical_language>actual Guid important 'Guid.newGuid()'</technical_language>

Target:
public void serializeCollectionsSingletonList() { ManageNetworkClustersParameters params = new ManageNetworkClustersParameters( Collections.singletonList(new NetworkCluster( Guid.newGuid(), Guid.newGuid(), NetworkStatus.NON_OPERATIONAL, false, false, false, false, false))); JsonObjectSerializer serializer = new JsonObjectSerializer(); String json = serializer.serialize(params); assertTrue(json.length() > 0); ManageNetworkClustersParameters deserializedParams = new JsonObjectDeserializer().deserialize( json, ManageNetworkClustersParameters.class); assertEquals(params.getExecutionReason(), deserializedParams.getExecutionReason()); }
Source:
<code>public Configuration deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Configuration configuration = new Configuration(); JsonObject jo = (JsonObject) json; for (Entry<String, JsonElement> e : jo.entrySet()) { JsonPrimitive value = e.getValue().getAsJsonPrimitive(); if (value.isString()) { configuration.put(e.getKey(), value.getAsString()); } else if (value.isNumber()) { configuration.put(e.getKey(), value.getAsBigDecimal()); } else if (value.isBoolean()) { <START> configuration.put(e.getKey(), value.getAsBigDecimal()); <END> } } return configuration; }</code><technical_language>this value.getAsBoolean()</technical_language>

Target:
public Configuration deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Configuration configuration = new Configuration(); JsonObject jo = (JsonObject) json; for (Entry<String, JsonElement> e : jo.entrySet()) { JsonPrimitive value = e.getValue().getAsJsonPrimitive(); if (value.isString()) { configuration.put(e.getKey(), value.getAsString()); } else if (value.isNumber()) { configuration.put(e.getKey(), value.getAsBigDecimal()); } else if (value.isBoolean()) { configuration.put(e.getKey(), value.getAsBoolean()); } } return configuration; }
Source:
<code>public SQLQueryEngine(MetaDataStore metaDataStore, com.yahoo.elide.contrib.dynamicconfighelpers.compile.ConnectionDetails defaultConnectionDetails, Map<String, com.yahoo.elide.contrib.dynamicconfighelpers.compile.ConnectionDetails> detailsMap) { <START> if (defaultConnectionDetails == null) { <END> this.defaultConnectionDetails = null; } else { this.defaultConnectionDetails = new ConnectionDetails(defaultConnectionDetails.getDataSource(), SQLDialectFactory.getDialect(defaultConnectionDetails.getDialect())); } if (!(detailsMap == null || detailsMap.size() == 0)) { detailsMap.forEach((name, details) -> { this.connectionDetailsMap.put(name, new ConnectionDetails(details.getDataSource(), SQLDialectFactory.getDialect(details.getDialect()))); }); } this.metaDataStore = metaDataStore; this.metadataDictionary = metaDataStore.getMetadataDictionary(); populateMetaData(metaDataStore); this.tables = metaDataStore.getMetaData(Table.class).stream() .collect(Collectors.toMap(Table::getId, Functions.identity())); this.referenceTable = new SQLReferenceTable(metaDataStore); }</code><technical_language>I put google preconditions defaultConn null detailsMap</technical_language>

Target:
public SQLQueryEngine(MetaDataStore metaDataStore, com.yahoo.elide.contrib.dynamicconfighelpers.compile.ConnectionDetails defaultConnectionDetails, Map<String, com.yahoo.elide.contrib.dynamicconfighelpers.compile.ConnectionDetails> detailsMap) { Preconditions.checkNotNull(defaultConnectionDetails); Preconditions.checkNotNull(detailsMap); this.defaultConnectionDetails = new ConnectionDetails(defaultConnectionDetails.getDataSource(), SQLDialectFactory.getDialect(defaultConnectionDetails.getDialect())); detailsMap.forEach((name, details) -> { this.connectionDetailsMap.put(name, new ConnectionDetails(details.getDataSource(), SQLDialectFactory.getDialect(details.getDialect()))); }); this.metaDataStore = metaDataStore; this.metadataDictionary = metaDataStore.getMetadataDictionary(); populateMetaData(metaDataStore); this.tables = metaDataStore.getMetaData(Table.class).stream() .collect(Collectors.toMap(Table::getId, Functions.identity())); this.referenceTable = new SQLReferenceTable(metaDataStore); }