auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testBatchMessageThreadPoolSize() throws InterruptedException { <START> for (MockParticipantManager participant : _participants) { <END> int customizedPoolSize = 10; participant.getStateMachineEngine().registerStateModelFactory("OnlineOffline", new TestOnlineOfflineStateModelFactory(customizedPoolSize), "TestFactory"); } String dbName = "TestDBABatch"; IdealState idealState = new FullAutoModeISBuilder(dbName).setStateModel("OnlineOffline") .setStateModelFactoryName("TestFactory").setNumPartitions(100).setNumReplica(1).build(); idealState.setBatchMessageMode(true); _setupTool.getClusterManagementTool().addResource(CLUSTER_NAME, dbName, idealState); _setupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, 1); Thread.sleep(2000L); for (int i = 0; i < NODE_NR; i++) { DefaultMessagingService svc = (DefaultMessagingService) (_participants[i].getMessagingService()); HelixTaskExecutor helixExecutor = svc.getExecutor(); ThreadPoolExecutor executor = (ThreadPoolExecutor) (helixExecutor._batchMessageExecutorService); Assert.assertNotNull(executor); Assert.assertTrue(executor.getPoolSize() > 0); } }</code><technical_language>need a test number of resources group message enabled > threapool size. This is scenario current code deadlocks. This test case cover scenario</technical_language>

Target:
public void testBatchMessageThreadPoolSize() throws InterruptedException { int customizedPoolSize = 5; _participants[0].getStateMachineEngine().registerStateModelFactory("OnlineOffline", new TestOnlineOfflineStateModelFactory(customizedPoolSize, 2000), "TestFactory"); for (int i = 1; i < _participants.length; i++) { _participants[i].syncStop(); } Thread.sleep(2000L); int numberOfDbs = 10; for (int i = 0; i < numberOfDbs; i++) { String dbName = "TestDBABatch" + i; IdealState idealState = new FullAutoModeISBuilder(dbName).setStateModel("OnlineOffline") .setStateModelFactoryName("TestFactory").setNumPartitions(10).setNumReplica(1).build(); idealState.setBatchMessageMode(true); _setupTool.getClusterManagementTool().addResource(CLUSTER_NAME, dbName, idealState); _setupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, 1); } Thread.sleep(2000L); DefaultMessagingService svc = (DefaultMessagingService) (_participants[0].getMessagingService()); HelixTaskExecutor helixExecutor = svc.getExecutor(); ThreadPoolExecutor executor = (ThreadPoolExecutor) (helixExecutor._batchMessageExecutorService); Assert.assertNotNull(executor); Assert.assertTrue(executor.getPoolSize() >= numberOfDbs); BestPossibleExternalViewVerifier verifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkAddr(ZK_ADDR).build(); Assert.assertTrue(verifier.verify()); }
Source:
<code><START> public void setForShareSupported(boolean forShareSupported) { <END> this.forShareSupported = forShareSupported; }</code><technical_language>kick review then. protected, templates report support forShare</technical_language>

Target:
protected void setForShareSupported(boolean forShareSupported) { this.forShareSupported = forShareSupported; }
Source:
<code>public void prepare(WorkerTopologyContext context, GlobalStreamId stream, List<Integer> targetTasks) { random = new Random(); sourceNodeInfo = new NodeInfo(context.getThisWorkerHost(), Sets.newHashSet((long) context.getThisWorkerPort())); taskToNodePort = context.getTaskToNodePort(); this.targetTasks = targetTasks; <START> CAPACITY = targetTasks.size() == 1 ? 1 : targetTasks.size() * MAX_WEIGHT; <END> conf = context.getConf(); dnsToSwitchMapping = ReflectionUtils.newInstance((String) conf.get(Config.STORM_NETWORK_TOPOGRAPHY_PLUGIN)); localityGroup = new HashMap<>(); currentScope = Scope.WORKER_LOCAL; higherBound = ObjectReader.getDouble(conf.get(Config.TOPOLOGY_LOCALITYAWARE_HIGHER_BOUND_PERCENT)); lowerBound = ObjectReader.getDouble(conf.get(Config.TOPOLOGY_LOCALITYAWARE_LOWER_BOUND_PERCENT)); rets = (List<Integer>[]) new List<?>[targetTasks.size()]; int i = 0; for (int target : targetTasks) { rets[i] = Arrays.asList(target); orig.put(target, new IndexAndWeights(i)); i++; } choices = new int[CAPACITY]; current = new AtomicInteger(0); prepareChoices = new int[CAPACITY]; updateRing(null); }</code><technical_language>other logic leverage max weight, this work for targetTasks.size() == 1? If works, ideal test this case clear out wondering</technical_language>

Target:
public void prepare(WorkerTopologyContext context, GlobalStreamId stream, List<Integer> targetTasks) { random = new Random(); sourceNodeInfo = new NodeInfo(context.getThisWorkerHost(), Sets.newHashSet((long) context.getThisWorkerPort())); taskToNodePort = context.getTaskToNodePort(); this.targetTasks = targetTasks; capacity = targetTasks.size() == 1 ? 1 : Math.max(1000, targetTasks.size() * 5); conf = context.getConf(); dnsToSwitchMapping = ReflectionUtils.newInstance((String) conf.get(Config.STORM_NETWORK_TOPOGRAPHY_PLUGIN)); localityGroup = new HashMap<>(); currentScope = Scope.WORKER_LOCAL; higherBound = ObjectReader.getDouble(conf.get(Config.TOPOLOGY_LOCALITYAWARE_HIGHER_BOUND_PERCENT)); lowerBound = ObjectReader.getDouble(conf.get(Config.TOPOLOGY_LOCALITYAWARE_LOWER_BOUND_PERCENT)); rets = (List<Integer>[]) new List<?>[targetTasks.size()]; int i = 0; for (int target : targetTasks) { rets[i] = Arrays.asList(target); orig.put(target, new IndexAndWeights(i)); i++; } choices = new int[capacity]; current = new AtomicInteger(0); prepareChoices = new int[capacity]; updateRing(null); }
Source:
<code>public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { final String name = StringUtils.substringAfter(mixinClassName, MIXIN_PREFIX).toLowerCase(); Map<String, Boolean> patches = SpongeImpl.getGlobalConfig().getConfig().getCommands().getMultiWorldCommandPatches(); if (!patches.containsKey(name)) { <START> patches.put(name, false); <END> SpongeImpl.getGlobalConfig().save(); return !this.configState; } return patches.get(name) == this.configState; }</code><technical_language>this true? default, multi-world commands true</technical_language>

