auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private RootModule createRootModule() { final RootModule rootModule; try { final Properties props = createOverridingProperties(); <START> final MultiThreadModeConfiguration multiThreadModeConfiguration = <END> MultiThreadModeConfiguration.singleThreadMode(); final MultiThreadModuleResolver moduleResolver = new MultiThreadModuleResolver( multiThreadModeConfiguration); final Configuration config = ConfigurationLoader.loadConfiguration( configLocation, new PropertiesExpander(props), moduleResolver, !executeIgnoredModules); final ClassLoader moduleClassLoader = Checker.class.getClassLoader(); final ModuleFactory factory = new PackageObjectFactory( Checker.class.getPackage().getName() + ".", moduleClassLoader); rootModule = (RootModule) factory.createModule(config.getName()); rootModule.setModuleClassLoader(moduleClassLoader); if (rootModule instanceof Checker) { final ClassLoader loader = new AntClassLoader(getProject(), classpath); ((Checker) rootModule).setClassLoader(loader); } rootModule.configure(config); } catch (final CheckstyleException ex) { throw new BuildException(String.format(Locale.ROOT, "Unable to create Root Module: " + "configLocation {%s}, classpath {%s}.", configLocation, classpath), ex); } return rootModule; }</code><technical_language>type named MultiThreadModeConfiguration I prefer singleThreadModeConfiguration for variable, in fact single thread mode here</technical_language>

Target:
private RootModule createRootModule() { final RootModule rootModule; try { final Properties props = createOverridingProperties(); final ThreadModeSettings threadModeSettings = ThreadModeSettings.SINGLE_THREAD_MODE_INSTANCE; final Configuration configuration = ConfigurationLoader.loadConfiguration( config, new PropertiesExpander(props), !executeIgnoredModules, threadModeSettings); final ClassLoader moduleClassLoader = Checker.class.getClassLoader(); final ModuleFactory factory = new PackageObjectFactory( Checker.class.getPackage().getName() + ".", moduleClassLoader); rootModule = (RootModule) factory.createModule(configuration.getName()); rootModule.setModuleClassLoader(moduleClassLoader); if (rootModule instanceof Checker) { final ClassLoader loader = new AntClassLoader(getProject(), classpath); ((Checker) rootModule).setClassLoader(loader); } rootModule.configure(configuration); } catch (final CheckstyleException ex) { throw new BuildException(String.format(Locale.ROOT, "Unable to create Root Module: " + "config {%s}, classpath {%s}.", config, classpath), ex); } return rootModule; }
Source:
<code>public void initialize( Input input ) throws IOException { log.info( "Import starting" ); startTime = currentTimeMillis(); inputCache = new InputCache( fileSystem, storeDir, recordFormats, toIntExact( mebiBytes( 1 ) ) ); this.input = CachedInput.cacheAsNecessary( input, inputCache ); numberArrayFactory = auto( neoStore.getPageCache(), storeDir, config.allowCacheAllocationOnHeap() ); badCollector = input.badCollector(); idMapper = input.idMapper( numberArrayFactory ); nodeRelationshipCache = new NodeRelationshipCache( numberArrayFactory, config.denseNodeThreshold() ); Estimates inputEstimates = input.calculateEstimates( neoStore.getPropertyStore().newValueEncodedSizeCalculator() ); sanityCheckEstimatesWithRecordFormat( inputEstimates ); <START> dependencies.satisfyDependencies( inputEstimates, idMapper, neoStore, nodeRelationshipCache ); <END> if ( neoStore.determineDoubleRelationshipRecordUnits( inputEstimates ) ) { System.out.println( "Will use double record units for all relationships" ); } executionMonitor.initialize( dependencies ); }</code><technical_language>some System.out System.err print-outs in this class. about</technical_language>

Target:
public void initialize( Input input ) throws IOException { log.info( "Import starting" ); startTime = currentTimeMillis(); inputCache = new InputCache( fileSystem, storeDir, recordFormats, toIntExact( mebiBytes( 1 ) ) ); this.input = CachedInput.cacheAsNecessary( input, inputCache ); numberArrayFactory = auto( neoStore.getPageCache(), storeDir, config.allowCacheAllocationOnHeap() ); badCollector = input.badCollector(); idMapper = input.idMapper( numberArrayFactory ); nodeRelationshipCache = new NodeRelationshipCache( numberArrayFactory, config.denseNodeThreshold() ); Estimates inputEstimates = input.calculateEstimates( neoStore.getPropertyStore().newValueEncodedSizeCalculator() ); sanityCheckEstimatesWithRecordFormat( inputEstimates ); dependencies.satisfyDependencies( inputEstimates, idMapper, neoStore, nodeRelationshipCache ); if ( neoStore.determineDoubleRelationshipRecordUnits( inputEstimates ) ) { monitor.doubleRelationshipRecordUnitsEnabled(); } executionMonitor.initialize( dependencies ); }
Source:
<code>public void resourceChanged(IResourceChangeEvent event) { IResourceDelta resourceDelta = event.getDelta(); if (resourceDelta != null) { IResourceDelta[] affectedChildren = resourceDelta.getAffectedChildren(); for (IResourceDelta affectedChildResourceDelta : affectedChildren) { IResource resource = affectedChildResourceDelta.getResource(); int kind = affectedChildResourceDelta.getKind(); if (resource instanceof IProject && (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED)) { PlatformUI.getWorkbench().getDisplay() .asyncExec(() -> <START> Display.getDefault().timerExec(200, <END> switchTopControlRunnable)); return; } } } }</code><technical_language>hate me, I meant of places Display.getDefault() is :)</technical_language>

Target:
public void resourceChanged(IResourceChangeEvent event) { IResourceDelta resourceDelta = event.getDelta(); if (resourceDelta != null) { IResourceDelta[] affectedChildren = resourceDelta.getAffectedChildren(); for (IResourceDelta affectedChildResourceDelta : affectedChildren) { IResource resource = affectedChildResourceDelta.getResource(); int kind = affectedChildResourceDelta.getKind(); if (resource instanceof IProject && (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED)) { PlatformUI.getWorkbench().getDisplay() .asyncExec(() -> PlatformUI.getWorkbench().getDisplay().timerExec(200, switchTopControlRunnable)); return; } } } }
Source:
<code>protected void initMaxPings() { Integer maxPingsParam = getInitParameter("maxPings", Integer.class); <START> setMaxPings((maxPingsParam == null) ? DEFAULT_MAX_PINGS : maxPingsParam); <END> if (isDebug()) { LOGGER.debug("maxPings: {}", getMaxPings()); } }</code><technical_language>If changing this code, relying Optional a good move</technical_language>

