auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { final RevCommit c = source.next(); if (c == null) { return null; } boolean rewrote = false; final RevCommit[] pList = c.parents; final int nParents = pList.length; for (int i = 0; i < nParents; i++) { <START> final RevCommit oldp = pList[i]; <END> RevCommit newp; if (firstParent && i > 0) { newp = null; } else { newp = rewrite(oldp); } if (oldp != newp) { pList[i] = newp; rewrote = true; } } if (rewrote) { c.parents = cleanup(pList); } return c; }</code><technical_language>in "only parent" case, this is setting plist[i] null if i > 0 ? "cleanup" convert a new array element (after couple of for loops). is more readable do this in for loop: if (firstParent && i > 0) { c.parents = new RevCommit { rewrite(oldp) }; return c; }</technical_language>

Target:
RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { final RevCommit c = source.next(); if (c == null) { return null; } boolean rewrote = false; final RevCommit[] pList = c.parents; final int nParents = pList.length; for (int i = 0; i < nParents; i++) { final RevCommit oldp = pList[i]; if (firstParent && i > 0) { c.parents = new RevCommit[] { rewrite(oldp) }; return c; } final RevCommit newp = rewrite(oldp); if (oldp != newp) { pList[i] = newp; rewrote = true; } } if (rewrote) { c.parents = cleanup(pList); } return c; }
Source:
<code>private void executeAction() { LOG.trace("response processing for {}", requestTicket); for (ResponseListener listener : responseListeners) { if (listener != null) { if (hasException) { <START> LOG.debug("invoke response listener for requestTicket throws exception", requestTicket, exception); <END> listener.onError(endpoint, requestTicket, exception); } else { LOG.trace("invoke response listener for requestTicket with response {}", requestTicket, response); listener.onResponse(endpoint, requestTicket, response); } } } }</code><technical_language>Missing curly bracket for requestTicket</technical_language>

Target:
private void executeAction() { LOG.trace("response processing for {}", requestTicket); for (ResponseListener listener : responseListeners) { if (listener != null) { if (hasException) { LOG.debug("invoke response listener for requestTicket with exception", requestTicket, exception); listener.onError(client, requestTicket, exception); } else { LOG.trace("invoke response listener for requestTicket with response {}", requestTicket, response); listener.onResponse(client, requestTicket, response); } } } }
Source:
<code>private void clearProfileCache() { server_.clearProfile(htmlLocalPath_, new ServerRequestCallback<JavaScriptObject>() { @Override <START> public void onError(ServerError error) <END> { } }); }</code><technical_language>log this error if display user</technical_language>

Target:
private void clearProfileCache() { try { server_.clearProfile(htmlLocalPath_, new ServerRequestCallback<JavaScriptObject>() { @Override public void onError(ServerError error) { Debug.logError(error); } }); } catch(Exception e) { Debug.logException(e); } }
Source:
<code>public Configuration generate(JTestSuite jTestConfiguration) { Configuration configuration = new Configuration(); <START> List<Task> tasks = jTestConfiguration.getTestGroups().stream(). <END> map(TestGroupGenerator::generateFromTestGroup) .collect(Collectors.toList()); configuration.setTasks(tasks); ManagedList<SessionExecutionListener> seListeners = new ManagedList<>(); seListeners.add(basicSessionCollector); seListeners.add(basicAggregator); ManagedList<DistributionListener> teListeners = new ManagedList<>(); teListeners.add(basicSessionCollector); teListeners.add(basicAggregator); teListeners.add(e1MasterCollector); teListeners.add(e1ScenarioAggregator); teListeners.add(metricLogProcessor); teListeners.add(profilerLogProcessor); configuration.setSessionExecutionListeners(seListeners); configuration.setTaskExecutionListeners(teListeners); return configuration; }</code><technical_language>A period new line, checkstyle fail</technical_language>

Target:
public Configuration generate(JTestSuite jTestConfiguration) { Configuration configuration = new Configuration(); List<Task> tasks = jTestConfiguration.getTestGroups() .stream() .map(TestGroupGenerator::generateFromTestGroup) .collect(Collectors.toList()); configuration.setTasks(tasks); ManagedList<SessionExecutionListener> seListeners = new ManagedList<>(); seListeners.add(basicSessionCollector); seListeners.add(basicAggregator); ManagedList<DistributionListener> teListeners = new ManagedList<>(); teListeners.add(basicSessionCollector); teListeners.add(basicAggregator); teListeners.add(e1MasterCollector); teListeners.add(e1ScenarioAggregator); teListeners.add(metricLogProcessor); teListeners.add(profilerLogProcessor); teListeners.add(durationLogProcessor); configuration.setSessionExecutionListeners(seListeners); configuration.setTaskExecutionListeners(teListeners); return configuration; }
Source:
<code><START> public Constraint constraint(ProgramState state) { <END> Set<Type> numberTypes = EnumSet.of(Type.NUMBER, Type.BOOLEAN); Type firstType = firstOperandValue.constraint(state).type(); Type secondType = secondOperandValue.constraint(state).type(); if (firstType != null || secondType != null) { if (firstType == Type.STRING || secondType == Type.STRING) { return Constraint.STRING; } else if (numberTypes.contains(firstType) || numberTypes.contains(secondType)) { return Constraint.NUMBER; } } return Constraint.NUMBER.or(Constraint.STRING); }</code><technical_language>@vilchik-elena Suggested implementation fix invalid cases x + 1: Constraint numberOrBoolean = Constraint.NUMBER.or(Constraint.BOOLEAN); Constraint firstConstraint = firstOperandValue.constraint(state); Constraint secondConstraint = secondOperandValue.constraint(state); if (firstConstraint.isStricterOrEqualTo(Constraint.STRING) || secondConstraint.isStricterOrEqualTo(Constraint.STRING)) { return Constraint.STRING; } else if (firstConstraint.isStricterOrEqualTo(numberOrBoolean) && secondConstraint.isStricterOrEqualTo(numberOrBoolean)) { return Constraint.NUMBER; } return Constraint.NUMBER.or(Constraint.STRING);</technical_language>

