auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static VmNetworkInterface map(NIC model, VmNetworkInterface template) { VmNetworkInterface entity = template != null ? template : new VmNetworkInterface(); if (model.isSetVm() && model.getVm().isSetId()) { entity.setVmId(new Guid(model.getVm().getId())); } if (model.isSetId()) { entity.setId(new Guid(model.getId())); } if (model.isSetName()) { entity.setName(model.getName()); } if (model.isSetMac() && model.getMac().isSetAddress()) { entity.setMacAddress(model.getMac().getAddress()); } if (model.isSetNetwork() && model.getNetwork().isSetName()) { entity.setNetworkName(model.getNetwork().getName()); } if (model.isSetInterface()) { NicInterface nicType = NicInterface.fromValue(model.getInterface()); if (nicType != null) { entity.setType(map(nicType)); } } if (model.isSetActive()) { entity.setActive(model.isActive()); } <START> if (model.isSetPromisc()) { <END> model.setPromisc(entity.isPromisc()); } return entity; }</code><technical_language>this setter is longer relevant, recompile project generated new setters/getters schema change</technical_language>

Target:
public static VmNetworkInterface map(NIC model, VmNetworkInterface template) { VmNetworkInterface entity = template != null ? template : new VmNetworkInterface(); if (model.isSetVm() && model.getVm().isSetId()) { entity.setVmId(new Guid(model.getVm().getId())); } if (model.isSetId()) { entity.setId(new Guid(model.getId())); } if (model.isSetName()) { entity.setName(model.getName()); } if (model.isSetMac() && model.getMac().isSetAddress()) { entity.setMacAddress(model.getMac().getAddress()); } if (model.isSetNetwork() && model.getNetwork().isSetName()) { entity.setNetworkName(model.getNetwork().getName()); } if (model.isSetInterface()) { NicInterface nicType = NicInterface.fromValue(model.getInterface()); if (nicType != null) { entity.setType(map(nicType)); } } if (model.isSetActive()) { entity.setActive(model.isActive()); } if (model.isSetPromiscuous()) { model.setPromiscuous(entity.isPromisc()); } return entity; }
Source:
<code>public void setSendingEnabled(PerunSession sess, List<ApplicationMail> mails, boolean enabled) throws PerunException { if (mails == null) { throw new InternalErrorException("Mails definitions to update can't be null"); } for (ApplicationMail mail : mails) { if (Compatibility.isPostgreSql()) { int existence = jdbc.update("update application_mails set send=? where id=?", (enabled) ? "1" : "0", mail.getId()); <START> if (existence < 1) throw new ApplicationMailNotExistsException("Application mail does not exist.", mail); <END> } else { int existence = jdbc.update("update application_mails set send=? where id=?", enabled, mail.getId()); if (existence < 1) throw new ApplicationMailNotExistsException("Application mail does not exist.", mail); } perun.getAuditer().log(sess, new MailSending(mail, enabled)); } }</code><technical_language>try/catch jdbc.update() call. Handle EmptyResultDataAccessException ApplicationMailNotExistsException wrap RuntimeException InternalErrorException</technical_language>

Target:
public void setSendingEnabled(PerunSession sess, List<ApplicationMail> mails, boolean enabled) throws PerunException { if (mails == null) { throw new InternalErrorException("Mails definitions to update can't be null"); } for (ApplicationMail mail : mails) { if (Compatibility.isPostgreSql()) { try { int existence = jdbc.update("update application_mails set send=? where id=?", (enabled) ? "1" : "0", mail.getId()); if (existence < 1) throw new ApplicationMailNotExistsException("Application mail does not exist.", mail); } catch (RuntimeException e) { throw new InternalErrorException(e); } } else { int existence = jdbc.update("update application_mails set send=? where id=?", enabled, mail.getId()); if (existence < 1) throw new ApplicationMailNotExistsException("Application mail does not exist.", mail); } perun.getAuditer().log(sess, new MailSending(mail, enabled)); } }
Source:
<code>public EntitleByProductsJobConfig setOwner(final Owner owner) { if (owner == null) { throw new IllegalArgumentException("Owner is null"); } <START> this.setJobArgument(OWNER_KEY, owner.getKey()) <END> .setLogLevel(owner.getLogLevel()); return this; }</code><technical_language>Owner metadata is set</technical_language>

Target:
public EntitleByProductsJobConfig setOwner(final Owner owner) { if (owner == null) { throw new IllegalArgumentException("owner is null"); } this.setJobMetadata(OWNER_KEY, owner.getKey()) .setLogLevel(owner.getLogLevel()); return this; }
Source:
<code>public Location resolve(String spec, Map locationFlags) { try { Set<String> seenSoFar = specsSeen.get(); if (seenSoFar==null) { seenSoFar = new LinkedHashSet<String>(); specsSeen.set(seenSoFar); } if (seenSoFar.contains(spec)) throw new IllegalStateException("Circular reference in definition of location '"+spec+"' ("+seenSoFar+")"); seenSoFar.add(spec); LocationResolver resolver = getSpecResolver(spec); if (resolver != null) { return resolver.newLocationFromString(locationFlags, spec, this); } throw new NoSuchElementException("No resolver found for '"+spec+"': " <START> + "known resolvers are "+resolvers.keySet()+"; if you do not see an expected resolver, ensure your classpath is correct include META-INF/services"); <END> } finally { specsSeen.remove(); } }</code><technical_language>Incorrect grammar for "is correct include"? "is correctly including..." a semi-colon "include"</technical_language>

