auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldUpdateSalaryWhenAppraisalIsDue() throws Exception { Appraisal appraisal = new Appraisal(); appraisal.setJob(new Job()); appraisal.getJob().setAppointmentType(AppointmentType.CLASSIFIED_IT); DateTime endDate = new DateTime().plusDays(61).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); appraisal.getSalaries().add(new Salary()); Session session = HibernateUtil.getCurrentSession(); Transaction tx = session.beginTransaction(); BackendMgr mgr = getMgrInstance(); session = HibernateUtil.getCurrentSession(); <START> tx = session.beginTransaction(); <END> assert mgr.shouldUpdateSalaryInfo(appraisal) : "Should refresh since appraisal is due in one day"; endDate = new DateTime().plusDays(60).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); assert mgr.shouldUpdateSalaryInfo(appraisal) : "Should refresh since appraisal is due today"; endDate = new DateTime().plusDays(59).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); assert !mgr.shouldUpdateSalaryInfo(appraisal) : "Should not refresh since appraisal is due in past"; endDate = new DateTime().plusDays(60).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); appraisal.getSalaries().clear(); Salary salary = new Salary(); salary.setIncrease(7d); appraisal.getSalaries().add(salary); assert !mgr.shouldUpdateSalaryInfo(appraisal) : "Should not refresh since salary increase is set"; tx.commit(); }</code><technical_language>duplicate calls HibernateUtil.getCurrentSession() session.beginTransaction()</technical_language>

Target:
public void shouldUpdateSalaryWhenAppraisalIsDue() throws Exception { Appraisal appraisal = new Appraisal(); appraisal.setJob(new Job()); appraisal.getJob().setAppointmentType(AppointmentType.CLASSIFIED_IT); DateTime endDate = new DateTime().plusDays(61).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); appraisal.getSalaries().add(new Salary()); BackendMgr mgr = getMgrInstance(); Session session = HibernateUtil.getCurrentSession(); Transaction tx = session.beginTransaction(); assert mgr.shouldUpdateSalaryInfo(appraisal) : "Should refresh since appraisal is due in one day"; endDate = new DateTime().plusDays(60).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); assert mgr.shouldUpdateSalaryInfo(appraisal) : "Should refresh since appraisal is due today"; endDate = new DateTime().plusDays(59).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); assert !mgr.shouldUpdateSalaryInfo(appraisal) : "Should not refresh since appraisal is due in past"; endDate = new DateTime().plusDays(60).withTimeAtStartOfDay(); appraisal.setEndDate(endDate.toDate()); appraisal.getSalaries().clear(); Salary salary = new Salary(); salary.setIncrease(7d); appraisal.getSalaries().add(salary); assert !mgr.shouldUpdateSalaryInfo(appraisal) : "Should not refresh since salary increase is set"; tx.commit(); }
Source:
<code>public void testSetSocketBufferSize() throws Exception { Socket s = new Socket(); int initSendBufferSize = s.getSendBufferSize(); int initReceiveBufferSize = s.getReceiveBufferSize(); SocketUtil.setSocketBufferSize("test", s); Assert.assertEquals(initSendBufferSize, s.getSendBufferSize()); Assert.assertEquals(initReceiveBufferSize, s.getReceiveBufferSize()); int networkBufferSize = 1024 * 1024; SocketUtil.setNetworkBufferSize(networkBufferSize); SocketUtil.setSocketBufferSize("test", s); Assert.assertEquals(networkBufferSize, s.getSendBufferSize()); <START> Assert.assertEquals(networkBufferSize, s.getReceiveBufferSize()); <END> }</code><technical_language>testSetSocketBufferSize failed due Line 43,I guess fail due Line 36(no test)</technical_language>

Target:
public void testSetSocketBufferSize() throws Exception { Socket s = new Socket(); int initSendBufferSize = s.getSendBufferSize(); int initReceiveBufferSize = s.getReceiveBufferSize(); SocketUtil.setSocketBufferSize("test", s); Assert.assertEquals(initSendBufferSize, s.getSendBufferSize()); Assert.assertEquals(initReceiveBufferSize, s.getReceiveBufferSize()); int networkBufferSize = 32 * 1024; SocketUtil.setNetworkBufferSize(networkBufferSize); SocketUtil.setSocketBufferSize("test", s); Assert.assertEquals(networkBufferSize, s.getSendBufferSize()); Assert.assertEquals(networkBufferSize, s.getReceiveBufferSize()); }
Source:
<code>public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { if (_asyncNotSupportedSource != null) throw new IllegalStateException("!asyncSupported: " + _asyncNotSupportedSource); HttpChannelState state = getHttpChannelState(); if (_async == null) _async = new AsyncContextState(state); <START> AsyncContextEvent event = new AsyncContextEvent(_context, _async, state, this, servletRequest, servletResponse, true); <END> event.setDispatchContext(getServletContext()); state.startAsync(event); return _async; }</code><technical_language>I if pass providedUri instead of a boolean</technical_language>

Target:
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { if (_asyncNotSupportedSource != null) throw new IllegalStateException("!asyncSupported: " + _asyncNotSupportedSource); HttpChannelState state = getHttpChannelState(); if (_async == null) _async = new AsyncContextState(state); AsyncContextEvent event = new AsyncContextEvent(_context, _async, state, this, servletRequest, servletResponse, getHttpURI()); event.setDispatchContext(getServletContext()); state.startAsync(event); return _async; }
Source:
<code>public void onDataTypeEditModeToggle(final @Observes DataTypeEditModeToggleEvent event) { if (event.isEditModeEnabled()) { if (getCurrentEditingItem() != null && getItems().contains(getCurrentEditingItem())) { getCurrentEditingItem().disableEditMode(); } setCurrentEditingItem(event.getItem()); <START> } else if (event.getItem() == getCurrentEditingItem()) { <END> setCurrentEditingItem(null); } }</code><technical_language>this more correctly .equals(..) Objects.equals(..)</technical_language>

