auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean loadSegment(final DataSegment segment) throws SegmentLoadingException { <START> final Segment adapter; <END> try { adapter = segmentLoader.getSegment(segment); } catch (SegmentLoadingException e) { try { segmentLoader.cleanup(segment); } catch (SegmentLoadingException e1) { } throw e; } if (adapter == null) { throw new SegmentLoadingException("Null adapter from loadSpec[%s]", segment.getLoadSpec()); } synchronized (lock) { final String dataSource = segment.getDataSource(); final VersionedIntervalTimeline<String, ReferenceCountingSegment> loadedIntervals = dataSources.computeIfAbsent( dataSource, k -> new VersionedIntervalTimeline<>(Ordering.natural()) ); final PartitionHolder<ReferenceCountingSegment> entry = loadedIntervals.findEntry( segment.getInterval(), segment.getVersion() ); if ((entry != null) && (entry.getChunk(segment.getShardSpec().getPartitionNum()) != null)) { log.warn("Told to load a adapter for a segment[%s] that already exists", segment.getIdentifier()); return false; } loadedIntervals.add( segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(new ReferenceCountingSegment(adapter)) ); synchronized (dataSourceSizes) { dataSourceSizes.add(dataSource, segment.getSize()); } synchronized (dataSourceCounts) { dataSourceCounts.add(dataSource, 1L); } return true; } }</code><technical_language>Please extract adapter acquisition a method</technical_language>

Target:
public boolean loadSegment(final DataSegment segment) throws SegmentLoadingException { final Segment adapter = getAdapter(segment); synchronized (lock) { final String dataSource = segment.getDataSource(); final VersionedIntervalTimeline<String, ReferenceCountingSegment> loadedIntervals = dataSources.computeIfAbsent( dataSource, k -> new VersionedIntervalTimeline<>(Ordering.natural()) ); final PartitionHolder<ReferenceCountingSegment> entry = loadedIntervals.findEntry( segment.getInterval(), segment.getVersion() ); if ((entry != null) && (entry.getChunk(segment.getShardSpec().getPartitionNum()) != null)) { log.warn("Told to load a adapter for a segment[%s] that already exists", segment.getIdentifier()); return false; } loadedIntervals.add( segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(new ReferenceCountingSegment(adapter)) ); synchronized (dataSourceSizes) { dataSourceSizes.add(dataSource, segment.getSize()); } synchronized (dataSourceCounts) { dataSourceCounts.add(dataSource, 1L); } return true; } }
Source:
<code>public IZenSymbol resolve(IEnvironmentGlobal environment, List<Token> tokens) { if (tokens.size() == 1 && tokens.get(0).getValue().equals("*")) { <START> return symbolAny; <END> } if (tokens.size() > 2) { if (tokens.get(0).getValue().equals("material") && tokens.get(1).getValue().equals(":")) { return find(environment, tokens, 2, tokens.size()); } } return null; }</code><technical_language>symbol is for Items, is recommended in other bracket handlers (and *should* bracket handler, phased out in 1.12</technical_language>

Target:
public IZenSymbol resolve(IEnvironmentGlobal environment, List<Token> tokens) { if (tokens.size() > 2) { if (tokens.get(0).getValue().equals("material") && tokens.get(1).getValue().equals(":")) { return find(environment, tokens, 2, tokens.size()); } } return null; }
Source:
<code><START> public IBinding <END> getPromiscuousBinding() { return promiscuousBinding; }</code><technical_language>final</technical_language>

Target:
public final IBinding getPromiscuousBinding() { return promiscuousBinding; }
Source:
<code><START> public void handleGetConfigurationDeviceResponse(final DeviceResponse deviceResponse, <END> final ResponseMessageSender responseMessageSender, final String domain, final String domainVersion, final String messageType, final int retryCount) { ResponseMessageResultType result = ResponseMessageResultType.OK; OsgpException osgpException = null; Configuration configuration = null; try { final GetConfigurationDeviceResponse response = (GetConfigurationDeviceResponse) deviceResponse; this.deviceResponseService.handleDeviceMessageStatus(response.getStatus()); configuration = response.getConfiguration(); } catch (final Exception e) { LOGGER.error("Device Response Exception", e); result = ResponseMessageResultType.NOT_OK; osgpException = new TechnicalException(ComponentType.UNKNOWN, "Unexpected exception while retrieving response message", e); } final ProtocolResponseMessage responseMessage = new ProtocolResponseMessage(domain, domainVersion, messageType, deviceResponse.getCorrelationUid(), deviceResponse.getOrganisationIdentification(), deviceResponse.getDeviceIdentification(), result, osgpException, configuration, retryCount); responseMessageSender.send(responseMessage); }</code><technical_language>Is necessary this method public</technical_language>

Target:
private void handleGetConfigurationDeviceResponse(final DeviceResponse deviceResponse, final ResponseMessageSender responseMessageSender, final String domain, final String domainVersion, final String messageType, final int retryCount) { ResponseMessageResultType result = ResponseMessageResultType.OK; OsgpException osgpException = null; Configuration configuration = null; try { final GetConfigurationDeviceResponse response = (GetConfigurationDeviceResponse) deviceResponse; this.deviceResponseService.handleDeviceMessageStatus(response.getStatus()); configuration = response.getConfiguration(); } catch (final Exception e) { LOGGER.error("Device Response Exception", e); result = ResponseMessageResultType.NOT_OK; osgpException = new TechnicalException(ComponentType.UNKNOWN, "Unexpected exception while retrieving response message", e); } final ProtocolResponseMessage responseMessage = new ProtocolResponseMessage(domain, domainVersion, messageType, deviceResponse.getCorrelationUid(), deviceResponse.getOrganisationIdentification(), deviceResponse.getDeviceIdentification(), result, osgpException, configuration, retryCount); responseMessageSender.send(responseMessage); }
Source:
<code>private KeyPairCredential createKeyPairCredential(String algorithm, int size) throws NoSuchAlgorithmException, NoSuchProviderException { KeyPairGenerator keyPairGenerator; switch (algorithm) { case Pem.RSA_ALGORITHM: { <START> size = (size < 512 | size > 2048) ? 2048 : size; <END> break; } case Pem.DSA_ALGORITHM: { size = (size < 1024 | size > 2048) ? 1024 : size; break; } case Pem.EC_ALGORITHM: { size = (size < 112 | size > 571) ? 571 : size; break; } case Pem.EDDSA_ALGORITHM: { size = 256; break; } default: { algorithm = Pem.RSA_ALGORITHM; size = 2048; break; } } try { keyPairGenerator = (algorithm == Pem.EDDSA_ALGORITHM) ? KeyPairGenerator.getInstance(algorithm, EdDSASecurityProvider.PROVIDER_NAME) : KeyPairGenerator.getInstance(algorithm); } catch(NoSuchAlgorithmException e) { throw ElytronToolMessages.msg.unknownKeyPairAlgorithm(algorithm); } catch(NoSuchProviderException e) { throw ElytronToolMessages.msg.unknownKeyFactoryProvider(EdDSASecurityProvider.PROVIDER_NAME); } keyPairGenerator.initialize(size, new SecureRandom()); KeyPairCredential keyPairCredential = new KeyPairCredential(keyPairGenerator.generateKeyPair()); return keyPairCredential; }</code><technical_language>good add a link bounds update proposal match numbers here</technical_language>

Target:
private KeyPairCredential createKeyPairCredential(String algorithm, int size) throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator; switch (algorithm) { case RSA_ALGORITHM: { size = (512 <= size && size <= 16384) ? size : 2048; break; } case DSA_ALGORITHM: { size = (512 <= size && size <= 1024 && (size % 64) == 0) || size == 2048 || size == 3072 ? size : 2048; break; } case EC_ALGORITHM: { size = (112 <= size && size <= 571) ? size : 256; break; } default: { algorithm = RSA_ALGORITHM; size = 2048; break; } } try { keyPairGenerator = KeyPairGenerator.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw ElytronToolMessages.msg.unknownKeyPairAlgorithm(algorithm); } try { keyPairGenerator.initialize(size, new SecureRandom()); } catch (InvalidParameterException e) { throw ElytronToolMessages.msg.invalidKeySize(e.getMessage()); } KeyPairCredential keyPairCredential = new KeyPairCredential(keyPairGenerator.generateKeyPair()); return keyPairCredential; }
Source:
<code>public NodeMetadata apply(VagrantNode node) { Machine input = node.getMachine(); NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder() .ids(input.getId()) .name(input.getName()) <START> .group(input.getPath().getName()) <END> .location(Iterables.getOnlyElement(locations.get())) .hostname(input.getName()) .status(toPortableNodeStatus.apply(input.getStatus())) .loginPort(22) .privateAddresses(node.getNetworks()) .publicAddresses(ImmutableList.<String>of()) .hostname(node.getHostname()); Credentials credentials = credentialStore.get("node#" + input.getId()); if (credentials != null) { nodeMetadataBuilder.credentials(LoginCredentials.fromCredentials(credentials)); } else if (node.getSshConfig() != null) { SshConfig sshConfig = node.getSshConfig(); nodeMetadataBuilder.credentials(LoginCredentials.builder().user(sshConfig.getUser()).privateKey(sshConfig.getIdentityFile()).build()); } return nodeMetadataBuilder.build(); }</code><technical_language>This parsed name of machine, group parameter is configured in compute service adapter</technical_language>

