auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setUp(boolean enableRemote) throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.client.refresh.interval", CLIENT_REFRESH_RATE); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); if (enableRemote) { ConfigurationManager.getConfigInstance().setProperty("eureka.fetchRemoteRegionsRegistry", REMOTE_REGION); } ConfigurationManager.getConfigInstance().setProperty("eureka.myregion.availabilityZones", REMOTE_ZONE); ConfigurationManager.getConfigInstance().setProperty("eureka.backupregistry", MockBackupRegistry.class.getName()); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:" + NOT_AVAILABLE_EUREKA_PORT + MockRemoteEurekaServer.EUREKA_API_BASE_PATH); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); builder.setIPAddr("10.10.101.00"); builder.setHostName("Hosttt"); builder.setAppName("EurekaTestApp-" + UUID.randomUUID()); builder.setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig(), builder.build()); backupRegistry = new MockBackupRegistry(); setupBackupMock(); client = new DiscoveryClient(applicationInfoManager, new DefaultEurekaClientConfig(), null, <START> new Provider<BackupRegistry>() { <END> @Override public BackupRegistry get() { return backupRegistry; } }); }</code><technical_language>simplified Providers.of(backupRegistry);</technical_language>

Target:
public void setUp(boolean enableRemote) throws Exception { ConfigurationManager.getConfigInstance().setProperty("eureka.client.refresh.interval", CLIENT_REFRESH_RATE); ConfigurationManager.getConfigInstance().setProperty("eureka.registration.enabled", "false"); if (enableRemote) { ConfigurationManager.getConfigInstance().setProperty("eureka.fetchRemoteRegionsRegistry", REMOTE_REGION); } ConfigurationManager.getConfigInstance().setProperty("eureka.myregion.availabilityZones", REMOTE_ZONE); ConfigurationManager.getConfigInstance().setProperty("eureka.backupregistry", MockBackupRegistry.class.getName()); ConfigurationManager.getConfigInstance().setProperty("eureka.serviceUrl.default", "http://localhost:" + NOT_AVAILABLE_EUREKA_PORT + MockRemoteEurekaServer.EUREKA_API_BASE_PATH); InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); builder.setIPAddr("10.10.101.00"); builder.setHostName("Hosttt"); builder.setAppName("EurekaTestApp-" + UUID.randomUUID()); builder.setDataCenterInfo(new DataCenterInfo() { @Override public Name getName() { return Name.MyOwn; } }); ApplicationInfoManager applicationInfoManager = new ApplicationInfoManager(new MyDataCenterInstanceConfig(), builder.build()); backupRegistry = new MockBackupRegistry(); setupBackupMock(); client = new DiscoveryClient( applicationInfoManager, new DefaultEurekaClientConfig(), null, Providers.of((BackupRegistry)backupRegistry) ); }
Source:
<code>void fixStateIfRequired() throws IOException, StoreException { if (CompactionLog.isCompactionInProgress(dataDir.getAbsolutePath(), storeId)) { compactionLog = new CompactionLog(dataDir.getAbsolutePath(), storeId, storeKeyFactory, time); CompactionLog.Phase phase = compactionLog.getCompactionPhase(); switch (phase) { case COMMIT: <START> commit(true); <END> compactionLog.markCleanupStart(); case CLEANUP: cleanup(true); compactionLog.markCycleComplete(); break; case COPY: recoveryStartToken = compactionLog.getSafeToken(); case PREPARE: case DONE: break; default: throw new IllegalStateException("Unrecognized compaction phase: " + phase); } if (compactionLog.getCompactionPhase().equals(CompactionLog.Phase.DONE)) { endCompaction(); } } }</code><technical_language>hard delete needs fixing. Token invalid is indexes compacted hard delete token present</technical_language>

Target:
private void fixStateIfRequired() throws IOException, StoreException { if (CompactionLog.isCompactionInProgress(dataDir.getAbsolutePath(), storeId)) { compactionLog = new CompactionLog(dataDir.getAbsolutePath(), storeId, storeKeyFactory, time); CompactionLog.Phase phase = compactionLog.getCompactionPhase(); switch (phase) { case COMMIT: commit(true); compactionLog.markCleanupStart(); case CLEANUP: cleanup(true); compactionLog.markCycleComplete(); break; case COPY: recoveryStartToken = compactionLog.getSafeToken(); case PREPARE: case DONE: break; default: throw new IllegalStateException("Unrecognized compaction phase: " + phase); } if (compactionLog.getCompactionPhase().equals(CompactionLog.Phase.DONE)) { endCompaction(); } } }
Source:
<code>public Object[] factory() { <START> List<Object> tests = new ArrayList<>(3 * 2); <END> for (org.infinispan.configuration.cache.TransactionMode txMode : org.infinispan.configuration.cache.TransactionMode.values()) { if (txMode == org.infinispan.configuration.cache.TransactionMode.NONE) { continue; } for (LockingMode lockingMode : LockingMode.values()) { tests.add(new TopologyChangeFunctionalTest().transactionMode(txMode).lockingMode(lockingMode)); } } return tests.toArray(); }</code><technical_language>re: flatMap</technical_language>

Target:
public Object[] factory() { return Arrays.stream(org.infinispan.configuration.cache.TransactionMode.values()) .filter(tMode -> tMode != org.infinispan.configuration.cache.TransactionMode.NONE) .flatMap(txMode -> Arrays.stream(LockingMode.values()) .map(lockingMode -> new TopologyChangeFunctionalTest() .transactionMode(txMode) .lockingMode(lockingMode))) .toArray(); }
Source:
<code>protected MapSqlParameterSource createFullParametersMapper(VmDevice entity) { return createIdParameterMapper(entity.getId()) .addValue("device", entity.getDevice()) .addValue("type", entity.getType().getValue()) .addValue("address", entity.getAddress()) .addValue("boot_order", entity.getBootOrder()) .addValue("spec_params", entity.getSpecParams() == null ? null : SerializationFactory .getSerializer() .serialize(entity.getSpecParams())) .addValue("is_managed", entity.getIsManaged()) .addValue("is_plugged", entity.getIsPlugged()) .addValue("is_readonly", entity.getIsReadOnly()) .addValue("alias", entity.getAlias()) <START> .addValue("custom_properties", entity.getCustomProperties()); <END> }</code><technical_language>assumption is implementation class of Map (LinkedHashMap in this case) care of serialization. However, reading string DB converting string, parsing is done manually. I semantics specParams (line 46) store read (line 146). In rely LinkedHashMap expected format if changes</technical_language>

