auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testCorrectMergeOperatorSet() throws Exception { prepareRocksDB(); final ColumnFamilyOptions columnFamilyOptions = userMisuseOptimizeForPointLookup ? <START> spy(optimizePointLookupOption(new ColumnFamilyOptions())) : spy(new ColumnFamilyOptions()); <END> RocksDBKeyedStateBackend<Integer> test = null; try { test = RocksDBTestUtils.builderForTestDB( tempFolder.newFolder(), IntSerializer.INSTANCE, db, defaultCFHandle, columnFamilyOptions) .setEnableIncrementalCheckpointing(enableIncrementalCheckpointing) .build(); ValueStateDescriptor<String> stubState1 = new ValueStateDescriptor<>("StubState-1", StringSerializer.INSTANCE); test.createInternalState(StringSerializer.INSTANCE, stubState1); ValueStateDescriptor<String> stubState2 = new ValueStateDescriptor<>("StubState-2", StringSerializer.INSTANCE); test.createInternalState(StringSerializer.INSTANCE, stubState2); verify(columnFamilyOptions, Mockito.times(2)) .setMergeOperatorName(RocksDBKeyedStateBackend.MERGE_OPERATOR_NAME); } finally { if (test != null) { IOUtils.closeQuietly(test); test.dispose(); } columnFamilyOptions.close(); } }</code><technical_language>spy required Mockito.verify. this issue is a blocker mockito tests existing for a while, is here, find some time try remove mockito tests later</technical_language>

Target:
public void testCorrectMergeOperatorSet() throws Exception { prepareRocksDB(); final ColumnFamilyOptions columnFamilyOptions = spy(new ColumnFamilyOptions()); RocksDBKeyedStateBackend<Integer> test = null; try { test = RocksDBTestUtils.builderForTestDB( tempFolder.newFolder(), IntSerializer.INSTANCE, db, defaultCFHandle, columnFamilyOptions) .setEnableIncrementalCheckpointing(enableIncrementalCheckpointing) .build(); ValueStateDescriptor<String> stubState1 = new ValueStateDescriptor<>("StubState-1", StringSerializer.INSTANCE); test.createInternalState(StringSerializer.INSTANCE, stubState1); ValueStateDescriptor<String> stubState2 = new ValueStateDescriptor<>("StubState-2", StringSerializer.INSTANCE); test.createInternalState(StringSerializer.INSTANCE, stubState2); verify(columnFamilyOptions, Mockito.times(2)) .setMergeOperatorName(RocksDBKeyedStateBackend.MERGE_OPERATOR_NAME); } finally { if (test != null) { IOUtils.closeQuietly(test); test.dispose(); } columnFamilyOptions.close(); } }
Source:
<code>public void testSessionFactoryUnique() throws Exception { deployBundle("org.nuxeo.ecm.platform.mail"); pushInlineDeployments("org.nuxeo.ecm.platform.mail.test:OSGI-INF/mailService-session-factory-test-contrib.xml"); MailService mailService = Framework.getService(MailService.class); Session session1 = mailService.getSession("testFactory"); assertNotNull(session1); Session session1a = mailService.getSession("testFactory"); assertNotNull(session1a); <START> assertTrue("Sessions should be equals", session1 == session1a); <END> Session session2 = mailService.getSession("testFactory2"); assertNotNull(session2); assertFalse("Sessions shouldn't be equals", session1 == session2); }</code><technical_language>assertSame instead (same assertNotSame below)</technical_language>

Target:
public void testSessionFactoryUnique() throws Exception { deployBundle("org.nuxeo.ecm.platform.mail"); pushInlineDeployments("org.nuxeo.ecm.platform.mail.test:OSGI-INF/mailService-session-factory-test-contrib.xml"); MailService mailService = Framework.getService(MailService.class); Session session1 = mailService.getSession("testFactory"); assertNotNull(session1); Session session1a = mailService.getSession("testFactory"); assertNotNull(session1a); assertSame("Sessions should be equals", session1, session1a); Session session2 = mailService.getSession("testFactory2"); assertNotNull(session2); assertNotSame("Sessions shouldn't be equals", session1, session2); }
Source:
<code>public Stream<Pair<MethodYield, ProgramState>> statesAfterInvocation(List<SymbolicValue> invocationArguments, List<Type> invocationTypes, ProgramState programState, Supplier<SymbolicValue> svSupplier) { Set<ProgramState> results = new LinkedHashSet<>(); for (int index = 0; index < invocationArguments.size(); index++) { Constraint constraint = getConstraint(index, invocationTypes); if (constraint == null) { continue; } SymbolicValue invokedArg = invocationArguments.get(index); Set<ProgramState> programStates = programStatesForConstraint(results.isEmpty() ? Lists.newArrayList(programState) : results, invokedArg, constraint); if (programStates.isEmpty()) { return Stream.empty(); } results = programStates; } if(results.isEmpty()) { results.add(programState); } SymbolicValue sv; if (resultIndex < 0) { sv = svSupplier.get(); } else { sv = invocationArguments.get(resultIndex); } Stream<ProgramState> stateStream = results.stream().map(s -> s.stackValue(sv)); if (resultConstraint != null) { stateStream = stateStream.map(s -> s.addConstraint(sv, resultConstraint)); } <START> return stateStream.distinct().map(ps -> new Pair<>(this, ps)); <END> }</code><technical_language>This is a complicated hack try stream api odds in EGWalker. I try get rid of Pair class do a proper loop</technical_language>