Target:
public NodeMetadata apply(VagrantNode node) { NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder() .ids(node.id()) .name(node.name()) .group(node.group()) .imageId(node.image().getId()) .location(location) .hardware(getHardware(node)) .operatingSystem(node.image().getOperatingSystem()) .hostname(node.name()) .status(node.machineState()) .loginPort(getLoginPort(node.image())) .privateAddresses(node.networks()) .publicAddresses(ImmutableList.<String> of()) .hostname(node.hostname()); return nodeMetadataBuilder.build(); }
Source:
<code>public PartitionUpdate( String name, boolean isNew, Path writePath, Path targetPath, List<String> fileNames, long rowCount, long inMemoryDataSizeInBytes, long onDiskDataSizeInBytes) { this.name = requireNonNull(name, "name is null"); this.isNew = isNew; this.writePath = requireNonNull(writePath, "writePath is null"); this.targetPath = requireNonNull(targetPath, "targetPath is null"); this.fileNames = ImmutableList.copyOf(requireNonNull(fileNames, "fileNames is null")); checkArgument(rowCount >= 0, "rowCount is expected to be greater or equal than zero: %d", rowCount); this.rowCount = rowCount; checkArgument(inMemoryDataSizeInBytes >= 0, "inMemoryDataSizeInBytes is expected to be greater or equal than zero: %d", inMemoryDataSizeInBytes); this.inMemoryDataSizeInBytes = inMemoryDataSizeInBytes; <START> checkArgument(onDiskDataSizeInBytes >= 0, "onDiskDataSizeInBytes is expected to be greater or equal than zero: %d", onDiskDataSizeInBytes); <END> this.onDiskDataSizeInBytes = onDiskDataSizeInBytes; }</code><technical_language>& > greater equal zero "greater equal zero" (or "non-negative")</technical_language>

Target:
public PartitionUpdate( String name, boolean isNew, Path writePath, Path targetPath, List<String> fileNames, long rowCount, long inMemoryDataSizeInBytes, long onDiskDataSizeInBytes) { this.name = requireNonNull(name, "name is null"); this.isNew = isNew; this.writePath = requireNonNull(writePath, "writePath is null"); this.targetPath = requireNonNull(targetPath, "targetPath is null"); this.fileNames = ImmutableList.copyOf(requireNonNull(fileNames, "fileNames is null")); checkArgument(rowCount >= 0, "rowCount is negative: %d", rowCount); this.rowCount = rowCount; checkArgument(inMemoryDataSizeInBytes >= 0, "inMemoryDataSizeInBytes is negative: %d", inMemoryDataSizeInBytes); this.inMemoryDataSizeInBytes = inMemoryDataSizeInBytes; checkArgument(onDiskDataSizeInBytes >= 0, "onDiskDataSizeInBytes is negative: %d", onDiskDataSizeInBytes); this.onDiskDataSizeInBytes = onDiskDataSizeInBytes; }
Source:
<code>public static void setup() throws IOException { <START> } <END></code><technical_language>If lines this method, simply remove</technical_language>