Target:
protected void initMaxPings() { Integer maxPingsParam = getInitParameter("maxPings", Integer.class); setMaxPings(Optional.ofNullable(getInitParameter("maxPings", Integer.class)).orElse(DEFAULT_MAX_PINGS)); if (isDebug()) { LOGGER.debug("maxPings: {}", getMaxPings()); } }
Source:
<code>public void doesntLinkUnrelatedSpansWhenMissingRootSpan() { <START> List<DependencyLinkSpan> trace = asList( <END> new DependencyLinkSpan(new TraceId(0L, 1L), 3L, 1L, Kind.SERVER, "service1", null), new DependencyLinkSpan(new TraceId(0L, 1L), 3L, 2L, Kind.SERVER, "service2", null) ); assertThat(new DependencyLinker() .putTrace(trace.iterator()).link()) .isEmpty(); }</code><technical_language>in tests, of time, incrementing numbers obvious order in tree. This confused a 3 is parent of 1 2. rework a little? long parentId = 1L; // declaring a local, is obvious parent is missing. is more obvious traceId is parent id. // (parentId, 2L) (parentId, 3L)</technical_language>

Target:
public void doesntLinkUnrelatedSpansWhenMissingRootSpan() { long missingParentId = 1; List<DependencyLinkSpan> trace = asList( new DependencyLinkSpan(new TraceId(0L, 1L), missingParentId, 2L, Kind.SERVER, "service1", null), new DependencyLinkSpan(new TraceId(0L, 1L), missingParentId, 3L, Kind.SERVER, "service2", null) ); assertThat(new DependencyLinker() .putTrace(trace.iterator()).link()) .isEmpty(); }
Source:
<code>protected byte[] runHttpMethod(HttpMethodType httpMethod, String contentType, String body, HttpURLConnection connection) { byte[] result = null; try { connection.setRequestProperty("Content-Type", contentType); connection.setDoInput(true); connection.setDoOutput(httpMethod != HttpMethodType.GET); connection.setRequestMethod(httpMethod.toString()); if (body != null) { byte[] bytes = body.getBytes(StandardCharsets.UTF_8); <START> connection.setRequestProperty(String.valueOf(bytes.length), "Content-Length"); <END> try (OutputStream outputStream = connection.getOutputStream()) { outputStream.write(bytes); } } result = getResponse(connection); } catch (SSLException e) { throw new EngineException(EngineError.PROVIDER_SSL_FAILURE, e.getMessage()); } catch (IOException e) { handleException(e); } finally { if (connection != null) { connection.disconnect(); } } return result; }</code><technical_language>switched key order</technical_language>

Target:
protected byte[] runHttpMethod(HttpMethodType httpMethod, String contentType, String body, HttpURLConnection connection) { byte[] result = null; try { connection.setRequestProperty("Content-Type", contentType); connection.setDoInput(true); connection.setDoOutput(httpMethod != HttpMethodType.GET); connection.setRequestMethod(httpMethod.toString()); if (body != null) { byte[] bytes = body.getBytes(StandardCharsets.UTF_8); connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); try (OutputStream outputStream = connection.getOutputStream()) { outputStream.write(bytes); } } result = getResponse(connection); } catch (SSLException e) { throw new EngineException(EngineError.PROVIDER_SSL_FAILURE, e.getMessage()); } catch (IOException e) { handleException(e); } finally { if (connection != null) { connection.disconnect(); } } return result; }
Source:
<code>private static String getString(String suffix) { <START> return Constant.messages.getString(String.format("fuzz.payloads.generator.json.%1$2s", suffix)); <END> }</code><technical_language>concatenate instead of formatter</technical_language>

Target:
private static String getString(String suffix) { return Constant.messages.getString("fuzz.payloads.generator.json." + suffix); }
Source:
<code>public FilteringArtifactClassLoader(ClassLoader parent, ArtifactClassLoader artifactClassLoader, ClassLoaderFilter filter, List<ExportedService> exportedServices) { super(parent); checkArgument(artifactClassLoader != null, "ArtifactClassLoader cannot be null"); checkArgument(filter != null, "Filter cannot be null"); checkArgument(exportedServices != null, "exportedServiceProviders cannot be null"); this.artifactClassLoader = artifactClassLoader; this.filter = filter; this.exportedServices = exportedServices; <START> verboseLogging = LOGGER.isDebugEnabled() || isVerboseLoggingEnabled(); <END> }</code><technical_language>this breaks feature of changing log levels runtime</technical_language>

Target:
public FilteringArtifactClassLoader(ClassLoader parent, ArtifactClassLoader artifactClassLoader, ClassLoaderFilter filter, List<ExportedService> exportedServices) { super(parent); checkArgument(artifactClassLoader != null, "ArtifactClassLoader cannot be null"); checkArgument(filter != null, "Filter cannot be null"); checkArgument(exportedServices != null, "exportedServiceProviders cannot be null"); this.artifactClassLoader = artifactClassLoader; this.filter = filter; this.exportedServices = exportedServices; verboseLogging = valueOf(getProperty(MULE_LOG_VERBOSE_CLASSLOADING)); }
Source:
<code>SignatureAlgorithm(String value, String description, String familyName, String jcaName, boolean jdkStandard, int digestLength, int minKeyLength) { <START> this(value, description,familyName, jcaName, jdkStandard, digestLength, minKeyLength, null); <END> }</code><technical_language>Instead of passing null, is OIDs listed in OpenJDK link I provided for other algorithms? Thoughts</technical_language>