Target:
protected MapSqlParameterSource createFullParametersMapper(VmDevice entity) { return createIdParameterMapper(entity.getId()) .addValue("device", entity.getDevice()) .addValue("type", entity.getType().getValue()) .addValue("address", entity.getAddress()) .addValue("boot_order", entity.getBootOrder()) .addValue("spec_params", entity.getSpecParams() == null ? null : SerializationFactory .getSerializer() .serialize(entity.getSpecParams())) .addValue("is_managed", entity.getIsManaged()) .addValue("is_plugged", entity.getIsPlugged()) .addValue("is_readonly", entity.getIsReadOnly()) .addValue("alias", entity.getAlias()) .addValue("custom_properties", entity.getCustomProperties() == null ? null : SerializationFactory .getSerializer() .serialize(entity.getCustomProperties())); }
Source:
<code><START> private static MethodTree findEnclosingMethod(Tree tree) { <END> while (!tree.is(Tree.Kind.CLASS, Tree.Kind.METHOD)) { tree = tree.parent(); } if (tree.is(Tree.Kind.CLASS)) { return null; } return (MethodTree) tree; }</code><technical_language>this duplicates findEnclosingMethod CipherBlockChainingCheck - move ExpressionsHelper similar</technical_language>

Target:
public static MethodTree findEnclosingMethod(Tree tree) { while (!tree.is(Tree.Kind.CLASS, Tree.Kind.METHOD)) { tree = tree.parent(); } if (tree.is(Tree.Kind.CLASS)) { return null; } return (MethodTree) tree; }
Source:
<code>void setUlimit(Instance instance, Map<String, Object> fromInspect) { Object ulimits = CollectionUtils.getNestedValue(fromInspect, HOST_CONFIG, "Ulimits"); if (ulimits == null) { return; } List<Ulimit> ret = new ArrayList<>(); if (ulimits instanceof List) { for (Object ulimit : (List<Object>) ulimits) { if (ulimit instanceof Map) { Ulimit l = new Ulimit(); Map<String, Object> temp = (Map<String, Object>) ulimit; if (temp.get("Name") instanceof String) { l.setName(temp.get("Name").toString()); } <START> if (temp.get("Hard") instanceof Integer) { <END> l.setHard((Integer) temp.get("Hard")); } if (temp.get("Soft") instanceof Integer) { l.setSoft((Integer) temp.get("Soft")); } if (!l.getName().isEmpty()) { ret.add(l); } } } } setField(instance, FIELD_ULIMITS, ret); }</code><technical_language>Number instead of integer below? So, check if is instance of Number cast a number Number's intValue() function convert int</technical_language>

Target:
void setUlimit(Instance instance, Map<String, Object> fromInspect) { Object ulimits = CollectionUtils.getNestedValue(fromInspect, HOST_CONFIG, "Ulimits"); if (ulimits == null) { return; } List<Ulimit> ret = new ArrayList<>(); if (ulimits instanceof List) { for (Object ulimit : (List<Object>) ulimits) { if (ulimit instanceof Map) { Ulimit l = new Ulimit(); Map<String, Object> temp = (Map<String, Object>) ulimit; if (temp.get("Name") instanceof String) { l.setName(temp.get("Name").toString()); } if (temp.get("Hard") instanceof Number) { l.setHard(((Number) temp.get("Hard")).intValue()); } if (temp.get("Soft") instanceof Integer) { l.setSoft(((Number) temp.get("Soft")).intValue()); } if (!l.getName().isEmpty()) { ret.add(l); } } } } if (!ret.isEmpty()) { setField(instance, FIELD_ULIMITS, ret); } }
Source:
<code>private Map getViews(){ <START> Map allViews = new HashMap<>(); <END> allViews.put( ViewType.CLI, getCliViews() ); allViews.put( ViewType.JSON, getJsonViews() ); return allViews; }</code><technical_language>final :D</technical_language>

Target:
private Map getViews(){ final Map allViews = new HashMap<>(); allViews.put( ViewType.CLI, getCliViews() ); allViews.put( ViewType.JSON, getJsonViews() ); return allViews; }
Source:
<code>public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { <START> if (syntaxNode.is(Tree.Kind.DIVIDE_ASSIGNMENT, Tree.Kind.DIVIDE, Tree.Kind.REMAINDER_ASSIGNMENT, Tree.Kind.REMAINDER)) { <END> ExpressionTree denominator; SymbolicValue denominatorSV; ProgramState programState = context.getState(); List<SymbolicValue> symbolicValues = programState.peekValues(2); if (syntaxNode.is(Tree.Kind.REMAINDER_ASSIGNMENT, Tree.Kind.DIVIDE_ASSIGNMENT)) { denominator = ((AssignmentExpressionTree) syntaxNode).expression(); denominatorSV = symbolicValues.get(1); } else { denominator = ((BinaryExpressionTree) syntaxNode).rightOperand(); denominatorSV = symbolicValues.get(0); } if (isZero(programState, denominatorSV)) { String operation = syntaxNode.is(Tree.Kind.REMAINDER, Tree.Kind.REMAINDER_ASSIGNMENT) ? "modulation" : "division"; String denominatorName = "this expression"; if (denominator.is(Tree.Kind.IDENTIFIER)) { denominatorName = "'" + ((IdentifierTree) denominator).name() + "'"; } context.reportIssue(denominator, this, "Make sure " + denominatorName + " can't be zero before doing this " + operation + "."); return null; } } PreStatementVisitor visitor = new PreStatementVisitor(context); syntaxNode.accept(visitor); return visitor.programState; }</code><technical_language>if a prestatement visitor, this check</technical_language>