Target:
public Stream<ProgramState> statesAfterInvocation(List<SymbolicValue> invocationArguments, List<Type> invocationTypes, ProgramState programState, Supplier<SymbolicValue> svSupplier) { Set<ProgramState> results = new LinkedHashSet<>(); for (int index = 0; index < invocationArguments.size(); index++) { Constraint constraint = getConstraint(index, invocationTypes); if (constraint == null) { continue; } SymbolicValue invokedArg = invocationArguments.get(index); Set<ProgramState> programStates = programStatesForConstraint(results.isEmpty() ? Lists.newArrayList(programState) : results, invokedArg, constraint); if (programStates.isEmpty()) { return Stream.empty(); } results = programStates; } if(results.isEmpty()) { results.add(programState); } SymbolicValue sv; if (resultIndex < 0) { sv = svSupplier.get(); } else { sv = invocationArguments.get(resultIndex); } Stream<ProgramState> stateStream = results.stream().map(s -> s.stackValue(sv)); if (resultConstraint != null) { stateStream = stateStream.map(s -> s.addConstraint(sv, resultConstraint)); } return stateStream.distinct(); }
Source:
<code>private final void fireCommandManagerChanged(final CommandManagerEvent event) { if (event == null) { throw new NullPointerException(); } final Object[] listeners = getListeners(); for (Object <START> listener2 : <END> listeners) { final ICommandManagerListener listener = (ICommandManagerListener) listener2; listener.commandManagerChanged(event); } }</code><technical_language>rename</technical_language>

Target:
private final void fireCommandManagerChanged(final CommandManagerEvent event) { if (event == null) { throw new NullPointerException(); } final Object[] listeners = getListeners(); for (Object listener : listeners) { final ICommandManagerListener commandManagerListener = (ICommandManagerListener) listener; commandManagerListener.commandManagerChanged(event); } }
Source:
<code>private void doNamesection(Jar dot, Manifest manifest) { Parameters namesection = parseHeader(getProperties().getProperty(NAMESECTION)); Instructions instructions = new Instructions(namesection); Set<String> resources = new HashSet<>(dot.getResources() .keySet()); dot.getDirectories() .keySet() <START> .stream() <END> .map(d -> d.concat( "/")) .forEach(resources::add); for (Map.Entry<Instruction, Attrs> instr : instructions.entrySet()) { boolean matched = false; for (Iterator<String> i = resources.iterator(); i.hasNext();) { String path = i.next(); if (instr.getKey() .matches(path)) { matched = true; if (!instr.getKey() .isNegated()) { Attributes attrs = manifest.getAttributes(path); if (attrs == null) { attrs = new Attributes(); manifest.getEntries() .put(path, attrs); } for (Map.Entry<String, String> property : instr.getValue() .entrySet()) { setProperty("@", path); try { String processed = getReplacer().process(property.getValue()); attrs.putValue(property.getKey(), processed); } finally { unsetProperty("@"); } } } i.remove(); } } if (!matched && resources.size() > 0) warning("The instruction %s in %s did not match any resources", instr.getKey(), NAMESECTION); } }</code><technical_language>I need filter out empty dirs, no? <LINK_0> is a resource is added creates a directory resource is removed. This is getPackages() filters out empty directories</technical_language>

Target:
private void doNamesection(Jar dot, Manifest manifest) { Parameters namesection = parseHeader(getProperties().getProperty(NAMESECTION)); Instructions instructions = new Instructions(namesection); Set<String> resources = new HashSet<>(dot.getResources() .keySet()); MapStream.of(dot.getDirectories()) .filterValue(mdir -> Objects.nonNull(mdir) && !mdir.isEmpty()) .keys() .map(d -> d.concat( "/")) .forEach(resources::add); for (Map.Entry<Instruction, Attrs> instr : instructions.entrySet()) { boolean matched = false; for (Iterator<String> i = resources.iterator(); i.hasNext();) { String path = i.next(); Instruction instruction = instr.getKey(); if (path.endsWith("/") && !instruction.toString() .endsWith("/")) { } else if (instruction.matches(path)) { matched = true; if (!instr.getKey() .isNegated()) { Attributes attrs = manifest.getAttributes(path); if (attrs == null) { attrs = new Attributes(); manifest.getEntries() .put(path, attrs); } for (Map.Entry<String, String> property : instr.getValue() .entrySet()) { setProperty("@", path); try { String processed = getReplacer().process(property.getValue()); attrs.putValue(property.getKey(), processed); } finally { unsetProperty("@"); } } } i.remove(); } } if (!matched && resources.size() > 0) warning("The instruction %s in %s did not match any resources", instr.getKey(), NAMESECTION); } }
Source:
<code>public CourseEditInstructorPanel(int instructorToShowIndex, int instructorIndex, InstructorAttributes instructor, List<String> sectionNames, List<String> feedbackNames) { if (instructorToShowIndex == -1) { index = instructorIndex; isAccessControlDisplayed = false; } else { index = instructorToShowIndex; isAccessControlDisplayed = true; } this.instructor = instructor; createSectionRows(instructorIndex, sectionNames, feedbackNames); permissionInputGroup1 = createPermissionInputGroup1ForInstructorPanel(); permissionInputGroup2 = createPermissionInputGroup2ForInstructorPanel(); <START> permissionInputGroup3 = createPermissionInputGroup3ForInstructorPanel(); <END> if (instructor != null) { String style = null; if (instructor.privileges.numberOfSectionsSpecial() >= sectionNames.size()) { style = "display: none;"; } String onClick = "showTuneSectionPermissionsDiv(" + index + ", " + instructor.privileges.numberOfSectionsSpecial() + ")"; String content = "Give different permissions for a specific section"; String id = "addSectionLevelForInstructor" + index; addSectionLevelForInstructorButton = createButton(content, "small", id, "javascript:;", style, onClick); } }</code><technical_language>createSectionRows return variable for consistency</technical_language>