Target:
SignatureAlgorithm(String value, String description, String familyName, String jcaName, boolean jdkStandard, int digestLength, int minKeyLength) { this(value, description,familyName, jcaName, jdkStandard, digestLength, minKeyLength, jcaName); }
Source:
<code>public static OlapAnnotation getOlapAnnotationByName( final String name, List<OlapAnnotation> annotations) { OlapAnnotation foundAnnotation = null; for( OlapAnnotation annotation : annotations ) { if ( name.equals( annotation.getName() ) ) { <START> foundAnnotation = annotation; <END> } } return foundAnnotation; }</code><technical_language>break for loop if annotation is</technical_language>

Target:
public static OlapAnnotation getOlapAnnotationByName( final String name, List<OlapAnnotation> annotations) { OlapAnnotation foundAnnotation = null; for( OlapAnnotation annotation : annotations ) { if ( name.equals( annotation.getName() ) ) { foundAnnotation = annotation; break; } } return foundAnnotation; }
Source:
<code>public void load(File file) { try(InputStream in = Files.newInputStream(file.toPath())) { PropertiesConfiguration config = newPropertiesConfiguration(); <START> new FileHandler(config).load(cleanUp(in)); <END> ((CompositeConfiguration) internalConfig).addConfiguration(config); } catch (ConfigurationException | IOException e) { throw new IllegalArgumentException(e); } }</code><technical_language>Again, need FileHandler... PropertyConfigurationLayout: java config.getLayout().load(config, cleanUp(in));</technical_language>

Target:
public void load(File file) { try (InputStream in = Files.newInputStream(file.toPath())) { PropertiesConfiguration config = new PropertiesConfiguration(); config.getLayout().load(config, checkProps(in)); ((CompositeConfiguration) internalConfig).addConfiguration(config); } catch (ConfigurationException | IOException e) { throw new IllegalArgumentException(e); } }
Source:
<code>protected ObjectNode executePost(HttpPost httpPost) { Preconditions.checkNotNull(httpPost); ObjectNode result = null; CloseableHttpResponse response = null; String entityString = null; try { response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); <START> if (response.getStatusLine() != null && response.getStatusLine().getStatusCode() >= 200 && entity != null) { <END> entityString = EntityUtils.toString(entity); result = mapper.readValue(entityString, ObjectNode.class); } } catch (IOException e) { LOGGER.error("IO error:\n{}\n{}\n{}", httpPost.toString(), response, e.getMessage()); } finally { try { response.close(); } catch (IOException e) } return result; }</code><technical_language>Is a response code enum instead of '200'</technical_language>

Target:
protected ObjectNode executePost(HttpPost httpPost) { Preconditions.checkNotNull(httpPost); ObjectNode result = null; CloseableHttpResponse response = null; String entityString = null; try { response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine() != null && response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK && entity != null) { entityString = EntityUtils.toString(entity); result = mapper.readValue(entityString, ObjectNode.class); } } catch (IOException e) { LOGGER.error("IO error:\n{}\n{}\n{}", httpPost.toString(), response, e.getMessage()); } finally { try { response.close(); } catch (IOException e) } return result; }
Source:
<code>public UdpServerListeningEvent(UnicastReceivingChannelAdapter adapter, int port) { super(adapter); <START> Assert.notNull(adapter, "'adapter' cannot be null"); <END> this.port = port; }</code><technical_language>need this. super-super-super class: public EventObject(Object source) { if (source == null) throw new IllegalArgumentException("null source"); this.source = source; }</technical_language>

Target:
public UdpServerListeningEvent(UnicastReceivingChannelAdapter adapter, int port) { super(adapter); this.port = port; }
Source:
<code>public void removeMessageHandler(final Class<? extends Message> messageType, final MessageHandler handler) { if (messageType == null) { throw new IllegalArgumentException("Cannot remove handler for null message type"); } if (handler == null) { throw new IllegalArgumentException("Cannot remove null handler"); } synchronized (messageHandlers) { List<MessageHandler> handlers = messageHandlers.get(messageType); if (handlers == null || !handlers.contains(handler)) { LOGGER.log(Level.WARNING, "{0} is not registered as a handler", handler); return; } <START> handlers.remove(handler); <END> if (handlers.isEmpty()) { messageHandlers.remove(messageType); } } }</code><technical_language>some log finer/finest this happened</technical_language>

Target:
public void removeMessageHandler(final Class<? extends Message> messageType, final MessageHandler handler) { if (messageType == null) { throw new IllegalArgumentException("Cannot remove handler for null message type"); } if (handler == null) { throw new IllegalArgumentException("Cannot remove null handler"); } LOGGER.log(Level.FINEST, "Removing message handler {0} for message type: {1}", new Object[] {handler, messageType}); synchronized (messageHandlers) { List<MessageHandler> handlers = messageHandlers.get(messageType); if (handlers == null || !handlers.contains(handler)) { LOGGER.log(Level.WARNING, "{0} is not registered as a handler", handler); return; } handlers.remove(handler); if (handlers.isEmpty()) { messageHandlers.remove(messageType); } } }
Source:
<code>protected void executeVmCommand() { AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getInterface().getType()).getDescription()).toString()); boolean succeeded = false; try { getInterface().setSpeed(VmInterfaceType.forValue(getInterface().getType()).getSpeed()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(oldIface); getVmNetworkInterfaceDao().update(getInterface()); if (macAddressChanged) { MacPoolManager.getInstance().freeMac(oldIface.getMacAddress()); } getCompensationContext().stateChanged(); return null; } }); succeeded = updateHost(); } finally { setSucceeded(succeeded); if (!succeeded && macAddressChanged) { MacPoolManager.getInstance().addMac(oldIface.getMacAddress()); <START> MacPoolManager.getInstance().freeMac(getInterface().getMacAddress()); <END> } } }</code><technical_language>getMacAddress() -> getInterface().getMacAddress() this change</technical_language>