Target:
public Constraint constraint(ProgramState state) { Set<Type> numberTypes = EnumSet.of(Type.NUMBER, Type.BOOLEAN); Type firstType = firstOperandValue.constraint(state).type(); Type secondType = secondOperandValue.constraint(state).type(); if (firstType != null || secondType != null) { if (firstType == Type.STRING || secondType == Type.STRING) { return Constraint.STRING; } else if (numberTypes.contains(firstType) && numberTypes.contains(secondType)) { return Constraint.NUMBER; } } return Constraint.NUMBER.or(Constraint.STRING); }
Source:
<code>public static void updateServerBinding(SonarQubeServer server, ConnectedSonarLintEngine engine, boolean background, boolean onlyProjects) { Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); List<Project> projects = new ArrayList<>(openProjects.length); List<String> moduleKeys = new ArrayList<>(openProjects.length); Set<String> unique = new HashSet<>(); for (Project p : openProjects) { SonarLintProjectSettings projectSettings = SonarLintUtils.get(p, SonarLintProjectSettings.class); String moduleKey = projectSettings.getProjectKey(); <START> if (projectSettings.isBindingEnabled() && server.getName().equals(projectSettings.getServerId()) && moduleKey != null && unique.add(moduleKey)) { <END> projects.add(p); moduleKeys.add(moduleKey); } } ServerUpdateTask task = new ServerUpdateTask(engine, server, projects, moduleKeys, onlyProjects); if (background) { ProgressManager.getInstance().run(task.asBackground()); } else { ProgressManager.getInstance().run(task.asModal()); } }</code><technical_language>If 2 projects bound module -> module key unique, want analyze projects. simply a Set hold moduleKeys</technical_language>

Target:
public static void updateServerBinding(SonarQubeServer server, ConnectedSonarLintEngine engine, boolean background, boolean onlyProjects) { Project[] openProjects = ProjectManager.getInstance().getOpenProjects(); Map<String, List<Project>> projectsPerModule = new HashMap<>(); for (Project p : openProjects) { SonarLintProjectSettings projectSettings = SonarLintUtils.get(p, SonarLintProjectSettings.class); String moduleKey = projectSettings.getProjectKey(); if (projectSettings.isBindingEnabled() && server.getName().equals(projectSettings.getServerId()) && moduleKey != null) { List<Project> projects = projectsPerModule.computeIfAbsent(moduleKey, k -> new ArrayList<>()); projects.add(p); } } ServerUpdateTask task = new ServerUpdateTask(engine, server, projectsPerModule, onlyProjects); if (background) { ProgressManager.getInstance().run(task.asBackground()); } else { ProgressManager.getInstance().run(task.asModal()); } }
Source:
<code>public static synchronized SparkSession getSession() { String threadName = Thread.currentThread().getName(); if (!SpliceClient.isClient() && !threadName.startsWith("olap-worker-")) { throw new RuntimeException("Trying to get a SparkSession from outside the OlapServer"); } SparkSession result = sessions.get(); if (result == null) { <START> result = session.newSession(); <END> sessions.set(result); } return result; }</code><technical_language>Is session is initialized null getSession s called time</technical_language>

Target:
public static synchronized SparkSession getSession() { String threadName = Thread.currentThread().getName(); if (!SpliceClient.isClient() && !threadName.startsWith("olap-worker-")) { throw new RuntimeException("Trying to get a SparkSession from outside the OlapServer"); } SparkSession result = sessions.get(); if (result == null) { result = getSessionUnsafe().newSession(); sessions.set(result); } return result; }
Source:
<code>public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); config.validate(); if (!config.containsMacro("timeTable") && config.timeTable != null) { pipelineConfigurer.createDataset(config.timeTable, KeyValueTable.class, DatasetProperties.EMPTY); } if (config.getSchema() != null) { pipelineConfigurer.getStageConfigurer().setOutputSchema(config.getSchema()); } else { <START> pipelineConfigurer.getStageConfigurer().setOutputSchema(DEFAULT_SCHEMA); <END> } }</code><technical_language>This correct. For example, if schema is null format is avro, set output schema default schema, is wrong. setting actual output schema here. schema set in input format is set here</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); config.validate(); if (!config.containsMacro("timeTable") && config.timeTable != null) { pipelineConfigurer.createDataset(config.timeTable, KeyValueTable.class, DatasetProperties.EMPTY); } if (config.getSchema() != null) { pipelineConfigurer.getStageConfigurer().setOutputSchema(config.getSchema()); } else if ("text".equalsIgnoreCase(config.format)) { pipelineConfigurer.getStageConfigurer().setOutputSchema(PathTrackingInputFormat.getTextOutputSchema (config.pathField)); } else { pipelineConfigurer.getStageConfigurer().setOutputSchema(null); } }
Source:
<code>public void add(int index, E element) { throw new UnsupportedOperationException("No <START> add(index) in <END> " + this.getClass().getName()); }</code><technical_language>add(int, E)</technical_language>

Target:
public void add(int index, E element) { throw new UnsupportedOperationException("No add(int, E) in " + this.getClass().getName()); }
Source:
<code>public void newServerDetailsChanged(IProgressMonitor monitor) { try { getWorkingCopyDelegate(monitor).newServerDetailsChanged(monitor); } catch (Exception e) { if (Trace.SEVERE) { Trace.trace(Trace.STRING_SEVERE, "Error calling delegate setDefaultServerName() " + toString(), e); } <START> ServerUtil.setServerDefaultName(this); <END> } }</code><technical_language>This line moved line 691 getWorkingCopyDelegate().... line. wizard is supposed suggest default server name. If setServerDefaultName() is called exception case, proper default server name set default this introduce regression</technical_language>

Target:
public void newServerDetailsChanged(IProgressMonitor monitor) { try { getWorkingCopyDelegate(monitor).newServerDetailsChanged(monitor); } catch (Exception e) { if (Trace.SEVERE) { Trace.trace(Trace.STRING_SEVERE, "Error calling delegate newServerDetailsChanged() " + toString(), e); } } }
Source:
<code>public Void call() throws Exception { <START> mavenArtifactManagementService.store(repositoryPath, is); <END> return null; }</code><technical_language>@fuss86 need check exceptions here</technical_language>