Target:
public CourseEditInstructorPanel(int instructorToShowIndex, int instructorIndex, InstructorAttributes instructor, List<String> sectionNames, List<String> feedbackNames) { if (instructorToShowIndex == -1) { index = instructorIndex; isAccessControlDisplayed = false; } else { index = instructorToShowIndex; isAccessControlDisplayed = true; } this.instructor = instructor; sectionRows = createSectionRows(instructorIndex, sectionNames, feedbackNames); permissionInputGroup1 = createPermissionInputGroup1ForInstructorPanel(); permissionInputGroup2 = createPermissionInputGroup2ForInstructorPanel(); permissionInputGroup3 = createPermissionInputGroup3ForInstructorPanel(); if (instructor != null) { String style = null; if (instructor.privileges.numberOfSectionsSpecial() >= sectionNames.size()) { style = "display: none;"; } String onClick = "showTuneSectionPermissionsDiv(" + index + ", " + instructor.privileges.numberOfSectionsSpecial() + ")"; String content = "Give different permissions for a specific section"; String id = "addSectionLevelForInstructor" + index; addSectionLevelForInstructorButton = createButton(content, "small", id, "javascript:;", style, onClick); } }
Source:
<code>private void dropStored() { final int titleId = (adapter.getCheckedCount() > 0) ? R.string.caches_remove_selected : R.string.caches_remove_all; final int count= adapter.getCheckedOrAllCount(); final String message = (adapter.getCheckedCount() > 0) ? <START> res.getQuantityString(R.plurals.caches_remove_selected_confirm, count, count) : res.getQuantityString(R.plurals.caches_remove_all_confirm,count,count); <END> Dialogs.confirmYesNo(this, titleId, message, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int id) { final List<Geocache> selected = adapter.getCheckedOrAllCaches(); final int lastListPosition = getListView().getFirstVisiblePosition(); new DropDetailsTask(lastListPosition).execute(selected.toArray(new Geocache[selected.size()])); dialog.cancel(); } }); }</code><technical_language>I prefer java final String message = getQuantityString(adapter.getCheckedCount() > 0 ? R.plurals.caches_remove_selected_confirm : R.plurals.caches_remove_all_confirm, count, count); minimize repetitions</technical_language>

Target:
private void dropStored() { final int titleId = (adapter.getCheckedCount() > 0) ? R.string.caches_remove_selected : R.string.caches_remove_all; final int count= adapter.getCheckedOrAllCount(); final String message=res.getQuantityString(adapter.getCheckedCount() > 0 ? R.plurals.caches_remove_selected_confirm:R.plurals.caches_remove_all_confirm,count,count); Dialogs.confirmYesNo(this, titleId, message, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int id) { final List<Geocache> selected = adapter.getCheckedOrAllCaches(); final int lastListPosition = getListView().getFirstVisiblePosition(); new DropDetailsTask(lastListPosition).execute(selected.toArray(new Geocache[selected.size()])); dialog.cancel(); } }); }
Source:
<code>private List<Map.Entry<String, String>> validate( final List<Map.Entry<String, String>> pairs) throws UnsupportedEncodingException { final List<Map.Entry<String, String>> ext = new LinkedList<Map.Entry<String, String>>(); ext.add( new AbstractMap.SimpleEntry<String, String>( "cmd", "_notify-validate" ) ); ext.addAll(pairs); try { <START> new JdkRequest(URI.create("<LINK_0>")) <END> .body() .set(this.join(ext)) .back() .fetch() .as(RestResponse.class) .assertBody(Matchers.equalTo("VERIFIED")); } catch (IOException ex) { throw new IllegalStateException(ex); } return pairs; }</code><technical_language>need URI, String work</technical_language>