Target:
protected void executeVmCommand() { AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getInterface().getType()).getDescription()).toString()); boolean succeeded = false; boolean macAddedToPool = false; try { if (macShouldBeChanged) { macAddedToPool = addMacToPool(getMacAddress()); } getInterface().setSpeed(VmInterfaceType.forValue(getInterface().getType()).getSpeed()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(oldIface); getVmNetworkInterfaceDao().update(getInterface()); getCompensationContext().stateChanged(); return null; } }); succeeded = updateHost(); } finally { setSucceeded(succeeded); if (macAddedToPool) { if (succeeded) { MacPoolManager.getInstance().freeMac(oldIface.getMacAddress()); } else { MacPoolManager.getInstance().freeMac(getMacAddress()); } } } }
Source:
<code>public void validate(Element element, AnnotationElements validatedElements, IsValid valid) { validatorHelper.enclosingElementHasEnhancedComponentAnnotation(element, validatedElements, valid); ExecutableElement executableElement = (ExecutableElement) element; <START> validatorHelper.hasTraceAnnotationAndReturnValue(executableElement, validatedElements, valid); <END> validatorHelper.hasWakeLockPermission(element, androidManifest, valid); validatorHelper.isNotPrivate(element, valid); validatorHelper.isNotFinal(element, valid); }</code><technical_language>check for positive case. For example isNotPrivate. name this doesnotHaveTraceAnnotationAndReturnValue sg that</technical_language>

Target:
public void validate(Element element, AnnotationElements validatedElements, IsValid valid) { validatorHelper.enclosingElementHasEnhancedComponentAnnotation(element, validatedElements, valid); ExecutableElement executableElement = (ExecutableElement) element; validatorHelper.doesNotHaveTraceAnnotationAndReturnValue(executableElement, validatedElements, valid); validatorHelper.doesNotUseFlagsWithPartialWakeLock(element, validatedElements, valid); validatorHelper.hasWakeLockPermission(element, androidManifest, valid); validatorHelper.isNotPrivate(element, valid); validatorHelper.isNotFinal(element, valid); }
Source:
<code>public static String redactUrl(String path) { URL url; try { url = new URL(path); } catch (MalformedURLException e) { return path; } if (url.getUserInfo() != null) { return url.toString().replace(url.getUserInfo(), REDACTED_USER_INFO); } else { <START> return url.toString(); <END> } }</code><technical_language>return path here? url.toString() differ path</technical_language>

Target:
public static String redactUrl(String path) { URL url; try { url = new URL(path); } catch (MalformedURLException e) { return path; } if (url.getUserInfo() != null) { return url.toString().replace(url.getUserInfo(), REDACTED_USER_INFO); } else { return path; } }
Source:
<code>public void testListNullElement() { Dog dog1 = new Dog(); dog1.setName("Dog 1"); Dog dog2 = new Dog(); dog2.setName("Dog 2"); ArrayList<Dog> list = new ArrayList<Dog>(); list.addAll(Arrays.asList(dog1, null, dog2)); realm.beginTransaction(); try { realm.insert(list); <START> } catch (NullPointerException ignore) { <END> } finally { realm.cancelTransaction(); } }</code><technical_language>add fail() insert</technical_language>

Target:
public void testListNullElement() { Dog dog1 = new Dog(); dog1.setName("Dog 1"); Dog dog2 = new Dog(); dog2.setName("Dog 2"); ArrayList<Dog> list = new ArrayList<Dog>(); list.addAll(Arrays.asList(dog1, null, dog2)); realm.beginTransaction(); try { realm.insert(list); fail("Should trigger IllegalArgumentException"); } catch (NullPointerException ignore) { } finally { realm.cancelTransaction(); } }
Source:
<code>public static ConnectionDetails newForNode(final Node node, final ConnectionDetails connectionDetails) { final Builder connectionBuilder; if (node.getEndpoint() == null || node.getEndpoint().equals("FAILED_TO_DETERMINE_DATAPATH_IP_ADDRESS")) { LOG.trace("Running against an old version of the DS3 API, reusing existing endpoint configuration"); connectionBuilder = builder(connectionDetails.getEndpoint(), connectionDetails.getCredentials()); } else { LOG.trace("Creating new Connection Details for endpoint: " + node.getEndpoint()); <START> connectionBuilder = builder(node.getEndpoint() + ":" + getPort(node, connectionDetails), connectionDetails.getCredentials()); <END> } connectionBuilder.withRedirectRetries(connectionDetails.getRetries()) .withHttps(connectionDetails.isHttps()) .withCertificateVerification(connectionDetails.isCertificateVerification()) .withBufferSize(connectionDetails.getBufferSize()) .withProxy(connectionDetails.getProxy()); return connectionBuilder.build(); }</code><technical_language>Moving Integer.toString cleaner</technical_language>

Target:
public static ConnectionDetails newForNode(final Node node, final ConnectionDetails connectionDetails) { final Builder connectionBuilder; if (node.getEndpoint() == null || node.getEndpoint().equals("FAILED_TO_DETERMINE_DATAPATH_IP_ADDRESS")) { LOG.trace("Running against an old version of the DS3 API, reusing existing endpoint configuration"); connectionBuilder = builder(connectionDetails.getEndpoint(), connectionDetails.getCredentials()); } else { LOG.trace("Creating new Connection Details for endpoint: " + node.getEndpoint()); connectionBuilder = builder(buildAuthority(node, connectionDetails), connectionDetails.getCredentials()); } connectionBuilder.withRedirectRetries(connectionDetails.getRetries()) .withHttps(connectionDetails.isHttps()) .withCertificateVerification(connectionDetails.isCertificateVerification()) .withBufferSize(connectionDetails.getBufferSize()) .withProxy(connectionDetails.getProxy()); return connectionBuilder.build(); }
Source:
<code>public static String simplePrint(GraphQLSchemaElement schemaElement) { if (schemaElement instanceof GraphQLType) { return simplePrint((GraphQLType) schemaElement); } if (schemaElement instanceof GraphQLNamedSchemaElement) { return ((GraphQLNamedSchemaElement) schemaElement).getName(); } <START> return "null"; <END> }</code><technical_language>null "null"</technical_language>