Target:
public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { PreStatementVisitor visitor = new PreStatementVisitor(context); syntaxNode.accept(visitor); return visitor.programState; }
Source:
<code>public VariantType getType() { if (this.alternate.equals(".")) { return VariantType.NO_ALTERNATE; } <START> if (reference.length() == alternate.length()) { <END> if (getLength() > 1) { return VariantType.MNV; } else { return VariantType.SNV; } } else if (getLength() <= SV_THRESHOLD) { return VariantType.INDEL; } else { return VariantType.SV; } }</code><technical_language>else if, for consistency rest of method structure</technical_language>

Target:
public VariantType getType() { if (this.alternate.equals(".")) { return VariantType.NO_ALTERNATE; } else if (reference.length() == alternate.length()) { if (getLength() > 1) { return VariantType.MNV; } else { return VariantType.SNV; } } else if (getLength() <= SV_THRESHOLD) { return VariantType.INDEL; } else { return VariantType.SV; } }
Source:
<code>public void run() { while (true) { <START> int delay = PqsConfiguration.getReportingInterval(); <END> phoenixGlobalMetricsCollection = PhoenixRuntime.getGlobalPhoenixClientMetrics(); this.pqsSink.writeGlobal(phoenixGlobalMetricsCollection); try { Thread.sleep(delay); } catch (InterruptedException e) { LOG.error(" Sleep thread interrupted for metrics collection "); } } }</code><technical_language>this constant? Get set this once</technical_language>

Target:
public void run() { boolean run = true; reporter.start(); while (run) { phoenixGlobalMetricsCollection = PhoenixRuntime.getGlobalPhoenixClientMetrics(); this.pqsSink.writeGlobal(phoenixGlobalMetricsCollection); try { Thread.sleep(reportingInterval); } catch (InterruptedException e) { LOG.error(" Sleep thread interrupted for metrics collection. " + "So stopping global metrics collection. ",e); run = false; } } }
Source:
<code>public void testOS() throws Exception { OSDelegatingFileTailingMessageProducer adapter = new OSDelegatingFileTailingMessageProducer(); adapter.setOptions("-F -n 99999999"); testGuts(adapter, "reader"); <START> } <END></code><technical_language>Gary, this test pass for Windows tail-wrapper: - default > [message=tail: invalid option -- F, file=C:\Users\cleric\LOCALS~1\Temp\FileTailingMessageProducerTests\foo] - --follow=name --retry -n 99999999 > org.junit.ComparisonFailure: > Expected :hello50 > Actual :8 - time: > java.io.FileNotFoundException: C:\Users\cleric\LOCALS~1\Temp\FileTailingMessageProducerTests\foo (Access Denied) @Ignore it? is guarantee, another Windows tail-tool work differently..</technical_language>

Target:
public void testOS() throws Exception { OSDelegatingFileTailingMessageProducer adapter = new OSDelegatingFileTailingMessageProducer(); adapter.setOptions(TAIL_OPTIONS_FOLLOW_NAME_MANY_LINES); testGuts(adapter, "reader"); }
Source:
<code>public boolean isAllowed(HttpServletRequest request, Project project) { return checkAll( request, "plugin_framework_project_cache", project, new AuthorizationEntity.PluginDecisionPredicate() { @Override public boolean decision(IAuthorizationPlugin plugin) { return plugin.isAllowed(request, project); } }, new AuthorizationEntity.PluginSkippingPredicate() { @Override <START> public boolean shouldSkip(AuthorizationEntity entity) { <END> if (entity.forProjects().isEmpty() && entity.forGroups().isEmpty()) { return false; } if (entity.forProjects().contains(project.getName())) { return false; } return true; } }); }</code><technical_language>more readable if entity called authEntity such. similarly for other isAllowed() method</technical_language>

Target:
public boolean isAllowed(HttpServletRequest request, Project project) { return checkAll( request, "plugin_framework_project_cache", project, new AuthorizationEntity.PluginDecisionPredicate() { @Override public boolean decision(IAuthorizationPlugin plugin) { return plugin.isAllowed(request, project); } }, new AuthorizationEntity.PluginSkippingPredicate() { @Override public boolean shouldSkip(AuthorizationEntity authEntity) { if (authEntity.forProjects().isEmpty() && authEntity.forGroups().isEmpty()) { return false; } if (authEntity.forProjects().contains(project.getName())) { return false; } return true; } }); }
Source:
<code>public void createTask(String type, Task task) { <START> Log.e("Create a new task", "Called"); <END> if (type.equals(CREATE)) task = new Task(); if (type.equals(COMPLETE)){ task.setComplete(true); createTaskRequest(task, type); return; } if (type.equals(UNCOMPLETE)){ task.setComplete(false); createTaskRequest(task, type); return; } task.setTitle(mTitleField.getText().toString()); task.setDescription(mDescriptionField.getText().toString()); task.setAssignerId(mParentActivity.getUserId()); task.setDueDate(mDate); task.setAssigneeId(mUser.getId()); task.setMiniSiteId(mMiniSite.getId()); task.setComplete(false); Utility.hideKeyboard(mParentActivity, mLayout); createTaskRequest(task, type); }</code><technical_language>need for this</technical_language>

Target:
public void createTask(String type, Task task) { if (type.equals(CREATE)) task = new Task(); if (type.equals(COMPLETE)){ task.setComplete(true); createTaskRequest(task, type); return; } if (type.equals(UNCOMPLETE)){ task.setComplete(false); createTaskRequest(task, type); return; } task.setTitle(mTitleField.getText().toString()); task.setDescription(mDescriptionField.getText().toString()); task.setAssignerId(mParentActivity.getUserId()); task.setDueDate(mDate); task.setAssigneeId(mUser.getId()); task.setMiniSiteId(mMiniSite.getId()); task.setComplete(false); Utility.hideKeyboard(mParentActivity, mLayout); createTaskRequest(task, type); }
Source:
<code><START> public Message(Message message, String id) { <END> _record = new SessionAwareZNRecord(message.getRecord(), id); initStat(); setMsgId(id); }</code><technical_language>This used, deprecate it</technical_language>