Target:
public Exception call() throws Exception { try { mavenArtifactManagementService.store(repositoryPath, is); } catch (Exception ex) { return ex; } return null; }
Source:
<code>public void testServerSpanNoURLClientSpanUnavailable() throws RetryAttemptException { SpanCache spanCacheMock = Mockito.mock(SpanCache.class); NodeDetailsDeriver nodeDetailsDeriver = new NodeDetailsDeriver(spanCacheMock); Annotation sr = new Annotation(); sr.setValue("sr"); sr.setTimestamp(0); Annotation ss = new Annotation(); ss.setTimestamp(1000); ss.setValue("ss"); Span serverSpan = new Span(Collections.emptyList(), Arrays.asList(sr, ss)); serverSpan.setId("2"); serverSpan.setTraceId("1"); serverSpan.setTimestamp(0L); <START> serverSpan.setDuration(ss.getTimestamp() - sr.getTimestamp()); <END> Mockito.when(spanCacheMock.get(null, SpanUniqueIdGenerator.getClientId(serverSpan.getId()))) .thenReturn(null); nodeDetailsDeriver.processOneToOne(null, serverSpan); }</code><technical_language>timestamp duration is necessary</technical_language>

Target:
public void testServerSpanNoURLClientSpanUnavailable() throws RetryAttemptException { SpanCache spanCacheMock = Mockito.mock(SpanCache.class); NodeDetailsDeriver nodeDetailsDeriver = new NodeDetailsDeriver(spanCacheMock); Annotation sr = new Annotation(); sr.setValue("sr"); Annotation ss = new Annotation(); ss.setValue("ss"); Span serverSpan = new Span(Collections.emptyList(), Arrays.asList(sr, ss)); serverSpan.setId("2"); serverSpan.setTraceId("1"); Mockito.when(spanCacheMock.get(null, SpanUniqueIdGenerator.getClientId(serverSpan.getId()))) .thenReturn(null); nodeDetailsDeriver.processOneToOne(null, serverSpan); }
Source:
<code>public void testCheckThreadLocalLeaks() throws Exception { final ConfigurationBuilder builder = new ConfigurationBuilder(); builder .eviction().strategy(EvictionStrategy.LRU).maxEntries(4096) .locking().concurrencyLevel(2048) .loaders().passivation(false).shared(false).preload(true) .addFileCacheStore().location(tmpDirectory) .fsyncMode(FileCacheStoreConfigurationBuilder.FsyncMode.PER_WRITE); Future<Map<String, Map<ThreadLocal<?>, Object>>> result = fork( new Callable<Map<String, Map<ThreadLocal<?>, Object>>>() { @Override public Map<String, Map<ThreadLocal<?>, Object>> call() throws Exception { EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(builder); try { Cache<Object, Object> c = cm.getCache(); <START> c.put("key", "value"); <END> } finally { TestingUtil.killCacheManagers(cm); Set<Thread> threadSet = Collections.singleton(Thread.currentThread()); Map<String, Map<ThreadLocal<?>, Object>> allThreadLocals = new HashMap<String, Map<ThreadLocal<?>, Object>>(); for (Thread thread : threadSet) { Map<ThreadLocal<?>, Object> threadLocalLeaks = findThreadLocalLeaks(thread); if (threadLocalLeaks != null && !threadLocalLeaks.isEmpty()) allThreadLocals.put(thread.getName(), threadLocalLeaks); } return allThreadLocals; } } }); Map<String, Map<ThreadLocal<?>, Object>> allThreadLocals = result.get(30, TimeUnit.SECONDS); if (!allThreadLocals.isEmpty()) throw new IllegalStateException("Thread locals still present: " + allThreadLocals); }</code><technical_language>test call put 2 threads, thread locals cleared - in thread calling stop</technical_language>

Target:
public void testCheckThreadLocalLeaks() throws Exception { final ConfigurationBuilder builder = new ConfigurationBuilder(); builder .eviction().strategy(EvictionStrategy.LRU).maxEntries(4096) .locking().concurrencyLevel(2048) .loaders().passivation(false).shared(false).preload(true) .addFileCacheStore().location(tmpDirectory) .fsyncMode(FileCacheStoreConfigurationBuilder.FsyncMode.PER_WRITE); Future<Map<String, Map<ThreadLocal<?>, Object>>> result = fork( new Callable<Map<String, Map<ThreadLocal<?>, Object>>>() { @Override public Map<String, Map<ThreadLocal<?>, Object>> call() throws Exception { Thread forkedThread = doStuffWithCache(builder); beforeGC(); System.gc(); Thread.sleep(500); System.gc(); afterGC(); List<Thread> threadSet = Arrays.asList(Thread.currentThread(), forkedThread); Map<String, Map<ThreadLocal<?>, Object>> allThreadLocals = new HashMap<String, Map<ThreadLocal<?>, Object>>(); for (Thread thread : threadSet) { Map<ThreadLocal<?>, Object> threadLocalLeaks = findThreadLocalLeaks(thread); if (threadLocalLeaks != null && !threadLocalLeaks.isEmpty()) allThreadLocals.put(thread.getName(), threadLocalLeaks); } return allThreadLocals; } }); Map<String, Map<ThreadLocal<?>, Object>> allThreadLocals = result.get(30, TimeUnit.SECONDS); if (!allThreadLocals.isEmpty()) throw new IllegalStateException("Thread locals still present: " + allThreadLocals); }
Source:
<code>private EntityNameResolver createEntityNamesResolver(MediaType mediaType) { if (mediaType.match(APPLICATION_PROTOSTREAM)) { return new ProtobufEntityNameResolver(serCtx); } else { ClassLoader classLoader = cr.getGlobalComponentRegistry().getComponent(ClassLoader.class); ReflectionEntityNamesResolver reflectionEntityNamesResolver = new ReflectionEntityNamesResolver(classLoader); return reflectionEntityNamesResolver; } <START> } <END></code><technical_language>is this longer necessary</technical_language>