Target:
public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { String name = StringUtils.substringAfter(mixinClassName, MIXIN_PREFIX).toLowerCase(Locale.ENGLISH); if (name.equals("showseed")) { name = "seed"; } Map<String, Boolean> patches = SpongeImpl.getGlobalConfig().getConfig().getCommands().getMultiWorldCommandPatches(); if (!patches.containsKey(name)) { patches.put(name, true); SpongeImpl.getGlobalConfig().save(); return this.configState; } return patches.get(name) == this.configState; }
Source:
<code>static MessageProcessor<Integer> defaultQosProcessor() { return message -> { Object header = message.getHeaders().get(MqttHeaders.QOS); <START> Assert.state(header == null || header instanceof Integer, MqttHeaders.QOS + " header must be Integer"); <END> return (Integer) header; }; }</code><technical_language>rely MessageHeaders.<T> T get(Object key, Class<T> type) ? Right, is IllegalArgumentException, consistent regular MessageHeaders usage</technical_language>

Target:
static MessageProcessor<Integer> defaultQosProcessor() { return message -> message.getHeaders().get(MqttHeaders.QOS, Integer.class); }
Source:
<code>public void createNewGroup(Group group) { <START> List<Id> memberIDs = new ArrayList<>(); <END> List<User> members = group.getUsers(); for (User u : members){ memberIDs.add(u.getId()); } Request groupAddRequest = RequestBuilder .GroupCreateRequest(group.getUsers().get(0).getId(), group.getName(), memberIDs); Log.d("REQUEST", "Add new group"); mService.sendRequest(groupAddRequest); }</code><technical_language>Null check in full file</technical_language>