Target:
public Message(Message message, String id) { super(new SessionAwareZNRecord(message.getRecord(), id)); setMsgId(id); }
Source:
<code>public void testGenerateSpectraS3GetBucketRequestPrototype() throws IOException, TemplateModelException { final TestFileUtilsImpl fileUtils = new TestFileUtilsImpl(); <START> Map<String,Object> testMap = new HashMap<>(); <END> final String responseType = StructHelper.getResponseTypeName("ListBucketResult"); final Request requestEntry = new Request( "GetBucketRequest", Classification.spectrads3, HttpVerb.GET, "\"/_rest_/\", bucket_name, NULL", null, null, RequestConverter.getParamList(responseType), true, false, responseType ); testMap.put("requestEntry", requestEntry); final CCodeGenerator codeGenerator = new CCodeGenerator(); codeGenerator.processTemplate(testMap, "header-templates/RequestPrototype.ftl", fileUtils.getOutputStream()); final ByteArrayOutputStream bstream = (ByteArrayOutputStream) fileUtils.getOutputStream(); final String output = new String(bstream.toByteArray()); final String expectedOutput = "ds3_error* get_bucket_request(const ds3_client* client, const ds3_request* request, const ds3_list_bucket_result_response** response);"; assertEquals(expectedOutput, output); }</code><technical_language>Missing final</technical_language>

Target:
public void testGenerateSpectraS3GetBucketRequestPrototype() throws IOException, TemplateModelException { final TestFileUtilsImpl fileUtils = new TestFileUtilsImpl(); final Map<String,Object> testMap = new HashMap<>(); final String responseType = StructHelper.getResponseTypeName("ListBucketResult"); final Request requestEntry = new Request( "GetBucketRequest", Classification.spectrads3, HttpVerb.GET, "\"/_rest_/\", bucket_name, NULL", null, null, RequestConverter.getParamList(responseType), true, false, responseType ); testMap.put("requestEntry", requestEntry); final CCodeGenerator codeGenerator = new CCodeGenerator(); codeGenerator.processTemplate(testMap, "header-templates/RequestPrototype.ftl", fileUtils.getOutputStream()); final ByteArrayOutputStream bstream = (ByteArrayOutputStream) fileUtils.getOutputStream(); final String output = new String(bstream.toByteArray()); final String expectedOutput = "ds3_error* get_bucket_request(const ds3_client* client, const ds3_request* request, const ds3_list_bucket_result_response** response);"; assertEquals(expectedOutput, output); }
Source:
<code>protected void testAccessControl() throws Exception { FeedbackSessionAttributes fs = typicalBundle.feedbackSessions.get("session2InCourse1"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, fs.getCourseId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.getFeedbackSessionName(), }; verifyUnaccessibleWithoutLogin(submissionParams); verifyUnaccessibleForUnregisteredUsers(submissionParams); verifyUnaccessibleForStudents(submissionParams); verifyUnaccessibleForInstructorsOfOtherCourses(submissionParams); verifyUnaccessibleWithoutModifySessionPrivilege(submissionParams); verifyAccessibleForInstructorsOfTheSameCourse(submissionParams); FeedbackSessionsLogic.inst().deleteFeedbackSessionCascade(fs.getSessionName(), fs.getCourseId()); <START> <END> FeedbackSessionsLogic.inst().createFeedbackSession(fs); verifyAccessibleForAdminToMasqueradeAsInstructor(submissionParams); }</code><technical_language>deleting previous entity, remove next part recreating entity? fs modified</technical_language>

Target:
protected void testAccessControl() throws Exception { FeedbackSessionAttributes fs = typicalBundle.feedbackSessions.get("session2InCourse1"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, fs.getCourseId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.getFeedbackSessionName(), }; verifyUnaccessibleWithoutLogin(submissionParams); verifyUnaccessibleForUnregisteredUsers(submissionParams); verifyUnaccessibleForStudents(submissionParams); verifyUnaccessibleForInstructorsOfOtherCourses(submissionParams); verifyUnaccessibleWithoutModifySessionPrivilege(submissionParams); verifyAccessibleForInstructorsOfTheSameCourse(submissionParams); verifyAccessibleForAdminToMasqueradeAsInstructor(submissionParams); }
Source:
<code><START> private boolean draftIsNotEmpty() { <END> if (mMessageContentView.getText().length() != 0) return true; if (!attachmentPresenter.createAttachmentList().isEmpty()) return true; if (mSubjectView.getText().length() != 0) return true; return false; }</code><technical_language>recipients signature fields checked</technical_language>

Target:
private boolean draftIsNotEmpty() { if (messageContentView.getText().length() != 0) { return true; } if (!attachmentPresenter.createAttachmentList().isEmpty()) { return true; } if (subjectView.getText().length() != 0) { return true; } if (!recipientPresenter.getToAddresses().isEmpty() || !recipientPresenter.getCcAddresses().isEmpty() || !recipientPresenter.getBccAddresses().isEmpty()) { return true; } return false; }
Source:
<code>protected void onResume() { String action = getIntent().getAction(); if (action == null || !action.equals("Already created")) { Intent intent = new Intent(this, AddBudgetActivity.class); startActivity(intent); finish(); } else { getIntent().setAction(null); } <START> super.onResume(); <END> }</code><technical_language>Move this call start of method, generally done</technical_language>