Target:
private EntityNameResolver createEntityNamesResolver(MediaType mediaType) { if (mediaType.match(APPLICATION_PROTOSTREAM)) { return new ProtobufEntityNameResolver(serCtx); } else { ClassLoader classLoader = cr.getGlobalComponentRegistry().getComponent(ClassLoader.class); ReflectionEntityNamesResolver reflectionEntityNamesResolver = new ReflectionEntityNamesResolver(classLoader); if (searchMapping != null) { QueryInterceptor queryInterceptor = cr.getComponent(QueryInterceptor.class); Map<String, Class<?>> indexedEntities = queryInterceptor.indexedEntities(); return name -> { Class<?> c = indexedEntities.get(name); if (c == null) { c = reflectionEntityNamesResolver.resolve(name); } return c; }; } return reflectionEntityNamesResolver; } }
Source:
<code>protected void executeCommand() { int selectedId = 1; <START> List<Integer> map = LinqUtils.foreach(vds_spm_id_mapList, new Function<vds_spm_id_map, Integer>() { <END> @Override public Integer eval(vds_spm_id_map vds_spm_id_map) { return vds_spm_id_map.getvds_spm_id(); } }); Collections.sort(map); for (int id : map) { if (selectedId == id) { selectedId++; } else { break; } } vds_spm_id_map newMap = new vds_spm_id_map(getVds().getstorage_pool_id(), getVdsId(), selectedId); DbFacade.getInstance().getVdsSpmIdMapDao().save(newMap); if (getParameters().isCompensationEnabled()) { getCompensationContext().snapshotNewEntity(newMap); getCompensationContext().stateChanged(); } setSucceeded(true); }</code><technical_language>bad usage name of variable. confusing read this. "map" a type of "List" Try avoid LinqUtils, get rid of this</technical_language>

Target:
protected void executeCommand() { int selectedId = 1; List<Integer> list = LinqUtils.foreach(vds_spm_id_mapList, new Function<vds_spm_id_map, Integer>() { @Override public Integer eval(vds_spm_id_map vds_spm_id_map) { return vds_spm_id_map.getvds_spm_id(); } }); Collections.sort(list); for (int id : list) { if (selectedId == id) { selectedId++; } else { break; } } vds_spm_id_map newMap = new vds_spm_id_map(getVds().getstorage_pool_id(), getVdsId(), selectedId); DbFacade.getInstance().getVdsSpmIdMapDao().save(newMap); if (getParameters().isCompensationEnabled()) { getCompensationContext().snapshotNewEntity(newMap); getCompensationContext().stateChanged(); } setSucceeded(true); }
Source:
<code>public StorageQueryExecutor(final ExecutionGraphNode node) { super(node); <START> if (node.getDefaultConfig() == null) { <END> throw new IllegalArgumentException("Default config cannot be null."); } if (node.graph() == null) { throw new IllegalStateException("Execution graph cannot be null."); } if (Strings.isNullOrEmpty(((Config) node.getDefaultConfig()).getStorageId())) { throw new IllegalArgumentException("Default storage ID must be non-empty."); } data_store = (TimeSeriesDataStore) node.graph().tsdb().getRegistry() .getPlugin(TimeSeriesDataStore.class, ((Config) node.getDefaultConfig()).getStorageId()); if (data_store == null) { throw new IllegalStateException("No data store found for ID " + ((Config) node.getDefaultConfig()).getStorageId()); } }</code><technical_language>I node.* done in super class constructor</technical_language>

Target:
public StorageQueryExecutor(final ExecutionGraphNode node) { super(node); if (Strings.isNullOrEmpty(((Config) node.getDefaultConfig()).getStorageId())) { throw new IllegalArgumentException("Default storage ID must be non-empty."); } try { data_store = (TimeSeriesDataStore) node.graph().tsdb().getRegistry() .getPlugin(TimeSeriesDataStore.class, ((Config) node.getDefaultConfig()).getStorageId()); if (data_store == null) { throw new IllegalStateException("No data store found for ID " + ((Config) node.getDefaultConfig()).getStorageId()); } } catch (RuntimeException e) { throw new RuntimeException("Unexpected exception initializing " + "storage query executor", e); } }
Source:
<code>private boolean isDepositRecord(Resource bxc3Resc) { <START> PIDs.get(bxc3Resc.toString().toLowerCase()); <END> return bxc3Resc.hasProperty(FedoraProperty.hasModel.getProperty(), ContentModel.DEPOSIT_RECORD.getResource()); }</code><technical_language>this line removed</technical_language>

Target:
private boolean isDepositRecord(Resource bxc3Resc) { return bxc3Resc.hasProperty(FedoraProperty.hasModel.getProperty(), ContentModel.DEPOSIT_RECORD.getResource()); }
Source:
<code>private boolean isMissingData(List<Address> newMembers, List<Address> oldMembers) { int missingMembers = 0; for (Address a : oldMembers) if (!newMembers.contains(a)) missingMembers++; <START> Configuration cacheConfiguration = cache.getCacheConfiguration(); <END> int numOwners = cacheConfiguration.clustering().hash().numOwners(); return missingMembers >= numOwners; }</code><technical_language>a SecurityAction</technical_language>

Target:
private boolean isMissingData(List<Address> newMembers, List<Address> oldMembers) { int missingMembers = 0; for (Address a : oldMembers) if (!newMembers.contains(a)) missingMembers++; int numOwners = configuration.clustering().hash().numOwners(); return missingMembers >= numOwners; }
Source:
<code>public TabletFile(String metadataEntry) { this.metadataPath = new Path(metadataEntry); <START> this.metadataEntry = metadataEntry; <END> this.fileName = metadataPath.getName(); Path tabletDirPath = metadataPath.getParent(); this.tabletDir = tabletDirPath.getName(); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(tabletDir); Path tableIdPath = tabletDirPath.getParent(); this.tableId = TableId.of(tableIdPath.getName()); Path volumePath = TabletFileUtil.getVolumeFromFullPath(metadataPath, "tables"); TabletFileUtil.validateVolume(volumePath); this.volume = volumePath.toString(); }</code><technical_language>want fail fast: suggestion this.metadataEntry = Objects.requireNonNull(metadataEntry); This line assignment for metadataPath</technical_language>