Target:
private List<Map.Entry<String, String>> validate( final List<Map.Entry<String, String>> pairs) throws UnsupportedEncodingException { final List<Map.Entry<String, String>> ext = new LinkedList<Map.Entry<String, String>>(); ext.add( new AbstractMap.SimpleEntry<String, String>( "cmd", "_notify-validate" ) ); ext.addAll(pairs); try { new JdkRequest("<LINK_0>") .body() .set(this.join(ext)) .back() .fetch() .as(RestResponse.class) .assertBody(Matchers.equalTo("VERIFIED")); } catch (IOException ex) { throw new IllegalStateException(ex); } return pairs; }
Source:
<code>private List<JackrabbitAccessControlList> findAcls(ResourceResolver resourceResolver, String principalName, JackrabbitAccessControlManager accessControlManager) throws RepositoryException { final Set<String> paths = new HashSet<String>(); final List<JackrabbitAccessControlList> acls = new ArrayList<JackrabbitAccessControlList>(); final Map<String, String> params = new HashMap<String, String>(); params.put("type", AccessControlConstants.NT_REP_ACE); params.put("property", AccessControlConstants.REP_PRINCIPAL_NAME); params.put("property.value", principalName); params.put("p.limit", "-1"); final Query query = queryBuilder.createQuery(PredicateGroup.create(params), resourceResolver.adaptTo(Session.class)); <START> final Iterator<Resource> resources = query.getResult().getResources(); <END> while (resources.hasNext()) { Resource contentResource = resources.next().getParent().getParent(); if (!paths.contains(contentResource.getPath())) { for (AccessControlPolicy policy : accessControlManager.getPolicies(contentResource.getPath())) { if (policy instanceof JackrabbitAccessControlList) { acls.add((JackrabbitAccessControlList) policy); break; } } } } return acls; }</code><technical_language>QueryBuilder a RR resource leak - write this as: query.getResult().getPaths().steam().forEach(path -> { Resource resource = resourceResolver.getResource(path); ... }</technical_language>

Target:
private List<JackrabbitAccessControlList> findAcls(ResourceResolver resourceResolver, String principalName, JackrabbitAccessControlManager accessControlManager) throws RepositoryException { final Set<String> paths = new HashSet<String>(); final List<JackrabbitAccessControlList> acls = new ArrayList<JackrabbitAccessControlList>(); final Map<String, String> params = new HashMap<String, String>(); params.put("type", AccessControlConstants.NT_REP_ACE); params.put("property", AccessControlConstants.REP_PRINCIPAL_NAME); params.put("property.value", principalName); params.put("p.limit", "-1"); final Query query = queryBuilder.createQuery(PredicateGroup.create(params), resourceResolver.adaptTo(Session.class)); ResourceResolver leakingResourceResolver = null; for (final Hit hit : query.getResult().getHits()) { try { if (leakingResourceResolver == null) { leakingResourceResolver = hit.getResource().getResourceResolver(); } final Resource aceResource = resourceResolver.getResource(hit.getPath()); final Resource contentResource = aceResource.getParent().getParent(); if (!paths.contains(contentResource.getPath())) { for (AccessControlPolicy policy : accessControlManager.getPolicies(contentResource.getPath())) { if (policy instanceof JackrabbitAccessControlList) { acls.add((JackrabbitAccessControlList) policy); break; } } } } catch (RepositoryException e) { log.error("Failed to get resource for query result.", e); } } if (leakingResourceResolver != null) { leakingResourceResolver.close(); } return acls; }
Source:
<code>public final Flowable<T> toFlowable(BackpressureStrategy strategy) { Flowable<T> o = new FlowableFromObservable<T>(this); switch (strategy) { case DROP: return o.onBackpressureDrop(); case LATEST: return o.onBackpressureLatest(); case NONE: return o; case ERROR: return o.onBackpressureError(); <START> case BUFFER: <END> return o.onBackpressureBuffer(); default: throw new UnsupportedOperationException(); } }</code><technical_language>Please leave default: default case coverage-tested</technical_language>

Target:
public final Flowable<T> toFlowable(BackpressureStrategy strategy) { Flowable<T> o = new FlowableFromObservable<T>(this); switch (strategy) { case DROP: return o.onBackpressureDrop(); case LATEST: return o.onBackpressureLatest(); case NONE: return o; case ERROR: return RxJavaPlugins.onAssembly(new FlowableOnBackpressureError<T>(o)); default: return o.onBackpressureBuffer(); } }
Source:
<code>void setSessionTimeout(int seconds) { if (seconds < 0) { throw new IllegalArgumentException(); } <START> sessionTimeout = seconds; <END> }</code><technical_language>timeout is changed some sessions invalidated removed cache. do this a follow-up, a reminder somewhere</technical_language>

Target:
void setSessionTimeout(int seconds) { sessionTimeout = seconds; }
Source:
<code>protected Compressor<ByteBuf> buildCompressor() { return (Compressor<ByteBuf>) Reflection.buildFromConfig( this, <START> DefaultDriverOption.COMPRESSOR_CLASS, <END> Compressor.class, "com.datastax.oss.driver.internal.core.protocol") .orElse(Compressor.none()); }</code><technical_language>Another case a section (protocol) removed for option, others. this sense compression tied protocol user's perspective</technical_language>

Target:
protected Compressor<ByteBuf> buildCompressor() { DriverConfigProfile defaultProfile = config().getDefaultProfile(); if (defaultProfile.isDefined(DefaultDriverOption.PROTOCOL_COMPRESSION)) { String name = defaultProfile.getString(DefaultDriverOption.PROTOCOL_COMPRESSION); if (name.equalsIgnoreCase("lz4")) { return new Lz4Compressor(this); } else if (name.equalsIgnoreCase("snappy")) { return new SnappyCompressor(this); } else { throw new IllegalArgumentException( String.format( "Unsupported compression algorithm '%s' (from configuration option %s)", name, DefaultDriverOption.PROTOCOL_COMPRESSION.getPath())); } } else { return Compressor.none(); } }
Source:
<code>public FeedbackTextResponseDetails(String answer) { super(FeedbackQuestionType.TEXT); <START> this.answer = answer == null ? null : Sanitizer.sanitizeForRichText(answer); <END> }</code><technical_language>This bit of code repeat multiple times. Abstract a small utility method</technical_language>

Target:
public FeedbackTextResponseDetails(String answer) { super(FeedbackQuestionType.TEXT); this.answer = Sanitizer.sanitizeForRichText(answer); }
Source:
<code>public KubernetesSlave(PodTemplate template, String nodeDescription, KubernetesCloud cloud, String labelStr, RetentionStrategy rs) throws Descriptor.FormException, IOException { <START> this(template, nodeDescription, cloud, labelStr); <END> this.setRetentionStrategy(rs); }</code><technical_language>I do other around, call this(template, nodeDescription, cloud, labelStr, rs); in constructor, call super in</technical_language>

Target:
public KubernetesSlave(PodTemplate template, String nodeDescription, KubernetesCloud cloud, String labelStr, RetentionStrategy rs) throws Descriptor.FormException, IOException { super(getSlaveName(template), nodeDescription, template.getRemoteFs(), 1, Node.Mode.NORMAL, labelStr == null ? null : labelStr, new JNLPLauncher(), rs, template.getNodeProperties()); this.cloud = cloud; }
Source:
<code><START> public void setRelide(int value) { <END> if (value < 0) { throw new IllegalArgumentException("`value' is negative"); } this.relide = value; }</code><technical_language>I wondering if move project scala kotlin data objects verbose</technical_language>

Target:
public void setRelide(int value) { if (value < 0) { throw new IllegalArgumentException("value is negative"); } this.relide = value; }
Source:
<code>void triggerWorkers() { logger.trace( "Trigger works now" ); while ( frontier.hasMore() ) { Map<RemoteRepository, List<RescanableResourceWrapper>> resources = frontier.remove( config.getBatchSize() ); logger.trace( "Start to trigger threads to download {}", resources ); boolean hasResourceDownload = false; for ( Map.Entry<RemoteRepository, List<RescanableResourceWrapper>> resource : resources.entrySet() ) { if ( resource.getValue() != null && !resource.getValue().isEmpty() ) { hasResourceDownload = true; break; } <START> } <END> if ( hasResourceDownload ) { prefetchExecutor.execute( new PrefetchWorker( transfers, frontier, resources, PrefetchManager.this, specialPathManager ) ); } } }</code><technical_language>Do need await existing, running downloads? want end partial downloads</technical_language>

Target:
void triggerWorkers() { logger.trace( "Trigger works now" ); while ( frontier.hasMore() ) { Map<RemoteRepository, List<RescanableResourceWrapper>> resources = frontier.remove( config.getBatchSize() ); logger.trace( "Start to trigger threads to download {}", resources ); prefetchExecutor.execute( new PrefetchWorker( transfers, frontier, resources, PrefetchManager.this, specialPathManager ) ); } }
Source:
<code>public String[] getCodecs() { <START> return this.codecs.toArray(new String[]{}); <END> }</code><technical_language>array length (based codecs.size) optimize. <LINK_0></technical_language>

Target:
public String[] getCodecs() { return this.codecs.toArray(new String[codecs.size()]); }
Source:
<code><START> private boolean isFieldListHost(FormIndex index) { <END> if (!(this.getModel().getForm().getChild(index) instanceof GroupDef)) { return false; } GroupDef gd = (GroupDef)this.getModel().getForm().getChild(index); return ("field-list".equalsIgnoreCase(gd.getAppearanceAttr())); }</code><technical_language>This method is duplicated in FormController FormEntryController, right? implementation in core static android code call that</technical_language>

Target:
public boolean isFieldListHost(FormIndex index) { if (!(this.getModel().getForm().getChild(index) instanceof GroupDef)) { return false; } GroupDef gd = (GroupDef)this.getModel().getForm().getChild(index); return (FIELD_LIST.equalsIgnoreCase(gd.getAppearanceAttr())); }
Source:
<code>public void layout(boolean changed) { <START> super.requestLayout(); <END> hookSashListeners(); }</code><technical_language>Please change layout</technical_language>

Target:
public void layout(boolean changed) { super.layout(changed); hookSashListeners(); }
Source:
<code>public void finishMemoryRevoke() { if (state == State.CONSUMING_INPUT) { index.clear(); operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes()); operatorContext.setRevocableMemoryReservation(0L); state = State.SPILLING_INPUT; return; } if (state == State.LOOKUP_SOURCE_BUILT) { lookupSourceFactory.setPartitionSpilledLookupSource(partitionIndex, spilledLookupSourceHandle); lookupSourceNotNeeded = Optional.empty(); index.clear(); operatorContext.setMemoryReservation(index.getEstimatedSize().toBytes()); operatorContext.setRevocableMemoryReservation(0L); state = State.LOOKUP_SOURCE_SPILLED; return; } long reservedRevocableBytes = operatorContext.getReservedRevocableBytes(); if (reservedRevocableBytes == 0) { return; } <START> throw new IllegalStateException("Cannot finish unknown revoking"); <END> }</code><technical_language>error message in startMemoryRevoking</technical_language>