Target:
protected void onResume() { super.onResume(); String action = getIntent().getAction(); if (action == null || !action.equals("Already created")) { Intent intent = new Intent(this, AddBudgetActivity.class); startActivity(intent); finish(); } else { getIntent().setAction(null); } }
Source:
<code>public void flush(boolean sync) { List<BatchEntry> temp; if (sync) { <START> flushTransactionLock.lock(); <END> } bufferLock.lock(); try { lastFlush = System.currentTimeMillis(); if (batch == batchSize) { logger.trace("[{}] Batch empty, not flushing", name); return; } batch = batchSize; temp = buffer; buffer = new LinkedList<>(); } finally { bufferLock.unlock(); } try { flushTransactionLock.lock(); final long start = System.currentTimeMillis(); de.beginTransaction(); for (BatchEntry entry : temp) { de.addBatch(entry.getTableName(), entry.getEntityEntry()); } de.flush(); de.commit(); logger.trace("[{}] Batch flushed. Took ms, rows.", name, (System.currentTimeMillis() - start), temp.size()); } catch (Exception e) { logger.error(dev, "[{}] Error occurred while flushing.", name, e); onFlushFailure(temp.toArray(new BatchEntry[temp.size()])); } finally { try { if (de.isTransactionActive()) { de.rollback(); } } catch (Exception e) { logger.trace("[{}] Batch failed to check the flush transaction state", name); } flushTransactionLock.unlock(); } }</code><technical_language>Ideally this lock a try finally, in case wrong</technical_language>

Target:
public void flush(boolean sync) { if (!sync) { flush(); } else { try { flushTransactionLock.lock(); flush(); } finally { flushTransactionLock.unlock(); } } }
Source:
<code>public boolean isAnsiSupported() { if (forceAnsi) { return true; <START> } else { <END> return ansiEnabled && ansiSupported; } }</code><technical_language>a small code style thing: else clause is redundant. jut if(forceAnsi) {return true}; return ansiEnabled && ansiSupported simply return forceAnsi || (ansiEnabled && ansiSupported)</technical_language>

Target:
public boolean isAnsiSupported() { return forceAnsi || (ansiEnabled && ansiSupported); }
Source:
<code>protected KieContainer getKieContainer(RegistryContext context, ReleaseId releaseId) { KieContainer kieContainer; if (releaseId != null) { KieServices kieServices = KieServices.Factory.get(); kieContainer = kieServices.newKieContainer(releaseId); } else { kieContainer = context.lookup(KieContainer.class); if (kieContainer == null) { <START> throw new RuntimeException("ReleaseId was not specfied, nor was an existing KieContainer assigned to the Registry"); <END> } } return kieContainer; }</code><technical_language>Typo specfied</technical_language>

Target:
protected KieContainer getKieContainer(RegistryContext context, ReleaseId releaseId) { KieContainer kieContainer; if (releaseId != null) { KieServices kieServices = KieServices.Factory.get(); kieContainer = kieServices.newKieContainer(releaseId); } else { kieContainer = context.lookup(KieContainer.class); if (kieContainer == null) { throw new RuntimeException("ReleaseId was not specified, nor was an existing KieContainer assigned to the Registry"); } } return kieContainer; }
Source:
<code>public Long saveOrUpdate(PasswordHistoryDTO passwordHistoryDTO) { Assert.notNull(passwordHistoryDTO); PasswordHistoryEntity entity = modelMapper.map(passwordHistoryDTO, PasswordHistoryEntity.class); entity.setUserEntity(userRepository.findOne(passwordHistoryDTO.getUserId())); try { Long retId = passwordHistoryRepository.save(entity).getId(); if(passwordHistoryRepository.findByUserEntity(entity.getUserEntity()).size()>=5){ deleteOldestPassword(passwordHistoryDTO.getUserId()); } return retId; } catch (ConstraintViolationException | DataIntegrityViolationException ex) { log.error("Save to repository failed.", ex); <START> String historyId = passwordHistoryDTO.getId().toString(); <END> throw new DuplicateRecordException(historyId, "Duplication occurred when saving password history with ID: " + historyId, ex); } }</code><technical_language>id is null calling web layer, result in unhandled NPE please find alternative value, eg: user id</technical_language>

Target:
public Long saveOrUpdate(PasswordHistoryDTO passwordHistoryDTO) { Assert.notNull(passwordHistoryDTO); PasswordHistoryEntity entity = modelMapper.map(passwordHistoryDTO, PasswordHistoryEntity.class); entity.setUserEntity(userRepository.findOne(passwordHistoryDTO.getUserId())); try { Long retId = passwordHistoryRepository.save(entity).getId(); if(passwordHistoryRepository.findByUserEntity(entity.getUserEntity()).size()>=5){ deleteOldestPassword(passwordHistoryDTO.getUserId()); } return retId; } catch (ConstraintViolationException | DataIntegrityViolationException ex) { log.error("Save to repository failed.", ex); String userId = passwordHistoryDTO.getUserId().toString(); throw new DuplicateRecordException(userId, "Duplication occurred when saving password history for user with ID: " + userId, ex); } }
Source:
<code>private void checkDelta(IMarkerDelta[] deltas) throws AssertionFailedError { assertEquals("wrong number of changes", attributeMap.size(), deltas.length); for (int i = 0; i < deltas.length; i++) { <START> Map values = attributeMap.get(new Long(deltas[i].getId())); <END> assertEquals("Changes different from expecations", deltas[i].getAttributes(), values); } }</code><technical_language>This map generified well</technical_language>

Target:
private void checkDelta(IMarkerDelta[] deltas) throws AssertionFailedError { assertEquals("wrong number of changes", attributeMap.size(), deltas.length); for (int i = 0; i < deltas.length; i++) { Map<String, Object> values = attributeMap.get(new Long(deltas[i].getId())); assertEquals("Changes different from expecations", deltas[i].getAttributes(), values); } }
Source:
<code>protected void configure() { <START> bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT); <END> bind(BlobStore.class).to(GlacierBlobStore.class); bind(AsyncBlobStore.class).to(GlacierAsyncBlobStore.class); }</code><technical_language>this EVENTUAL</technical_language>