Target:
public TabletFile(String metadataEntry) { this.metadataEntry = Objects.requireNonNull(metadataEntry); String errorMsg = " is missing from tablet file metadata entry: " + metadataEntry; Path metaPath = new Path(metadataEntry); this.fileName = metaPath.getName(); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(fileName); Path tabletDirPath = Objects.requireNonNull(metaPath.getParent(), "Tablet dir" + errorMsg); this.tabletDir = tabletDirPath.getName(); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(tabletDir); Path tableIdPath = Objects.requireNonNull(tabletDirPath.getParent(), "Table ID" + errorMsg); this.tableId = TableId.of(tableIdPath.getName()); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(tableId.canonical()); Path volumePath = Objects.requireNonNull( TabletFileUtil.getVolumeFromFullPath(metaPath, "tables"), "Volume" + errorMsg); this.volume = volumePath.toString(); this.suffix = tableId.canonical() + "/" + tabletDir + "/" + fileName; }
Source:
<code>private void write_int_LSB_0(final int value, final int nofBitsToWrite) { if (nofBitsToWrite == 0) return; if (nofBitsToWrite < 1 || nofBitsToWrite > 32) throw new RuntimeIOException("Expecting 1 to 32 bits."); <START> if (nofBitsToWrite <= 8) <END> write((byte) value, nofBitsToWrite); else { for (int i = nofBitsToWrite - 8; i >= 0; i -= 8) { final byte v = (byte) (value >>> i); writeByte(v); } if (nofBitsToWrite % 8 != 0) { final byte v = (byte) value; write(v, nofBitsToWrite % 8); } } }</code><technical_language>add while</technical_language>

Target:
void write_int_LSB_0(final int value, final int nofBitsToWrite) { if (nofBitsToWrite == 0) return; if (nofBitsToWrite < 1 || nofBitsToWrite > 32) throw new RuntimeIOException("Expecting 1 to 32 bits."); if (nofBitsToWrite <= 8) write((byte) value, nofBitsToWrite); else { for (int i = nofBitsToWrite - 8; i >= 0; i -= 8) { final byte v = (byte) (value >>> i); writeByte(v); } if (nofBitsToWrite % 8 != 0) { final byte v = (byte) value; write(v, nofBitsToWrite % 8); } } }
Source:
<code>public CRAMFileReader(final File file, final InputStream is, final ReferenceSource referenceSource) { if (file == null && is == null) throw new NullPointerException( <START> "Either file or input stream is required."); <END> this.file = file; this.is = is; this.referenceSource = referenceSource; getIterator(); }</code><technical_language>throwing a NPE? IllegalArgumentException more informative</technical_language>

Target:
public CRAMFileReader(final File file, final InputStream is, final ReferenceSource referenceSource) { if (file == null && is == null) throw new IllegalArgumentException( "Either file or input stream is required."); this.file = file; this.is = is; this.referenceSource = referenceSource; getIterator(); }
Source:
<code>public MultiProvider(final HostProviderFactory factory, final Environment environment, @Assisted final Configuration configuration) { final Set<String> entries = configuration.subKeys(); final Config underlying = configuration.underlying(); for (String key : entries) { if (underlying.getValue(key).valueType() == ConfigValueType.OBJECT) { if (!underlying.hasPath(key + ".type")) { <START> LOGGER.warn() <END> .setMessage("Expected type for host provider") .addData("key", key) .log(); } final Configuration subConfig = configuration.getConfig(key).withFallback(configuration); final Props subProps = factory.create(subConfig, ConfigurationHelper.<Actor>getType(environment, subConfig, "type")); context().actorOf(subProps); } } }</code><technical_language>this warn continue? a terminal condition</technical_language>

Target:
public MultiProvider(final HostProviderFactory factory, final Environment environment, @Assisted final Configuration configuration) { final Set<String> entries = configuration.subKeys(); final Config underlying = configuration.underlying(); for (String key : entries) { if (underlying.getValue(key).valueType() == ConfigValueType.OBJECT) { if (!underlying.hasPath(key + ".type")) { LOGGER.warn() .setMessage("Expected type for host provider") .addData("key", key) .log(); continue; } final Configuration subConfig = configuration.getConfig(key).withFallback(configuration); final Props subProps = factory.create(subConfig, ConfigurationHelper.getType(environment, subConfig, "type")); context().actorOf(subProps); } } }
Source:
<code>public void stripsXml() throws Exception { final StringWriter out = new StringWriter(); final BufferedWriter writer = new BufferedWriter(out); writer.write("<a>"); writer.newLine(); writer.write("<b/>"); writer.newLine(); writer.write("</a>"); writer.close(); final String actual = out.getBuffer().toString(); MatcherAssert.assertThat( XSLDocument.STRIP.transform( new XMLDocument("<a> <b/> </a>") ).toString(), <START> Matchers.containsString(actual) <END> ); }</code><technical_language>maybe, inline actual way: java Matchers.containsString( new StringBuilder() .append("<a>") .append(System.lineSeparator()) .append("<b/>") .append(System.lineSeparator()) .append("</a>") .toString() ); do think</technical_language>

Target:
public void stripsXml() throws Exception { MatcherAssert.assertThat( XSLDocument.STRIP.transform( new XMLDocument("<a> <b/> </a>") ).toString(), Matchers.containsString( new StringBuilder() .append("<a>") .append(System.lineSeparator()) .append("<b/>") .append(System.lineSeparator()) .append("</a>") .toString() ) ); }
Source:
<code>protected void doShutdown() { boolean waitForConsumers = false; synchronized (this.consumersMonitor) { if (this.started || this.aborted) { actualShutDown(); waitForConsumers = true; } } if (waitForConsumers) { try { if (this.cancellationLock.await(getShutdownTimeout(), TimeUnit.MILLISECONDS)) { this.logger.info("Successfully waited for consumers to finish."); } else { this.logger.info("Consumers not finished."); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); this.logger.warn("Interrupted waiting for consumers. Continuing with shutdown."); } finally { this.startedLatch = new CountDownLatch(1); this.started = false; this.aborted = false; this.hasStopped = true; } } if (!this.taskSchedulerSet && this.taskScheduler != null) { ((ThreadPoolTaskScheduler) this.taskScheduler).shutdown(); <START> this.taskScheduler = null; <END> } }</code><technical_language>Well, squash GH changes notify email. I missed this change :cry:</technical_language>