Target:
public static void setup() throws IOException { SESSION = new ScriptSessionProvider().getInstance(); }
Source:
<code>public void onConnectionFailed(@NonNull ConnectionResult result) { if (mSignInProgress != STATE_IN_PROGRESS) { if (!GoogleApiAvailability.getInstance().isUserResolvableError(result.getErrorCode())) { if (!PrefUtils.shouldShowFatalPlayServiceMessage(this)) { return; } PrefUtils.setFatalPlayServiceMessageShown(this); } mSignInIntent = result.getResolution(); if (mSignInIntent != null) { resolveSignInError(); } else { <START> if (PrefUtils.shouldShowFatalPlayServiceMessage(this)) { <END> Timber.e("Google Play Service did not resolve error"); GoogleApiAvailability.getInstance().showErrorNotification(this, result.getErrorCode()); PrefUtils.setFatalPlayServiceMessageShown(this); } } } }</code><technical_language>this is shown? in line 281, setting shown</technical_language>

Target:
public void onConnectionFailed(@NonNull ConnectionResult result) { if (mSignInProgress != STATE_IN_PROGRESS) { if (isFatalPlayServiceError(result.getErrorCode())) { if (PrefUtils.shouldShowFatalPlayServiceMessage(this)) { showFatalPlayServiceMessage(result); } return; } mSignInIntent = result.getResolution(); if (mSignInIntent != null) { resolveSignInError(); } else { if (PrefUtils.shouldShowFatalPlayServiceMessage(this)) { showFatalPlayServiceMessage(result); } } } }
Source:
<code>public TestFrameworkRegistry(Set<TestRunner> runners) { <START> System.out.println("inititilaized TestFrameworkRegistry " + runners.size() + " fefef " + runners.toString()); <END> runners.forEach(this::register); }</code><technical_language>logger if need log</technical_language>

Target:
public TestFrameworkRegistry(Set<TestRunner> runners) { runners.forEach(this::register); }
Source:
<code>public static boolean fileExistsInSources(IFile original, String fileName) { <START> if (fileName.trim().equals("")) { END> return false; } IContainer container = original.getParent(); IResource resourceToOpen = container.findMember(fileName); IFile file = null; if (resourceToOpen == null) { IResource sourcesFolder = container.getProject().findMember( "SOURCES"); file = container.getFile(new Path(fileName)); if (sourcesFolder != null) { file = ((IFolder) sourcesFolder).getFile(new Path(fileName)); } if (!file.exists()) { return false; } } return true; }</code><technical_language>I isEmpty in cases - clearer noise (non-nls on)</technical_language>

Target:
public static boolean fileExistsInSources(IFile original, String fileName) { if (fileName.trim().isEmpty()) { return false; } IContainer container = original.getParent(); IResource resourceToOpen = container.findMember(fileName); IFile file = null; if (resourceToOpen == null) { IResource sourcesFolder = container.getProject().findMember( "SOURCES"); file = container.getFile(new Path(fileName)); if (sourcesFolder != null) { file = ((IFolder) sourcesFolder).getFile(new Path(fileName)); } if (!file.exists()) { return false; } } return true; }
Source:
<code>private Request startBlockwiseUpload(final Exchange exchange, final Request request) { final KeyUri key = getKey(exchange, request); <START> Block1BlockwiseStatus status = getOutboundBlock1Status(key, exchange, request); <END> final Request block = status.getNextRequestBlock(); block.addMessageObserver(new MessageObserverAdapter() { private void copyToken() { request.setToken(block.getToken()); } @Override public void onAcknowledgement() { copyToken(); } @Override public void onReject() { copyToken(); clearBlock1Status(key); } @Override public void onTimeout() { copyToken(); clearBlock1Status(key); } @Override public void onCancel() { clearBlock1Status(key); } }); return block; }</code><technical_language>This methods start a new blockwise Upload, start a fresh BlockwiseStatus in getOutboundBlock1Status return existing Block1BlockwiseStatus ? I suspect this is case try do 2 blockwise for endpoint/same resource right</technical_language>

Target:
private Request startBlockwiseUpload(final Exchange exchange, final Request request) { final KeyUri key = getKey(exchange, request); synchronized (block1Transfers) { Block1BlockwiseStatus status = getBlock1Status(key); if (status != null) { status.cancelRequest(); clearBlock1Status(key); } status = getOutboundBlock1Status(key, exchange, request); final Request block = status.getNextRequestBlock(); block.addMessageObserver(new MessageObserverAdapter() { private void copyToken() { request.setToken(block.getToken()); } @Override public void onAcknowledgement() { copyToken(); } @Override public void onReject() { copyToken(); clearBlock1Status(key); } @Override public void onTimeout() { copyToken(); clearBlock1Status(key); } @Override public void onCancel() { clearBlock1Status(key); } }); return block; } }
Source:
<code>protected EEFWidgetStyle getWidgetStyle() { EEFWidgetStyle style = this.description.getStyle(); if (style == null) { <START> EEFTextStyle textStyle = EefFactory.eINSTANCE.createEEFTextStyle(); <END> super.setDefaultInheritedLabelStyle(textStyle, composite); setDefaultInheritedStyle(textStyle); style = textStyle; } return style; }</code><technical_language>creating another text style object</technical_language>

Target:
protected EEFWidgetStyle getWidgetStyle() { return this.description.getStyle(); }
Source:
<code>protected void publishIfNeeded(List<TimeAlert> alerts) { TimeAlert triggeredAlert = null; for (TimeAlert alert : alerts) { boolean alertTriggerable = isTrigger(alert); if (isPolicyAttached(alert) && alertTriggerable && null == triggeredAlert) { publish(alert); <START> triggeredAlert = alert; <END> } else if (alertTriggerable && triggeredAlert != null) { historyService.createEntry(ScalingStatus.TRIGGER_FAILED, String.format( "Autoscaling Schedule '%s' overlaps with '%s'.", alert.getName(), triggeredAlert.getName()), alert.getCluster()); } } }</code><technical_language>of history changes part of another patch right? please backport independently of this change</technical_language>