Target:
public void finishMemoryRevoke() { checkState(finishMemoryRevoke.isPresent(), "Cannot finish unknown revoking"); finishMemoryRevoke.get().run(); finishMemoryRevoke = Optional.empty(); }
Source:
<code>public List<String> resolveVirtualAttributeValueChange(PerunSessionImpl perunSession, String message) throws InternalErrorException, WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeAssignmentException { List<String> resolvingMessages = new ArrayList<>(); if (message == null) return resolvingMessages; <START> System.out.println(getPatternsForMatch().size()); <END> if (messageNeedsResolve(message)) { log.debug("Resolving virtual attribute value change for message: " + message); User user = perunSession.getPerunBl().getModulesUtilsBl().getUserFromMessage(perunSession, message); if (user != null) { Attribute attribute = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, user, getDestinationAttributeName()); @SuppressWarnings("unchecked") List<String> attributeValue = (ArrayList<String>) attribute.getValue(); String messageAttributeSet; if (attributeValue == null || attributeValue.isEmpty()) { AttributeDefinition attributeDefinition = new AttributeDefinition(attribute); messageAttributeSet = attributeDefinition.serializeToString() + " removed for " + user.serializeToString() + "."; } else { messageAttributeSet = attribute.serializeToString() + " set for " + user.serializeToString() + "."; } resolvingMessages.add(messageAttributeSet); } if(!resolvingMessages.isEmpty()) log.debug("These new messages will be generated: " + resolvingMessages); } return resolvingMessages; }</code><technical_language>remove this line. is for debugging</technical_language>

Target:
public List<String> resolveVirtualAttributeValueChange(PerunSessionImpl perunSession, String message) throws InternalErrorException, WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeAssignmentException { List<String> resolvingMessages = new ArrayList<>(); if (message == null) return resolvingMessages; if (messageNeedsResolve(message)) { log.debug("Resolving virtual attribute value change for message: " + message); User user = perunSession.getPerunBl().getModulesUtilsBl().getUserFromMessage(perunSession, message); if (user != null) { Attribute attribute = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, user, getDestinationAttributeName()); @SuppressWarnings("unchecked") List<String> attributeValue = (ArrayList<String>) attribute.getValue(); String messageAttributeSet; if (attributeValue == null || attributeValue.isEmpty()) { AttributeDefinition attributeDefinition = new AttributeDefinition(attribute); messageAttributeSet = attributeDefinition.serializeToString() + " removed for " + user.serializeToString() + "."; } else { messageAttributeSet = attribute.serializeToString() + " set for " + user.serializeToString() + "."; } resolvingMessages.add(messageAttributeSet); } if(!resolvingMessages.isEmpty()) log.debug("These new messages will be generated: " + resolvingMessages); } return resolvingMessages; }
Source:
<code>public void endDocument() throws SAXException { for (PmcIngestAuthor pmcAuthor : currentAuthors) { Author author = Author.newBuilder() <START> .setAffiliationPositions(Lists.newArrayList()) <END> .setFullname(pmcAuthor.getSurname() + ", " + pmcAuthor.getGivenNames()) .setAffiliationPositions(pmcAuthor.getAffiliationPos()) .build(); builder.getAuthors().add(author); } }</code><technical_language>set aff positions later, is needed</technical_language>