Target:
public Location resolve(String spec, Map locationFlags) { try { Set<String> seenSoFar = specsSeen.get(); if (seenSoFar==null) { seenSoFar = new LinkedHashSet<String>(); specsSeen.set(seenSoFar); } if (seenSoFar.contains(spec)) throw new IllegalStateException("Circular reference in definition of location '"+spec+"' ("+seenSoFar+")"); seenSoFar.add(spec); LocationResolver resolver = getSpecResolver(spec); if (resolver != null) { return resolver.newLocationFromString(locationFlags, spec, this); } throw new NoSuchElementException("No resolver found for '"+spec+"': " + "known resolvers are "+resolvers.keySet()+"; if you do not see an expected resolver, " + "ensure your classpath is correct and includes META-INF/services"); } finally { specsSeen.remove(); } }
Source:
<code>public void testMatchesWithDescriptors() <START> throws Exception <END> { RichColumnDescriptor tableColumn = getTableColumn(); String val = "Test"; Slice slice = Slices.utf8Slice(val); TupleDomain<ColumnDescriptor> effectivePredicate = getEffectivePredicate(tableColumn, VarcharType.createVarcharType(255), val); List<RichColumnDescriptor> tableColumns = Collections.singletonList(tableColumn); TupleDomainParquetPredicate predicate = new TupleDomainParquetPredicate(effectivePredicate, tableColumns); ParquetDictionaryPage page = new ParquetDictionaryPage(slice, 2, ParquetEncoding.PLAIN_DICTIONARY); assertTrue(predicate.matches(Collections.singletonMap(tableColumn, new ParquetDictionaryDescriptor(tableColumn, Optional.of(page))))); }</code><technical_language>unnecessary throws clause</technical_language>