Target:
protected void publishIfNeeded(List<TimeAlert> alerts) { for (TimeAlert alert : alerts) { if (isPolicyAttached(alert) && isTrigger(alert)) { publish(alert); break; } } }
Source:
<code>private void validate(JsonNode contentNode) throws DevfileFormatException { try { List<Problem> validationErrors = new ArrayList<>(); ProblemHandler handler = ProblemHandler.collectingTo(validationErrors); if (!contentNode.hasNonNull("apiVersion")) { throw new DevfileFormatException( "Devfile schema validation failed. Error: The object must have a property whose name is \"apiVersion\"."); } String apiVersion = contentNode.get("apiVersion").asText(); if (!schemasByVersion.containsKey(apiVersion)) { throw new DevfileFormatException( <START> String.format("version '%s' of the devfile is not supported", apiVersion)); <END> } JsonSchema schema = schemasByVersion.get(apiVersion); try (JsonReader reader = service.createReader( new StringReader(jsonMapper.writeValueAsString(contentNode)), schema, handler)) { reader.read(); } if (!validationErrors.isEmpty()) { String error = errorMessageComposer.extractMessages(validationErrors, new StringBuilder()); throw new DevfileFormatException( format("Devfile schema validation failed. Error: %s", error)); } } catch (IOException e) { throw new DevfileFormatException("Unable to validate Devfile. Error: " + e.getMessage()); } }</code><technical_language>sense print supported versions here</technical_language>

Target:
private void validate(JsonNode contentNode) throws DevfileFormatException { try { List<Problem> validationErrors = new ArrayList<>(); ProblemHandler handler = ProblemHandler.collectingTo(validationErrors); if (!contentNode.hasNonNull("apiVersion")) { throw new DevfileFormatException( "Devfile schema validation failed. Error: The object must have a property whose name is \"apiVersion\"."); } String apiVersion = contentNode.get("apiVersion").asText(); if (!schemasByVersion.containsKey(apiVersion)) { throw new DevfileFormatException( String.format( "Version '%s' of the devfile is not supported. Supported versions are '%s'.", apiVersion, SUPPORTED_VERSIONS)); } JsonSchema schema = schemasByVersion.get(apiVersion); try (JsonReader reader = service.createReader( new StringReader(jsonMapper.writeValueAsString(contentNode)), schema, handler)) { reader.read(); } if (!validationErrors.isEmpty()) { String error = errorMessageComposer.extractMessages(validationErrors, new StringBuilder()); throw new DevfileFormatException( format("Devfile schema validation failed. Error: %s", error)); } } catch (IOException e) { throw new DevfileFormatException("Unable to validate Devfile. Error: " + e.getMessage()); } }
Source:
<code>public SAMSequenceRecord(final String name, final int sequenceLength) { if (name != null) { <START> if (!LEGAL_RNAME_PATTERN.matcher(name).useAnchoringBounds(true).matches()) { <END> throw new SAMException(String.format("Sequence name '%s' doesn't match regex: '%s' ", name, LEGAL_RNAME_PATTERN)); } validateSequenceName(name); mSequenceName = name.intern(); } else { mSequenceName = null; } mSequenceLength = sequenceLength; }</code><technical_language>move this validate method</technical_language>

Target:
public SAMSequenceRecord(final String name, final int sequenceLength) { if (name != null) { validateSequenceName(name); mSequenceName = name.intern(); } else { mSequenceName = null; } mSequenceLength = sequenceLength; }
Source:
<code>private void importFromFileSystem(List<Process> processes) { if (isActionParameterInvalid("sourcefolder")) { return; } URI sourceFolder = new File(this.parameters.get("sourcefolder")).toURI(); try { if (!fileService.isDirectory(sourceFolder)) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "Directory " + this.parameters.get("sourcefolder") + " does not exisist"); return; } for (Process process : processes) { Integer processId = process.getId(); String processTitle = process.getTitle(); URI imagesFolder = serviceManager.getProcessService().getImagesOrigDirectory(false, process); if (fileService.getSubUris(imagesFolder).size() > 0) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "", "The process " + processTitle + " [" + processId + "] has already data in image folder"); } else { URI sourceFolderProcess = fileService.createResource(sourceFolder, processTitle); if (!fileService.isDirectory(sourceFolder)) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "", "The directory for process " + processTitle + " [" + processId + "] is not existing"); } else { fileService.copyDirectory(sourceFolderProcess, imagesFolder); Helper.setMeldung(KITODO_SCRIPT_FIELD, "", "The directory for process " + processTitle + " [" + processId + "] is copied"); } Helper.setMeldung(KITODO_SCRIPT_FIELD, "", "The process " + processTitle + " [" + processId + "] is copied"); } } } catch (IOException e) { Helper.setFehlerMeldung(e); <START> logger.error(e.getMessage(), e); <END> } }</code><technical_language>setErrorMessage</technical_language>

Target:
private void importFromFileSystem(List<Process> processes) { if (isActionParameterInvalid("sourcefolder")) { return; } URI sourceFolder = new File(this.parameters.get("sourcefolder")).toURI(); try { if (!fileService.isDirectory(sourceFolder)) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "Directory " + this.parameters.get("sourcefolder") + " does not exisist"); return; } for (Process process : processes) { Integer processId = process.getId(); String processTitle = process.getTitle(); URI imagesFolder = serviceManager.getProcessService().getImagesOrigDirectory(false, process); if (fileService.getSubUris(imagesFolder).size() > 0) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "", "The process " + processTitle + " [" + processId + "] has already data in image folder"); } else { URI sourceFolderProcess = fileService.createResource(sourceFolder, processTitle); if (!fileService.isDirectory(sourceFolder)) { Helper.setFehlerMeldung(KITODO_SCRIPT_FIELD, "", "The directory for process " + processTitle + " [" + processId + "] is not existing"); } else { fileService.copyDirectory(sourceFolderProcess, imagesFolder); Helper.setMeldung(KITODO_SCRIPT_FIELD, "", "The directory for process " + processTitle + " [" + processId + "] is copied"); } Helper.setMeldung(KITODO_SCRIPT_FIELD, "", "The process " + processTitle + " [" + processId + "] is copied"); } } } catch (IOException e) { Helper.setErrorMessage(e.toString(), logger, e); } }
Source:
<code>public Class<?> getPicklistClass(){ String version = getApiVersion(); <START> String pattern = "20\\d{2}.\\d+"; <END> if(version != null && Pattern.matches(pattern, version)){ Class<?> valueClass; try { valueClass = Class.forName("com.netsuite.webservices.v"+version.replace('.', '_')+".platform.core.ListOrRecordRef"); } catch (ClassNotFoundException e) { return null; } return valueClass; } return null; }</code><technical_language>is char in regex, please escape</technical_language>