Target:
protected void doShutdown() { boolean waitForConsumers = false; synchronized (this.consumersMonitor) { if (this.started || this.aborted) { actualShutDown(); waitForConsumers = true; } } if (waitForConsumers) { try { if (this.cancellationLock.await(getShutdownTimeout(), TimeUnit.MILLISECONDS)) { this.logger.info("Successfully waited for consumers to finish."); } else { this.logger.info("Consumers not finished."); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); this.logger.warn("Interrupted waiting for consumers. Continuing with shutdown."); } finally { this.startedLatch = new CountDownLatch(1); this.started = false; this.aborted = false; this.hasStopped = true; } } }
Source:
<code>public Assignment getAssignment() throws ParseException { String author; Date date; WebElement submit = getDriver().findElement(By.cssSelector("a[href^=\"deliveries\"]")); final List<WebElement> elements = getDriver().findElements(By.tagName("dd")); <START> author = elements.get(0).getText(); <END> date = new SimpleDateFormat("EEEE dd MMMM yyyy k:m", Locale.US).parse(elements.get(1).getText()); return new Assignment(author, date, submit); }</code><technical_language>Please initialize variable well. is a non-constant variable</technical_language>

Target:
public Assignment getAssignment() throws ParseException { return new Assignment(getDriver().findElement(By.cssSelector("a[href^=\"deliveries\"]"))); }
Source:
<code>private void handleRegularAccount() { Account selectedAccount = Preferences.getPreferences(this).getAccount(selectedAccountUuid); <START> unreadAccount.setSummary(selectedAccount.getName()); <END> unreadFolderEnabled.setEnabled(true); unreadFolder.setEnabled(true); }</code><technical_language>This displays sender name instead of account name</technical_language>

Target:
private void handleRegularAccount() { Account selectedAccount = Preferences.getPreferences(this).getAccount(selectedAccountUuid); String summary = selectedAccount.getDescription(); if (summary == null || summary.isEmpty()) { summary = selectedAccount.getEmail(); } unreadAccount.setSummary(summary); unreadFolderEnabled.setEnabled(true); unreadFolder.setEnabled(true); }
Source:
<code>public void newValue(Observation observation, LwM2mNode value) { Client client = clientRegistry.findByRegistrationId(observation.getRegistrationId()); if (isQueueMode(client.getBindingMode()) && clientStatusTracker.setClientReachable(client.getEndpoint()) && clientStatusTracker.startClientReceiving(client.getEndpoint())) { <START> LOG.debug("Notify from {}. Sending queued requests.", client.getEndpoint()); <END> processingExecutor.execute(newRequestSendingTask(client.getEndpoint())); } }</code><technical_language>isDebugEnabled</technical_language>

Target:
public void newValue(Observation observation, LwM2mNode value) { Client client = clientRegistry.findByRegistrationId(observation.getRegistrationId()); if (isQueueMode(client.getBindingMode()) && clientStatusTracker.setClientReachable(client.getEndpoint()) && clientStatusTracker.startClientReceiving(client.getEndpoint())) { if(LOG.isDebugEnabled()) { LOG.debug("Notify from {}. Sending queued requests.", client.getEndpoint()); } processingExecutor.execute(newRequestSendingTask(client.getEndpoint())); } }
Source:
<code>public void insertNoPrimaryKey(long reps) { AllTypes allTypes = new AllTypes(); realm.beginTransaction(); for (long i = 0; i < reps; i++) { realm.insert(allTypes); } <START> realm.commitTransaction(); <END> }</code><technical_language>Note this method is biggest contributor this benchmark. If possible, I try move beginTransaction/commitTransaction/cancelTransaction() this method</technical_language>

Target:
public void insertNoPrimaryKey(long reps) { AllTypes allTypes = new AllTypes(); for (long i = 0; i < reps; i++) { realm.insert(allTypes); } }
Source:
<code>public void guiClose() { Keyboard.enableRepeatEvents(false); <START> getBaseScreen().initGui(); <END> ClientConfiguration config = LogisticsPipes.getClientPlayerConfig(); try { config.setRenderPipeDistance(renderDistance.getInteger()); config.setRenderPipeContentDistance(contentRenderDistance.getInteger()); } catch (Exception e) { e.printStackTrace(); } MainProxy.sendPacketToServer( PacketHandler.getPacket(PlayerConfigToServerPacket.class).setConfig(config)); }</code><technical_language>This (getBaseScreen().initGui();) done manually, in base screen class time a subscreen closes</technical_language>

Target:
public void guiClose() { ClientConfiguration config = LogisticsPipes.getClientPlayerConfig(); try { config.setRenderPipeDistance(renderDistance.getInteger()); config.setRenderPipeContentDistance(contentRenderDistance.getInteger()); } catch (Exception e) { e.printStackTrace(); } MainProxy.sendPacketToServer( PacketHandler.getPacket(PlayerConfigToServerPacket.class).setConfig(config)); }
Source:
<code>public synchronized int read(final byte[] b, final int off, final int len) throws IOException { if (b != null) { LOG.debug("read requested b.length = offset = len = {}", b.length, off, len); } else { LOG.debug("read requested b = null offset = len = {}", off, len); } int currentOff = off; int currentLen = len; int lastReadBytes; int totalReadBytes = 0; if (streamStatistics != null) { streamStatistics.readOperationStarted(off, len); } incrementReadOps(); do { <START> lastReadBytes = readToUserBuffer(b, currentOff, currentLen); <END> if (lastReadBytes > 0) { currentOff += lastReadBytes; currentLen -= lastReadBytes; totalReadBytes += lastReadBytes; } if (currentLen <= 0 || currentLen > b.length - currentOff) { break; } } while (lastReadBytes > 0); return totalReadBytes > 0 ? totalReadBytes : lastReadBytes; }</code><technical_language>change? Please revert if require</technical_language>