Target:
public void createNewGroup(Group group) { Objects.requireNonNull(group); List<Id> memberIDs = new ArrayList<>(); List<User> members = group.getUsers(); for (User u : members){ memberIDs.add(u.getId()); } Request groupAddRequest = RequestBuilder .GroupCreateRequest(group.getUsers().get(0).getId(), group.getName(), memberIDs); Log.d("REQUEST", "Add new group"); mService.sendRequest(groupAddRequest); }
Source:
<code>private void resetSearchView() { ((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false); mSearchView.onActionViewCollapsed(); mSearchView.setQuery("", false); mCurFilter = null; mListView.setSelection(0); <START> if (mListener != null) <END> mListener.showSlidingTabLayout(); }</code><technical_language>{}</technical_language>

Target:
private void resetSearchView() { ((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false); mSearchView.onActionViewCollapsed(); mSearchView.setQuery("", false); mCurFilter = null; mListView.setSelection(0); if (mListener != null) { mListener.showSlidingTabLayout(); } }
Source:
<code>protected TaxonConcept findPrincipal(Taxonomy taxonomy) { List<TaxonConcept> concepts = this.getConcepts(); if (concepts.isEmpty()) return null; if (concepts.size() == 1) return concepts.get(0); concepts.sort((tc1, tc2) -> tc2.getProviderScore() - tc1.getProviderScore()); final int cutoff = taxonomy.getAcceptedCutoff(); List<TaxonConcept> accepted = concepts.stream().filter(tc -> tc.isFormal() && tc.hasAccepted() && tc.getPrincipalScore() > cutoff).collect(Collectors.toList()); <START> if (accepted.size() == 0) <END> return concepts.get(0); if (accepted.size() == 1) return accepted.get(0); List<TaxonConcept> authored = accepted.stream().filter(tc -> tc.isAuthored()).collect(Collectors.toList()); if (authored.size() == 0) return accepted.get(0); if (authored.size() == 1) return authored.get(0); taxonomy.report(IssueType.COLLISION, "scientificName.collision", this, authored.get(0), authored.get(1)); final int score = authored.stream().mapToInt(TaxonConcept::getPrincipalScore).max().orElse(Integer.MIN_VALUE); List<TaxonConcept> candidates = authored.stream().filter(tc -> tc.getPrincipalScore() == score).collect(Collectors.toList()); if (candidates.size() > 1) taxonomy.report(IssueType.PROBLEM, "scientificName.collision.match", this, candidates.get(0), candidates.get(1)); return candidates.get(0); }</code><technical_language>Change isEmpty, also, for consistency condition above</technical_language>

Target:
protected TaxonConcept findPrincipal(Taxonomy taxonomy) { List<TaxonConcept> concepts = this.getConcepts(); if (concepts.isEmpty()) return null; if (concepts.size() == 1) return concepts.get(0); concepts.sort(REVERSE_PROVIDER_SCORE_COMPARATOR); final int cutoff = taxonomy.getAcceptedCutoff(); List<TaxonConcept> accepted = concepts.stream().filter(tc -> tc.isFormal() && tc.hasAccepted() && tc.getPrincipalScore() > cutoff).collect(Collectors.toList()); if (accepted.size() == 0) return concepts.get(0); if (accepted.size() == 1) return accepted.get(0); List<TaxonConcept> authored = accepted.stream().filter(tc -> tc.isAuthored()).collect(Collectors.toList()); if (authored.size() == 0) return accepted.get(0); if (authored.size() == 1) return authored.get(0); taxonomy.report(IssueType.COLLISION, "scientificName.collision", this, authored.get(0), authored.get(1)); final int score = authored.stream().mapToInt(TaxonConcept::getPrincipalScore).max().orElse(TaxonomicElement.MIN_SCORE); List<TaxonConcept> candidates = authored.stream().filter(tc -> tc.getPrincipalScore() == score).collect(Collectors.toList()); if (candidates.size() > 1) taxonomy.report(IssueType.PROBLEM, "scientificName.collision.match", this, candidates.get(0), candidates.get(1)); return candidates.get(0); }
Source:
<code>public void delete(SQLiteDatabase db, InstanceAdapter entityAdapter, boolean isSyncAdapter) { TaskAdapter taskAdapter = entityAdapter.taskAdapter(); if (taskAdapter.valueOf(TaskAdapter.ORIGINAL_INSTANCE_ID) != null) { long masterTaskId = taskAdapter.valueOf(TaskAdapter.ORIGINAL_INSTANCE_ID); DateTime originalTime = entityAdapter.valueOf(InstanceAdapter.INSTANCE_ORIGINAL_TIME); mDelegate.delete(db, taskAdapter, false); Cursor c = db.query(TaskDatabaseHelper.Tables.TASKS, null , TaskContract.Tasks._ID + "=" + masterTaskId, null, null, null, null); try { <START> if (c.moveToFirst()) <END> { TaskAdapter masterTaskAdapter = new CursorContentValuesTaskAdapter(masterTaskId, c, new ContentValues()); addExDate(masterTaskAdapter, originalTime); mDelegate.update(db, masterTaskAdapter, false); } } finally { c.close(); } } else if (taskAdapter.isRecurring()) { addExDate(taskAdapter, entityAdapter.valueOf(InstanceAdapter.INSTANCE_ORIGINAL_TIME)); mDelegate.update(db, taskAdapter, false); } else { mDelegate.delete(db, taskAdapter, false); } }</code><technical_language>a direct update a recurring instance? lead simply changing it, braking data consistency of recurrence set? detected if is a recurring instance? RRULE RDATE copied master, handled if branch here</technical_language>

Target:
public void delete(SQLiteDatabase db, InstanceAdapter entityAdapter, boolean isSyncAdapter) { TaskAdapter taskAdapter = entityAdapter.taskAdapter(); if (taskAdapter.valueOf(TaskAdapter.ORIGINAL_INSTANCE_ID) != null) { long masterTaskId = taskAdapter.valueOf(TaskAdapter.ORIGINAL_INSTANCE_ID); DateTime originalTime = entityAdapter.valueOf(InstanceAdapter.INSTANCE_ORIGINAL_TIME); mDelegate.delete(db, taskAdapter, false); try (Cursor c = db.query(TaskDatabaseHelper.Tables.TASKS, null , TaskContract.Tasks._ID + "=" + masterTaskId, null, null, null, null)) { if (c.moveToFirst()) { TaskAdapter masterTaskAdapter = new CursorContentValuesTaskAdapter(masterTaskId, c, new ContentValues()); addExDate(masterTaskAdapter, originalTime); mDelegate.update(db, masterTaskAdapter, false); } } } else if (taskAdapter.isRecurring()) { addExDate(taskAdapter, entityAdapter.valueOf(InstanceAdapter.INSTANCE_ORIGINAL_TIME)); mDelegate.update(db, taskAdapter, false); } else { mDelegate.delete(db, taskAdapter, false); } }
Source:
<code>private static DetailNode getFirstChildOfType(DetailNode node, int tokenType, int offset) { return Arrays.stream(node.getChildren()) .filter(child -> child.getIndex() >= offset && child.getType() == tokenType) .findFirst() <START> .orElse(null); <END> }</code><technical_language>is throw exception return Optional for case. I good handling for null values in invocations of getFirstChildOfType method</technical_language>

Target:
private static Optional<DetailNode> getFirstChildOfType(DetailNode node, int tokenType, int offset) { return Arrays.stream(node.getChildren()) .filter(child -> child.getIndex() >= offset && child.getType() == tokenType) .findFirst(); }
Source:
<code>public void testStartProcessThrowException() throws Exception { <START> Assertions.assertThatThrownBy(() -> { <END> RuleFlowProcess process = new RuleFlowProcess(); process.setId(PROCESS_ID); process.setName("test"); process.setPackageName("org.mycomp.myprocess"); KieSession workingMemory = createKieSession(process); workingMemory.startProcess(PROCESS_ID); }); }</code><technical_language>I want nitpicking, mitigate false positives I add .isInstanceOf(IllegalArgumentException.class) possibly .hasMessage("Runtime exception occurred") .hasMessageContaining(...) EDIT: is enclose in lambda a call workingMemory.startProcess(PROCESS_ID);</technical_language>

Target:
public void testStartProcessThrowException() throws Exception { RuleFlowProcess process = new RuleFlowProcess(); process.setId(PROCESS_ID); process.setName("test"); process.setPackageName("org.mycomp.myprocess"); KieSession workingMemory = createKieSession(process); assertThatThrownBy(() -> workingMemory.startProcess(PROCESS_ID)) .isInstanceOf(IllegalArgumentException.class); }
Source:
<code>public Metrics metrics(Vertx vertx, VertxOptions options) { MetricsImpl metrics = new MetricsImpl(vertx, options); if (options.isJmxEnabled()) { String jmxDomain = options.getJmxDomain(); if (jmxDomain == null) { jmxDomain = "vertx" + "@" + Integer.toHexString(vertx.hashCode()); } <START> JmxReporter.forRegistry(metrics.registry()).inDomain(jmxDomain).build().start(); <END> } return metrics; }</code><technical_language>is this JMXReporter stopped? lifetime tied lifetime of Vert.x instance, Vert.x instance is closed closed MBeans unregistered. -> memory leak</technical_language>

Target:
public Metrics metrics(Vertx vertx, VertxOptions options) { MetricsImpl metrics = new MetricsImpl(vertx, options); if (options.isJmxEnabled()) { String jmxDomain = options.getJmxDomain(); if (jmxDomain == null) { jmxDomain = "vertx" + "@" + Integer.toHexString(vertx.hashCode()); } JmxReporter reporter = JmxReporter.forRegistry(metrics.registry()).inDomain(jmxDomain).build(); metrics.setDoneHandler(v -> reporter.stop()); reporter.start(); } return metrics; }
Source:
<code>protected final Collection<T> sortItems(Collection<T> items) { if (items == null || comparator == null) { return items; } <START> List<T> sortedList = new ArrayList<T>() { <END> private static final long serialVersionUID = 499355412389856325L; @Override public boolean add(T e) { boolean ret = super.add(e); Collections.sort(this, comparator); return ret; } @Override public boolean addAll(Collection<? extends T> c) { boolean ret = super.addAll(c); Collections.sort(this, comparator); return ret; } }; sortedList.addAll(items); return sortedList; }</code><technical_language>contract of List compatible SortedListModel is supposed do, due methods add(item, pos). SortedListModel maintains data constantly consistently sorted comparator, while add(item, pos) allow a developer mess ordering break contract inconsistent behavior. right do suggest this alternative internal implementation for SortedCollection other patch, SortedListModel SortedCollection is consistent requirements</technical_language>

Target:
protected final Collection<T> sortItems(Collection<T> items) { if (items == null || comparator == null) { return items; } List<T> sortedList = new ArrayList<T>(items); Collections.sort(sortedList, comparator); return sortedList; }
Source:
<code><START> public Collection<Staff> selectAll() { <END> String query = "select a from staff a where a.admin = true"; return (List<Staff>)hibernateTemplate.find(query); }</code><technical_language>I add LEFT JOIN FETCH for contact methods home_address for of impacted *.jdbc classes HQL query. so, of queries N \* M separate queries N is number of staff instances returned M is number of attributes class joined another table (contact methods address in case of Person)</technical_language>

Target:
public Collection<Staff> selectAll() { String query = "select a from staff a " + "left join fetch a.homeAddress " + "left join fetch a.contactMethods " + "where a.isAdmin = true"; return (List<Staff>)hibernateTemplate.find(query); }
Source:
<code>public InputStream getBody() throws IOException { <START> return new FileInputStream(this.cachedFile); <END> }</code><technical_language>is this stream closed again</technical_language>

Target:
public InputStream getBody() throws IOException { if (this.body == null) { this.body = new FileInputStream(this.cachedFile); } return this.body; }
Source:
<code><START> public static Map<String, GraphQLDirective> nonRepeatableDirectivesByName(List<GraphQLDirective> directives) { <END> Map<String, List<GraphQLDirective>> map = allDirectivesByName(directives); List<GraphQLDirective> singletonDirectives = map.entrySet().stream() .filter(e -> e.getKey() != null && isAllNonRepeatable(e.getValue())) .flatMap(e -> e.getValue().stream()).collect(Collectors.toList()); return FpKit.getByName(singletonDirectives, GraphQLDirective::getName); }</code><technical_language>nonRepeatableDirectivesByName travel directives times. code faster: java public static Map<String, GraphQLDirective> nonRepeatableDirectivesByName(List<GraphQLDirective> directives) { // filter repeatable directives List<GraphQLDirective> singletonDirectives = directives.stream() .filter(d -> !d.isRepeatable()).collect(Collectors.toList()); return FpKit.getByName(singletonDirectives, GraphQLDirective::getName); }</technical_language>

Target:
public static Map<String, GraphQLDirective> nonRepeatableDirectivesByName(List<GraphQLDirective> directives) { List<GraphQLDirective> singletonDirectives = directives.stream() .filter(d -> !d.isRepeatable()).collect(Collectors.toList()); return FpKit.getByName(singletonDirectives, GraphQLDirective::getName); }
Source:
<code><START> public Person updateFHIRPerson(Person thePerson,String theId){ <END> org.openmrs.api.PersonService personService = Context.getPersonService(); org.openmrs.Person retrievedPerson=personService.getPersonByUuid(theId); if(retrievedPerson!=null){ org.openmrs.Person omrsPerson = FHIRPersonUtil.generateOpenMRSPerson(thePerson); Set<PersonName> all=retrievedPerson.getNames(); boolean needToSetPrefferedName=false; for(PersonName name: omrsPerson.getNames()){ if(name.getPreferred()){ needToSetPrefferedName=true; } } if(needToSetPrefferedName){ for(PersonName name: all){ name.setPreferred(false); } } for(PersonName name: omrsPerson.getNames()){ all.add(name); } retrievedPerson.setNames(all); Set<PersonAddress> allAddress=retrievedPerson.getAddresses(); boolean needToSetHome=false; for(PersonAddress address: omrsPerson.getAddresses()){ if(address.isPreferred()){ needToSetHome=true; } } if(needToSetHome){ for(PersonAddress address: allAddress){ address.setPreferred(false); } } for(PersonAddress address1: omrsPerson.getAddresses()){ allAddress.add(address1); } retrievedPerson.setAddresses(allAddress); retrievedPerson.setPersonVoided(omrsPerson.getVoided()); if(omrsPerson.getVoided()){ retrievedPerson.setPersonVoidReason("Deleted from FHIR module"); } retrievedPerson.setBirthdate(omrsPerson.getBirthdate()); retrievedPerson.setGender(omrsPerson.getGender()); Context.getPersonService().savePerson(retrievedPerson); return FHIRPersonUtil.generatePerson(omrsPerson); }else{ return createFHIRPerson(thePerson); } }</code><technical_language>please openmrs code formatter. Need space beteen passing parameters</technical_language>

Target:
public Person updateFHIRPerson(Person thePerson, String theId) { org.openmrs.api.PersonService personService = Context.getPersonService(); org.openmrs.Person retrievedPerson = personService.getPersonByUuid(theId); if (retrievedPerson != null) { org.openmrs.Person omrsPerson = FHIRPersonUtil.generateOpenMRSPerson(thePerson); retrievedPerson = FHIRPersonUtil.updatePersonAttributes(omrsPerson, retrievedPerson); Context.getPersonService().savePerson(retrievedPerson); return FHIRPersonUtil.generatePerson(retrievedPerson); } else { if (thePerson.getId() == null) { IdDt uuid = new IdDt(); uuid.setValue(theId); thePerson.setId(uuid); } return createFHIRPerson(thePerson); } }
Source:
<code>public void dispose() { <START> for (Node node : nodeMap.values()) { <END> graph.removeNode(node); } nodeMap.clear(); }</code><technical_language>call node.dispose() here</technical_language>

Target:
public void dispose() { for (Node node : nodeMap.values()) { graph.removeNode(node); node.dispose(); } nodeMap.clear(); }
Source:
<code>public VdcActionParametersBase getParameters(Template incoming, VmTemplate entity) { VmTemplate updated = getMapper(modelType, VmTemplate.class).map(incoming, entity); Version compatibilityVersion = Version.getLast(); if (!updated.isBlank()) { compatibilityVersion = lookupCluster(updated.getVdsGroupId()).getCompatibilityVersion(); <START> } <END> updated.setUsbPolicy(VmMapper.getUsbPolicyOnUpdate(incoming.getUsb(), entity.getUsbPolicy(), compatibilityVersion)); UpdateVmTemplateParameters params = new UpdateVmTemplateParameters(updated); if (incoming.isSetRngDevice()) { params.setUpdateRngDevice(true); params.setRngDevice(RngDeviceMapper.map(incoming.getRngDevice(), null)); } if(incoming.isSetSoundcardEnabled()) { params.setSoundDeviceEnabled(incoming.isSoundcardEnabled()); } IconHelper.setIconToParams(incoming, params); DisplayHelper.setGraphicsToParams(incoming.getDisplay(), params); return getMapper(modelType, UpdateVmTemplateParameters.class).map(incoming, params); }</code><technical_language>This business rule part of backend, of RESTAPI</technical_language>

Target:
public VdcActionParametersBase getParameters(Template incoming, VmTemplate entity) { VmTemplate updated = getMapper(modelType, VmTemplate.class).map(incoming, entity); updated.setUsbPolicy(VmMapper.getUsbPolicyOnUpdate(incoming.getUsb(), entity.getUsbPolicy())); UpdateVmTemplateParameters params = new UpdateVmTemplateParameters(updated); if (incoming.isSetRngDevice()) { params.setUpdateRngDevice(true); params.setRngDevice(RngDeviceMapper.map(incoming.getRngDevice(), null)); } if(incoming.isSetSoundcardEnabled()) { params.setSoundDeviceEnabled(incoming.isSoundcardEnabled()); } IconHelper.setIconToParams(incoming, params); DisplayHelper.setGraphicsToParams(incoming.getDisplay(), params); return getMapper(modelType, UpdateVmTemplateParameters.class).map(incoming, params); }
Source:
<code>private void checkDefinition(Definition parsedDef) { CheckRHSVariables checkRHSVariables = new CheckRHSVariables(errors); stream(parsedDef.modules()).forEach(m -> stream(m.localSentences()).forEach(checkRHSVariables::check)); if (!errors.isEmpty()) { kem.addAllKException(errors.stream().map(e -> e.exception).collect(Collectors.toList())); <START> kem.print(); <END> throw KEMException.compilerError("Had " + errors.size() + " structural errors."); } }</code><technical_language>this right. call kem.print() in FrontEnd.java execution ends. this done</technical_language>

Target:
private void checkDefinition(Definition parsedDef) { CheckRHSVariables checkRHSVariables = new CheckRHSVariables(errors); stream(parsedDef.modules()).forEach(m -> stream(m.localSentences()).forEach(checkRHSVariables::check)); if (!errors.isEmpty()) { kem.addAllKException(errors.stream().map(e -> e.exception).collect(Collectors.toList())); throw KEMException.compilerError("Had " + errors.size() + " structural errors."); } }
Source:
<code>private void queryVirtualFunctionMap(IdQueryParameters idQueryParameters) { Frontend.getInstance() .runQuery(QueryType.GetVfToPfMapByHostId, idQueryParameters, new AsyncQuery<QueryReturnValue>(returnValue -> { vfToPfMap = Optional.ofNullable((Map<Guid, Guid>) returnValue.getReturnValue()) .orElse(Collections.emptyMap()); <START> queryIsHostLockedOnNetworkOperation(idQueryParameters); <END> })); }</code><technical_language>a candidate for runMultipleQueries? expert that... chained for a reason</technical_language>

Target:
private void queryVirtualFunctionMap(IdQueryParameters idQueryParameters) { Frontend.getInstance() .runQuery(QueryType.GetVfToPfMapByHostId, idQueryParameters, new AsyncQuery<QueryReturnValue>(returnValue -> { vfToPfMap = Optional.ofNullable((Map<Guid, Guid>) returnValue.getReturnValue()) .orElse(Collections.emptyMap()); queryHostInterfaces(idQueryParameters); })); }
Source:
<code>public void reactOnEventTypesChange() throws InterruptedException { checkForNewChange(); <START> while (null != queuedChanges.peek()) { <END> final DelayedChange change = queuedChanges.peek(); LOG.info("Reacting on delayed change {}", change); final Set<String> unlockedEventTypes = localLocking.lockedEventTypesChanged(change.lockedEventTypes); for (final String unlocked : unlockedEventTypes) { LOG.info("Notifying about unlock of {}", unlocked); final List<Consumer<String>> toNotify; synchronized (consumerListeners) { toNotify = consumerListeners.containsKey(unlocked) ? new ArrayList<>(consumerListeners.get(unlocked)) : null; } if (null != toNotify) { for (final Consumer<String> listener : toNotify) { try { listener.accept(unlocked); } catch (final RuntimeException ex) { LOG.error("Failed to notify about event type unlock", unlocked, ex); } } } } try { zooKeeperHolder.get().setData().forPath( toZkPath("/nodes/" + thisId), String.valueOf(change.version).getBytes(Charsets.UTF_8)); } catch (final Exception ex) { LOG.error("Failed to update node version in zk. Will try to reprocess again", ex); return; } queuedChanges.poll(); LOG.info("Delayed change successfully processed", change); } }</code><technical_language>do peek (next line), move a variable isEmpty</technical_language>

Target:
public void reactOnEventTypesChange() throws InterruptedException { checkForNewChange(); while (!queuedChanges.isEmpty()) { final DelayedChange change = queuedChanges.peek(); LOG.info("Reacting on delayed change {}", change); final Set<String> unlockedEventTypes = localLocking.lockedEventTypesChanged(change.lockedEventTypes); for (final String unlocked : unlockedEventTypes) { LOG.info("Notifying about unlock of {}", unlocked); final List<Consumer<String>> toNotify; synchronized (consumerListeners) { toNotify = consumerListeners.containsKey(unlocked) ? new ArrayList<>(consumerListeners.get(unlocked)) : null; } if (null != toNotify) { for (final Consumer<String> listener : toNotify) { try { listener.accept(unlocked); } catch (final RuntimeException ex) { LOG.error("Failed to notify about event type unlock", unlocked, ex); } } } } try { zooKeeperHolder.get().setData().forPath( toZkPath("/nodes/" + nodeId), String.valueOf(change.version).getBytes(Charsets.UTF_8)); } catch (final Exception ex) { LOG.error("Failed to update node version in zk. Will try to reprocess again", ex); return; } queuedChanges.poll(); LOG.info("Delayed change successfully processed", change); } }
Source:
<code>public Factory(Connection conn) { <START> this(conn, ""); <END> }</code><technical_language>nit: Is a reason change this null? I find null more intuitive (in java) represent string, a present string is empty</technical_language>

Target:
public Factory(Connection conn) { this(conn, null); }
Source:
<code>public CompletionStage<Void> putAllAsync(@Nonnull Map<? extends K, Collection<? extends V>> m) { checkTrueUnsupportedOperation(isClusterVersionGreaterOrEqual(Versions.V4_1), MINIMUM_VERSION_ERROR_4_1); InternalCompletableFuture<Void> future = new InternalCompletableFuture<>(); Map<Data, Data> dataMap = new HashMap<>(); for (Map.Entry e : m.entrySet()) { <START> dataMap.put(toData(e.getKey()), toData(e.getValue())); <END> } putAllInternal(dataMap, future); return future; }</code><technical_language>I realized is issue serialization of Collection<? extends V> here: - Collection<? extends V> is serialized Data - passed MapEntries field of PutAllOperation - In [PutAllOperation](<LINK_0> is deserialized. Data deserialized Collection<? extends V>. problem this is requires collection's element class Class<? extends V> present server, MultiMap stores items in binary format. solution is serialize element, Collection<? extends V> is turned a Collection<Data>, perform serialization of Collection<Data> a single Data put in dataMap: for (Map.Entry e : m.entrySet()) { Collection<Data> dataCollection = asDataCollection(e.getValue()); dataMap.put(toData(e.getKey()), toData(dataCollection)); } ... Collection<Data> asDataCollection(Collection<? extends V> values) { // iterate values serialize }</technical_language>

Target:
public CompletionStage<Void> putAllAsync(@Nonnull Map<? extends K, Collection<? extends V>> m) { checkTrueUnsupportedOperation(isClusterVersionGreaterOrEqual(Versions.V4_1), MINIMUM_VERSION_ERROR_4_1); InternalCompletableFuture<Void> future = new InternalCompletableFuture<>(); Map<Data, Data> dataMap = new HashMap<>(); for (Map.Entry e : m.entrySet()) { Collection<Data> dataCollection = CollectionUtil .objectToDataCollection(((Collection<? extends V>) e.getValue()), getNodeEngine().getSerializationService()); dataMap.put(toData(e.getKey()), toData(new DataCollection(dataCollection))); } putAllInternal(dataMap, future); return future; }
Source:
<code>public String getDefaultValue4Build() { <START> if (isTrim() && defaultValue != null) { <END> return defaultValue.trim(); } else { return defaultValue; } }</code><technical_language>I this simplified Util.fixNull(andTrim) called</technical_language>

Target:
public String getDefaultValue4Build() { if (isTrim()) { return Util.fixNull(defaultValue).trim(); } return defaultValue; }
Source:
<code>public static List<String> getPropertyStrings(Resource resource, String namePattern) { String[] vals = resource.getValueMap().get(namePattern, String[].class); <START> List<String> valsList = new ArrayList<>(); <END> if (vals != null) { for (String val : vals) { valsList.add(val); } } return valsList; }</code><technical_language>Arrays.asList() here? reason (at I of) for resulting list mutable</technical_language>

Target:
public static List<String> getPropertyStrings(Resource resource, String namePattern) { String[] vals = resource.getValueMap().get(namePattern, String[].class); return vals != null ? Arrays.asList(vals) : Collections.EMPTY_LIST; }
Source:
<code>private ValidationResult validateWithHostSetupNetworksValidator(VDS host) { NetworkAttachment <START> networkAttachment = <END> selectNetworkAttachmentForValidatation(); HostSetupNetworksValidator validator = new HostSetupNetworksValidator(host, getParameters(), getExistingNics(), getExistingAttachments(), networkAttachment, getNetworkBusinessEntityMap(), networkClusterDao, networkDao, vdsDao, findActiveVmsUsingNetwork, hostSetupNetworksValidatorHelper, networkExclusivenessValidatorResolver, networkAttachmentIpConfigurationValidator, unmanagedNetworkValidator, backend); return validator.validate(); }</code><technical_language>variable is required</technical_language>

Target:
private ValidationResult validateWithHostSetupNetworksValidator(VDS host) { HostSetupNetworksValidator validator = new HostSetupNetworksValidator(host, getParameters(), getExistingNics(), getExistingAttachments(), selectNetworkAttachmentForValidatation(), getNetworkBusinessEntityMap(), networkClusterDao, networkDao, vdsDao, findActiveVmsUsingNetwork, hostSetupNetworksValidatorHelper, networkExclusivenessValidatorResolver, networkAttachmentIpConfigurationValidator, unmanagedNetworkValidator, backend); return validator.validate(); }
Source:
<code>private static int getLastNodeLineNumber(DetailAST lambdaBody) { DetailAST node = lambdaBody.getLastChild(); int result = node.getLineNo(); <START> while (node != null) { <END> result = node.getLineNo(); node = node.getLastChild(); } return result; }</code><technical_language>Please change this loop do { ... } while(). is strange node != null node.getLineNo()</technical_language>

Target:
private static int getLastNodeLineNumber(DetailAST lambdaBody) { DetailAST node = lambdaBody; int result; do { result = node.getLineNo(); node = node.getLastChild(); } while (node != null); return result; }
Source:
<code>private void requestForbidden(HttpServerExchange exchange, String messageId, String qualifiedTopicName) { messageErrorProcessor.sendQuietly( exchange, <START> error("Permission.", AUTH_ERROR), <END> messageId, qualifiedTopicName); }</code><technical_language>"Permission." -> "Permission denied."</technical_language>

Target:
private void requestForbidden(HttpServerExchange exchange, String messageId, String qualifiedTopicName) { messageErrorProcessor.sendQuietly( exchange, error("Permission denied.", AUTH_ERROR), messageId, qualifiedTopicName); }
Source:
<code>public HttpResponse doTest() { Jenkins j = Jenkins.getInstance(); String referer = Stapler.getCurrentRequest().getReferer(); <START> String redirect = buildRedirect(referer, j); <END> LOGGER.log(Level.FINE, "coming from {0} and redirecting to {1}", new Object[] {referer, redirect}); return new HttpRedirect(redirect); }</code><technical_language>I finding hard follow code here. example for redirect this change</technical_language>

Target:
public HttpResponse doTest() { String referer = Stapler.getCurrentRequest().getReferer(); Jenkins j = Jenkins.getInstance(); String redirect = j.getRootUrl() + "administrativeMonitor/" + id + "/testForReverseProxySetup/" + (referer != null ? Util.rawEncode(referer) : "NO-REFERER") + "/"; LOGGER.log(Level.FINE, "coming from {0} and redirecting to {1}", new Object[] {referer, redirect}); return new HttpRedirect(redirect); }
Source:
<code>public void calculateDerivedFields() { OBSERVED_UNIQUE_UMIS = observedUmis.size(); INFERRED_UNIQUE_UMIS = inferredUmis.size(); PCT_UMI_WITH_N = (double) observedUmiWithN/ ((double) observedUmiWithN + (double) totalObservedUmis); OBSERVED_UMI_ENTROPY = effectiveNumberOfBases(observedUmis); INFERRED_UMI_ENTROPY = effectiveNumberOfBases(inferredUmis); UMI_BASE_QUALITIES = QualityUtil.getPhredScoreFromErrorProbability((double) OBSERVED_BASE_ERRORS / (double) observedUmiBases); <START> <END> }</code><technical_language>remove whitespace</technical_language>

Target:
public void calculateDerivedFields() { OBSERVED_UNIQUE_UMIS = observedUmis.size(); INFERRED_UNIQUE_UMIS = inferredUmis.size(); PCT_UMI_WITH_N = (double) observedUmiWithNs/ ((double) observedUmiWithNs + (double) totalObservedUmisWithoutNs); OBSERVED_UMI_ENTROPY = effectiveNumberOfBases(observedUmis); INFERRED_UMI_ENTROPY = effectiveNumberOfBases(inferredUmis); UMI_BASE_QUALITIES = QualityUtil.getPhredScoreFromErrorProbability((double) OBSERVED_BASE_ERRORS / (double) observedUmiBases); }
Source:
<code>public Matrix feedForward(final Matrix input) { <START> this.bernoulliMatrix = matrixFactory.bernoulli(inputHeight, inputWidth, dropoutRatio); <END> return bernoulliMatrix.mul(input); }</code><technical_language>bernouliMatrix # rows # columns input matrix. More precisley, "the number of outputs of preceding FullyConnectedLayer" rows \* "the number of columns of input (the number of data instances in batch)" columns. Number of rows columns **NOT** inputHeight & inputWidth</technical_language>

Target:
public Matrix feedForward(final Matrix input) { this.bernoulliMatrix = matrixFactory .bernoulli(input.getRows(), input.getColumns(), 1 - dropoutRatio, 1 / (1 - dropoutRatio)); return bernoulliMatrix.mul(input); }
Source:
<code>public GetConfigurationObjectResponse getGetConfigurationObjectResponse( @RequestPayload final GetConfigurationObjectAsyncRequest request) throws OsgpException { GetConfigurationObjectResponse response = null; try { response = new GetConfigurationObjectResponse(); final MeterResponseData meterResponseData = this.meterResponseDataService .dequeue(request.getCorrelationUid()); response.setResult(OsgpResultType.fromValue(meterResponseData.getResultType().getValue())); <START> if (meterResponseData.getMessageData() instanceof String) { <END> response.setDescription((String) meterResponseData.getMessageData()); } } catch (final Exception e) { this.handleException(e); } return response; }</code><technical_language>I throw exception if casting is ok. Else description empty notification is send user. exception is logged. E.g.: <code> try{ response.setDescription((String) meterResponseData.getMessageData()); } catch(final ClassCastException e){ throw new OsgpException(ComponentType.DOMAIN_SMART_METERING, "cast exception " + e.getMessage()); } </code> <code> if (meterResponseData.getMessageData() instanceof String) { // do ... } else { throw new OsgpWsExceptionBlabla("casting " + meterResponseData.getMessageData().getClass() + " String is possible"); } </code> Edit: check for 'instance of' class cast exception happen. method 'handleException' handle exception, change include 'detailMessage' of exception. Else reason technical exception is thrown is given</technical_language>

Target:
public GetConfigurationObjectResponse getGetConfigurationObjectResponse( @RequestPayload final GetConfigurationObjectAsyncRequest request) throws OsgpException { GetConfigurationObjectResponse response = null; try { final MeterResponseData meterResponseData = this.meterResponseDataService.dequeue( request.getCorrelationUid(), com.alliander.osgp.domain.core.valueobjects.smartmetering.GetConfigurationObjectResponse.class); this.throwExceptionIfResultNotOk(meterResponseData, "retrieving the configuration object"); response = this.configurationMapper.map(meterResponseData.getMessageData(), GetConfigurationObjectResponse.class); } catch (final Exception e) { this.handleException(e); } return response; }
Source:
<code>public void testListCustomerImages() { FluentIterable<CustomerImage> customerImages = api.getServerImageApi().listCustomerImages().concat(); assertNotNull(customerImages); for (CustomerImage customerImage : customerImages) { assertNotNull(customerImage); <START> } <END> }</code><technical_language>Instead of asserting null, check if image interested in is in list</technical_language>

Target:
public void testListCustomerImages() { FluentIterable<CustomerImage> customerImages = api.getServerImageApi().listCustomerImages().concat(); assertNotNull(customerImages); assertTrue(customerImages.anyMatch(new Predicate<CustomerImage>() { @Override public boolean apply(CustomerImage input) { return input.id().equals(cloneImageId); } })); }
Source:
<code>public String chooseForm() { String response = super.chooseForm(); try { this.loadFieldIntoDatatableFromBpm(); } catch (ApsSystemException t) { <START> logger.error("Error in chooseForm", t); <END> } return response; }</code><technical_language>this set response = FAILURE? important logical change</technical_language>

Target:
public String chooseForm() { String response = super.chooseForm(); try { this.loadFieldIntoDatatableFromBpm(); } catch (ApsSystemException t) { logger.error("Error in chooseForm", t); return FAILURE; } return response; }
Source:
<code>Builder addClientCapabilities(Collection<String> clientCapabilities) { for (String cap: clientCapabilities) { if (cap.startsWith("agent=")) { <START> setAgent(cap.substring("agent=".length())); END> } else { clientCaps.add(cap); } } return this; }</code><technical_language>optional: clearer assign 'agent = cap.substring(...)' more obvious happening (setAgent overridden class is final, check)</technical_language>

Target:
Builder addClientCapabilities(Collection<String> clientCapabilities) { for (String cap: clientCapabilities) { if (cap.startsWith("agent=")) { agent = cap.substring("agent=".length()); } else { clientCaps.add(cap); } } return this; }
Source:
<code>public StorageDeviceListReturnForXmlRpc getStorageDeviceList() { JsonRpcRequest request = new RequestBuilder("GlusterHost.storageDevicesList").build(); <START> Map<String, Object> response = new FutureMap(this.client, request).withIgnoreResponseKey(); <END> return new StorageDeviceListReturnForXmlRpc(response); }</code><technical_language>expect response key in StorageDeviceListReturnForXmlRpc for 'deviceInfo'. Please vdsm sends properly build dictionary</technical_language>

Target:
public StorageDeviceListReturnForXmlRpc getStorageDeviceList() { JsonRpcRequest request = new RequestBuilder("GlusterHost.storageDevicesList").build(); Map<String, Object> response = new FutureMap(this.client, request).withResponseKey("deviceInfo"); return new StorageDeviceListReturnForXmlRpc(response); }
Source:
<code>public void nodePublishVolume(NodePublishVolumeRequest request, StreamObserver<NodePublishVolumeResponse> responseObserver) { try { Files.createDirectories(Paths.get(request.getTargetPath())); String mountCommand = String.format("goofys --endpoint %s %s %s", s3Endpoint, request.getVolumeId(), request.getTargetPath()); <START> LOG.info("Executing " + mountCommand); <END> executeCommand(mountCommand); responseObserver.onNext(NodePublishVolumeResponse.newBuilder() .build()); responseObserver.onCompleted(); } catch (Exception e) { responseObserver.onError(e); } }</code><technical_language>NIT: LOG.info("Executing {}", mountCommand);</technical_language>

Target:
public void nodePublishVolume(NodePublishVolumeRequest request, StreamObserver<NodePublishVolumeResponse> responseObserver) { try { Files.createDirectories(Paths.get(request.getTargetPath())); String mountCommand = String.format("goofys --endpoint %s %s %s", s3Endpoint, request.getVolumeId(), request.getTargetPath()); LOG.info("Executing {}", mountCommand); executeCommand(mountCommand); responseObserver.onNext(NodePublishVolumeResponse.newBuilder() .build()); responseObserver.onCompleted(); } catch (Exception e) { responseObserver.onError(e); } }
Source:
<code>void beginTransaction() throws ProducerFencedException; void sendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets, String consumerGroupId) throws ProducerFencedException; void sendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets, <START> ConsumerGroupMetadata groupMetadata) throws ProducerFencedException, <END> IllegalGenerationException, UnknownMemberIdException, FencedInstanceIdException; void commitTransaction() throws ProducerFencedException; void abortTransaction() throws ProducerFencedException; Future<RecordMetadata> send(ProducerRecord<K, V> record); Future<RecordMetadata> send(ProducerRecord<K, V> record, Callback callback); void flush(); List<PartitionInfo> partitionsFor(String topic); Map<MetricName, ? extends Metric> metrics(); void close(); @Deprecated default void close(long timeout, TimeUnit unit) { close(Duration.ofMillis(unit.toMillis(timeout))); }</code><technical_language>other exceptions declared while in KafkaProducer ProducerFenced is declared</technical_language>

Target:
void beginTransaction() throws ProducerFencedException; void sendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets, String consumerGroupId) throws ProducerFencedException; void sendOffsetsToTransaction(Map<TopicPartition, OffsetAndMetadata> offsets, ConsumerGroupMetadata groupMetadata) throws ProducerFencedException; void commitTransaction() throws ProducerFencedException; void abortTransaction() throws ProducerFencedException; Future<RecordMetadata> send(ProducerRecord<K, V> record); Future<RecordMetadata> send(ProducerRecord<K, V> record, Callback callback); void flush(); List<PartitionInfo> partitionsFor(String topic); Map<MetricName, ? extends Metric> metrics(); void close(); @Deprecated default void close(long timeout, TimeUnit unit) { close(Duration.ofMillis(unit.toMillis(timeout))); }
Source:
<code>public void start() throws ServerConnectorException { String pollingInterval = getProperties().get(Constants.POLLING_INTERVAL); if (pollingInterval != null) { <START> this.interval = Long.parseLong(pollingInterval); <END> } pollingTaskRunner = new PollingTaskRunner(this); pollingTaskRunner.start(); }</code><technical_language>check for NumberFormatException removed</technical_language>

Target:
public void start() throws ServerConnectorException { String pollingInterval = getProperties().get(Constants.POLLING_INTERVAL); if (pollingInterval != null) { try { this.interval = Long.parseLong(pollingInterval); } catch (NumberFormatException e) { throw new ServerConnectorException("Could not parse parameter: " + Constants.POLLING_INTERVAL + " to numeric type: Long", e); } } pollingTaskRunner = new PollingTaskRunner(this); pollingTaskRunner.start(); }
Source:
<code><START> public AttributeEntryModel(long id, long parentId, String name, long start, long end, int quark) { <END> super(id, parentId, name, start, end, true); fQuark = quark; }</code><technical_language>builders want external code create new entries, content, constructor private protected</technical_language>

Target:
protected AttributeEntryModel(long id, long parentId, String name, long start, long end, int quark) { super(id, parentId, name, start, end, true); fQuark = quark; }