Target:
public Class<?> getPicklistClass(){ String version = getApiVersion(); String pattern = "20\\d{2}\\.\\d+"; if(version != null && Pattern.matches(pattern, version)){ Class<?> valueClass; try { valueClass = Class.forName("com.netsuite.webservices.v"+version.replace('.', '_')+".platform.core.ListOrRecordRef"); } catch (ClassNotFoundException e) { return null; } return valueClass; } return null; }
Source:
<code>private RpslObject getAbuseContactRoleInternal(final RpslObject object) { <START> RpslObject abuseContact; <END> try { abuseContact = getAbuseC(object); if (abuseContact == null) { if (object.containsAttribute(AttributeType.ORG)) { final RpslObject organisation = objectDao.getByKey(ObjectType.ORGANISATION, object.getValueForAttribute(AttributeType.ORG)); abuseContact = getAbuseC(organisation); } } } catch (EmptyResultDataAccessException ignored) { LOGGER.debug("Ignored invalid reference (object {})", object.getKey()); abuseContact = null; } return abuseContact; }</code><technical_language>this code simplified? hard follow</technical_language>

Target:
private RpslObject getAbuseContactRoleInternal(final RpslObject object) { try { RpslObject abuseContact = getAbuseC(object); if (abuseContact != null) { return abuseContact; } return getOrgAbuseC(object); } catch (EmptyResultDataAccessException ignored) { LOGGER.debug("Ignored invalid reference (object {})", object.getKey()); } return null; }
Source:
<code>static void submitTasksAndWaitForResults(ExecutorService executor, Callable[] tasks) throws Exception { final List<Future> results = Lists.newArrayListWithCapacity(tasks.length); for (Callable task : tasks) { results.add(executor.submit(task)); } for (Future result : results) { result.get(); } <START> executor.shutdown(); <END> executor.awaitTermination(10, TimeUnit.SECONDS); }</code><technical_language>This util is widely in tests caller shutdown in finally region. is shutdown in this common place avoid this executor some other usages afterwards. verify results in finally region executor shutdown in this specific unit test</technical_language>

Target:
static void submitTasksAndWaitForResults(ExecutorService executor, Callable[] tasks) throws Exception { final List<Future> results = Lists.newArrayListWithCapacity(tasks.length); for (Callable task : tasks) { results.add(executor.submit(task)); } for (Future result : results) { result.get(); } }
Source:
<code>protected void updateWorkingDirFromConfig(ILaunchConfiguration config) { if (workingDirText != null) { String workingDir = EMPTY_STRING; try { workingDir = config.getAttribute(ATTR_REMOTE_WORKING_DIRECTORY_NAME, EMPTY_STRING); } catch (CoreException ce) { ProfileLaunchPlugin.log(ce); } if (workingDir.equals(EMPTY_STRING)){ if(this.fProjText != null){ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject(this.fProjText.getText()); if(project != null){ IRemoteFileProxy remoteFileProxy = null; try { remoteFileProxy = RemoteProxyManager.getInstance().getFileProxy(project); } catch (CoreException e) { <START> e.printStackTrace(); <END> } URI workingDirURI = remoteFileProxy.getWorkingDir(); workingDir = workingDirURI.toString(); } } } workingDirText.setText(workingDir); } }</code><technical_language>failure error message set do this file</technical_language>

Target:
protected void updateWorkingDirFromConfig(ILaunchConfiguration config) { if (workingDirText != null) { String projectDir = EMPTY_STRING; try { projectDir = config.getAttribute(ATTR_REMOTE_WORKING_DIRECTORY_NAME, EMPTY_STRING); } catch (CoreException ce) { ProfileLaunchPlugin.log(ce); } if (projectDir.equals(EMPTY_STRING)){ if(this.fProjText != null){ IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject(this.fProjText.getText()); try { projectDir = RemoteProxyManager.getInstance().getRemoteProjectLocation(project); } catch (CoreException e) { setErrorMessage(fPreviouslyCheckedWorkingDirErrorMsg = ProxyLaunchMessages.error_accessing_working_directory); } } } workingDirText.setText(projectDir); } }
Source:
<code><START> private static Symbol isSwitchAssigningVariable(SwitchStatementTree switchStatementTree) { <END> Symbol switchAssigningVariable = null; for (CaseGroupTree caseGroupTree : switchStatementTree.cases()) { if (hasSingleStatement(caseGroupTree.body(), THROW_STATEMENT)) { continue; } Symbol variable = assigningVariable(caseGroupTree.body()); if (variable == null) { return null; } if (switchAssigningVariable == null) { switchAssigningVariable = variable; } else if (switchAssigningVariable != variable) { return null; } } return switchAssigningVariable; }</code><technical_language>Missing @CheckForNull annotation. convinced null check everywhere. Optional instead</technical_language>

Target:
private static Symbol isSwitchAssigningVariable(SwitchStatementTree switchStatementTree) { Set<Symbol> assignedVariables = switchStatementTree.cases().stream() .filter(caseGroup -> !hasSingleStatement(caseGroup.body(), THROW_STATEMENT)) .map(UseSwitchExpressionCheck::assigningVariable) .collect(Collectors.toSet()); return assignedVariables.size() == 1 ? assignedVariables.iterator().next() : null; }
Source:
<code>private static void enableJunit5ForTestTask(Test task) { if (!useJUnitPlatformEnabled(task)) { task.useJUnitPlatform(); } task.systemProperty("junit.platform.output.capture.stdout", "true"); task.systemProperty("junit.platform.output.capture.stderr", "true"); task.systemProperty("junit.jupiter.execution.parallel.enabled", "true"); task.systemProperty("junit.jupiter.execution.parallel.config.strategy", "dynamic"); task.getTestLogging().getEvents().add(TestLogEvent.FAILED); if ("true".equals(System.getenv("CI"))) { <START> task.getTestLogging() <END> .getEvents() .addAll(ImmutableSet.of(TestLogEvent.STARTED, TestLogEvent.PASSED, TestLogEvent.SKIPPED)); } }</code><technical_language>@CRogers try apply this ./gradlew test tasks unit-tests?</technical_language>