Target:
public void onDataTypeEditModeToggle(final @Observes DataTypeEditModeToggleEvent event) { if (event.isEditModeEnabled()) { if (getCurrentEditingItem() != null && getItems().contains(getCurrentEditingItem())) { getCurrentEditingItem().disableEditMode(); } setCurrentEditingItem(event.getItem()); } else if (Objects.equals(event.getItem(), getCurrentEditingItem())) { setCurrentEditingItem(null); } }
Source:
<code>public void addCatchUpPointMetricForPartition(PartitionId partitionId) { if (!cloudReplicaCatchUpPoint.containsKey(partitionId)) { cloudReplicaCatchUpPoint.put(partitionId, 0L); Gauge<Long> catchUpPoint = () -> cloudReplicaCatchUpPoint.get(partitionId); registry.register(MetricRegistry.name(ReplicaThread.class, <START> "Partition-" + partitionId.toPathString() + "-catchupPointFromCloud"), catchUpPoint); <END> } }</code><technical_language>minor: I done for other similar metrics, this name format is in methods a helper method generate name java String getCatchupPointFromCloudMetricName(PartitionId partitionId) { return MetricRegistry.name(ReplicaThread.class, "Partition-" + partitionId.toPathString() + "-catchupPointFromCloud"); }</technical_language>

Target:
public void addCatchUpPointMetricForPartition(PartitionId partitionId) { if (!cloudReplicaCatchUpPoint.containsKey(partitionId)) { cloudReplicaCatchUpPoint.put(partitionId, 0L); Gauge<Long> catchUpPoint = () -> cloudReplicaCatchUpPoint.get(partitionId); registry.register(MetricRegistry.name(ReplicaThread.class, String.format(CATCH_POINT_FROM_CLOUD_METRIC_NAME_TEMPLATE, partitionId.toPathString())), catchUpPoint); } }
Source:
<code>public IRunnableWithProgress getRunnable() { return new WorkspaceModifyDelegatingOperation(imonitor -> { final Exception except[] = new Exception[1]; getShell().getDisplay().syncExec(() -> { IRunnableWithProgress op = new WorkspaceModifyDelegatingOperation(monitor -> { final IProgressMonitor fMonitor; if (monitor == null) { fMonitor = new NullProgressMonitor(); } else { fMonitor = monitor; } SubMonitor subMonitor = <START> SubMonitor.convert(fMonitor, <END> 3); subMonitor.subTask(CUIPlugin.getResourceString(OP_DESC)); doRunPrologue(subMonitor.split(1)); subMonitor.setWorkRemaining(2); try { doRun(subMonitor.split(1)); subMonitor.setWorkRemaining(1); } catch (CoreException e) { except[0] = e; } doRunEpilogue(subMonitor.split(1)); subMonitor.setWorkRemaining(0); }); try { getContainer().run(false, true, op); } catch (InvocationTargetException e1) { except[0] = e1; } catch (InterruptedException e2) { except[0] = e2; } }); if (except[0] != null) { if (except[0] instanceof InvocationTargetException) { throw (InvocationTargetException) except[0]; } if (except[0] instanceof InterruptedException) { throw (InterruptedException) except[0]; } throw new InvocationTargetException(except[0]); } }); }</code><technical_language>this convert includes null checks, remove lines 217-223 pass monitor convert</technical_language>

Target:
public IRunnableWithProgress getRunnable() { return new WorkspaceModifyDelegatingOperation(imonitor -> { final Exception except[] = new Exception[1]; getShell().getDisplay().syncExec(() -> { IRunnableWithProgress op = new WorkspaceModifyDelegatingOperation(monitor -> { SubMonitor subMonitor = SubMonitor.convert(monitor, 3); subMonitor.subTask(CUIPlugin.getResourceString(OP_DESC)); doRunPrologue(subMonitor.split(1)); try { doRun(subMonitor.split(1)); } catch (CoreException e) { except[0] = e; } doRunEpilogue(subMonitor.split(1)); }); try { getContainer().run(false, true, op); } catch (InvocationTargetException e1) { except[0] = e1; } catch (InterruptedException e2) { except[0] = e2; } }); if (except[0] != null) { if (except[0] instanceof InvocationTargetException) { throw (InvocationTargetException) except[0]; } if (except[0] instanceof InterruptedException) { throw (InterruptedException) except[0]; } throw new InvocationTargetException(except[0]); } }); }
Source:
<code><START> public boolean equals(Object obj) { <END> if (obj instanceof Application) { Application other = (Application) obj; return Objects.equal(this.getId(), other.getId()) && Objects.equal(this.getSlug(), other.getSlug()) && Objects.equal(this.getTitle(), other.getTitle()) && Objects.equal(this.getDescription(), other.getDescription()) && Objects.equal(this.getCreated(), other.getCreated()) && Objects.equal(this.getCredentials(), other.getCredentials()) && Objects.equal(this.getSources(), other.getSources()); } return false; }</code><technical_language>This do instance equality check, i.e. if (this == obj) { return true }</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Application) { Application other = (Application) obj; return this.getId().equals(other.getId()) && this.getSlug().equals(other.getSlug()) && Objects.equal(this.getTitle(), other.getTitle()) && Objects.equal(this.getDescription(), other.getDescription()) && this.getCreated().equals(other.getCreated()) && this.getCredentials().equals(other.getCredentials()) && this.getSources().equals(other.getSources()); } return false; }
Source:
<code>public static TmfProtocol getProtocol(Protocol protocol) { for (TmfProtocol prot : TmfProtocol.values()) { if (prot.getName().equals(protocol.getName())) { return prot; } } <START> return UNKNOWN; <END> }</code><technical_language>return null</technical_language>

Target:
public static TmfProtocol getProtocol(Protocol protocol) { switch (protocol) { case ETHERNET_II: return TmfProtocol.ETHERNET_II; case IPV4: return TmfProtocol.IPV4; case PCAP: return TmfProtocol.PCAP; case TCP: return TmfProtocol.TCP; case UDP: return TmfProtocol.UDP; case UNKNOWN: default: return TmfProtocol.UNKNOWN; } }
Source:
<code>public ParameterizedCurveVectorFunction(final double[] samplePoints, final ParameterizedCurve curve) { ArgumentChecker.notEmpty(samplePoints, "samplePoints"); ArgumentChecker.notNull(curve, "curve"); _samplePoints = samplePoints; <START> _curve = curve; <END> }</code><technical_language>items copy constructed opposed rewired</technical_language>