Target:
public void endDocument() throws SAXException { for (JatsAuthor pmcAuthor : currentAuthors) { Author author = Author.newBuilder() .setFullname(pmcAuthor.getSurname() + ", " + pmcAuthor.getGivenNames()) .setAffiliationPositions(pmcAuthor.getAffiliationPos()) .build(); builder.getAuthors().add(author); } }
Source:
<code>public InstructorCourseEnrollResultPageData(AccountAttributes account, String courseId, List<StudentAttributes>[] students, boolean hasSection, String enrollStudents) { super(account); this.courseId = courseId; this.students = students; this.hasSection = hasSection; this.enrollStudents = enrollStudents; enrollResultPanelList = new ArrayList<EnrollResultPanel>(); for (int i = 0; i < UpdateStatus.STATUS_COUNT; i++) { String panelClass = ""; if (i == UpdateStatus.ERROR.numericRepresentation) { panelClass = "panel panel-danger"; } else if (i == UpdateStatus.NEW.numericRepresentation) { panelClass = "panel panel-primary"; } else if (i == UpdateStatus.MODIFIED.numericRepresentation) { panelClass = "panel panel-warning"; } else if (i == UpdateStatus.UNMODIFIED.numericRepresentation) { <START> panelClass = "panel panel-info"; <END> } else if (i == UpdateStatus.NOT_IN_ENROLL_LIST.numericRepresentation) { panelClass = "panel panel-default"; } else { panelClass = "panel panel-danger"; } String messageForEnrollmentStatus = getMessageForEnrollmentStatus(i); EnrollResultPanel enrollResultPanel = new EnrollResultPanel(panelClass, messageForEnrollmentStatus, students[i]); enrollResultPanelList.add(enrollResultPanel); } }</code><technical_language>Extracting this another method getMessageForEnrollmentStatus() a switch-case this easier read. Also, considering start "panel ", put frontend instead</technical_language>

Target:
public InstructorCourseEnrollResultPageData(AccountAttributes account, String courseId, List<StudentAttributes>[] students, boolean hasSection, String enrollStudents) { super(account); this.courseId = courseId; this.students = students; this.hasSection = hasSection; this.enrollStudents = enrollStudents; enrollResultPanelList = new ArrayList<EnrollResultPanel>(); for (int i = 0; i < UpdateStatus.STATUS_COUNT; i++) { String panelClass = ""; switch (UpdateStatus.enumRepresentation(i)) { case ERROR : panelClass = "panel-danger"; break; case NEW : panelClass = "panel-primary"; break; case MODIFIED : panelClass = "panel-warning"; break; case UNMODIFIED : panelClass = "panel-info"; break; case NOT_IN_ENROLL_LIST : panelClass = "panel-default"; break; case UNKNOWN : panelClass = "panel-danger"; break; default : log.severe("Unknown Enrollment status " + i); break; } String messageForEnrollmentStatus = getMessageForEnrollmentStatus(i); EnrollResultPanel enrollResultPanel = new EnrollResultPanel(panelClass, messageForEnrollmentStatus, students[i]); enrollResultPanelList.add(enrollResultPanel); } }
Source:
<code>public Page<CollectionRest> findAuthorizedByCommunity( @Parameter(value = "uuid", required = true) UUID communityUuid, Pageable pageable, <START> @Parameter(value = "query") String q) { <END> try { Context context = obtainContext(); Community com = communityService.find(context, communityUuid); if (com == null) { throw new ResourceNotFoundException( CommunityRest.CATEGORY + "." + CommunityRest.NAME + " with id: " + communityUuid + " not found"); } List<Collection> collections = new LinkedList<Collection>(); DiscoverResult resp = discoverAuthorizedCollections(pageable, q, context, com); long tot = resp.getTotalSearchResults(); for (IndexableObject solrCollections : resp.getIndexableObjects()) { Collection c = ((IndexableCollection) solrCollections).getIndexedObject(); collections.add(c); } return converter.toRestPage(collections, pageable, tot , utils.obtainProjection()); } catch (SQLException | SearchServiceException e) { throw new RuntimeException(e.getMessage(), e); } }</code><technical_language>is case for this new "query" parameter ? in rest contract: <LINK_0></technical_language>