Target:
public static String simplePrint(GraphQLSchemaElement schemaElement) { if (schemaElement instanceof GraphQLType) { return simplePrint((GraphQLType) schemaElement); } if (schemaElement instanceof GraphQLNamedSchemaElement) { return ((GraphQLNamedSchemaElement) schemaElement).getName(); } return assertShouldNeverHappen("unexpected schema element: " + schemaElement); }
Source:
<code>public ICompletionProposal[] getCompletionProposals() { Parser parser = Parser.getDefault(); TargetNode rootNode = parser.getRootNode(); if (rootNode == null) return new ICompletionProposal[] {}; UnitNode node = rootNode.getEnclosingUnit(offset); if (acKey.equalsIgnoreCase(ITargetConstants.UNIT_ID_ATTR)) { if (node != null) { <START> LocationNode location = node.getParent(); <END> if (location.getRepositoryLocation() == null) { return getErrorCompletion(); } RepositoryCache cache = RepositoryCache.getDefault(); if (!cache.isUpToDate(location.getRepositoryLocation())) { UpdateJob job = new UpdateJob(location); job.setUser(true); job.schedule(); return getInformativeProposal(); } List<UnitNode> units = cache.getUnitsByPrefix(location.getRepositoryLocation(), prefix); return convertToProposals(units); } } if (acKey.equalsIgnoreCase(ITargetConstants.UNIT_VERSION_ATTR)) { if (node != null) { LocationNode location = node.getParent(); if (location.getRepositoryLocation() == null) { return getErrorCompletion(); } RepositoryCache cache = RepositoryCache.getDefault(); if (!cache.isUpToDate(location.getRepositoryLocation())) { UpdateJob job = new UpdateJob(location); job.setUser(true); job.schedule(); return getInformativeProposal(); } List<UnitNode> byPrefix = cache.getUnitsByPrefix(location.getRepositoryLocation(), node.getId()); List<String> versions = byPrefix.get(0).getAvailableVersions(); return convertToVersionProposals(versions); } } return new ICompletionProposal[] {}; }</code><technical_language>Duplicate code (see line 76). Create method</technical_language>

Target:
public ICompletionProposal[] getCompletionProposals() { Parser parser = Parser.getDefault(); TargetNode rootNode = parser.getRootNode(); if (rootNode == null) return new ICompletionProposal[] {}; UnitNode node = rootNode.getEnclosingUnit(offset); if (acKey.equalsIgnoreCase(ITargetConstants.UNIT_ID_ATTR)) { if (node != null) { LocationNode location = node.getParent(); String repoLocation = location.getRepositoryLocation(); if (repoLocation == null) { return getErrorCompletion(); } RepositoryCache cache = RepositoryCache.getDefault(); if (!cache.isUpToDate(repoLocation)) { scheduleUpdateJob(location); return getInformativeProposal(); } List<UnitNode> units = cache.getUnitsByPrefix(repoLocation, prefix); return convertToProposals(units); } } if (acKey.equalsIgnoreCase(ITargetConstants.UNIT_VERSION_ATTR)) { if (node != null) { LocationNode location = node.getParent(); String repoLocation = location.getRepositoryLocation(); if (repoLocation == null) { return getErrorCompletion(); } RepositoryCache cache = RepositoryCache.getDefault(); if (!cache.isUpToDate(repoLocation)) { scheduleUpdateJob(location); return getInformativeProposal(); } List<UnitNode> byPrefix = cache.getUnitsByPrefix(repoLocation, node.getId()); List<String> versions = byPrefix.get(0).getAvailableVersions(); return convertToVersionProposals(versions); } } return new ICompletionProposal[] {}; }
Source:
<code>private String getCurrentValueFromViewer(MergeViewerSide side) { <START> final boolean isLeft = (MergeViewerSide.LEFT == side) != getCompareConfiguration().isMirrored(); <END> final GetContentRunnable runnable = new GetContentRunnable(isLeft); Display.getDefault().syncExec(runnable); return (String)runnable.getResult(); }</code><technical_language>Please separate lines readable. boolean isLeft = MergeViewerSide.LEFT == side; if (getCompareConfiguration.isMirrored()) { isLeft = MergeViewerSide.RIGHT == side; }</technical_language>

Target:
private String getCurrentValueFromViewer(MergeViewerSide side) { boolean isLeft = MergeViewerSide.LEFT == side; if (getCompareConfiguration().isMirrored()) { isLeft = MergeViewerSide.RIGHT == side; } final GetContentRunnable runnable = new GetContentRunnable(isLeft); Display.getDefault().syncExec(runnable); return (String)runnable.getResult(); }
Source:
<code>public Object execute() throws Exception { JaasRealm realm = (JaasRealm) session.get(JAAS_REALM); if (realm == null) { System.err.println("No JAAS Realm has been selected"); return null; } if (!(realm instanceof Config)) { System.err.println("Selected JAAS Realm was not added via jaas:add-realm, only those are supported!"); return null; } if (!checkIfClassExists(loginModule)) { System.err.println("Module class '" + loginModule + "' is unknown!"); <START> return null; <END> } Module module = createModuleFromCmdParameters(loginModule, propertiesList); List<Module> modulesList = new ArrayList<>(Arrays.asList(((Config) realm).getModules())); modulesList.add(module); Module[] newModules = modulesList.toArray(new Module[]{}); ((Config) realm).setModules(newModules); return null; }</code><technical_language>raise exception there</technical_language>

Target:
public Object execute() throws Exception { JaasRealm realm = (JaasRealm) session.get(JAAS_REALM); if (realm == null) { System.err.println("No JAAS Realm has been selected"); throw new IllegalStateException("No JAAS Realm has been selected"); } if (!(realm instanceof Config)) { System.err.println("Selected JAAS Realm was not added via jaas:add-realm, only those are supported!"); throw new IllegalStateException("Selected JAAS Realm was not added via jaas:add-realm, only those are supported!"); } if (!checkIfClassExists(loginModule)) { System.err.println("Module class '" + loginModule + "' is unknown!"); throw new IllegalArgumentException("Module class '" + loginModule + "' is unknown!"); } Module module = createModuleFromCmdParameters(loginModule, propertiesList); List<Module> modulesList = new ArrayList<>(Arrays.asList(((Config) realm).getModules())); modulesList.add(module); Module[] newModules = modulesList.toArray(new Module[]{}); ((Config) realm).setModules(newModules); return null; }
Source:
<code>protected void onHandleIntent(Intent intent) { mContext = getApplicationContext(); if (intent != null) { final String action = intent.getAction(); if (ACTION_SYNC.equals(action)) { final int param1 = intent.getIntExtra(SYNC_PERIOD, 1); <START> acquireSerialDevice(); <END> handleActionSync(param1, getApplicationContext(), mSerialDevice); } } }</code><technical_language>acquireSerialDevice return serial device, get rid of member variable</technical_language>