Target:
public ParameterizedCurveVectorFunction(final double[] samplePoints, final ParameterizedCurve curve) { ArgumentChecker.notEmpty(samplePoints, "samplePoints"); ArgumentChecker.notNull(curve, "curve"); _samplePoints = Arrays.copyOf(samplePoints, samplePoints.length); _curve = curve; }
Source:
<code>public ByContentSpec unspecified(String mimeType) { unspecifiedHandler = ctx -> { ctx.getResponse().contentType(mimeType); <START> blocks.get(mimeType).execute(); <END> }; return this; }</code><technical_language>if block for content type</technical_language>

Target:
public ByContentSpec unspecified(String mimeType) { unspecifiedHandler = handleWithMimeTypeBlock(mimeType); return this; }
Source:
<code><START> protected Predicate<DetailedS3Object> getOwnerPredicate() throws CommandException { <END> if (Guard.isMapNullOrEmpty(this.filterParams)) { return Predicates.notNull(); } final String owner = metaLookup(OWNER); if (Guard.isStringNullOrEmpty(owner)) { return Predicates.notNull(); } return new Predicate<DetailedS3Object>() { @Override public boolean apply(@Nullable final DetailedS3Object input) { return input.getOwner().equals(owner); } }; }</code><technical_language>this needs protected private</technical_language>

Target:
private Predicate<DetailedS3Object> getOwnerPredicate() throws CommandException { if (Guard.isMapNullOrEmpty(this.filterParams)) { return Predicates.notNull(); } final String owner = paramLookup(OWNER); if (Guard.isStringNullOrEmpty(owner)) { return Predicates.notNull(); } return new Predicate<DetailedS3Object>() { @Override public boolean apply(@Nullable final DetailedS3Object input) { return input.getOwner().equals(owner); } }; }
Source:
<code>public void setContent(CharSequence text) { content.fromHtml(text.toString()); updateFailedMediaList(); overlayFailedMedia(); <START> convertUploadingUponStartToFailed(); <END> }</code><technical_language>call this markAllUploadingMediaAsFailed() EditorFragment clear this do media</technical_language>

Target:
public void setContent(CharSequence text) { content.fromHtml(text.toString()); updateFailedMediaList(); overlayFailedMedia(); markAllUploadingMediaAsFailed(); }
Source:
<code>public List<Closeable> inject(ForkliftMessage msg, final Object instance) { final List<Closeable> closeMe = new ArrayList<>(); injectFields.keySet().stream().forEach(decorator -> { final Map<Class<?>, List<Field>> fields = injectFields.get(decorator); fields.keySet().stream().forEach(clazz -> { fields.get(clazz).forEach(field -> { log.trace("Inject target> Field: ({}) Decorator: ({})", field, decorator); try { String fieldName = Optional.ofNullable(field.getAnnotation(Named.class)) <START> .map(a -> a.value()).orElse(field.getName()); <END> Object value = getInjectableValue(field.getAnnotation(decorator), fieldName, clazz, msg); if (value instanceof ForkliftProducerI) { closeMe.add((ForkliftProducerI)value); } if (value != null) { field.set(instance, value); } } catch (JsonMappingException | JsonParseException e) { log.warn("Unable to parse json for injection.", e); } catch (Exception e) { log.error("Error injecting data into Msg Handler", e); e.printStackTrace(); throw new RuntimeException("Error injecting data into Msg Handler"); } }); }); }); return closeMe; }</code><technical_language>do want orElse orElseGet? orElse is executed orElseGet is</technical_language>

Target:
public List<Closeable> inject(ForkliftMessage msg, final Object instance) { final List<Closeable> closeMe = new ArrayList<>(); injectFields.keySet().stream().forEach(decorator -> { final Map<Class<?>, List<Field>> fields = injectFields.get(decorator); fields.keySet().stream().forEach(clazz -> { fields.get(clazz).forEach(field -> { log.trace("Inject target> Field: ({}) Decorator: ({})", field, decorator); try { String fieldName = Optional.ofNullable(field.getAnnotation(Named.class)) .map(a -> a.value()).orElseGet(() -> field.getName()); Object value = getInjectableValue(field.getAnnotation(decorator), fieldName, clazz, msg); if (value instanceof ForkliftProducerI) { closeMe.add((ForkliftProducerI)value); } if (value != null) { field.set(instance, value); } } catch (JsonMappingException | JsonParseException e) { log.warn("Unable to parse json for injection.", e); } catch (Exception e) { log.error("Error injecting data into Msg Handler", e); e.printStackTrace(); throw new RuntimeException("Error injecting data into Msg Handler"); } }); }); }); return closeMe; }
Source:
<code>public Map<String, String> getShellEnvironment() { MutableMap<String, String> result = MutableMap.copyOf(super.getShellEnvironment()); <START> result.put("ERL_EPMD_PORT", "" + getEntity().getEpmdListenerPort()); <END> return result; }</code><technical_language>Integer.toString(getEntity().getEpmdListenerPort()) automagic coercion String addition</technical_language>

Target:
public Map<String, String> getShellEnvironment() { MutableMap<String, String> result = MutableMap.copyOf(super.getShellEnvironment()); result.put("ERL_EPMD_PORT", "" + Integer.toString(getEntity().getEpmdListenerPort())); return result; }
Source:
<code>public Aggregator factorize(final ColumnSelectorFactory metricFactory) { if (metricColumns == null) { final BaseObjectColumnValueSelector<ArrayOfDoublesSketch> selector = metricFactory .makeColumnValueSelector(fieldName); if (selector instanceof NilColumnValueSelector) { return new ArrayOfDoublesSketchNoOpAggregator(numberOfValues); } return new ArrayOfDoublesSketchMergeAggregator(selector, nominalEntries, numberOfValues); } final DimensionSelector keySelector = metricFactory .makeDimensionSelector(new DefaultDimensionSpec(fieldName, fieldName)); <START> if (keySelector instanceof NullDimensionSelector) { <END> return new ArrayOfDoublesSketchNoOpAggregator(numberOfValues); } final List<BaseDoubleColumnValueSelector> valueSelectors = new ArrayList<>(); for (final String column: metricColumns) { final BaseDoubleColumnValueSelector valueSelector = metricFactory.makeColumnValueSelector(column); valueSelectors.add(valueSelector); } return new ArrayOfDoublesSketchBuildAggregator(keySelector, valueSelectors, nominalEntries); }</code><technical_language>NilColumnValueSelector, NullDimensionSelector is guaranteed for absent columns. SearchQueryRunner.isNilSelector(). Please move this method DimensionSelectorUtils it</technical_language>