Target:
public Page<CollectionRest> findAuthorizedByCommunity( @Parameter(value = "uuid", required = true) UUID communityUuid, Pageable pageable, @Parameter(value = "query") String q) { try { Context context = obtainContext(); Community com = communityService.find(context, communityUuid); if (com == null) { throw new ResourceNotFoundException( CommunityRest.CATEGORY + "." + CommunityRest.NAME + " with id: " + communityUuid + " not found"); } List<Collection> collections = cs.findAuthorizedCollectionsInSOLR(q, context, com, Math.toIntExact(pageable.getOffset()), Math.toIntExact(pageable.getOffset() + pageable.getPageSize())); int tot = cs.countAuthorizedCollectionsInSOLR(q, context, com); return converter.toRestPage(collections, pageable, tot , utils.obtainProjection()); } catch (SQLException | SearchServiceException e) { throw new RuntimeException(e.getMessage(), e); } }
Source:
<code>private synchronized KeyPair getKeyPairFromAndroidKeyStore() throws GeneralSecurityException, IOException { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); try { if (!keyStore.containsAlias(KEY_STORE_CERT_ALIAS)) { Logger.v(TAG, "Key entry is not available"); <START> Calendar start = Calendar.getInstance(); <END> Calendar end = Calendar.getInstance(); end.add(Calendar.YEAR, 100); final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore"); generator.initialize(getKeyPairGeneratorSpec(mContext, start.getTime(), end.getTime())); try { generator.generateKeyPair(); } catch (final IllegalStateException exception) { throw new KeyStoreException(exception); } Logger.v(TAG, "Key entry is generated"); } else { Logger.v(TAG, "Key entry is available"); } } catch (final NullPointerException exception) { throw new KeyStoreException(exception); } Logger.v(TAG, "Reading Key entry"); try { final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry( KEY_STORE_CERT_ALIAS, null); return new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); } catch (RuntimeException e) { throw new KeyStoreException(e); } }</code><technical_language>NullPointerException is a broad dangerous exception catch functions throw due a bug. I call keyStore.containsAlias in try catch, save result in 'if' statement. a try{}catch(NullPointerException) wrapped keystore methods. able exclude date logging functions try catch</technical_language>

Target:
private synchronized KeyPair getKeyPairFromAndroidKeyStore() throws GeneralSecurityException, IOException { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); final boolean isKeyStoreCertAliasExisted; try { isKeyStoreCertAliasExisted = keyStore.containsAlias(KEY_STORE_CERT_ALIAS); } catch (final NullPointerException exception) { throw new KeyStoreException(exception); } if (!isKeyStoreCertAliasExisted) { Logger.v(TAG, "Key entry is not available"); Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); end.add(Calendar.YEAR, 100); final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore"); generator.initialize(getKeyPairGeneratorSpec(mContext, start.getTime(), end.getTime())); try { generator.generateKeyPair(); } catch (final IllegalStateException exception) { throw new KeyStoreException(exception); } Logger.v(TAG, "Key entry is generated"); } else { Logger.v(TAG, "Key entry is available"); } Logger.v(TAG, "Reading Key entry"); try { final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry( KEY_STORE_CERT_ALIAS, null); return new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); } catch (RuntimeException e) { throw new KeyStoreException(e); } }
Source:
<code>public long getReadOperations() { <START> return ioStatisticsStore.counters().get(StreamStatisticNames.STREAM_READ_OPERATIONS); <END> }</code><technical_language>consider static imports for statistic names</technical_language>

Target:
public long getReadOperations() { return ioStatisticsStore.counters().get(STREAM_READ_OPERATIONS); }
Source:
<code>public void dataSourcesAndDurations(JoinQuery query) { builder.setDimension( "dataSourcesAndDurations", <START> DataSourceUtil.getMetricName(query.getDataSources()) <END> ); }</code><technical_language>emit list of values, setDimension(String, String[]). dimension is called "dataSourcesAndDurations", data source names emitted. if this change is done, getMetricName() method name confusing</technical_language>

Target:
public void dataSourcesAndDurations(JoinQuery query) { builder.setDimension( "dataSourcesAndDurations", query.getDataSources().stream() .map( spec -> "{dataSource=" + DataSourceUtil.getMetricName(spec.getDataSource()) + ",duration=" + query.getDuration(spec.getDataSource()) + "}" ) .toArray(String[]::new) ); }
Source:
<code>public void init() { this.owner = new Owner(); this.owner.setId("test-owner-id"); this.translator = new StandardTranslator(mockConsumerTypeCurator, <START> mockEnvironmentCurator, <END> ownerCurator, entitlementCurator); i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK); this.importer = new EntitlementImporter(certSerialCurator, cdnCurator, i18n, mockProductCurator, ec, translator); ConsumerType ctype = TestUtil.createConsumerType(); ctype.setId("test-ctype"); consumer = TestUtil.createConsumer(ctype, owner); consumerDTO = this.translator.translate(consumer, ConsumerDTO.class); consumerDTO.setUrlWeb(""); consumerDTO.setUrlApi(""); when(this.mockConsumerTypeCurator.getConsumerType(eq(consumer))).thenReturn(ctype); when(this.mockConsumerTypeCurator.get(eq(ctype.getId()))).thenReturn(ctype); cert = createEntitlementCertificate("my-test-key", "my-cert"); cert.setId("test-id"); reader = mock(Reader.class); meta = new Meta(); meta.setCdnLabel("test-cdn"); testCdn = new Cdn("test-cdn", "Test CDN", "<LINK_0>"); when(cdnCurator.getByLabel("test-cdn")).thenReturn(testCdn); }</code><technical_language>Missed formatting correction</technical_language>

Target:
public void init() { this.owner = new Owner(); this.owner.setId("test-owner-id"); this.translator = new StandardTranslator(mockConsumerTypeCurator, mockEnvironmentCurator, ownerCurator); i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK); this.importer = new EntitlementImporter(certSerialCurator, cdnCurator, i18n, mockProductCurator, ec, translator); ConsumerType ctype = TestUtil.createConsumerType(); ctype.setId("test-ctype"); consumer = TestUtil.createConsumer(ctype, owner); consumerDTO = this.translator.translate(consumer, ConsumerDTO.class); consumerDTO.setUrlWeb(""); consumerDTO.setUrlApi(""); when(this.mockConsumerTypeCurator.getConsumerType(eq(consumer))).thenReturn(ctype); when(this.mockConsumerTypeCurator.get(eq(ctype.getId()))).thenReturn(ctype); cert = createEntitlementCertificate("my-test-key", "my-cert"); cert.setId("test-id"); reader = mock(Reader.class); meta = new Meta(); meta.setCdnLabel("test-cdn"); testCdn = new Cdn("test-cdn", "Test CDN", "<LINK_0>"); when(cdnCurator.getByLabel("test-cdn")).thenReturn(testCdn); }
Source:
<code>private void createStreamClient() throws IOException { if (streamClient == null) { RestStreamClient.Builder builder = RestStreamClient.builder(host, port); builder.ssl(sslEnabled); if (authToken != null && !authToken.equals("")) { builder.authToken(authToken); } builder.writerPoolSize(writerPoolSize); builder.version(version); try { streamClient = builder.build(); <START> streamClient.create(streamName); <END> } catch (IOException e) { closeClientQuietly(); throw new IOException("Can not create client stream by name: " + streamName, e); } } try { if (writer == null) { writer = streamClient.createWriter(streamName); } } catch (IOException e) { closeWriterQuietly(); throw new IOException("Can not create stream writer by name: " + streamName, e); } }</code><technical_language>Again. Please do create stream here. If a stream exist, flume send it</technical_language>

Target:
private void createStreamClient() throws IOException { if (streamClient == null) { RestStreamClient.Builder builder = RestStreamClient.builder(host, port); builder.ssl(sslEnabled); builder.writerPoolSize(writerPoolSize); builder.version(version); streamClient = builder.build(); try { if (writer == null) { writer = streamClient.createWriter(streamName); } } catch (Throwable t) { closeWriterQuietly(); throw new IOException("Can not create stream writer by name: " + streamName, t); } } }
Source:
<code><START> @Override public Class<${componentNameClass}Properties> getPropertyClass() { <END> return ${componentNameClass}Properties.class; }</code><technical_language>please put Override annotation in separate line (to style consistent)</technical_language>