Target:
protected void onHandleIntent(Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_SYNC.equals(action)) { final int param1 = intent.getIntExtra(SYNC_PERIOD, 1); UsbSerialDriver driver = acquireSerialDevice(); if (driver != null) { handleActionSync(param1, getApplicationContext(), driver); } } } }
Source:
<code>public void testResourceHandlerClearedByJVM() { if (System.getProperty("java.version").startsWith("1.7")) { return; <START> } <END> createDanglingObjectHandler(); long poolSize = poolOfString.poolSize(); while (poolOfString.poolSize() == poolSize) { System.gc(); } Assert.assertEquals(poolSize + 1, poolOfString.poolSize()); }</code><technical_language>is this more reliable in java versions higher, in java 1.8, System.gc() is a hint</technical_language>

Target:
public void testResourceHandlerClearedByJVM() throws InterruptedException { if (System.getProperty("java.version").startsWith("1.7")) { return; } String leakedString = createDanglingObjectHandler(); for (int i = 0; i < 6000 && poolOfString.leakedObjectsCount() == 0; i++) { System.gc(); byte[] garbage = new byte[10_000_000]; Thread.sleep(10); } Assert.assertEquals(leakedString, 1, poolOfString.leakedObjectsCount()); }
Source:
<code>public boolean supports(AuthenticationToken token) { if (!(token instanceof BaseAuthenticationToken)) { LOGGER.debug( "The supplied authentication token is not an instance of BaseAuthenticationToken. Sending back not supported."); return false; } BaseAuthenticationToken authToken = (BaseAuthenticationToken) token; Object credentials = authToken.getCredentials(); if (credentials == null || authToken.getType() != AuthenticationTokenType.USERNAME) { LOGGER.debug( <START> "The supplied authentication token has null/empty credentials. Sending back no supported."); <END> return false; } LOGGER.debug( "Token is supported by {}.", token.getClass(), UsernamePasswordRealm.class.getName()); return true; }</code><technical_language>S/b "Sending supported."</technical_language>

Target:
public boolean supports(AuthenticationToken token) { if (!(token instanceof BaseAuthenticationToken)) { LOGGER.debug( "The supplied authentication token is not an instance of BaseAuthenticationToken. Sending back not supported."); return false; } BaseAuthenticationToken authToken = (BaseAuthenticationToken) token; Object credentials = authToken.getCredentials(); if (credentials == null || authToken.getType() != AuthenticationTokenType.USERNAME) { LOGGER.debug( "The supplied authentication token has null/empty credentials. Sending back not supported."); return false; } if (credentials instanceof String) { LOGGER.debug( "Token is supported by {}.", token.getClass(), UsernamePasswordRealm.class.getName()); return true; } return false; }
Source:
<code>public SwaggerParseResult readLocation(String url, List<AuthorizationValue> auth, ParseOptions options) { SwaggerParseResult result = new SwaggerParseResult(); try { result = readWithInfo(url,auth); if (result.getOpenAPI() != null) { String version = result.getOpenAPI().getOpenapi(); if (auth == null) { auth = new ArrayList<>(); } if (version != null && version.startsWith("3.0")) { if (options != null) { if (options.isResolve()) { <START> result.setOpenAPI(new OpenAPIResolver(result.getOpenAPI(), auth, null).resolve()); <END> } if (options.isResolveFully()) { result.setOpenAPI(new OpenAPIResolver(result.getOpenAPI(), auth, null).resolve()); new ResolverFully().resolveFully(result.getOpenAPI()); } } } } } catch (Exception e) { result.setMessages(Arrays.asList(e.getMessage())); } return result; }</code><technical_language>update this block avoid double call OpenAPIResolver</technical_language>

Target:
public SwaggerParseResult readLocation(String url, List<AuthorizationValue> auth, ParseOptions options) { SwaggerParseResult result = new SwaggerParseResult(); try { result = readWithInfo(url,auth); if (result.getOpenAPI() != null) { String version = result.getOpenAPI().getOpenapi(); if (auth == null) { auth = new ArrayList<>(); } if (version != null && version.startsWith("3.0")) { if (options != null) { OpenAPIResolver resolver = new OpenAPIResolver(result.getOpenAPI(), auth, null); if (options.isResolve()) { result.setOpenAPI(resolver.resolve()); } if (options.isResolveFully()) { result.setOpenAPI(resolver.resolve()); new ResolverFully().resolveFully(result.getOpenAPI()); } } } } } catch (Exception e) { result.setMessages(Arrays.asList(e.getMessage())); } return result; }
Source:
<code>public void check(final IProgressMonitor monitor) { if (null != monitor) { monitor.subTask("Validate dependencies for element types."); } final Collection<String> requiredPlugins = new HashSet<>(); NEEDED_REQUIRED_PLUGINS.stream().forEach(needRequiredPlugin -> requiredPlugins.add(needRequiredPlugin)); final Collection<String> existingRequiredPlugins = new HashSet<>(); <START> ProjectManagementService.getPluginDependencies(project).stream().forEach(dependency <END> -> existingRequiredPlugins.add(dependency.getName())); requiredPlugins.removeIf(requiredPlugin -> existingRequiredPlugins.contains(requiredPlugin)); if (!requiredPlugins.isEmpty()) { final IFile manifestFile = ProjectManagementService.getManifestFile(project); requiredPlugins.stream().forEach(requiredPlugin -> { MarkersService.createMarker(manifestFile, ElementTypesPluginValidationConstants.ELEMENTTYPES_PLUGIN_VALIDATION_TYPE, "The plug-in '" + requiredPlugin + "' must be defined as required plug-in.", IMarker.SEVERITY_WARNING); }); } if (null != monitor) { monitor.worked(1); } }</code><technical_language>this result in null. This rare this tested</technical_language>