Target:
private static void enableJunit5ForTestTask(Test task) { if (!useJUnitPlatformEnabled(task)) { task.useJUnitPlatform(); } task.systemProperty("junit.platform.output.capture.stdout", "true"); task.systemProperty("junit.platform.output.capture.stderr", "true"); task.systemProperty("junit.jupiter.execution.parallel.enabled", "true"); task.systemProperty("junit.jupiter.execution.parallel.config.strategy", "dynamic"); task.getTestLogging().getEvents().add(TestLogEvent.FAILED); if (!task.getName().equals("test") && "true".equals(System.getenv("CI"))) { task.getTestLogging() .getEvents() .addAll(ImmutableSet.of(TestLogEvent.STARTED, TestLogEvent.PASSED, TestLogEvent.SKIPPED)); } }
Source:
<code>public void calculate_changelog() throws IOException, InterruptedException, SftpException, JSchException { final URL changesUrl; final String TEST_COMMIT_MESSAGE = "Second commit"; Build b; GitRepo repo = buildGitRepo(); repo.branch("testBranch"); <START> repo.commit(TEST_COMMIT_MESSAGE); <END> repo.transferToDockerContainer(host, port); job.useScm(GitScm.class) .url(repoUrl) .credentials(USERNAME) .calculateChangelog("origin", "testBranch"); job.save(); b = job.startBuild(); b.shouldSucceed(); changesUrl = b.url("changes"); assertThat( b.getConsole(), Matchers.containsRegexp("Using 'Changelog to branch' strategy.", Pattern.MULTILINE) ); assertThat( visit(changesUrl).getPageSource(), Matchers.containsRegexp(TEST_COMMIT_MESSAGE, Pattern.MULTILINE) ); }</code><technical_language>Test fails is commit. branch in line 220 is committed</technical_language>

Target:
public void calculate_changelog() { final URL changesUrl; final String TEST_COMMIT_MESSAGE = "Second commit"; Build b; GitRepo repo = buildGitRepo(); repo.createBranch("testBranch"); repo.changeAndCommitFoo(TEST_COMMIT_MESSAGE); repo.transferToDockerContainer(host, port); job.useScm(GitScm.class) .url(repoUrl) .credentials(USERNAME) .calculateChangelog("origin", "testBranch"); job.save(); b = job.startBuild(); b.shouldSucceed(); changesUrl = b.url("changes"); assertThat( b.getConsole(), Matchers.containsRegexp("Using 'Changelog to branch' strategy.", Pattern.MULTILINE) ); assertThat( visit(changesUrl).getPageSource(), Matchers.containsRegexp(TEST_COMMIT_MESSAGE, Pattern.MULTILINE) ); }
Source:
<code>public CinderlibReturnValue runCommand(CinderlibCommand command, CinderlibCommandParameters params) throws Exception { <START> File dir = Paths.get(config.getUsrDir().getAbsolutePath() + CINDERLIB_DIR).toFile(); <END> ProcessBuilder cinderlibProcessBuilder = new ProcessBuilder() .directory(dir) .command(generateCommand(command, params)) .redirectErrorStream(true); Process process = cinderlibProcessBuilder.start(); String output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8); log.info("cinderlib output: {}", output); if (!process.waitFor(2, TimeUnit.MINUTES)) { throw new Exception("cinderlib call timed out"); } CinderlibReturnValue returnValue = new CinderlibReturnValue(process.exitValue(), output); return returnValue; }</code><technical_language>This created time init phase</technical_language>

Target:
public CinderlibReturnValue runCommand(CinderlibCommand command, CinderlibCommandParameters params) throws Exception { ProcessBuilder cinderlibProcessBuilder = new ProcessBuilder() .directory(cinderlibDir) .command(generateCommand(command, params)) .redirectErrorStream(true); Process process = cinderlibProcessBuilder.start(); String output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8); log.info("cinderlib output: {}", output); if (!process.waitFor(2, TimeUnit.MINUTES)) { throw new Exception("cinderlib call timed out"); } CinderlibReturnValue returnValue = new CinderlibReturnValue(process.exitValue(), output); return returnValue; }
Source:
<code>public void triggerElection() throws IOException { if ( !refuseToBecomeLeader ) { handle( new RaftMessages.Timeout.Election( myself ) ); } else { log.info( <START> format( "Election timeout occured triggered, but {%s} is configured to not tirgger an election. " + <END> "See setting: %s", myself, CausalClusteringSettings.refuse_to_be_leader.name() ) ); } }</code><technical_language>occured triggered</technical_language>

Target:
public void triggerElection() throws IOException { if ( !refuseToBecomeLeader ) { handle( new RaftMessages.Timeout.Election( myself ) ); } else { log.info( format( "Election timeout occured, but {%s} is configured to not tirgger an election. " + "See setting: %s", myself, CausalClusteringSettings.refuse_to_be_leader.name() ) ); } }
Source:
<code>public IId<?> fromExternalFormLenient(String externalForm) { if (externalForm == null) { return null; } String[] tmp = externalForm.split(":", 2); if (tmp.length != 2) { return null; } String typeName = tmp[0]; Class<? extends IId<?>> idClass = m_nameToClassMap.get(typeName); if (idClass == null) { return null; } <START> return BEANS.get(IdFactory.class).createFromString(idClass, tmp[1]); <END> }</code><technical_language>lazy</technical_language>

Target:
public IId<?> fromExternalFormLenient(String externalForm) { if (externalForm == null) { return null; } String[] tmp = externalForm.split(":", 2); if (tmp.length != 2) { return null; } String typeName = tmp[0]; Class<? extends IId<?>> idClass = m_nameToClassMap.get(typeName); if (idClass == null) { return null; } return m_idFactory.get().createFromString(idClass, tmp[1]); }
Source:
<code>public ApplicationListener<?> xdInitializer(ApplicationContext context) { XdConfigLoggingInitializer delegate = new XdConfigLoggingInitializer(true); delegate.setEnvironment(context.getEnvironment()); <START> if (zooKeeperConnection != null) { <END> delegate.setZkConnectString(zooKeeperConnection.getClient().getZookeeperClient().getCurrentConnectionString()); } return new SourceFilteringListener(context, delegate); }</code><technical_language>fault of this PR, feels weird in Environment **except** zk connection string</technical_language>