Target:
public synchronized int read(final byte[] b, final int off, final int len) throws IOException { if (b != null) { LOG.debug("read requested b.length = offset = len = {}", b.length, off, len); } else { LOG.debug("read requested b = null offset = len = {}", off, len); } int currentOff = off; int currentLen = len; int lastReadBytes; int totalReadBytes = 0; if (streamStatistics != null) { streamStatistics.readOperationStarted(off, len); } incrementReadOps(); do { if (shouldReadFully()) { lastReadBytes = readFileCompletely(b, currentOff, currentLen); } else if (shouldReadLastBlock()) { lastReadBytes = readLastBlock(b, currentOff, currentLen); } else { lastReadBytes = readOneBlock(b, currentOff, currentLen); } if (lastReadBytes > 0) { currentOff += lastReadBytes; currentLen -= lastReadBytes; totalReadBytes += lastReadBytes; } if (currentLen <= 0 || currentLen > b.length - currentOff) { break; } } while (lastReadBytes > 0); return totalReadBytes > 0 ? totalReadBytes : lastReadBytes; }
Source:
<code>private int getCurrValidWorkers(Collection<ImmutableWorkerInfo> workers) { final Predicate<ImmutableWorkerInfo> isValidWorker = ProvisioningUtil.createValidWorkerPredicate(config); final int currValidWorkers = Collections2.filter(workers, isValidWorker).size(); <START> log.info("Current valid workers: %d", currValidWorkers); <END> return currValidWorkers; }</code><technical_language>suggest debug level</technical_language>

Target:
private int getCurrValidWorkers(Collection<ImmutableWorkerInfo> workers) { final Predicate<ImmutableWorkerInfo> isValidWorker = ProvisioningUtil.createValidWorkerPredicate(config); final int currValidWorkers = Collections2.filter(workers, isValidWorker).size(); log.debug("Current valid workers: %d", currValidWorkers); return currValidWorkers; }
Source:
<code>private Map<String, String> getSegmentsMetadataFromServer(String tableNameWithType) throws InvalidConfigException, IOException { <START> LOGGER.trace("Inside getSegmentsMetadataFromServer() entry"); <END> TableMetadataReader tableMetadataReader = new TableMetadataReader(_executor, _connectionManager, _pinotHelixResourceManager); LOGGER.trace("Inside getSegmentsMetadataFromServer() exit"); return tableMetadataReader.getSegmentsMetadata(tableNameWithType, _controllerConf.getServerAdminRequestTimeoutSeconds() * 1000); }</code><technical_language>remove trace logs please</technical_language>

Target:
private JsonNode getSegmentsMetadataFromServer(String tableNameWithType) throws InvalidConfigException, IOException { TableMetadataReader tableMetadataReader = new TableMetadataReader(_executor, _connectionManager, _pinotHelixResourceManager); return tableMetadataReader.getSegmentsMetadata(tableNameWithType, _controllerConf.getServerAdminRequestTimeoutSeconds() * 1000); }
Source:
<code>public SubscribedRepository(PubSubConfig.Subscriber s) throws IOException { remote = s.getRemote(); <START> repository = new FileRepository(s.getDirectory()); <END> specs = s.getSubscribeSpecs(); name = s.getName(); }</code><technical_language>This is ok for now, want tie this permanently a FileRepository</technical_language>

Target:
public SubscribedRepository(PubSubConfig.Subscriber s) throws IOException { this(s, new FileRepository(s.getDirectory())); }
Source:
<code>public String getValue() { return String.format( Locale.ROOT, "%d years %d mons %d days %d hours %d mins %f secs", years, months, days, hours, minutes, <START> wholeSeconds + microSeconds / 1e6d <END> ); }</code><technical_language>started TimeUnit.* convert time units. a bit more readable</technical_language>

Target:
public String getValue() { return String.format( Locale.ROOT, "%d years %d mons %d days %d hours %d mins %s secs", years, months, days, hours, minutes, new DecimalFormat("0.0#####").format(getSeconds()) ); }
Source:
<code>public ChatComponent addExtra(String string) { $lock.writeLock().lock(); <START> this.extra.add(ChatComponent.create().setText(string)); <END> $lock.writeLock().unlock(); return this; }</code><technical_language>THREAD-SAFETY need mind (lol), thread safe collection lock. Please try-finally idiom explicit locks well</technical_language>

Target:
public ChatComponent addExtra(String string) { this.extra.add(ChatComponent.create().setText(string)); return this; }
Source:
<code>public void createProfiles() { List<ExtensionEntry> authnExtensions = ConfigurationLoader.getInstance().getExtensionsByService(AUTHN_SERVICE); <START> List<ExtensionEntry> authzExtensions = ConfigurationLoader.getInstance().getExtensionsByService(AUTHZ_SERVICE); <END> Map<String, ExtensionEntry> authnMap = new HashMap<>(); Map<String, ExtensionEntry> authzMap = new HashMap<>(); if (authnExtensions != null) { for (ExtensionEntry entry : authnExtensions) { authnMap.put(entry.getConfig().getString(AUTHN_PROFILE), entry); } } if (authzExtensions != null) { for (ExtensionEntry entry : authzExtensions) { authzMap.put(entry.getConfig().getString(AUTHZ_PROFILE), entry); } } for (Map.Entry<String, ExtensionEntry> mapEntry : authnMap.entrySet()) { ExtensionEntry authzEntry = authzMap.get(mapEntry.getKey()); if (authzEntry != null) { Directory directory = DirectoryManager.getInstance().parseDirectory(authzEntry.getConfig()); Authenticator authenticator = AuthenticatorManager.getInstance().parseAuthenticator(mapEntry.getValue().getConfig()); AuthenticationProfile profile = new AuthenticationProfile(mapEntry.getKey(), authenticator, directory); profiles.put(mapEntry.getKey(), profile); } } }</code><technical_language>need... acquire name, authn is referring to</technical_language>