Target:
public void testMatchesWithDescriptors() { RichColumnDescriptor column = getColumn(); String value = "Test2"; TupleDomain<ColumnDescriptor> effectivePredicate = getEffectivePredicate(column, createVarcharType(255), value); List<RichColumnDescriptor> columns = singletonList(column); TupleDomainParquetPredicate predicate = new TupleDomainParquetPredicate(effectivePredicate, columns); ParquetDictionaryPage page = new ParquetDictionaryPage(utf8Slice(value), 2, PLAIN_DICTIONARY); assertTrue(predicate.matches(singletonMap(column, new ParquetDictionaryDescriptor(column, Optional.of(page))))); }
Source:
<code>public static String makeApiCall(String... urlChunks){ String url = canvasURL + CANVAS_API_VERSION; <START> for (String chunk : urlChunks) { <END> url = url + chunk; } M_log.info("API call: " + url); HttpResponse response = Utils.processApiCall(new HttpGet(url)); if (response == null) { M_log.error(String.format("The Api call %s failed with errors", url)); return null; } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { M_log.error(String.format("The Api call %s has failed with status code %s", url, statusCode)); return null; } String apiResponse; String errMsg = "The API call %s has failed to extract the response due to %s"; try { apiResponse = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (IOException e) { M_log.error(String.format(errMsg, url, e.getMessage())); return null; } catch (Exception e) { M_log.error(String.format(errMsg, url, e.getMessage())); return null; } return apiResponse; }</code><technical_language>"url += chunk;" work? I avoids reallocating strings join</technical_language>

Target:
public static String makeApiCall(String... urlChunks){ String url = canvasURL + CANVAS_API_VERSION; for (String chunk : urlChunks) { url += chunk; } M_log.info("API call: " + url); HttpResponse response = Utils.executeApiCall(new HttpGet(url)); if (response == null) { M_log.error(String.format("The Api call %s failed with errors", url)); return null; } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { M_log.error(String.format("The Api call %s has failed with status code %s", url, statusCode)); return null; } String apiResponse; String errMsg = "The API call %s has failed to extract the response due to %s"; try { apiResponse = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (IOException e) { M_log.error(String.format(errMsg, url, e.getMessage())); return null; } catch (Exception e) { M_log.error(String.format(errMsg, url, e.getMessage())); return null; } return apiResponse; }
Source:
<code>public List<Runnable> shutdownNow() { shutdown(true); final ArrayList<Runnable> list = new ArrayList<>(); TaskNode head = this.head; QNode headNext; for (;;) { headNext = head.getNext(); if (headNext != head && headNext instanceof TaskNode) { TaskNode taskNode = (TaskNode) headNext; if (compareAndSetHead(head, taskNode)) { <START> head.setNextRelaxed(head); <END> if (! NO_QUEUE_LIMIT) decreaseQueueSize(); head = taskNode; list.add(taskNode.task); } } else { return list; } } }</code><technical_language>prove this nodes skipped</technical_language>

Target:
public List<Runnable> shutdownNow() { shutdown(true); final ArrayList<Runnable> list = new ArrayList<>(); TaskNode head = this.head; QNode headNext; for (;;) { headNext = head.getNext(); if (headNext == head) { head = this.head; continue; } if (headNext instanceof TaskNode) { TaskNode taskNode = (TaskNode) headNext; if (compareAndSetHead(head, taskNode)) { head.setNextOrdered(head); if (! NO_QUEUE_LIMIT) decreaseQueueSize(); head = taskNode; list.add(taskNode.task); } } else { return list; } } }
Source:
<code>public Map<String, String> getAvailableStorageResourceIdList() throws AppCatalogException { try { Map<String, String> storageResourceMap = new HashMap<String, String>(); List<StorageResourceDescription> storageResourceDescriptionList = select(QueryConstants.FIND_ALL_STORAGE_RESOURCES, 0); if (storageResourceDescriptionList != null) { for (StorageResourceDescription storageResourceDescription: storageResourceDescriptionList) { <START> if (storageResourceDescription.isEnabled()) { <END> storageResourceMap.put(storageResourceDescription.getStorageResourceId(), storageResourceDescription.getHostName()); } } } return storageResourceMap; } catch (Exception e) { logger.error("Error while retrieving storage resource ID list", e); throw new AppCatalogException(e); } }</code><technical_language>great filter this out in query itself. code is 130 factored out</technical_language>

Target:
public Map<String, String> getAvailableStorageResourceIdList() throws AppCatalogException { try { Map<String, String> storageResourceMap = new HashMap<String, String>(); List<StorageResourceDescription> storageResourceDescriptionList = select(QueryConstants.FIND_ALL_AVAILABLE_STORAGE_RESOURCES, 0); return getStorageResourceMap(storageResourceDescriptionList); } catch (Exception e) { logger.error("Error while retrieving available storage resource ID map", e); throw new AppCatalogException("Error while retrieving available storage resource ID map", e); } }
Source:
<code>private void showAccessRestrictionDialog(BPListElement selElement) { AccessRulesDialog dialog = new AccessRulesDialog(getShell(), selElement, fCurrJProject, fPageContainer != null); int res = dialog.open(); if (res == Window.OK || res == AccessRulesDialog.SWITCH_PAGE) { selElement.setAttribute(BPListElement.ACCESSRULES, dialog .getAccessRules()); selElement.setAttribute(BPListElement.COMBINE_ACCESSRULES, <START> Boolean.valueOf(dialog.doCombineAccessRules())); <END> fProjectsList.refresh(); fBuildpathList.dialogFieldChanged(); if (res == AccessRulesDialog.SWITCH_PAGE) { dialog.performPageSwitch(fPageContainer); } } }</code><technical_language>autoboxing</technical_language>

Target:
private void showAccessRestrictionDialog(BPListElement selElement) { AccessRulesDialog dialog = new AccessRulesDialog(getShell(), selElement, fCurrJProject, fPageContainer != null); int res = dialog.open(); if (res == Window.OK || res == AccessRulesDialog.SWITCH_PAGE) { selElement.setAttribute(BPListElement.ACCESSRULES, dialog .getAccessRules()); selElement.setAttribute(BPListElement.COMBINE_ACCESSRULES, dialog.doCombineAccessRules()); fProjectsList.refresh(); fBuildpathList.dialogFieldChanged(); if (res == AccessRulesDialog.SWITCH_PAGE) { dialog.performPageSwitch(fPageContainer); } } }
Source:
<code>@Test public void testInsertCreateNewCompositeUdt() throws Exception { try (Connection c = connect(); Statement s = c.createStatement()) { boolean b = s.execute("create type mytype as (i int, j int)"); assertThat(b, is(false)); <START> b = s.execute("create table w (i int not null, j mytype)"); assertThat(b, is(false)); int x = s.executeUpdate("insert into w " + "values (1, mytype(1, 1))"); assertThat(x, is(1)); <END> try (ResultSet r = s.executeQuery("select * from w")) { assertThat(r.next(), is(true)); assertThat(r.getInt("i"), is(1)); assertArrayEquals(r.getObject("j", Struct.class).getAttributes(), new Object[] {1, 1}); assertThat(r.next(), is(false)); } } }</code><technical_language>Change assertThat(b, is(false)) assertFalse(b)</technical_language>

Target:
@Test public void testInsertCreateNewCompositeUdt() throws Exception { try (Connection c = connect(); Statement s = c.createStatement()) { boolean b = s.execute("create type mytype as (i int, j int)"); assertFalse(b); b = s.execute("create table w (i int not null, j mytype)"); assertFalse(b); int x = s.executeUpdate("insert into w " + "values (1, mytype(1, 1))"); assertEquals(x, 1); try (ResultSet r = s.executeQuery("select * from w")) { assertTrue(r.next()); assertEquals(r.getInt("i"), 1); assertArrayEquals(r.getObject("j", Struct.class).getAttributes(), new Object[] {1, 1}); assertFalse(r.next()); } } }
Source:
<code>private void registerTransformers(SubsystemRegistration subsystem) { ChainedTransformationDescriptionBuilder chainedBuilder = TransformationDescriptionBuilder.Factory.createChainedSubystemInstance(subsystem.getSubsystemVersion()); ResourceTransformationDescriptionBuilder buildWfly10 = chainedBuilder.createBuilder(subsystem.getSubsystemVersion(), MODEL_VERSION_WFLY10); ResourceTransformationDescriptionBuilder builderEap64 = chainedBuilder.createBuilder(MODEL_VERSION_WFLY10, MODEL_VERSION_EAP64); builderEap64.getAttributeBuilder() .addRename(TransactionSubsystemRootResourceDefinition.USE_JOURNAL_STORE, CommonAttributes.USE_HORNETQ_STORE) .addRename(TransactionSubsystemRootResourceDefinition.JOURNAL_STORE_ENABLE_ASYNC_IO, CommonAttributes.HORNETQ_STORE_ENABLE_ASYNC_IO) .addRename(TransactionSubsystemRootResourceDefinition.STATISTICS_ENABLED, CommonAttributes.ENABLE_STATISTICS) <START> .setDiscard(DiscardAttributeChecker.ALWAYS, TransactionSubsystemRootResourceDefinition.USE_ACTIONSTATUSSERVICE_RECOVERY_FILTER); <END> ResourceTransformationDescriptionBuilder builderEap63 = chainedBuilder.createBuilder(MODEL_VERSION_EAP64, MODEL_VERSION_EAP63); builderEap63.rejectChildResource(CMResourceResourceDefinition.PATH_CM_RESOURCE); ResourceTransformationDescriptionBuilder builderEap62 = chainedBuilder.createBuilder(MODEL_VERSION_EAP63, MODEL_VERSION_EAP62); chainedBuilder.buildAndRegister(subsystem, new ModelVersion[]{ MODEL_VERSION_WFLY10, MODEL_VERSION_EAP62, MODEL_VERSION_EAP63, MODEL_VERSION_EAP64, }); }</code><technical_language>This is a boolean of values (and undefined, default value). discarded if is behaviour hosts use, rejected if is new behaviour available/configurable host</technical_language>

Target:
private void registerTransformers(SubsystemRegistration subsystem) { ChainedTransformationDescriptionBuilder chainedBuilder = TransformationDescriptionBuilder.Factory.createChainedSubystemInstance(subsystem.getSubsystemVersion()); ResourceTransformationDescriptionBuilder builderEap64 = chainedBuilder.createBuilder(subsystem.getSubsystemVersion(), MODEL_VERSION_EAP64); builderEap64.getAttributeBuilder() .addRename(TransactionSubsystemRootResourceDefinition.USE_JOURNAL_STORE, CommonAttributes.USE_HORNETQ_STORE) .addRename(TransactionSubsystemRootResourceDefinition.JOURNAL_STORE_ENABLE_ASYNC_IO, CommonAttributes.HORNETQ_STORE_ENABLE_ASYNC_IO) .addRename(TransactionSubsystemRootResourceDefinition.STATISTICS_ENABLED, CommonAttributes.ENABLE_STATISTICS); ResourceTransformationDescriptionBuilder builderEap63 = chainedBuilder.createBuilder(MODEL_VERSION_EAP64, MODEL_VERSION_EAP63); builderEap63.rejectChildResource(CMResourceResourceDefinition.PATH_CM_RESOURCE); ResourceTransformationDescriptionBuilder builderEap62 = chainedBuilder.createBuilder(MODEL_VERSION_EAP63, MODEL_VERSION_EAP62); chainedBuilder.buildAndRegister(subsystem, new ModelVersion[]{ MODEL_VERSION_EAP62, MODEL_VERSION_EAP63, MODEL_VERSION_EAP64, }); }
Source:
<code>private void updateHead() { while (headRecord == null && !fifoQueue.isEmpty()) { final ConsumerRecord<byte[], byte[]> raw = fifoQueue.pollFirst(); final ConsumerRecord<Object, Object> deserialized = recordDeserializer.deserialize(processorContext, raw); if (deserialized == null) { continue; } final long timestamp; try { <START> timestamp = timestampExtractor.extract(deserialized, partitionTime); <END> } catch (final StreamsException internalFatalExtractorException) { throw internalFatalExtractorException; } catch (final Exception fatalUserException) { throw new StreamsException( String.format("Fatal user code error in TimestampExtractor callback for record %s.", deserialized), fatalUserException); } log.trace("Source node extracted timestamp for record {}", source.name(), timestamp, deserialized); if (timestamp < 0) { log.warn( "Skipping record due to negative extracted timestamp. topic=[{}] partition=[{}] offset=[{}] extractedTimestamp=[{}] extractor=[{}]", deserialized.topic(), deserialized.partition(), deserialized.offset(), timestamp, timestampExtractor.getClass().getCanonicalName() ); skipRecordsSensor.record(); continue; } headRecord = new StampedRecord(deserialized, timestamp); if (timestamp > partitionTime) { partitionTime = timestamp; } } }</code><technical_language>update method timestamp() headRecordTimestamp() more explicit returns? orthogonal actual fix, a good improvement</technical_language>

Target:
private void updateHead() { while (headRecord == null && !fifoQueue.isEmpty()) { final ConsumerRecord<byte[], byte[]> raw = fifoQueue.pollFirst(); final ConsumerRecord<Object, Object> deserialized = recordDeserializer.deserialize(processorContext, raw); if (deserialized == null) { continue; } final long timestamp; try { timestamp = timestampExtractor.extract(deserialized, partitionTime); } catch (final StreamsException internalFatalExtractorException) { throw internalFatalExtractorException; } catch (final Exception fatalUserException) { throw new StreamsException( String.format("Fatal user code error in TimestampExtractor callback for record %s.", deserialized), fatalUserException); } log.trace("Source node extracted timestamp for record {}", source.name(), timestamp, deserialized); if (timestamp < 0) { log.warn( "Skipping record due to negative extracted timestamp. topic=[{}] partition=[{}] offset=[{}] extractedTimestamp=[{}] extractor=[{}]", deserialized.topic(), deserialized.partition(), deserialized.offset(), timestamp, timestampExtractor.getClass().getCanonicalName() ); skipRecordsSensor.record(); continue; } headRecord = new StampedRecord(deserialized, timestamp); partitionTime = Math.max(partitionTime, timestamp); } }
Source:
<code>public HasValueContainer(final String key, final Predicate predicate, final Object value, Collection<PropertyDefinition> propertyDefinitions) { this.key = key; this.value = value; this.predicate = predicate; this.propertyDefinitions = propertyDefinitions; PropertyDefinition propertyDefinition = PropertyDefinition.findPropertyDefinition(propertyDefinitions, key); <START> if (!predicate.isSupported(propertyDefinition)) { <END> throw new VertexiumException("Check your TextIndexHint settings. Predicate " + predicate.toString() + " cannot be used with property " + key); } }</code><technical_language>Instead of isSupported this validate(propertyDefinition) a more meaningful error message, for example in case missing full text hint</technical_language>

Target:
public HasValueContainer(final String key, final Predicate predicate, final Object value, Collection<PropertyDefinition> propertyDefinitions) { this.key = key; this.value = value; this.predicate = predicate; this.propertyDefinitions = propertyDefinitions; PropertyDefinition propertyDefinition = PropertyDefinition.findPropertyDefinition(propertyDefinitions, key); predicate.validate(propertyDefinition); }
Source:
<code>protected void executeQueryCommand() { List<VmTemplate> vmTemplateList = getDbFacade().getVmTemplateDao() .getAllForNetwork(getParameters().getNetworkId()); List<VmNetworkInterface> vmNetworkInterfaceList = getDbFacade().getVmNetworkInterfaceDao() .getAllForTemplatesByNetwork(getParameters().getNetworkId()); final Map<Guid, VmTemplate> vmTemplatesById = Entities.businessEntitiesById(vmTemplateList); List<Pair<VmNetworkInterface, VmTemplate>> vmInterfaceVmPairs = new ArrayList<Pair<VmNetworkInterface, VmTemplate>>(); for (VmNetworkInterface vmNetworkInterface : vmNetworkInterfaceList) { <START> vmInterfaceVmPairs.add(new Pair(vmNetworkInterface, <END> vmTemplatesById.get(vmNetworkInterface.getVmTemplateId()))); } getQueryReturnValue().setReturnValue(vmInterfaceVmPairs); }</code><technical_language>I guess this replaced PairQueryable</technical_language>

Target:
protected void executeQueryCommand() { List<VmTemplate> vmTemplateList = getDbFacade().getVmTemplateDao() .getAllForNetwork(getParameters().getNetworkId()); List<VmNetworkInterface> vmNetworkInterfaceList = getDbFacade().getVmNetworkInterfaceDao() .getAllForTemplatesByNetwork(getParameters().getNetworkId()); final Map<Guid, VmTemplate> vmTemplatesById = Entities.businessEntitiesById(vmTemplateList); List<PairQueryable<VmNetworkInterface, VmTemplate>> vmInterfaceVmPairs = new ArrayList<PairQueryable<VmNetworkInterface, VmTemplate>>(); for (VmNetworkInterface vmNetworkInterface : vmNetworkInterfaceList) { vmInterfaceVmPairs.add(new PairQueryable(vmNetworkInterface, vmTemplatesById.get(vmNetworkInterface.getVmTemplateId()))); } getQueryReturnValue().setReturnValue(vmInterfaceVmPairs); }
Source:
<code>private void processConnectionRequest(final XMPPAccount account) { JID currentJID = connectionHandler.getLocalJID(); JID newJID = new JID(account.getUsername(), account.getDomain()); if (currentJID == null) { connectToAccount(account, false); return; } <START> if (newJID.strictlyEquals(currentJID)) { <END> LOG.debug( "Ignoring connection action as account is already connected. current JID: " + currentJID + ", new JID: " + newJID); return; } ISarosSession sarosSession = sarosSessionManager.getSession(); if (sarosSession == null) { connectToAccount(account, true); return; } String message = Messages.ConnectServerAction_leave_session_confirmation_message; if (sarosSession.isHost()) { message += Messages.ConnectServerAction_leave_session_confirmation_host_addendum_message; } boolean reallyReconnect; try { reallyReconnect = SafeDialogUtils.showYesNoDialog( project, message, Messages.ConnectServerAction_leave_session_confirmation_title); } catch (IllegalAWTContextException e) { LOG.error("Failed to show question on whether to really switch accounts to user", e); NotificationPanel.showError( MessageFormat.format( Messages.ConnectServerAction_leave_session_confirmation_host_addendum_error_message, e.getMessage()), Messages.ConnectServerAction_leave_session_confirmation_host_addendum_error_title); return; } if (reallyReconnect) { connectToAccount(account, true); } }</code><technical_language>equals</technical_language>

Target:
private void processConnectionRequest(final XMPPAccount account) { JID currentJID = connectionHandler.getLocalJID(); JID newJID = new JID(account.getUsername(), account.getDomain()); if (currentJID == null) { connectToAccount(account, false, false); return; } if (newJID.equals(currentJID)) { LOG.debug( "Ignoring connection action as account is already connected. current JID: " + currentJID + ", new JID: " + newJID); return; } ISarosSession sarosSession = sarosSessionManager.getSession(); if (sarosSession == null) { connectToAccount(account, true, false); return; } String message = Messages.ConnectServerAction_leave_session_confirmation_message; if (sarosSession.isHost()) { message += Messages.ConnectServerAction_leave_session_confirmation_host_addendum_message; } boolean reallyReconnect; try { reallyReconnect = SafeDialogUtils.showYesNoDialog( project, message, Messages.ConnectServerAction_leave_session_confirmation_title); } catch (IllegalAWTContextException e) { LOG.error("Failed to show question on whether to really switch accounts to user", e); NotificationPanel.showError( MessageFormat.format( Messages.ConnectServerAction_leave_session_confirmation_host_addendum_error_message, e.getMessage()), Messages.ConnectServerAction_leave_session_confirmation_host_addendum_error_title); return; } if (reallyReconnect) { connectToAccount(account, true, true); } }
Source:
<code>public Operation exec(Prolog engine) throws PrologException { engine.setB0(); Term a1 = arg1.dereference(); Term a2 = arg2.dereference(); Term a3 = arg3.dereference(); PrologEnvironment env = (PrologEnvironment) engine.control; final PatchSet.Id id = StoredValues.PATCH_SET_ID.get(engine); PatchSetInfoFactory psiFactory = env.getInjector().getInstance(PatchSetInfoFactory.class); Term idTerm; Term nameTerm = Prolog.Nil; Term emailTerm = Prolog.Nil; try { <START> UserIdentity author = psiFactory.get(id).getAuthor(); <END> Account.Id authorId = author.getAccount(); if (authorId == null) { idTerm = SymbolTerm.intern("anonymous"); } else { idTerm = new IntegerTerm(authorId.get()); } String name = author.getName(); if (name != null && !name.equals("")) { nameTerm = SymbolTerm.intern(name); } String email = author.getEmail(); if (email != null && !email.equals("")) { emailTerm = SymbolTerm.intern(email); } } catch (PatchSetInfoNotAvailableException err) { throw new JavaException(this, 1, err); } if (!a1.unify(new StructureTerm(user, idTerm), engine.trail)) { return engine.fail(); } if (!a2.unify(nameTerm, engine.trail)) { return engine.fail(); } if (!a3.unify(emailTerm, engine.trail)) { return engine.fail(); } return cont; }</code><technical_language>psiFactory.get(id) is costly. this a StoredValue create PrologEnvironment</technical_language>

Target:
public Operation exec(Prolog engine) throws PrologException { engine.setB0(); PatchSetInfo psInfo = StoredValues.PATCH_SET_INFO.get(engine); UserIdentity author = psInfo.getAuthor(); return exec(engine, author); }
Source:
<code>public static List<ProcessVariableSummary> adaptCollection(List<VariableInstance> variables, Map<String, String> properties, long processInstanceId, String deploymentId, String serverTemplateId) { List<VariableInstance> filteredVariables = variables.stream() .filter(variable -> !excludedVariables.contains(variable.getVariableName())) .collect(Collectors.toList()); List<ProcessVariableSummary> variablesSummary = new ArrayList<>(); properties.forEach((key, value) -> { VariableProcessor processor = processors.getOrDefault(value, new DefaultVariableProcessor()); processor.process(processInstanceId, key, value, filteredVariables, variableSummary -> { variablesSummary.add(variableSummary); variableSummary.setDeploymentId(deploymentId); variableSummary.setServerTemplateId(serverTemplateId); }); }); if (!filteredVariables.isEmpty()) { filteredVariables.forEach(variable -> { <START> ProcessVariableSummary variableSummary = new ProcessVariableSummary(variable.getVariableName(), <END> variable.getVariableName(), variable.getProcessInstanceId(), variable.getOldValue(), variable.getValue(), variable.getDate().getTime(), ""); variablesSummary.add(variableSummary); variableSummary.setDeploymentId(deploymentId); variableSummary.setServerTemplateId(serverTemplateId); }); } variablesSummary.sort(Comparator.comparing(ProcessVariableSummary::getName)); return variablesSummary; }</code><technical_language>I suggest constructor pass variables transform this a stream style, filteredVariables.map. map function isolated function tested independently</technical_language>

Target:
public static List<ProcessVariableSummary> adaptCollection(List<VariableInstance> variables, Map<String, String> properties, long processInstanceId, String deploymentId, String serverTemplateId) { List<VariableInstance> filteredVariables = variables.stream() .filter(variable -> !excludedVariables.contains(variable.getVariableName())) .collect(toList()); List<ProcessVariableSummary> variablesSummary = new ArrayList<>(); properties.forEach((key, value) -> { VariableProcessor processor = processors.getOrDefault(value, new DefaultVariableProcessor()); processor.process(processInstanceId, key, value, filteredVariables, deploymentId, serverTemplateId, variableSummary -> variablesSummary.add(variableSummary)); }); variablesSummary.addAll(ofNullable(filteredVariables).orElse(emptyList()) .stream() .map(new ProcessInstanceVariableMapper(deploymentId, serverTemplateId, "")) .collect(toList())); variablesSummary.sort(Comparator.comparing(ProcessVariableSummary::getName)); return variablesSummary; }
Source:
<code><START> public MarshallingResponseBuilder messages(List<MarshallingMessage> messages) { <END> this.messages.addAll(messages); return this; }</code><technical_language>if a reason for removing parametrized type MarshallingResponseBuilder<T>, setting messages loose type. other methods state, addMessage, resout type</technical_language>

Target:
public MarshallingResponseBuilder<T> messages(List<MarshallingMessage> messages) { this.messages.addAll(messages); return this; }
Source:
<code>public String run(String[] args) throws Exception { JCommander jc = new JCommander(this); jc.setProgramName(this.getClass().getSimpleName()); try { jc.parse(args); if (mBaseParameters.mHelp) { jc.usage(); System.exit(0); } } catch (Exception e) { LOG.error("Failed to parse command: ", e); jc.usage(); throw e; } prepare(); AlluxioConfiguration conf = new InstancedConfiguration(ConfigurationUtils.defaults()); String className = this.getClass().getCanonicalName(); if (mBaseParameters.mCluster) { long jobId = JobGrpcClientUtils.run(generateJobConfig(args), 0, conf); JobInfo jobInfo = JobGrpcClientUtils.getJobStatus(jobId, conf, true); return jobInfo.getResult().toString(); } if (mBaseParameters.mInProcess) { LOG.debug("Run in process, mDistributed={}", mBaseParameters.mDistributed); T result = runLocal(); if (mBaseParameters.mDistributed) { return result.toJson(); } final String s = result.aggregator().aggregate(Collections.singletonList(result)).toJson(); return s; } else { List<String> command = new ArrayList<>(); command.add(conf.get(PropertyKey.HOME) + "/bin/alluxio"); command.add("runClass"); command.add(className); command.addAll(Arrays.asList(args)); command.add(BaseParameters.IN_PROCESS_FLAG); command.addAll(mBaseParameters.mJavaOpts); <START> LOG.debug("running command: " + String.join(" ", command)); <END> return ShellUtils.execCommand(command.toArray(new String[0])); } }</code><technical_language>is this debug now</technical_language>

Target:
public String run(String[] args) throws Exception { JCommander jc = new JCommander(this); jc.setProgramName(this.getClass().getSimpleName()); try { jc.parse(args); if (mBaseParameters.mHelp) { jc.usage(); System.exit(0); } } catch (Exception e) { LOG.error("Failed to parse command: ", e); jc.usage(); throw e; } prepare(); AlluxioConfiguration conf = new InstancedConfiguration(ConfigurationUtils.defaults()); String className = this.getClass().getCanonicalName(); if (mBaseParameters.mCluster) { long jobId = JobGrpcClientUtils.run(generateJobConfig(args), 0, conf); JobInfo jobInfo = JobGrpcClientUtils.getJobStatus(jobId, conf, true); return jobInfo.getResult().toString(); } if (mBaseParameters.mInProcess) { T result = runLocal(); if (mBaseParameters.mDistributed) { return result.toJson(); } final String s = result.aggregator().aggregate(Collections.singletonList(result)).toJson(); return s; } else { List<String> command = new ArrayList<>(); command.add(conf.get(PropertyKey.HOME) + "/bin/alluxio"); command.add("runClass"); command.add(className); command.addAll(Arrays.asList(args)); command.add(BaseParameters.IN_PROCESS_FLAG); command.addAll(mBaseParameters.mJavaOpts); LOG.info("running command: " + String.join(" ", command)); return ShellUtils.execCommand(command.toArray(new String[0])); } }
Source:
<code>public String <START> toString() <END> { int resultSize = computeLength(); if (resultSize <= 0) return EMPTY_STRING; char[] result = new char[resultSize]; int offset = 0; if (device != null) { int size = device.length(); device.getChars(0, size, result, offset); offset += size; } if ((separators & HAS_LEADING) != 0) result[offset++] = SEPARATOR; if ((separators & IS_UNC) != 0) result[offset++] = SEPARATOR; int len = segments.length - 1; if (len >= 0) { for (int i = 0; i < len; i++) { int size = segments[i].length(); segments[i].getChars(0, size, result, offset); offset += size; result[offset++] = SEPARATOR; } int size = segments[len].length(); segments[len].getChars(0, size, result, offset); offset += size; } if ((separators & HAS_TRAILING) != 0) result[offset++] = SEPARATOR; return new String(result); }</code><technical_language>Please review toString method. is intended paths for Posix Windows identical printed</technical_language>

Target:
public String toString() { int resultSize = computeLength(); if (resultSize <= 0) return EMPTY_STRING; char[] result = new char[resultSize]; int offset = 0; if (device != null) { int size = device.length(); device.getChars(0, size, result, offset); offset += size; } if ((flags & HAS_LEADING) != 0) result[offset++] = SEPARATOR; if ((flags & IS_UNC) != 0) result[offset++] = SEPARATOR; int len = segments.length - 1; if (len >= 0) { for (int i = 0; i < len; i++) { int size = segments[i].length(); segments[i].getChars(0, size, result, offset); offset += size; result[offset++] = SEPARATOR; } int size = segments[len].length(); segments[len].getChars(0, size, result, offset); offset += size; } if ((flags & HAS_TRAILING) != 0) result[offset++] = SEPARATOR; return new String(result); }
Source:
<code>public void saveModuleDerivedParser(ParsedDefinitionWrapper wrapper, String moduleName, KExceptionManager kem) { UserParser parser = wrapper.getModuleDerviedParser(moduleName, kem); <START> String fileName = "extras/" + moduleName +"_Parser.bin"; <END> loader.saveOrDie(files.resolveKompiled(fileName), parser); }</code><technical_language>FileUtil's constant for extras/</technical_language>

Target:
public void saveModuleDerivedParser(ParsedDefinitionWrapper wrapper, String moduleName, KExceptionManager kem) { UserParser parser = wrapper.getModuleDerviedParser(moduleName, kem); String modulePath = FileUtil.moduleDerivedParserPath(moduleName); loader.saveOrDie(files.resolveKompiled(modulePath), parser); }
Source:
<code>public String toString() { final StringBuilder sb = new StringBuilder("ClientMessage{"); sb.append("connection=").append(connection); sb.append(", length=").append(getFrameLength()); sb.append(", correlationId=").append(getCorrelationId()); sb.append(", operation=").append(getOperationName()); sb.append(", messageType=").append(getMessageType()); sb.append(", isRetryable=").append(isRetryable()); <START> sb.append(", isEvent=").append(isFlagSet(get(0).flags, IS_EVENT)); <END> sb.append('}'); return sb.toString(); }</code><technical_language>add other flag values well</technical_language>

Target:
public String toString() { final StringBuilder sb = new StringBuilder("ClientMessage{"); sb.append("connection=").append(connection); if (size() > 0) { sb.append(", length=").append(getFrameLength()); sb.append(", correlationId=").append(getCorrelationId()); sb.append(", operation=").append(getOperationName()); sb.append(", messageType=").append(getMessageType()); sb.append(", isRetryable=").append(isRetryable()); sb.append(", isEvent=").append(isFlagSet(get(0).flags, IS_EVENT_FLAG)); sb.append(", isFragmented=").append(!isFlagSet(get(0).flags, UNFRAGMENTED_MESSAGE)); } sb.append('}'); return sb.toString(); }
Source:
<code>public SEPTADatabase(Context context, int databaseVersion, String databaseFileName) { super(context, databaseFileName, null, databaseVersion); setDatabaseVersion(databaseVersion); CrashlyticsManager.log(Log.INFO, TAG, "Initializing DB: " + databaseVersion); setForcedUpgrade(); execSQL(new String[]{ <START> "CREATE INDEX stop_srd_index ON stop_route_direction (stop_id);", <END> "CREATE INDEX route_srd_index ON stop_route_direction (route_id);", "CREATE INDEX direction_srd_index ON stop_route_direction (direction_id);", "CREATE INDEX trips_bus_route_id_index ON trips_bus (route_id);", "CREATE INDEX trips_rail_route_id_trip_id_index ON trips_rail (route_id, trip_id);", "CREATE INDEX trips_rail_trip_id_route_id_index ON trips_rail (trip_id, route_id);", "CREATE INDEX routes_bus_route_id_index ON routes_bus (route_id);", "CREATE INDEX routes_rail_route_id_index ON routes_rail (route_id);", "CREATE INDEX reverseStopSearch_reverse_stop_id_stop_id_index ON reverseStopSearch (reverse_stop_id, stop_id);", "CREATE INDEX reverseStopSearch_stop_id_reverse_stop_id_index ON reverseStopSearch (stop_id, reverse_stop_id);", "CREATE INDEX bus_stop_directions_Route_index ON bus_stop_directions (Route);", "CREATE INDEX stop_times_rail_trip_id_stop_id_stop_sequence_index ON stop_times_rail (trip_id, stop_id, stop_sequence);", "CREATE INDEX stop_times_rail_stop_id_trip_id_index ON stop_times_rail (stop_id, trip_id);", "VACUUM;" }); }</code><technical_language>externalized. store in a text file read in put Strings values other SQL. hard coding is a good idea</technical_language>

Target:
public SEPTADatabase(Context context, int databaseVersion, String databaseFileName) { super(context, databaseFileName, null, databaseVersion); setDatabaseVersion(databaseVersion); CrashlyticsManager.log(Log.INFO, TAG, "Initializing DB: " + databaseVersion); setForcedUpgrade(); execSQL(new String[]{GeneralUtils.readRawTextFile(context, R.raw.db_init_script)}); }
Source:
<code>public Pair<Segment, Closeable> getAndIncrementSegment() { <START> ReferenceCountingSegment segment = adapter.get(); <END> while (true) { if (segment.increment()) { return new Pair<>(segment, segment.decrementOnce()); } ReferenceCountingSegment newSegment = adapter.get(); if (segment == newSegment) { throw new ISE("segment.close() is called somewhere outside FireHydrant.swapSegment()"); } segment = newSegment; } }</code><technical_language>This code is a duplicate of getIncrementedSegment(), extracted a method</technical_language>

Target:
public Pair<Segment, Closeable> getAndIncrementSegment() { ReferenceCountingSegment segment = getIncrementedSegment(); return new Pair<>(segment, segment.decrementOnceCloseable()); }
Source:
<code>private void selectFindInItem(final MenuItem menuItem) { if (menuItem == allItem) selectFindInItem(menuItem, PREFS_FINDIN_ALL, allIcon, UIText.HistoryPage_findbar_changeto_comments); else if (menuItem == commentsItem) selectFindInItem(menuItem, PREFS_FINDIN_COMMENTS, commentsIcon, UIText.HistoryPage_findbar_changeto_author); else if (menuItem == authorItem) selectFindInItem(menuItem, PREFS_FINDIN_AUTHOR, authorIcon, UIText.HistoryPage_findbar_changeto_commit); else if (menuItem == commitIdItem) selectFindInItem(menuItem, PREFS_FINDIN_COMMITID, commitIdIcon, UIText.HistoryPage_findbar_changeto_committer); else if (menuItem == committerItem) selectFindInItem(menuItem, PREFS_FINDIN_COMMITTER, committerIcon, UIText.HistoryPage_findbar_changeto_all); else if (menuItem == referenceItem) selectFindInItem(menuItem, PREFS_FINDIN_REFERENCE, referenceIcon, <START> UIText.HistoryPage_findbar_changeto_reference); <END> }</code><technical_language>argument is wrong, swapped "..._changeto_all" of above. tooltip is shown hovering icon tells user *next* clicking it</technical_language>

Target:
private void selectFindInItem(final MenuItem menuItem) { if (menuItem == allItem) selectFindInItem(menuItem, PREFS_FINDIN_ALL, allIcon, UIText.HistoryPage_findbar_changeto_comments); else if (menuItem == commentsItem) selectFindInItem(menuItem, PREFS_FINDIN_COMMENTS, commentsIcon, UIText.HistoryPage_findbar_changeto_author); else if (menuItem == authorItem) selectFindInItem(menuItem, PREFS_FINDIN_AUTHOR, authorIcon, UIText.HistoryPage_findbar_changeto_commit); else if (menuItem == commitIdItem) selectFindInItem(menuItem, PREFS_FINDIN_COMMITID, commitIdIcon, UIText.HistoryPage_findbar_changeto_committer); else if (menuItem == committerItem) selectFindInItem(menuItem, PREFS_FINDIN_COMMITTER, committerIcon, UIText.HistoryPage_findbar_changeto_reference); else if (menuItem == referenceItem) selectFindInItem(menuItem, PREFS_FINDIN_REFERENCE, branchesIcon, UIText.HistoryPage_findbar_changeto_all); }
Source:
<code>private void getApprovalNames() throws OrmException { SortedMap<Short, String> acvMap = new TreeMap<Short, String>(); optionList = new ArrayList<CmdOption>(); <START> ResultSet<ApprovalCategory> rs = db.approvalCategories().all(); <END> for (ApprovalCategory c : rs) { if (c.getFunctionName().equals("MaxWithBlock")) { ResultSet<ApprovalCategoryValue> acvrs = db.approvalCategoryValues().byCategory(c.getId()); short min = Short.MAX_VALUE; short max = Short.MIN_VALUE; String usage = ""; for (ApprovalCategoryValue acv : acvrs) { if (min > acv.getValue()) { min = acv.getValue(); } if (max < acv.getValue()) { max = acv.getValue(); } acvMap.put(acv.getValue(), acv.getName()); } usage += "Score for " + c.getName() + "\n"; Iterator<Short> i = acvMap.keySet().iterator(); while (i.hasNext()) { Short key = i.next(); usage += String.format("%4d", key) + " - " + acvMap.get(key) + "\n"; } optionList.add(new CmdOption("--" + c.getName().toLowerCase() .replace(' ', '-'), usage, c.getId().get(), min, max, c.getName())); usage = ""; acvMap.clear(); } } }</code><technical_language>Actually, injection for this: @Inject private ApprovalTypes approvalTypes; discover categories for: for (ApprovalType type : approvalTypes.getApprovalTypes()) { final ApprovalCategory category = type.getCategory(); // values in sorted order, +2 -2. // order shown web UI // for (ApprovalCategoryValue v : type.getValues()) { } } methods ApprovalType discover min max. wrote this duplicated code bulk of logic in ApprovalTypes</technical_language>

Target:
private void getApprovalNames() throws OrmException { optionList = new ArrayList<CmdOption>(); for (ApprovalType type : approvalTypes.getApprovalTypes()) { String usage = ""; final ApprovalCategory category = type.getCategory(); if (category.getFunctionName().equals("MaxWithBlock")) { usage = "Score for " + category.getName() + "\n"; for (ApprovalCategoryValue v : type.getValues()) { usage += String.format("%4d", v.getValue()) + " - " + v.getName() + "\n"; } } optionList.add( new CmdOption( "--" + category.getName().toLowerCase().replace(' ', '-'), usage, category.getId().get(), type.getMin().getValue(), type.getMax().getValue(), category.getName())); } }
Source:
<code>public A create(I id) { final Constructor<A> entityConstructor = getEntityConstructor(); <START> final AggregateRoot<I> root = createAggregateRootEntity(id, getBoundedContext(), rootClass); <END> final A result = createAggregatePartEntity(entityConstructor, id, root); return result; }</code><technical_language>AggregateRoot is Entity</technical_language>

Target:
public A create(I id) { final Constructor<A> entityConstructor = getEntityConstructor(); final Class<R> rootClass = getGenericParameterType(this.getClass(), 2); final AggregateRoot<I> root = createAggregateRoot(id, getBoundedContext(), rootClass); final A result = createAggregatePart(entityConstructor, root); return result; }
Source:
<code>NettyPartitionRequestClient createPartitionRequestClient(ConnectionID connectionId) throws IOException, InterruptedException { while (true) { <START> AtomicReference<Optional<CompletableFuture<NettyPartitionRequestClient>>> computeFuture = new AtomicReference<>(Optional.empty()); CompletableFuture<NettyPartitionRequestClient> waitFuture = clients.computeIfAbsent(connectionId, unused -> { CompletableFuture<NettyPartitionRequestClient> future = new CompletableFuture<>(); computeFuture.set(Optional.of(future)); return future; }); computeFuture.get().ifPresent(future -> future.complete(connectWithRetries(connectionId))); <END> final NettyPartitionRequestClient client; try { client = waitFuture.get(); } catch (ExecutionException e) { throw new IOException(e); } if (client.incrementReferenceCounter()) { return client; } else { destroyPartitionRequestClient(connectionId, client); } } }</code><technical_language>AtomicReference<Optional<CompletableFuture<NettyPartitionRequestClient>>> is a bit complicated type easy understand is working. simpler more precisely expressing intention, caller completes future?: AtomicBoolean isFirstOne = new AtomicBoolean(false); CompletableFuture<NettyPartitionRequestClient> clientFuture = clients.computeIfAbsent(connectionId, unused -> { CompletableFuture<NettyPartitionRequestClient> future = new CompletableFuture<>(); isFirstOne.set(true); return future; }); if (isFirstOne.get()) { clientFuture.complete(connectWithRetries(connectionId))); }</technical_language>

Target:
NettyPartitionRequestClient createPartitionRequestClient(ConnectionID connectionId) throws IOException, InterruptedException { while (true) { AtomicBoolean isTheFirstOne = new AtomicBoolean(false); CompletableFuture<NettyPartitionRequestClient> clientFuture = clients.computeIfAbsent(connectionId, unused -> { isTheFirstOne.set(true); return new CompletableFuture<>(); }); if (isTheFirstOne.get()) { clientFuture.complete(connectWithRetries(connectionId)); } final NettyPartitionRequestClient client; try { client = clientFuture.get(); } catch (ExecutionException e) { throw new IOException(e); } if (client.incrementReferenceCounter()) { return client; } else { destroyPartitionRequestClient(connectionId, client); } } }