Target:
protected void configure() { bind(ConsistencyModel.class).toInstance(ConsistencyModel.EVENTUAL); bind(BlobStore.class).to(GlacierBlobStore.class); bind(AsyncBlobStore.class).to(GlacierAsyncBlobStore.class); }
Source:
<code>public void test_dr1591_DeduceArrayFromInitializerList_a() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), CPP); NameCollector col = new NameCollector(); tu.accept(col); ICPPFunctionTemplate f = (ICPPFunctionTemplate) col.getName(1).resolveBinding(); <START> assertEquals("f", col.getName(5).toString()); <END> IBinding fCall = col.getName(5).resolveBinding(); assertTrue(fCall instanceof IFunction); IFunction f2 = (IFunction) fCall; assertTrue(f2 instanceof ICPPTemplateInstance); assertSame(f, ((ICPPTemplateInstance) f2).getTemplateDefinition()); }</code><technical_language>days more robust test helpers BindingAssertionHelper avoid count names update counts if testcase changes. need change this now, in mind for future</technical_language>

Target:
public void test_dr1591_DeduceArrayFromInitializerList_a() throws Exception { IASTTranslationUnit tu = parse(getAboveComment(), CPP); NameCollector col = new NameCollector(); tu.accept(col); ICPPFunctionTemplate f = (ICPPFunctionTemplate) col.getName(1).resolveBinding(); assertEquals("f", col.getName(5).toString()); IBinding fCall = col.getName(5).resolveBinding(); assertInstance(fCall, IFunction.class); IFunction f2 = (IFunction) fCall; assertInstance(f2, ICPPTemplateInstance.class); assertSame(f, ((ICPPTemplateInstance) f2).getTemplateDefinition()); }
Source:
<code>public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) { super.bufferReceived(connectionID, buffer); try { Command command = (Command) wireFormat.unmarshal(buffer); boolean responseRequired = command.isResponseRequired(); int commandId = command.getCommandId(); if (command.getClass() != KeepAliveInfo.class) { Response response = null; try { setLastCommand(command); response = command.visit(commandProcessorInstance); } catch (Exception e) { e.printStackTrace(); if (responseRequired) { response = convertException(e); } } finally { setLastCommand(null); } if (response instanceof ExceptionResponse) { if (!responseRequired) { Throwable cause = ((ExceptionResponse) response).getException(); serviceException(cause); response = null; } } if (responseRequired) { if (response == null) { response = new Response(); response.setCorrelationId(command.getCommandId()); } } if (context != null) { if (context.isDontSendReponse()) { context.setDontSendReponse(false); response = null; } } if (response != null && !protocolManager.isStopping()) { response.setCorrelationId(commandId); dispatchSync(response); } } else { <START> System.out.println(this + "====server received a keepalive: " + System.currentTimeMillis()); <END> } } catch (Exception e) { ActiveMQServerLogger.LOGGER.debug(e); sendException(e); } }</code><technical_language>System.out?????? a Logger.getLogger(). trace.. trace is done in other places</technical_language>

Target:
public void bufferReceived(Object connectionID, ActiveMQBuffer buffer) { super.bufferReceived(connectionID, buffer); try { Command command = (Command) wireFormat.unmarshal(buffer); boolean responseRequired = command.isResponseRequired(); int commandId = command.getCommandId(); if (command.getClass() != KeepAliveInfo.class) { Response response = null; try { setLastCommand(command); response = command.visit(commandProcessorInstance); } catch (Exception e) { e.printStackTrace(); if (responseRequired) { response = convertException(e); } } finally { setLastCommand(null); } if (response instanceof ExceptionResponse) { if (!responseRequired) { Throwable cause = ((ExceptionResponse) response).getException(); serviceException(cause); response = null; } } if (responseRequired) { if (response == null) { response = new Response(); response.setCorrelationId(command.getCommandId()); } } if (context != null) { if (context.isDontSendReponse()) { context.setDontSendReponse(false); response = null; } } if (response != null && !protocolManager.isStopping()) { response.setCorrelationId(commandId); dispatchSync(response); } } } catch (Exception e) { ActiveMQServerLogger.LOGGER.debug(e); sendException(e); } }
Source:
<code>public RegistryConfigs authForBuild() throws DockerException { final AuthorizationData accessToken; try { accessToken = getAccessToken(); } catch (IOException e) { log.warn("unable to get access token for Google Container Registry, " + "configuration for building image will not contain RegistryAuth for GCR", e); return RegistryConfigs.empty(); } <START> final Map<String, RegistryAuth> configs = new HashMap<String, RegistryAuth>(1); <END> configs.put(accessToken.getProxyEndpoint(), authForAuthorizationData(accessToken)); return RegistryConfigs.create(configs); }</code><technical_language>nit: omit explicit type args in new HashMap<></technical_language>

Target:
public RegistryConfigs authForBuild() throws DockerException { final AuthorizationData accessToken; try { accessToken = getAccessToken(); } catch (IOException e) { log.warn("unable to get access token for AWS Elastic Container Registry, " + "configuration for building image will not contain RegistryAuth for ECR", e); return RegistryConfigs.empty(); } final Map<String, RegistryAuth> configs = new HashMap<String, RegistryAuth>(1); configs.put(accessToken.getProxyEndpoint(), authForAuthorizationData(accessToken)); return RegistryConfigs.create(configs); }
Source:
<code>public HashMap<Integer, ItemStack> addItem(ItemStack... items) { HashMap<Integer, ItemStack> result = new HashMap<>(); for (int i = 0; i < items.length; ++i) { ItemStack item = items[i]; while (item.getAmount() > 0) { int available = firstAvailable(item); if (available == -1) { result.put(i, item); break; } else { ItemStack curItem = getItem(available); int fill = item.getAmount(); if (curItem == null) { ItemStack temp = item.clone(); fill = item.getAmount() >= getMaxStackSize() ? getMaxStackSize() : item.getAmount(); temp.setAmount(fill); setItem(available, temp); } else { fill = item.getAmount() + curItem.getAmount() >= curItem.getMaxStackSize() ? curItem.getMaxStackSize() : curItem.getAmount() + item.getAmount(); curItem.setAmount(fill); } <START> item.setAmount(item.getAmount() - fill); <END> } } } return result; }</code><technical_language>this alter item is passed in? potentially break plugins</technical_language>