Target:
public ApplicationListener<?> xdInitializer(ApplicationContext context) { XdConfigLoggingInitializer delegate = new XdConfigLoggingInitializer(true); delegate.setEnvironment(context.getEnvironment()); return new SourceFilteringListener(context, delegate); }
Source:
<code>public E map(ResultSet rs, int columnNumber, StatementContext ctx) throws SQLException { String name = ctx.findColumnMapperFor(String.class) .orElseThrow(() -> new UnableToProduceResultException("a String column mapper is required to map Enums from names", ctx)) .map(rs, columnNumber, ctx); <START> return name == null ? null : nameValueCache.computeIfAbsent(name.toLowerCase(), lowercased -> getValueByName(enumClass, name, ctx)); <END> }</code><technical_language>I if cost of lowercasing outweighs cost of duplicate entries. Previously operated assumption users, if casing is wrong, tend consistently wrong - in case if redundant entries. if aren't, extra cache entries cheaper repeatedly lowercasing. Part of reason for adding this cache in place is avoid case sensitive operations. I worry this a performance regression if is common case</technical_language>

Target:
public E map(ResultSet rs, int columnNumber, StatementContext ctx) throws SQLException { String name = rs.getString(columnNumber); return name == null || name.isEmpty() ? null : nameValueCache.computeIfAbsent(name, n -> getValueByName(enumClass, name, ctx)); }
Source:
<code>public void testPasswordResetWithNoExistingUser_shouldThrow() { String username= "anyUser"; when(userRepository.findUser(anyString())).thenReturn(null); passwordResetService.resetUserPassword(username); Assert.assertNotNull(userRepository.findUser(username)); <START> verify(userRepository).findUser(username); <END> verify(passwordResetService).resetUserPassword(username); }</code><technical_language>@tumijacob I verifies called method call throw</technical_language>

Target:
public void testPasswordResetWithNoExistingUser_shouldThrow() { String username = "anyUser"; when(userRepository.findUser(anyString())).thenReturn(null); passwordResetService.resetUserPassword(username); }
Source:
<code>private HBMessage encodeNettySerializable(ByteBufAllocator alloc, INettySerializable netty_message, HBServerMessageType mType) { HBMessageData message_data = new HBMessageData(); HBMessage m = new HBMessage(); ByteBuf messageBuffer = alloc.heapBuffer(netty_message.encodeLength()); try { netty_message.write(messageBuffer); <START> message_data.set_message_blob(messageBuffer.array()); <END> m.set_type(mType); m.set_data(message_data); return m; } finally { messageBuffer.release(); } }</code><technical_language>I this is work. If alloc is a pooled allocator guarantees return a buffer large requested length, right size, .array returns backing array, is possibility put in array garbage end. this is a pooled heapBuffer release serialize HBMessage. This result in buffer reused overwritten data. I if want this model for serializing netty message need allocate a new buffer time, need return fully serialized HBMessage releasing buffer</technical_language>

Target:
private HBMessage encodeNettySerializable(ByteBufAllocator alloc, INettySerializable netty_message, HBServerMessageType mType) { HBMessageData message_data = new HBMessageData(); HBMessage m = new HBMessage(); byte[] messageBuffer = new byte[netty_message.encodeLength()]; ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(messageBuffer); try { netty_message.write(wrappedBuffer); message_data.set_message_blob(messageBuffer); m.set_type(mType); m.set_data(message_data); return m; } finally { wrappedBuffer.release(); } }
Source:
<code>public static String normalizeBranchName(String name) { if (name == null || name.length() == 0) { return name; } String result = name.trim(); String fullName = result.startsWith(Constants.R_HEADS) ? result : Constants.R_HEADS + result; if (isValidRefName(fullName)) { return result; } return result.replaceAll("\\s+([_:-])*?\\s+", "$1") .replaceAll(":", "-") .replaceAll("\\s+", "_") .replaceAll("_{2,}", "_") .replaceAll("-{2,}", "-") <START> .replaceAll("[^\\w-/]", "") END> .replaceAll("^_+", "") .replaceAll("^-+", ""); }</code><technical_language>Please this consistent isValidRefName: * / is allowed end * consecutive // allowed * . is allowed, character, a / * consecutive .. allowed</technical_language>

Target:
public static String normalizeBranchName(String name) { if (name == null || name.isEmpty()) { return name; } String result = name.trim(); String fullName = result.startsWith(Constants.R_HEADS) ? result : Constants.R_HEADS + result; if (isValidRefName(fullName)) { return result; } result = result.replaceAll("(?:\\h|\\v)+", "_"); StringBuilder b = new StringBuilder(); char p = '/'; for (int i = 0, len = result.length(); i < len; i++) { char c = result.charAt(i); if (c < ' ' || c == 127) { continue; } switch (c) { case '\\': case '^': case '~': case ':': case '?': case '*': case '[': case '@': case '<': case '>': case '|': case '"': c = '-'; break; default: break; } switch (c) { case '/': if (p == '/') { continue; } p = '/'; break; case '.': case '_': case '-': if (p == '/' || p == '-') { continue; } p = '-'; break; default: p = c; break; } b.append(c); } result = b.toString().replaceFirst("[/_.-]+$", "") .replaceAll("\\.lock($|/)", "_lock$1"); return FORBIDDEN_BRANCH_NAME_COMPONENTS.matcher(result) .replaceAll("$1+$2$3"); }
Source:
<code><START> public Response backupStart(@QueryParam("name") String name) { <END> if (name == null || name.isEmpty()) { return JaxRsUtils.buildStreamingResponse(factory, new StreamingJsonResponse() { @Override public void write(final JsonGenerator json) throws IOException { json.writeBooleanField("started", false); json.writeStringField("error", "name required"); } }); } return ClusterJobUtils.startJob(cluster, factory, CassandraFrameworkProtos.ClusterJobType.BACKUP, name); }</code><technical_language>Please provide a default name here. force user pick a name time</technical_language>