Target:
public void check(final IProgressMonitor monitor) { if (null != monitor) { monitor.subTask("Validate dependencies for element types."); } final Collection<String> requiredPlugins = new HashSet<>(); NEEDED_REQUIRED_PLUGINS.stream().forEach(needRequiredPlugin -> requiredPlugins.add(needRequiredPlugin)); final Collection<String> existingRequiredPlugins = new HashSet<>(); final List<BundleSpecification> dependencies = ProjectManagementService.getPluginDependencies(project); if (null != dependencies && !dependencies.isEmpty()) { dependencies.stream().forEach(dependency -> existingRequiredPlugins.add(dependency.getName())); requiredPlugins.removeIf(requiredPlugin -> existingRequiredPlugins.contains(requiredPlugin)); } if (!requiredPlugins.isEmpty()) { final IFile manifestFile = ProjectManagementService.getManifestFile(project); requiredPlugins.stream().forEach(requiredPlugin -> { MarkersService.createMarker(manifestFile, ElementTypesPluginValidationConstants.ELEMENTTYPES_PLUGIN_VALIDATION_TYPE, "The plug-in '" + requiredPlugin + "' must be defined as required plug-in.", IMarker.SEVERITY_WARNING); }); } if (null != monitor) { monitor.worked(1); } }
Source:
<code>void registerCapability(RegistrationParams params) { params.getRegistrations().forEach(reg -> { if ("workspace/didChangeWorkspaceFolders".equals(reg.getMethod())) { <START> Assert.isNotNull(serverCapabilities, <END> "Dynamic capability registration failed! Server not yet initialized?"); if (supportsWorkspaceFolders(serverCapabilities)) { LanguageServerPlugin.logWarning( "Dynamic registration of 'workspace/didChangeWorkspaceFolders' ignored. It was already enabled before", null); } else { onUnregistration(reg, () -> enableWorkspaceFolders(serverCapabilities, false)); enableWorkspaceFolders(serverCapabilities, true); } } else if ("workspace/executeCommand".equals(reg.getMethod())) { Gson gson = new Gson(); ExecuteCommandOptions executeCommandOptions = gson.fromJson((JsonObject) reg.getRegisterOptions(), ExecuteCommandOptions.class); List<String> newCommands = executeCommandOptions.getCommands(); if (!newCommands.isEmpty()) { onUnregistration(reg, () -> unregisterCommands(newCommands)); registerCommands(newCommands); } } }); }</code><technical_language>avoid null check get in a state serverCapabilities is expected null, this async getInitializedServer().thenRun(() -> { if (supportsWorkspaceFolders(serverCapabilities)) { LanguageServerPlugin.logWarning(...); } else { onUnregistration(reg, () -> enableWorkspaceFolders(serverCapabilities, false)); enableWorkspaceFolders(serverCapabilities, true); } })</technical_language>

Target:
void registerCapability(RegistrationParams params) { params.getRegistrations().forEach(reg -> { if ("workspace/didChangeWorkspaceFolders".equals(reg.getMethod())) { Assert.isNotNull(serverCapabilities, "Dynamic capability registration failed! Server not yet initialized?"); if (initiallySupportsWorkspaceFolders) { return; } else if (supportsWorkspaceFolders(serverCapabilities)) { LanguageServerPlugin.logWarning( "Dynamic registration of 'workspace/didChangeWorkspaceFolders' ignored. It was already enabled before", null); } else { addRegistration(reg, () -> setWorkspaceFoldersEnablement(false)); setWorkspaceFoldersEnablement(true); } } else if ("workspace/executeCommand".equals(reg.getMethod())) { Gson gson = new Gson(); ExecuteCommandOptions executeCommandOptions = gson.fromJson((JsonObject) reg.getRegisterOptions(), ExecuteCommandOptions.class); List<String> newCommands = executeCommandOptions.getCommands(); if (!newCommands.isEmpty()) { addRegistration(reg, () -> unregisterCommands(newCommands)); registerCommands(newCommands); } } }); }
Source:
<code><START> private String storeSensorPrefix(final String threadId, final String taskId, final String storeName) { <END> return taskSensorPrefix(threadId, taskId) + SENSOR_PREFIX_DELIMITER + "store" + SENSOR_PREFIX_DELIMITER + storeName; }</code><technical_language>nit: put args a separate line</technical_language>

Target:
private String storeSensorPrefix(final String threadId, final String taskId, final String storeName) { return taskSensorPrefix(threadId, taskId) + SENSOR_PREFIX_DELIMITER + SENSOR_STORE_LABEL + SENSOR_PREFIX_DELIMITER + storeName; }
Source:
<code><START> public static Guid getGuidValue(NGuid id) { <END> if (id == null) { return null; } return id.getValue(); }</code><technical_language>do this in a single line</technical_language>

Target:
public static Guid getGuidValue(NGuid id) { return id == null ? null : id.getValue(); }
Source:
<code>private void storeInDB(String serviceName, String type, String user, Object token) throws CredentialStoreException { try { Connection connection = getConnection(); try { String application = findApplicationName(); if(StringUtil.isEmpty(user)){ user = serviceName+application; } PreparedStatement ps = connection.prepareStatement("INSERT INTO "+getTableName()+" VALUES (?, ?, ?, ?, ?)"); <START> try { <END> byte[] apptoken = serialize(token); ps.setString(1, application); ps.setString(2, serviceName); ps.setObject(3, type); ps.setObject(4, user); ps.setObject(5, apptoken); ps.executeUpdate(); } finally { ps.close(); } } finally { connection.close(); } } catch (SQLException e) { logger.log(Level.SEVERE, "setAppToken : ", e); throw new CredentialStoreException(e, "DBTokenStore.java : setAppToken caused a SQLException"); } }</code><technical_language>nested try/catch/finally blocks mixed throws statements. simplify this</technical_language>