Target:
public void createProfiles() throws ConfigurationException { List<ExtensionEntry> authnExtensions = ConfigurationLoader.getInstance().getExtensionsByService(AUTHN_SERVICE); for (ExtensionEntry authnExtension: authnExtensions) { String pluginName = authnExtension.getConfig().getString(AUTHN_AUTHZ_PLUGIN); ExtensionEntry authzExtension = ConfigurationLoader.getInstance().getExtensionByName(pluginName); if (authzExtension == null) { throw new ConfigurationException("The authentication extension " + authnExtension.getName() + " does not have a matching authorization extension"); } Directory directory = DirectoryManager.getInstance().parseDirectory(authzExtension.getConfig()); Authenticator authenticator = AuthenticatorManager.getInstance().parseAuthenticator(authzExtension.getConfig()); if (directory == null) { throw new ConfigurationException("No directory could be obtained for authorization plugin " + authzExtension.getName()); } if (authenticator == null) { throw new ConfigurationException("No authenticator could be obtained for authentication plugin " + authnExtension.getName()); } String profileName = authnExtension.getConfig().getString(AUTHN_PROFILE); if (profileName == null) { throw new ConfigurationException("Profile name could not be obtained from configuration of authentication plugin " + authnExtension.getName()); } AuthenticationProfile profile = new AuthenticationProfile(profileName, authenticator, directory); profiles.put(profileName, profile); } }
Source:
<code>public void writeHeaderOnlyIfNotPresentContentSecurityPolicyHeader(){ this.response = spy(this.response); <START> doReturn(true).when(response).containsHeader(CONTENT_SECURITY_POLICY_HEADER); <END> this.writer.writeHeaders(this.request, this.response); verify(this.response, times(1)).containsHeader(anyString()); verify(this.response, never()).setHeader(anyString(), anyString()); verifyNoMoreInteractions(this.response); }</code><technical_language>tests a bit brittle depend writer is verifying existence of header. If tests did: java String = new String("value"); this.response.setHeader(CONTENT_SECURITY_POLICY_HEADER, value); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(CONTENT_SECURITY_POLICY_HEADER)).isSameAs(value); verify of writer implemented check</technical_language>

Target:
public void writeHeaderOnlyIfNotPresentContentSecurityPolicyHeader(){ String value = new String("value"); this.response.setHeader(CONTENT_SECURITY_POLICY_HEADER, value); this.writer.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(CONTENT_SECURITY_POLICY_HEADER)).isSameAs(value); }
Source:
<code>public String toString() { ToStringHelper stringHelper = toStringHelper(this) .add("equiCriteria", this.equiCriteria); <START> if (filter.isPresent()) { <END> stringHelper.add("filter", filter); } return stringHelper.toString(); }</code><technical_language>do this fluently ToStringHelper.omitNulls(). I readability is better</technical_language>

Target:
public String toString() { return toStringHelper(this) .omitNullValues() .add("equiCriteria", equiCriteria) .add("filter", filter.orElse(null)) .toString(); }
Source:
<code>public void BaudRate(int baudRate) { <START> this.baudRate = baudRate; <END> mPhysicaloid.setBaudrate(baudRate); Log.d(LOG_TAG, "Baud Rate: " + baudRate); }</code><technical_language>purpose of storing this if read? curious chose a function a property setter/getter</technical_language>

Target:
public void BaudRate(int baudRate) { this.baudRate = baudRate; Log.d(LOG_TAG, "Baud Rate: " + baudRate); if (mPhysicaloid != null) mPhysicaloid.setBaudrate(baudRate); else Log.w(LOG_TAG, "Could not set Serial Baud Rate to " + baudRate + ". Just saved, not applied to serial! Maybe you forgot to initialize it?"); }
Source:
<code>public Response getDeviceOrganizationStateById(@PathParam("deviceId") String deviceId) { if (deviceId.length() <= 0) { String errorMessage = "The parameter of the device organization ID is empty."; return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); } <START> int result; <END> DeviceOrganizationProviderService dops = new DeviceOrganizationProviderServiceImpl(); try { result = dops.getDeviceOrganizationStateById(deviceId); if (result == -1) { String msg = "Device with ID: " + deviceId + " not found."; log.error(msg); return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } return Response.status(Response.Status.OK).entity(result).build(); } catch (DeviceOrganizationException e) { String msg = "Error occurred while retrieving state of device with ID:" + deviceId + " to Device Organization "; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (InvalidConfigurationException e) { log.error("failed to add operation", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } }</code><technical_language>define result try-catch block. This allow compiler optimizations</technical_language>

Target:
public Response getDeviceOrganizationStateById(@PathParam("deviceId") String deviceId) { if (deviceId.isEmpty()) { String errorMessage = "The parameter of the device organization ID is empty."; return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); } int result; DeviceOrganizationProviderService dops = new DeviceOrganizationProviderServiceImpl(); try { result = dops.getDeviceOrganizationStateById(deviceId); if (result == -1) { String msg = "Device with ID: " + deviceId + " not found."; if (log.isDebugEnabled()) { log.debug(msg); } return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); } return Response.status(Response.Status.OK).entity(result).build(); } catch (DeviceOrganizationException e) { String msg = "Error occurred while retrieving state of device with ID:" + deviceId + " to Device " + "Organization "; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (InvalidConfigurationException e) { String msg = "failed to add operation"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } }
Source:
<code>public int hashCode() { return <START> Objects.hash(type, path, <END> localLocation); }</code><technical_language>here. Instead of adding 3 numbers code creates array, boxing etc. is optimization in style in performance</technical_language>

Target:
public int hashCode() { return type + path.hashCode() + localLocation.hashCode(); }
Source:
<code>public static Enum<EnumTarget> getForClass(Class<? extends Target> clazz) { return Arrays.stream(values()).filter(enumTarget -> enumTarget.clazz == clazz).findFirst().orElse(null); <START> } <END></code><technical_language>Return this enum Target instance</technical_language>

Target:
public static EnumTarget getForClass(Class<? extends Target> clazz) { return Arrays.stream(values()).filter(enumTarget -> enumTarget.clazz == clazz).findFirst().orElse(null); }