Target:
public Class<${componentNameClass}Properties> getPropertyClass() { return ${componentNameClass}Properties.class; }
Source:
<code>private UpdateResult updateInternal(final int type, final Bson filter, final Bson update, @Nullable final UpdateOptions options) { AtomicReference<UpdateResult> success = new AtomicReference<>(null); AtomicReference<ObjectServerError> error = new AtomicReference<>(null); OsJNIResultCallback<UpdateResult> callback = new OsJNIResultCallback<UpdateResult>(success, error) { @Override protected UpdateResult mapSuccess(Object result) { BsonArray array = JniBsonProtocol.decode((String) result, BsonArray.class, codecRegistry); long matchedCount = array.get(0).asInt32().getValue(); long modifiedCount = array.get(1).asInt32().getValue(); BsonValue upsertedId = array.get(2); if (upsertedId instanceof BsonNull) { upsertedId = null; } return new UpdateResult(matchedCount, modifiedCount, upsertedId); } }; String jsonFilter = JniBsonProtocol.encode(filter, codecRegistry); String jsonUpdate = JniBsonProtocol.encode(update, codecRegistry); switch (type) { case UPDATE_ONE: case UPDATE_MANY: nativeUpdate(type, nativePtr, jsonFilter, jsonUpdate, false, callback); break; case UPDATE_ONE_WITH_OPTIONS: case UPDATE_MANY_WITH_OPTIONS: <START> if (options == null) { <END> throw new IllegalArgumentException("UpdateOptions must not be null."); } nativeUpdate(type, nativePtr, jsonFilter, jsonUpdate, options.isUpsert(), callback); break; default: throw new IllegalArgumentException("Invalid update type: " + type); } return ResultHandler.handleResult(success, error); }</code><technical_language>Util.checkNull(val, args) for this kind of common checks</technical_language>

Target:
private UpdateResult updateInternal(final int type, final Bson filter, final Bson update, @Nullable final UpdateOptions options) { AtomicReference<UpdateResult> success = new AtomicReference<>(null); AtomicReference<ObjectServerError> error = new AtomicReference<>(null); OsJNIResultCallback<UpdateResult> callback = new OsJNIResultCallback<UpdateResult>(success, error) { @Override protected UpdateResult mapSuccess(Object result) { BsonArray array = JniBsonProtocol.decode((String) result, BsonArray.class, codecRegistry); long matchedCount = array.get(0).asInt32().getValue(); long modifiedCount = array.get(1).asInt32().getValue(); BsonValue upsertedId = array.get(2); if (upsertedId instanceof BsonNull) { upsertedId = null; } return new UpdateResult(matchedCount, modifiedCount, upsertedId); } }; final String jsonFilter = JniBsonProtocol.encode(filter, codecRegistry); final String jsonUpdate = JniBsonProtocol.encode(update, codecRegistry); switch (type) { case UPDATE_ONE: case UPDATE_MANY: nativeUpdate(type, nativePtr, jsonFilter, jsonUpdate, false, callback); break; case UPDATE_ONE_WITH_OPTIONS: case UPDATE_MANY_WITH_OPTIONS: Util.checkNull(options, "options"); nativeUpdate(type, nativePtr, jsonFilter, jsonUpdate, options.isUpsert(), callback); break; default: throw new IllegalArgumentException("Invalid update type: " + type); } return ResultHandler.handleResult(success, error); }
Source:
<code>public static boolean migrateFixtureDbBytes(SQLiteDatabase db, Context c) { CommCareApplication._().setCustomServiceBindTimeout(60 * 5 * 1000); long start = System.currentTimeMillis(); db.beginTransaction(); ConcreteAndroidDbHelper helper = new ConcreteAndroidDbHelper(c, db); Cursor cur = null; DataInputStream fixtureByteStream = null; try { SqlStorage<Persistable> userFixtureStorage = new SqlStorage<Persistable>("fixture", FormInstance.class, helper); cur = db.query("fixture", new String[]{DbUtil.ID_COL}, null, null, null, null, null); <START> Vector<Integer> ids = SqlStorage.fillIdWindow(cur, DbUtil.ID_COL); <END> for (Integer id : ids) { FormInstance fixture = new FormInstance(); fixtureByteStream = new DataInputStream(new ByteArrayInputStream(userFixtureStorage.readBytes(id))); fixture.migrateSerialization(fixtureByteStream, helper.getPrototypeFactory()); userFixtureStorage.update(id, fixture); } db.setTransactionSuccessful(); return true; } catch (Exception e) { db.setTransactionSuccessful(); Logger.log(AndroidLogger.SOFT_ASSERT, "fixture serialization db migration failed"); Logger.exception(e); return false; } finally { if (fixtureByteStream != null) { try { fixtureByteStream.close(); } catch (Exception e) { } } if (cur != null) { cur.close(); } db.endTransaction(); long elapse = System.currentTimeMillis() - start; Log.d(TAG, "Serialized fixture update complete in " + elapse + "ms"); } }</code><technical_language>do this process a storage iterator SqlStorage.iterate(false) give iterator load ID's. prefer do expose direct DB queries</technical_language>

Target:
public static boolean migrateFixtureDbBytes(SQLiteDatabase db, Context c) { CommCareApplication._().setCustomServiceBindTimeout(60 * 5 * 1000); long start = System.currentTimeMillis(); db.beginTransaction(); ConcreteAndroidDbHelper helper = new ConcreteAndroidDbHelper(c, db); DataInputStream fixtureByteStream = null; try { SqlStorage<Persistable> userFixtureStorage = new SqlStorage<Persistable>("fixture", FormInstance.class, helper); for (SqlStorageIterator i = userFixtureStorage.iterate(false); i.hasMore(); ) { int id = i.nextID(); FormInstance fixture = new FormInstance(); fixtureByteStream = new DataInputStream(new ByteArrayInputStream(userFixtureStorage.readBytes(id))); fixture.migrateSerialization(fixtureByteStream, helper.getPrototypeFactory()); userFixtureStorage.update(id, fixture); } db.setTransactionSuccessful(); return true; } catch (Exception e) { db.setTransactionSuccessful(); Logger.log(AndroidLogger.SOFT_ASSERT, "fixture serialization db migration failed"); Logger.exception(e); return true; } finally { if (fixtureByteStream != null) { try { fixtureByteStream.close(); } catch (Exception e) { } } db.endTransaction(); long elapse = System.currentTimeMillis() - start; Log.d(TAG, "Serialized fixture update complete in " + elapse + "ms"); } }