Target:
public Response backupStart(@QueryParam("name") String name) { if (name == null) { name = "backup-" + System.currentTimeMillis(); } return ClusterJobUtils.startJob(cluster, factory, CassandraFrameworkProtos.ClusterJobType.BACKUP, name); }
Source:
<code>public Void get() { <START> nrtManager.waitForGeneration(gen); <END> return null; }</code><technical_language>check understanding: this blocks reopenThread reopens a sufficiently new generation. thread polls faster a future is waiting</technical_language>

Target:
public Void get() throws InterruptedException, ExecutionException { if (!isDone()) { nrtManager.waitForGeneration(gen); set(null); } return super.get(); }
Source:
<code>protected MessageHandler createHandler() { MessageHandler handler; if (this.targetObject == null) { Assert.isTrue(!StringUtils.hasText(this.targetMethodName), "The target method is only allowed when a target object (ref or inner bean) is also provided."); } if (this.targetObject != null) { Assert.state(this.expression == null, "The 'targetObject' and 'expression' properties are mutually exclusive."); AbstractMessageProducingHandler actualHandler = this.extractTypeIfPossible(targetObject, AbstractMessageProducingHandler.class); boolean targetIsDirectReplyProducingHandler = actualHandler != null && this.canBeUsedDirect(actualHandler) && this.methodIsHandleMessageOrEmpty(this.targetMethodName); if (this.targetObject instanceof MessageProcessor<?>) { handler = this.createMessageProcessingHandler((MessageProcessor<?>) this.targetObject); } else if (targetIsDirectReplyProducingHandler) { if (logger.isDebugEnabled()) { <START> logger.debug("Wiring handler (" + beanName + ") directly into endpoint"); <END> } this.checkReuse(actualHandler); this.postProcessReplyProducer(actualHandler); handler = (MessageHandler) targetObject; } else { handler = this.createMethodInvokingHandler(this.targetObject, this.targetMethodName); } } else if (this.expression != null) { handler = this.createExpressionEvaluatingHandler(this.expression); } else { handler = this.createDefaultHandler(); } return handler; }</code><technical_language>I so. produce a new component inject existing one, targetObject is here. other side is place populate beanName property. is wrong, revert logic</technical_language>

Target:
protected MessageHandler createHandler() { MessageHandler handler; if (this.targetObject == null) { Assert.isTrue(!StringUtils.hasText(this.targetMethodName), "The target method is only allowed when a target object (ref or inner bean) is also provided."); } if (this.targetObject != null) { Assert.state(this.expression == null, "The 'targetObject' and 'expression' properties are mutually exclusive."); AbstractMessageProducingHandler actualHandler = this.extractTypeIfPossible(targetObject, AbstractMessageProducingHandler.class); boolean targetIsDirectReplyProducingHandler = actualHandler != null && this.canBeUsedDirect(actualHandler) && this.methodIsHandleMessageOrEmpty(this.targetMethodName); if (this.targetObject instanceof MessageProcessor<?>) { handler = this.createMessageProcessingHandler((MessageProcessor<?>) this.targetObject); } else if (targetIsDirectReplyProducingHandler) { if (logger.isDebugEnabled()) { logger.debug("Wiring handler (" + this.targetObject + ") directly into endpoint"); } this.checkReuse(actualHandler); this.postProcessReplyProducer(actualHandler); handler = (MessageHandler) targetObject; } else { handler = this.createMethodInvokingHandler(this.targetObject, this.targetMethodName); } } else if (this.expression != null) { handler = this.createExpressionEvaluatingHandler(this.expression); } else { handler = this.createDefaultHandler(); } return handler; }
Source:
<code>public Token appendCheckpoint() { long start = System.currentTimeMillis(); Token markerToken = rt.getSequencerView().next().getToken(); <START> rt.getAddressSpaceView().write(markerToken, "marker".getBytes()); <END> rt.getObjectsView().TXBuild() .type(TransactionType.SNAPSHOT) .snapshot(markerToken) .build() .begin(); try (Timer.Context context = MetricsUtils.getConditionalContext(appendCheckpointTimer)) { Token snapshot = TransactionalContext.getCurrentContext().getSnapshotTimestamp(); log.info("appendCheckpoint: Started checkpoint for at snapshot {}", streamId, snapshot); ICorfuSMR<T> corfuObject = (ICorfuSMR<T>) this.map; Set<Map.Entry> entries = this.map.entrySet(); long vloVersion = corfuObject.getCorfuSMRProxy().getVersion(); startCheckpoint(snapshot, vloVersion); appendObjectState(entries); finishCheckpoint(); log.info("appendCheckpoint: completed checkpoint for at snapshot in ms", streamId, snapshot, System.currentTimeMillis() - start); return snapshot; } finally { rt.getObjectsView().TXEnd(); } }</code><technical_language>Please a constant for "marker".getBytes()</technical_language>

Target:
public Token appendCheckpoint() { long start = System.currentTimeMillis(); Token markerToken = rt.getSequencerView().query().getToken(); if (Address.nonAddress(markerToken.getSequence())) { return markerToken; } rt.getAddressSpaceView().read(markerToken.getSequence()); rt.getObjectsView().TXBuild() .type(TransactionType.SNAPSHOT) .snapshot(markerToken) .build() .begin(); try (Timer.Context context = MetricsUtils.getConditionalContext(appendCheckpointTimer)) { Token snapshot = TransactionalContext.getCurrentContext().getSnapshotTimestamp(); log.info("appendCheckpoint: Started checkpoint for at snapshot {}", streamId, snapshot); ICorfuSMR<T> corfuObject = (ICorfuSMR<T>) this.map; Set<Map.Entry> entries = this.map.entrySet(); long vloVersion = corfuObject.getCorfuSMRProxy().getVersion(); startCheckpoint(snapshot, vloVersion); appendObjectState(entries); finishCheckpoint(); log.info("appendCheckpoint: completed checkpoint for {}, num of entries at snapshot in ms", streamId, entries.size(), snapshot, System.currentTimeMillis() - start); return snapshot; } finally { rt.getObjectsView().TXEnd(); } }