Target:
public HashMap<Integer, ItemStack> addItem(ItemStack... items) { HashMap<Integer, ItemStack> result = new HashMap<>(); for (int i = 0; i < items.length; ++i) { ItemStack item = ItemStack.sanitize(items[i]); if (item == null) continue; while (item.getAmount() > 0) { int available = firstAvailable(item); if (available == -1) { result.put(i, item); break; } else { ItemStack curItem = getItem(available); int curAmount = curItem == null ? 0 : curItem.getAmount(); int add; if (curAmount + item.getAmount() >= item.getMaxStackSize()) { add = item.getMaxStackSize() - curAmount; } else { add = item.getAmount(); } ItemStack temp = new ItemStack(item.getType(), curAmount + add); setItem(available, temp); item.setAmount(item.getAmount() - add); } } } return result; }
Source:
<code>private Iterator<Page> readPages() { checkState(writable, "Repeated reads are disallowed to prevent potential resource leaks"); writable = false; try { InputStream input = targetFile.newInputStream(); <START> Closeable resources = closer.register(input); <END> Iterator<Page> pages = PagesSerdeUtil.readPages(serde, new InputStreamSliceInput(input, BUFFER_SIZE)); return PrestoIterators.closeWhenExhausted(pages, resources); } catch (IOException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Failed to read spilled pages", e); } }</code><technical_language>resources is input. Remove variable: InputStream input = closer.register(targetFile.newInputStream());</technical_language>

Target:
private Iterator<Page> readPages() { checkState(writable, "Repeated reads are disallowed to prevent potential resource leaks"); writable = false; try { InputStream input = closer.register(targetFile.newInputStream()); Iterator<Page> pages = PagesSerdeUtil.readPages(serde, new InputStreamSliceInput(input, BUFFER_SIZE)); return PrestoIterators.closeWhenExhausted(pages, input); } catch (IOException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Failed to read spilled pages", e); } }
Source:
<code>private static SQLPatternPart makeInnerStreamModifierClausePattern(boolean captureTokens) { return SPF.oneOf( SPF.clause( SPF.token("export"),SPF.token("to"),SPF.token("target"), <START> SPF.group(captureTokens, "targetName", SPF.databaseObjectName()) <END> ), SPF.clause( SPF.token("partition"), SPF.token("on"), SPF.token("column"), SPF.group(captureTokens, "partitionColumnName", SPF.databaseObjectName()) ), SPF.clause( SPF.token("as"),SPF.token("topic"), SPF.optional( SPF.clause( SPF.token("profile"), SPF.group(captureTokens, "topicProfileName", SPF.databaseObjectName()) ) ), SPF.optional( SPF.clause( SPF.token("format"), SPF.group(captureTokens, "topicFormatName", SPF.databaseObjectName()) ) ), SPF.optional( SPF.clause( SPF.token("key-columns"), SPF.group(captureTokens, "topicKeyColumnNames", new SQLPatternPartElement("[\\w$]+(?:\\s*,\\s*[\\w$]+)*") ) ) ), SPF.optional( SPF.clause( SPF.token("allow"), SPF.group(captureTokens, "topicAllowedRoleNames", new SQLPatternPartElement("[\\w$]+(?:\\s*,\\s*[\\w$]+)*") ) ) ) ) ); }</code><technical_language>I this hardcoded strings in 3 places in 2 files. define constants</technical_language>

Target:
private static SQLPatternPart makeInnerStreamModifierClausePattern(boolean captureTokens) { return SPF.oneOf( SPF.clause( SPF.token("export"),SPF.token("to"),SPF.token("target"), SPF.group(captureTokens, CAPTURE_EXPORT_TARGET, SPF.databaseObjectName()) ), SPF.clause( SPF.token("partition"), SPF.token("on"), SPF.token("column"), SPF.group(captureTokens, CAPTURE_STREAM_PARTITION_COLUMN, SPF.databaseObjectName()) ), SPF.clause( SPF.token("as"),SPF.token("topic"), SPF.optional( SPF.clause( SPF.token("profile"), SPF.group(captureTokens, CAPTURE_TOPIC_PROFILE, SPF.databaseObjectName()) ) ), SPF.optional( SPF.clause( SPF.token("format"), SPF.group(captureTokens, CAPTURE_TOPIC_FORMAT, SPF.databaseObjectName()) ) ), SPF.optional( SPF.clause( SPF.token("key-columns"), SPF.group(captureTokens, CAPTURE_TOPIC_KEY_COLUMNS, new SQLPatternPartElement("[\\w$]+(?:\\s*,\\s*[\\w$]+)*") ) ) ), SPF.optional( SPF.clause( SPF.token("allow"), SPF.group(captureTokens, CAPTURE_TOPIC_ALLOWED_ROLES, new SQLPatternPartElement("[\\w$]+(?:\\s*,\\s*[\\w$]+)*") ) ) ) ) ); }
Source:
<code>private PasswordCredential getTenantAdminPasswordCredential(String tenantId) throws TException, ApplicationSettingsException { RegistryService.Client regClient = registryClientPool.getResource(); GatewayResourceProfile gwrp = regClient.getGatewayResourceProfile(tenantId); CredentialStoreService.Client csClient = csClientPool.getResource(); try { PasswordCredential TenantAdminPassword = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID()); csClientPool.returnResource(csClient); registryClientPool.returnResource(regClient); return TenantAdminPassword; }catch (Exception e){ <START> logger.error("Error while getting the tenant admin password", e); <END> AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while getting password credentials. More info : " + e.getMessage()); csClientPool.returnBrokenResource(csClient); registryClientPool.returnBrokenResource(regClient); throw exception; } }</code><technical_language>Print tenant id in log. figure out tenant this error is belonged</technical_language>

Target:
private PasswordCredential getTenantAdminPasswordCredential(String tenantId) throws TException, ApplicationSettingsException { RegistryService.Client regClient = registryClientPool.getResource(); GatewayResourceProfile gwrp = regClient.getGatewayResourceProfile(tenantId); CredentialStoreService.Client csClient = csClientPool.getResource(); try { PasswordCredential TenantAdminPassword = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID()); csClientPool.returnResource(csClient); registryClientPool.returnResource(regClient); return TenantAdminPassword; } catch (Exception e){ logger.error("Error while getting the tenant admin password for the tenant id "+tenantId+"", e); AiravataSystemException exception = new AiravataSystemException(); exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); exception.setMessage("Error while getting password credentials. More info : " + e.getMessage()); csClientPool.returnBrokenResource(csClient); registryClientPool.returnBrokenResource(regClient); throw exception; } }
Source:
<code>private boolean parseInputToCheckIfHEX(String newText) { if (newText.length() == 0) { return false; } <START> if (newText.length() != 9) { <END> return false; } try { Color.parseColor(newText); return true; } catch (IllegalArgumentException e) { return false; } }</code><technical_language>need check if newText.length() == 0 ... Additionally checking if newText is a valid hex input Color.parseColor decide for you. This leads this interesting feature / bug: <LINK_0></technical_language>

Target:
private int parseInputToCheckIfHEX(String newText) { if (newText.length() != 9 || !newText.substring(0, 1).equals("#")) { return NOT_A_HEX_VALUE; } try { return Color.parseColor(newText); } catch (IllegalArgumentException e) { return NOT_A_HEX_VALUE; } }
Source:
<code>protected int doWork() { IOUtil.assertFilesAreReadable(INPUT); try { InfiniumNormalizationManifest infiniumNormalizationManifest = new InfiniumNormalizationManifest(ILLUMINA_NORMALIZATION_MANIFEST); <START> InfiniumGTCFile gtcFileOne = new InfiniumGTCFile(new DataInputStream(new FileInputStream(INPUT.get(0))), infiniumNormalizationManifest); <END> InfiniumGTCFile gtcFileTwo = new InfiniumGTCFile(new DataInputStream(new FileInputStream(INPUT.get(1))), infiniumNormalizationManifest); compareGTCFiles(gtcFileOne, gtcFileTwo); if (!errors.isEmpty()) { for (String error : errors) { log.error(error); } return 1; } } catch (IOException | IllegalAccessException | InvocationTargetException e) { throw new PicardException("File error: ", e); } return 0; }</code><technical_language>opened closed, try-with-resources fix that, a bit awkward InfiniumGTCFile is AutoCloseable</technical_language>

Target:
protected int doWork() { IOUtil.assertFilesAreReadable(INPUT); InfiniumNormalizationManifest infiniumNormalizationManifest = new InfiniumNormalizationManifest(ILLUMINA_NORMALIZATION_MANIFEST); try (InfiniumGTCFile gtcFileOne = new InfiniumGTCFile(new DataInputStream(new FileInputStream(INPUT.get(0))), infiniumNormalizationManifest); InfiniumGTCFile gtcFileTwo = new InfiniumGTCFile(new DataInputStream(new FileInputStream(INPUT.get(1))), infiniumNormalizationManifest)) { compareGTCFiles(gtcFileOne, gtcFileTwo); if (!errors.isEmpty()) { for (String error : errors) { log.error(error); } return 1; } } catch (Exception e) { throw new PicardException("File error: ", e); } return 0; }
Source:
<code>private static InputStream openFileOrUrlInputStream(String filenameOrUrl) throws DbException { try { URI uri = new URI(filenameOrUrl); <START> if(uri.getScheme() == null) <END> return openFileInputStream(filenameOrUrl); else if(uri.getScheme().equals("hdfs")) return openHDFSInputStream(uri); else return uri.toURL().openConnection().getInputStream(); } catch(IllegalArgumentException e) { return openFileInputStream(filenameOrUrl); } catch(URISyntaxException e) { return openFileInputStream(filenameOrUrl); } catch(MalformedURLException e) { return openFileInputStream(filenameOrUrl); } catch(IOException e) { throw new DbException(e); } }</code><technical_language>spaces if/catch (we checkstyle running in travis manually reviewing for style errors)</technical_language>

Target:
private static InputStream openFileOrUrlInputStream(String filenameOrUrl) throws DbException { try { URI uri = new URI(filenameOrUrl); if (uri.getScheme() == null) { return openFileInputStream(filenameOrUrl); } else if (uri.getScheme().equals("hdfs")) { return openHdfsInputStream(uri); } else { return uri.toURL().openStream(); } } catch (IllegalArgumentException e) { return openFileInputStream(filenameOrUrl); } catch (URISyntaxException e) { return openFileInputStream(filenameOrUrl); } catch (MalformedURLException e) { return openFileInputStream(filenameOrUrl); } catch (IOException e) { throw new DbException(e); } }
Source:
<code>protected EmbeddedCacheManager createCacheManager() throws Exception { <START> Configuration c = getDefaultStandaloneConfig(true); <END> c.fluent() .indexing() .indexLocalOnly(true) .addProperty("hibernate.search.default.directory_provider", "ram") .addProperty("hibernate.search.lucene_version", "LUCENE_CURRENT"); EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(c); Cache<Object, Object> cache = cacheManager.getCache(); transactionManager = cache.getAdvancedCache().getTransactionManager(); searchManager = Search.getSearchManager(cache); return cacheManager; }</code><technical_language>deprecated configuration API. update new one? in process of eradicating usages of API. I updated other tests, examples</technical_language>

Target:
protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .indexing() .indexLocalOnly(true) .addProperty("hibernate.search.default.directory_provider", "ram") .addProperty("hibernate.search.lucene_version", "LUCENE_CURRENT"); EmbeddedCacheManager cacheManager = TestCacheManagerFactory.createCacheManager(cfg); Cache<Object, Object> cache = cacheManager.getCache(); transactionManager = cache.getAdvancedCache().getTransactionManager(); searchManager = Search.getSearchManager(cache); return cacheManager; }