Target:
public Aggregator factorize(final ColumnSelectorFactory metricFactory) { if (metricColumns == null) { final BaseObjectColumnValueSelector<ArrayOfDoublesSketch> selector = metricFactory .makeColumnValueSelector(fieldName); if (selector instanceof NilColumnValueSelector) { return new ArrayOfDoublesSketchNoOpAggregator(numberOfValues); } return new ArrayOfDoublesSketchMergeAggregator(selector, nominalEntries, numberOfValues); } final DimensionSelector keySelector = metricFactory .makeDimensionSelector(new DefaultDimensionSpec(fieldName, fieldName)); if (DimensionSelectorUtils.isNilSelector(keySelector)) { return new ArrayOfDoublesSketchNoOpAggregator(numberOfValues); } final List<BaseDoubleColumnValueSelector> valueSelectors = new ArrayList<>(); for (final String column : metricColumns) { final BaseDoubleColumnValueSelector valueSelector = metricFactory.makeColumnValueSelector(column); valueSelectors.add(valueSelector); } return new ArrayOfDoublesSketchBuildAggregator(keySelector, valueSelectors, nominalEntries); }
Source:
<code>protected int resolveInitializationVectorLength(PrivateKeyEncryptionContext encContext) throws GeneralSecurityException { int keyLength = resolveKeyLength(encContext); String cipherMode = encContext.getCipherMode(); String xformMode = "/" + cipherMode.toUpperCase() + "/"; List<CipherInformation> matches = BuiltinCiphers.VALUES.stream() .filter(c -> CIPHER_NAME.equalsIgnoreCase(c.getAlgorithm()) && (keyLength == c.getKeySize()) && c.getTransformation().contains(xformMode)) .collect(Collectors.toList()); int numMatches = GenericUtils.size(matches); if (numMatches <= 0) { throw new NoSuchAlgorithmException("No match found for " + encContext); } <START> if (numMatches > 1) { <END> throw new InvalidKeySpecException("Multiple matches (" + numMatches + ") for " + encContext); } CipherInformation ci = matches.get(0); return ci.getIVSize(); }</code><technical_language>code works, I understand check this. a coding error in BuiltinCiphers. If enum duplicate algorithm/keySize values, a bug in source. kind of test do in a unit test, runtime. match determine IV size</technical_language>