Target:
private void storeInDB(String serviceName, String type, String user, Object token) throws CredentialStoreException { try { Connection connection = getConnection(); try { String application = findApplicationName(); if(StringUtil.isEmpty(user)){ user = ""; } PreparedStatement ps = connection.prepareStatement("INSERT INTO "+getTableName()+" VALUES (?, ?, ?, ?, ?)"); try { byte[] apptoken = serialize(token); ps.setString(1, application); ps.setString(2, serviceName); ps.setObject(3, type); ps.setObject(4, user); ps.setObject(5, apptoken); ps.executeUpdate(); } finally { ps.close(); } } finally { connection.close(); } } catch (SQLException e) { logger.log(Level.SEVERE, "setAppToken : ", e); throw new CredentialStoreException(e, "DBTokenStore.java : setAppToken caused a SQLException"); } }
Source:
<code>public void setUp() throws InitializationError { <START> initMocks(this); mRunner = spy(new LongevityClassRunner(SampleTest.class)); <END> }</code><technical_language>great rely this knowing relies on. In particular, replace failing test elsewhere, immediately obvious this is running "sample" test I bottom of file</technical_language>

Target:
public void setUp() { initMocks(this); }
Source:
<code>public EnvVars getEnvironment() throws IOException, InterruptedException { if (cachedEnvironment != null) { <START> return cachedEnvironment; <END> } cachedEnvironment = EnvVars.getRemote(getChannel()); return cachedEnvironment; }</code><technical_language>if a write setting this null inbetween check of null</technical_language>

Target:
public EnvVars getEnvironment() throws IOException, InterruptedException { EnvVars cachedEnvironment = this.cachedEnvironment; if (cachedEnvironment != null) { return cachedEnvironment; } cachedEnvironment = EnvVars.getRemote(getChannel()); this.cachedEnvironment = cachedEnvironment; return cachedEnvironment; }
Source:
<code><START> public void testRule() throws Exception { <END> String[] command = Stream.concat(Arrays.stream(this.getCommandArgs()), Arrays.stream(this.getDefaultArgs())) .toArray(String[]::new); addAllExpectedMsgs(); Tailor.main(command); List<String> actualOutput = new ArrayList<>(); String[] msgs = outContent.toString(Charset.defaultCharset().name()).split(NEWLINE_REGEX); String summary = msgs[msgs.length - 1]; msgs = Arrays.copyOfRange(msgs, 4, msgs.length - 2); for (String msg : msgs) { if (msg.isEmpty() || msg.contains("**********")) { continue; } String truncatedMsg = msg.substring(msg.indexOf(TEST_INPUT_DIR) + TEST_INPUT_DIR.length()); actualOutput.add(truncatedMsg); } assertThat(summary, containsString(expectedMessages.size() + " violation")); assertArrayEquals(outContent.toString(Charset.defaultCharset().name()), this.expectedMessages.toArray(), actualOutput.toArray()); }</code><technical_language>java throws Exception replaced java throws ReflectiveOperationException, UnsupportedEncodingException</technical_language>

Target:
public void testRule() throws ReflectiveOperationException, UnsupportedEncodingException { String[] command = Stream.concat(Arrays.stream(this.getCommandArgs()), Arrays.stream(this.getDefaultArgs())) .toArray(String[]::new); addAllExpectedMsgs(); Tailor.main(command); List<String> actualOutput = new ArrayList<>(); String[] msgs = outContent.toString(Charset.defaultCharset().name()).split(NEWLINE_REGEX); String summary = msgs[msgs.length - 1]; msgs = Arrays.copyOfRange(msgs, 4, msgs.length - 2); for (String msg : msgs) { if (msg.isEmpty() || msg.contains("**********")) { continue; } String truncatedMsg = msg.substring(msg.indexOf(TEST_INPUT_DIR) + TEST_INPUT_DIR.length()); actualOutput.add(truncatedMsg); } assertThat(summary, containsString(expectedMessages.size() + " violation")); assertArrayEquals(outContent.toString(Charset.defaultCharset().name()), this.expectedMessages.toArray(), actualOutput.toArray()); }
Source:
<code>public WebElement getEditInstructorLink(int instrNum) { String id = "instrEditLink" + instrNum; <START> return browser.driver.findElement(By.id(id)); <END> }</code><technical_language>I is clear enough additional id variable for</technical_language>

Target:
public WebElement getEditInstructorLink(int instrNum) { return browser.driver.findElement(By.id("instrEditLink" + instrNum)); }
Source:
<code>public int writeCharacteristic(BluetoothGattCharacteristic characteristic, int offset, byte[] value) { if (offset != 0) { return BluetoothGatt.GATT_INVALID_OFFSET; } if (value.length != 2) { return BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH; } ByteBuffer byteBuffer = ByteBuffer.wrap(value); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); final int newMeasurementIntervalValue = byteBuffer.getShort(); <START> if (!isValidMeasurementIntervalValue(Integer.toString(newMeasurementIntervalValue))) { <END> return BluetoothGatt.GATT_FAILURE; } getActivity().runOnUiThread(new Runnable() { @Override public void run() { mMeasurementIntervalCharacteristic.setValue(newMeasurementIntervalValue, MEASUREMENT_INTERVAL_FORMAT, 0); resetTimer(newMeasurementIntervalValue); } }); return BluetoothGatt.GATT_SUCCESS; }</code><technical_language>avoid converting integer a string in isValid* function</technical_language>

Target:
public int writeCharacteristic(BluetoothGattCharacteristic characteristic, int offset, byte[] value) { if (offset != 0) { return BluetoothGatt.GATT_INVALID_OFFSET; } if (value.length != 2) { return BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH; } ByteBuffer byteBuffer = ByteBuffer.wrap(value); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); final int newMeasurementIntervalValue = byteBuffer.getShort(); if (!isValidMeasurementIntervalValue(newMeasurementIntervalValue)) { return BluetoothGatt.GATT_FAILURE; } getActivity().runOnUiThread(new Runnable() { @Override public void run() { mMeasurementIntervalCharacteristic.setValue(newMeasurementIntervalValue, MEASUREMENT_INTERVAL_FORMAT, 0); if (mMeasurementIntervalCCCDescriptor.getValue() == BluetoothGattDescriptor.ENABLE_INDICATION_VALUE) { resetTimer(newMeasurementIntervalValue); mTextViewNotifications.setText(R.string.notificationsEnabled); } } }); return BluetoothGatt.GATT_SUCCESS; }