Target:
protected int resolveInitializationVectorLength(PrivateKeyEncryptionContext encContext) throws GeneralSecurityException { int keyLength = resolveKeyLength(encContext); CipherInformation ci = resolveCipherInformation(keyLength, encContext.getCipherMode()); if (ci == null) { throw new NoSuchAlgorithmException("No match found for " + encContext); } return ci.getIVSize(); }
Source:
<code>public Version(String versionInString) { String[] list; if (versionInString.contains("-")) { list = versionInString.split("-", 3); } else { list = versionInString.split(".", 3); <START> } <END> if (list.length > 0) { major = Integer.parseInt(list[0]); } if (list.length > 1) { minor = Integer.parseInt(list[1]); } if (list.length > 2) { patch = list[2]; } }</code><technical_language>java } else if (versionInString.contains(".")) { ... } else { // throw some Exception/log.severe/Assumption.fail/... }</technical_language>

Target:
public Version(String versionInString) { originalRepresentation = versionInString; if (versionInString.contains("rc")) { versionInString = versionInString.replace("rc", ""); isRcVersion = true; } else { isRcVersion = false; } String[] list; if (versionInString.contains("-")) { list = versionInString.split("-", 3); } else { list = versionInString.split("\\.", 3); } if (list.length > 0) { major = list[0]; } if (list.length > 1) { minor = list[1]; } if (list.length > 2) { patch = list[2]; } }
Source:
<code>static void checkImageCaptureEnabled(EffectMode effectMode, Collection<UseCase> activeUseCases) { boolean isImageCaptureExtenderEnabled = false; boolean isMismatched = false; <START> if (activeUseCases == null) { <END> return; } for (UseCase useCase : activeUseCases) { EffectMode imageCaptureExtenderMode = useCase.getUseCaseConfig().retrieveOption( ImageCaptureExtender.OPTION_IMAGE_CAPTURE_EXTENDER_MODE, null); if (effectMode == imageCaptureExtenderMode) { isImageCaptureExtenderEnabled = true; } else if (imageCaptureExtenderMode != null) { isMismatched = true; } } if (isMismatched) { ExtensionsManager.postExtensionsError( ExtensionsErrorCode.MISMATCHED_EXTENSIONS_ENABLED); } else if (!isImageCaptureExtenderEnabled) { ExtensionsManager.postExtensionsError( ExtensionsErrorCode.IMAGE_CAPTURE_EXTENSION_REQUIRED); } }</code><technical_language>activeUseCases == null || activeUseCases.isEmpty() avoid line141 activeUseCases is empty</technical_language>

Target:
static void checkImageCaptureEnabled(EffectMode effectMode, Collection<UseCase> activeUseCases) { boolean isImageCaptureExtenderEnabled = false; boolean isMismatched = false; if (activeUseCases == null || activeUseCases.isEmpty()) { return; } for (UseCase useCase : activeUseCases) { EffectMode imageCaptureExtenderMode = useCase.getUseCaseConfig().retrieveOption( ImageCaptureExtender.OPTION_IMAGE_CAPTURE_EXTENDER_MODE, null); if (effectMode == imageCaptureExtenderMode) { isImageCaptureExtenderEnabled = true; } else if (imageCaptureExtenderMode != null) { isMismatched = true; } } if (isMismatched) { ExtensionsManager.postExtensionsError( ExtensionsErrorCode.MISMATCHED_EXTENSIONS_ENABLED); } else if (!isImageCaptureExtenderEnabled) { ExtensionsManager.postExtensionsError( ExtensionsErrorCode.IMAGE_CAPTURE_EXTENSION_REQUIRED); } }
Source:
<code>public void setPortNumber(int portNumber) { <START> this.portNumbers = new int[] { portNumber }; <END> }</code><technical_language>again, set element in array</technical_language>

Target:
public void setPortNumber(int portNumber) { setPortNumbers(new int[] { portNumber }); }
Source:
<code>public synchronized void write(final PagedMessage message) throws Exception { if (!file.isOpen()) { <START> throw new IllegalStateException("can't write to closed file " + file); <END> } final int messageEncodedSize = message.getEncodeSize(); final int bufferSize = messageEncodedSize + Page.SIZE_RECORD; final ByteBuffer buffer = fileFactory.newBuffer(bufferSize); ChannelBufferWrapper activeMQBuffer = wrapBuffer(bufferSize, buffer); activeMQBuffer.clear(); activeMQBuffer.writeByte(Page.START_BYTE); activeMQBuffer.writeInt(messageEncodedSize); message.encode(activeMQBuffer); activeMQBuffer.writeByte(Page.END_BYTE); assert (activeMQBuffer.readableBytes() == bufferSize) : "messageEncodedSize is different from expected"; assert (buffer.remaining() == bufferSize) : "buffer position or limit are changed"; file.writeDirect(buffer, false); if (pageCache != null) { pageCache.addLiveMessage(message); } numberOfMessages.lazySet(numberOfMessages.get() + 1); size.lazySet(size.get() + bufferSize); storageManager.pageWrite(message, pageId); }</code><technical_language>IllegalSTateException is this context. Do a case this is happening? a case file is open write it. do it</technical_language>

Target:
public synchronized void write(final PagedMessage message) throws Exception { if (!file.isOpen()) { throw ActiveMQMessageBundle.BUNDLE.cannotWriteToClosedFile(file); } final int messageEncodedSize = message.getEncodeSize(); final int bufferSize = messageEncodedSize + Page.SIZE_RECORD; final ByteBuffer buffer = fileFactory.newBuffer(bufferSize); ChannelBufferWrapper activeMQBuffer = wrapBuffer(bufferSize, buffer); activeMQBuffer.clear(); activeMQBuffer.writeByte(Page.START_BYTE); activeMQBuffer.writeInt(messageEncodedSize); message.encode(activeMQBuffer); activeMQBuffer.writeByte(Page.END_BYTE); assert (activeMQBuffer.readableBytes() == bufferSize) : "messageEncodedSize is different from expected"; assert (buffer.remaining() == bufferSize) : "buffer position or limit are changed"; file.writeDirect(buffer, false); if (pageCache != null) { pageCache.addLiveMessage(message); } numberOfMessages.lazySet(numberOfMessages.get() + 1); size.lazySet(size.get() + bufferSize); storageManager.pageWrite(message, pageId); }
Source:
<code>private ResponseEntity<?> createSubscription(final SubscriptionBase subscriptionBase, final NativeWebRequest request) throws InternalNakadiException, DuplicatedSubscriptionException { final List<String> noneExistingEventTypes = checkExistingEventTypes(subscriptionBase); if (!noneExistingEventTypes.isEmpty()) { final String errorMessage = createErrorMessage(noneExistingEventTypes); LOG.debug(errorMessage); return create(UNPROCESSABLE_ENTITY, errorMessage, request); } final Subscription subscription = subscriptionRepository.createSubscription(subscriptionBase); <START> return new ResponseEntity<>(subscription, HttpStatus.CREATED); <END> }</code><technical_language>do this more idiomatic status(HttpStatus.CREATED).body(subscription)</technical_language>

Target:
private ResponseEntity<?> createSubscription(final SubscriptionBase subscriptionBase, final NativeWebRequest request) throws InternalNakadiException, DuplicatedSubscriptionException { final List<String> noneExistingEventTypes = checkExistingEventTypes(subscriptionBase); if (!noneExistingEventTypes.isEmpty()) { final String errorMessage = createErrorMessage(noneExistingEventTypes); LOG.debug(errorMessage); return create(UNPROCESSABLE_ENTITY, errorMessage, request); } final Subscription subscription = subscriptionRepository.createSubscription(subscriptionBase); return status(HttpStatus.CREATED).body(subscription); }
Source:
<code>private void setCurrentProxySettings() { String currentProxyType = BriefcasePreferences.getBriefCaseProxyType(); <START> if (currentProxyType.equals(ProxyConnection.ProxyType.NO_PROXY.toString())){ <END> schemaComboBox.setSelectedIndex(0); } else if (currentProxyType.equals(ProxyConnection.ProxyType.HTTP.toString())) { schemaComboBox.setSelectedIndex(1); } else { schemaComboBox.setSelectedIndex(2); } txtHost.setText(BriefcasePreferences.getBriefCaseProxyHost()); txtHost.setEnabled(false); txtPort.setText(BriefcasePreferences.getBriefCaseProxyPort()); txtPort.setEnabled(false); }</code><technical_language>null check instead for proxy, return immediately setting schemaComboBox</technical_language>

Target:
private void setCurrentProxySettings() { ProxyConnection currentProxy = BriefcasePreferences.getBriefCaseProxyConnection(); if (currentProxy == null){ schemaComboBox.setSelectedIndex(0); return; } if (currentProxy.getProxyType().equals(ProxyConnection.ProxyType.HTTP.toString())) { schemaComboBox.setSelectedIndex(1); } else { schemaComboBox.setSelectedIndex(2); } txtHost.setText(currentProxy.getHost()); txtHost.setEnabled(false); txtPort.setText(currentProxy.getPort().toString()); txtPort.setEnabled(false); }
Source:
<code>private ServiceHandle<S> doRegister(ServiceEndPoint endPoint) { TimerContext context = _registerTimer.time(); checkNotNull(endPoint); ServiceHandle<S> toDelete = null; ServiceHandle<S> toReturn; synchronized (this) { HeavyServiceHandle<S> existingServiceHandle = _instancesPerEndpoint.get(endPoint); if (existingServiceHandle == null || existingServiceHandle.hasBeenFlaggedForEviction() || existingServiceHandle.isOld()) { S service = _serviceFactory.create(endPoint); _serviceCounter.inc(); HeavyServiceHandle<S> newServiceHandle = new HeavyServiceHandle<S>(service, endPoint); Map<ServiceEndPoint, HeavyServiceHandle<S>> sourceCopy = Maps.newHashMap(_instancesPerEndpoint); sourceCopy.put(endPoint, newServiceHandle); _instancesPerEndpoint = sourceCopy; toDelete = existingServiceHandle; toReturn = newServiceHandle; } else { toReturn = existingServiceHandle; } } if (toDelete != null) { destroyService(toDelete); _serviceCounter.dec(); } <START> context.stop(); <END> return toReturn; }</code><technical_language>this in finally block? Previous code in finally</technical_language>

Target:
private ServiceHandle<S> doRegister(ServiceEndPoint endPoint) { checkNotNull(endPoint); TimerContext context = _registerTimer.time(); ServiceHandle<S> toDelete = null; ServiceHandle<S> toReturn; synchronized (this) { HeavyServiceHandle<S> existingServiceHandle = _instancesPerEndpoint.get(endPoint); if (existingServiceHandle == null || existingServiceHandle.hasBeenFlaggedForEviction() || existingServiceHandle.isOld()) { S service = _serviceFactory.create(endPoint); _serviceCounter.inc(); HeavyServiceHandle<S> newServiceHandle = new HeavyServiceHandle<S>(service, endPoint); Map<ServiceEndPoint, HeavyServiceHandle<S>> sourceCopy = Maps.newHashMap(_instancesPerEndpoint); sourceCopy.put(endPoint, newServiceHandle); _instancesPerEndpoint = sourceCopy; toDelete = existingServiceHandle; toReturn = newServiceHandle; } else { toReturn = existingServiceHandle; } } if (toDelete != null) { destroyService(toDelete); _serviceCounter.dec(); } context.stop(); return toReturn; }
Source:
<code>public void onMessage(Message message) { BasicMessageWithExtraData<T> msgWithExtraData = parseMessage(message); if (msgWithExtraData == null) { return; } U responseBasicMessage = onBasicMessage(msgWithExtraData); ConsumerConnectionContext consumerConnectionContext = null; try { Destination replyTo = message.getJMSReplyTo(); if (replyTo != null) { getLog().debugf("RPC client asked to get response sent to [%s]", replyTo); MessageProcessor sender = getMessageSender(); if (sender == null) { msglog.errorNoMessageSenderInListener(); return; } consumerConnectionContext = getConsumerConnectionContext(); if (consumerConnectionContext == null) { msglog.errorNoConnectionContextInListener(); return; } ProducerConnectionContext producerContext = new ProducerConnectionContext(); producerContext.copy(consumerConnectionContext); producerContext.setDestination(replyTo); Session session = producerContext.getSession(); if (session == null) { msglog.errorNoSessionInListener(); } else { MessageProducer sessionProducer = session.createProducer(replyTo); producerContext.setMessageProducer(sessionProducer); sender.send(producerContext, responseBasicMessage); <START> sessionProducer.close(); <END> } } else { getLog().debug("Sender did not tell us where to reply - will not send any response back"); } } catch (Exception e) { msglog.errorFailedToSendResponse(e); return; } }</code><technical_language>this done in finally block here? If send() throws exception, close this</technical_language>

Target:
public void onMessage(Message message) { BasicMessageWithExtraData<T> msgWithExtraData = parseMessage(message); if (msgWithExtraData == null) { return; } U responseBasicMessage = onBasicMessage(msgWithExtraData); ConsumerConnectionContext consumerConnectionContext = null; MessageProducer sessionProducer = null; try { Destination replyTo = message.getJMSReplyTo(); if (replyTo != null) { getLog().debugf("RPC client asked to get response sent to [%s]", replyTo); MessageProcessor sender = getMessageSender(); if (sender == null) { msglog.errorNoMessageSenderInListener(); return; } consumerConnectionContext = getConsumerConnectionContext(); if (consumerConnectionContext == null) { msglog.errorNoConnectionContextInListener(); return; } ProducerConnectionContext producerContext = new ProducerConnectionContext(); producerContext.copy(consumerConnectionContext); producerContext.setDestination(replyTo); Session session = producerContext.getSession(); if (session == null) { msglog.errorNoSessionInListener(); } else { sessionProducer = session.createProducer(replyTo); producerContext.setMessageProducer(sessionProducer); sender.send(producerContext, responseBasicMessage); } } else { getLog().debug("Sender did not tell us where to reply - will not send any response back"); } } catch (Exception e) { msglog.errorFailedToSendResponse(e); return; } finally { try { if (sessionProducer != null) { sessionProducer.close(); } } catch (JMSException e) { msglog.errorFailedToCloseResourcesToRPCClient(e); } } }
Source:
<code><START> public synchronized void setTableDescriptionSupplier(Supplier<Map<SchemaTableName, ElasticsearchTableDescription>> tableDescriptionSupplier) <END> { this.tableDescriptionSupplier = Optional.of(requireNonNull(tableDescriptionSupplier, "tableDescriptionSupplier is null")); }</code><technical_language>pass this in constructor</technical_language>

Target:
public synchronized void setTableDescriptionSupplier(Supplier<Map<SchemaTableName, ElasticsearchTableDescription>> tableDescriptionSupplier) { requireNonNull(tableDescriptionSupplier, "tableDescriptionSupplier is null"); this.tableDescriptionSupplier = Optional.of(tableDescriptionSupplier); }
Source:
<code>private void calculateCompactSize() { int uniqueIds = 0; boolean[] seen = new boolean[dictionary.getPositionCount()]; boolean[] used = new boolean[dictionary.getPositionCount()]; for (int i = 0; i < positionCount; i++) { int position = getId(i); if (!seen[position]) { if (!dictionary.isNull(position)) { <START> used[position] = true; <END> } uniqueIds++; seen[position] = true; } } this.sizeInBytes = dictionary.getPositionsSizeInBytes(used) + (Integer.BYTES * (long) positionCount); this.uniqueIds = uniqueIds; }</code><technical_language>I a similar change is needed in getLogicalSizeInBytes getRegionSizeInBytes</technical_language>

Target:
private void calculateCompactSize() { int uniqueIds = 0; boolean[] used = new boolean[dictionary.getPositionCount()]; for (int i = 0; i < positionCount; i++) { int position = getId(i); if (!used[position]) { uniqueIds++; used[position] = true; } } this.sizeInBytes = dictionary.getPositionsSizeInBytes(used) + (Integer.BYTES * (long) positionCount); this.uniqueIds = uniqueIds; }
Source:
<code>void readsLineFromDefaultMaxCharsFileWithDefaultConfig(@TempDir Path tempDir) throws Exception { Path csvFile = writeClasspathResourceToFile("/default-max-chars.csv", tempDir.resolve("default-max-chars.csv")); CsvFileSource annotation = csvFileSource() .encoding("ISO-8859-1") .resources("/default-max-chars.csv") .files(csvFile.toAbsolutePath().toString()) .build(); Stream<Object[]> arguments = provideArguments(new CsvFileArgumentsProvider(), annotation); <START> assertThat(arguments).hasSize(2 * 1); <END> }</code><technical_language>2? default-max-chars.csv a single line a single set of arguments</technical_language>

Target:
void readsLineFromDefaultMaxCharsFileWithDefaultConfig(@TempDir Path tempDir) throws Exception { Path csvFile = writeClasspathResourceToFile("/default-max-chars.csv", tempDir.resolve("default-max-chars.csv")); CsvFileSource annotation = csvFileSource() .encoding("ISO-8859-1") .resources("/default-max-chars.csv") .files(csvFile.toAbsolutePath().toString()) .build(); Stream<Object[]> arguments = provideArguments(new CsvFileArgumentsProvider(), annotation); assertThat(arguments).hasSize(2); }
Source:
<code>private ObjectWalk setUpWalker( final Collection<? extends ObjectId> interestingObjects, final Collection<? extends ObjectId> uninterestingObjects, final Collection<? extends ObjectId> unshallowObjects, int depth) throws MissingObjectException, IOException, IncorrectObjectTypeException { <START> final ObjectWalk walker; <END> walker = new DepthWalk.ObjectWalk(reader, depth); walker.setRetainBody(false); walker.sort(RevSort.COMMIT_TIME_DESC); if (thin) walker.sort(RevSort.BOUNDARY, true); for (ObjectId id : interestingObjects) { RevObject o = walker.parseAny(id); walker.markStart(o); } if (uninterestingObjects != null) { for (ObjectId id : uninterestingObjects) { final RevObject o; try { o = walker.parseAny(id); } catch (MissingObjectException x) { if (ignoreMissingUninteresting) continue; throw x; } walker.markUninteresting(o); } } if (unshallowObjects != null) { for (ObjectId id : unshallowObjects) { final RevObject o; try { o = walker.parseAny(id); } catch (MissingObjectException x) { if (ignoreMissingUninteresting) continue; throw x; } ((DepthWalk.ObjectWalk)walker).markUnshallow(o); } } return walker; }</code><technical_language>Declare this DepthWalk.ObjectWalk need downcast below</technical_language>

Target:
private ObjectWalk setUpWalker( final Collection<? extends ObjectId> interestingObjects, final Collection<? extends ObjectId> uninterestingObjects, final Collection<? extends ObjectId> unshallowObjects, int depth) throws MissingObjectException, IOException, IncorrectObjectTypeException { final DepthWalk.ObjectWalk walker = new DepthWalk.ObjectWalk(reader, depth); walker.setRetainBody(false); for (ObjectId id : interestingObjects) { RevObject o = walker.parseAny(id); walker.markStart(o); } if (uninterestingObjects != null) { for (ObjectId id : uninterestingObjects) { final RevObject o; try { o = walker.parseAny(id); } catch (MissingObjectException x) { if (ignoreMissingUninteresting) continue; throw x; } walker.markUninteresting(o); } } if (unshallowObjects != null) { for (ObjectId id : unshallowObjects) { final RevObject o = walker.parseAny(id); walker.markUnshallow(o); } } return walker; }
Source:
<code>protected void setActionMessageParameters() { super.setActionMessageParameters(); addValidationMessage(EngineMessage.VAR__ACTION__SYNC); <START> addValidationMessage(EngineMessage.VAR__TYPE__GLUSTER_SERVICE); <END> }</code><technical_language>correct type. service</technical_language>

Target:
protected void setActionMessageParameters() { super.setActionMessageParameters(); addValidationMessage(EngineMessage.VAR__ACTION__SYNC); addValidationMessage(EngineMessage.VAR__TYPE__GLUSTER_VOLUME); }
Source:
<code>public GroupedPropertyList getPropertyList() { if (propertyList == null) { <START> try{ <END> boolean parallel = true; long t1 = System.currentTimeMillis(); propertyList = new GroupedPropertyList(individual, vreq, editing,parallel); log.debug(" getPropertyList parallel: "+parallel+" time :"+(System.currentTimeMillis()-t1)+" ms"); }catch(Exception e) { e.printStackTrace(); } } return propertyList; }</code><technical_language>I remove try/catch wrappers. checked Exceptions thrown. Is a Exception anticipating</technical_language>

Target:
public GroupedPropertyList getPropertyList() throws Exception { propertyList = new GroupedPropertyList(individual, vreq, editing); return propertyList; }
Source:
<code>public boolean rolesHavePermission(final Session userSession, final String absPath, final String[] actions, final Set<String> roles) { final String agent = userSession.getUserID(); final List<URI> actionURIs = actionsAsURIs(actions); <START> final Optional<URI> effectiveACL = getEffectiveAcl(new FedoraResourceImpl(userSession.getNode(absPath))); <END> final AuthorizationHandler authHandler = new AuthorizationHandlerImpl(); final Optional<boolean> userPermission = effectiveACL .map(x -> authHandler.getAuthorizations(x, absPath, agent)) .map(x -> isPermitted(actionURIs, x)); final Optional<boolean> groupPermission = effectiveACL .map(x -> authHandler.getAuthorizations(x, absPath, roles)) .map(x -> isPermitted(actionURIs, x)); final boolean permit = userPermission .orElse(groupPermission.orElse(false)); LOGGER.debug("Request for actions: {}, on path: {}, with roles: {}. Permission={}", actions, absPath, roles, permit); return permit; }</code><technical_language>need "internal-session" userSession permissions read ACL resources</technical_language>

Target:
public boolean rolesHavePermission(final Session userSession, final String absPath, final String[] actions, final Set<String> roles) { final Principal userPrincipal = (Principal) userSession.getAttribute(FEDORA_USER_PRINCIPAL); final String agent = userPrincipal.getName(); try { final Map<String, List<String>> resourceAccessRoles = accessRolesProvider.getRoles(userSession.getNode(absPath), true); final Set<String> effectiveRoles = new HashSet<>(); if (resourceAccessRoles.containsKey(agent)) { LOGGER.debug("Applying WebAC rules for user with modes {}", agent, resourceAccessRoles.get(agent)); effectiveRoles.addAll(resourceAccessRoles.get(agent)); } else { for (final String r : roles) { if (resourceAccessRoles.containsKey(r)) { effectiveRoles.addAll(resourceAccessRoles.get(r)); LOGGER.debug("Applying WebAC rules for group with modes {}", r, resourceAccessRoles.get(r)); } } } final boolean permit = effectiveRoles.containsAll(actionsAsURIs(actions)); LOGGER.debug("Request for actions: {}, on path: {}, with roles: {}. Permission={}", actions, absPath, roles, permit); return permit; } catch (final Exception ex) { return false; } }
Source:
<code>private void checkHeaders(final HttpServletRequest request) throws SanitizationException { final Enumeration<String> headerNames = request.getHeaderNames(); LOG.debug("About to check header malious code"); while (headerNames.hasMoreElements()) { final String name = headerNames.nextElement(); final String value = request.getHeader(name); try { boolean isValid = ESAPI.validator().isValidInput("HTTP header value: " + value, value, "HTTPHeaderValue", 200, true); if (!isValid) { StringBuilder strBuilder = new StringBuilder(); <START> strBuilder.append("Detect malious code -->orignal name/values: "); <END> strBuilder.append(name); strBuilder.append("/"); strBuilder.append(value); LOG.error(strBuilder.toString()); throw new SanitizationException(strBuilder.toString()); } } catch (IntrusionException ex) { throw new SanitizationException(ex); } } LOG.debug("End of checking header malious code"); }</code><technical_language>typo: malicious</technical_language>

Target:
private static void checkHeaders(final HttpServletRequest request) throws SanitizationException { final Enumeration<String> headerNames = request.getHeaderNames(); LOG.debug("About to check header malicious code"); while (headerNames.hasMoreElements()) { final String name = headerNames.nextElement(); final String value = request.getHeader(name); try { boolean isValid = ESAPI.validator().isValidInput("HTTP header value: " + value, value, "HTTPHeaderValue", 200, true); if (!isValid) { StringBuilder strBuilder = new StringBuilder(); strBuilder.append("Detect malicious code -->orignal name/values: "); strBuilder.append(name); strBuilder.append("/"); strBuilder.append(value); LOG.error(strBuilder.toString()); throw new SanitizationException(strBuilder.toString()); } } catch (IntrusionException ex) { throw new SanitizationException(ex); } } LOG.debug("End of checking header malicious code"); }
Source:
<code><START> protected IShowInTargetList <END> getShowInTargetList() { final String[] targetList= createShowInTargetList(); if (targetList != null && targetList.length > 0) { return () -> targetList; } return null; }</code><technical_language>@since 3.13 missing</technical_language>

Target:
private IShowInTargetList getShowInTargetList() { final String[] targetList= createShowInTargetList(); if (targetList != null && targetList.length > 0) { return () -> targetList; } return null; }
Source:
<code><START> private boolean checkForExistingForeignKey(ForeignKey foreignKey, TableInformation tableInformation) { <END> if (foreignKey.getName() == null || tableInformation == null) { return false; } final String referencingColumn = foreignKey.getColumn(0).getName(); final String referencedTable = foreignKey.getReferencedTable().getName(); Predicate<ColumnReferenceMapping> mappingPredicate = m -> { String existingReferencingColumn = m.getReferencingColumnMetadata().getColumnIdentifier().getText(); String existingReferencedTable = m.getReferencedColumnMetadata().getContainingTableInformation().getName().getTableName().getCanonicalName(); return referencingColumn.equals(existingReferencingColumn) && referencedTable.equals(existingReferencedTable); }; Stream<ForeignKeyInformation> keyStream = StreamSupport.stream(tableInformation.getForeignKeys().spliterator(), false); Stream<ColumnReferenceMapping> mappingStream = keyStream.flatMap(key -> StreamSupport.stream(key.getColumnReferenceMappings().spliterator(), false)); boolean found = mappingStream.anyMatch(mappingPredicate); if (found) return true; return tableInformation.getForeignKey(Identifier.toIdentifier(foreignKey.getName())) != null; }</code><technical_language>Please code this method adheres code checkstyles. For example, ( a space ) proceeded space in if-blocks, etc</technical_language>

Target:
private boolean checkForExistingForeignKey(ForeignKey foreignKey, TableInformation tableInformation) { if ( foreignKey.getName() == null || tableInformation == null ) { return false; } final String referencingColumn = foreignKey.getColumn( 0 ).getName(); final String referencedTable = foreignKey.getReferencedTable().getName(); Predicate<ColumnReferenceMapping> mappingPredicate = m -> { String existingReferencingColumn = m.getReferencingColumnMetadata().getColumnIdentifier().getText(); String existingReferencedTable = m.getReferencedColumnMetadata().getContainingTableInformation().getName().getTableName().getCanonicalName(); return referencingColumn.equals( existingReferencingColumn ) && referencedTable.equals( existingReferencedTable ); }; Stream<ForeignKeyInformation> keyStream = StreamSupport.stream( tableInformation.getForeignKeys().spliterator(), false ); Stream<ColumnReferenceMapping> mappingStream = keyStream.flatMap( k -> StreamSupport.stream( k.getColumnReferenceMappings().spliterator(), false ) ); boolean found = mappingStream.anyMatch( mappingPredicate ); if ( found ) { return true; } return tableInformation.getForeignKey( Identifier.toIdentifier( foreignKey.getName() ) ) != null; }