auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void nailMain(NGContext context) { context.out.println(); context.out.println(" context.getCommand(): " + context.getCommand()); context.out.println(" context.getInetAddress(): " + context.getInetAddress()); context.out.println(" context.getPort(): " + context.getPort()); context.out.println("context.getWorkingDirectory(): " + context.getWorkingDirectory()); context.out.println(" context.getFileSeparator(): " + context.getFileSeparator()); context.out.println(" context.getPathSeparator(): " + context.getPathSeparator()); context.out.println("\ncontext.getArgs():"); for (int i = 0; i < context.getArgs().length; ++i) { context.out.println(" args[" + i + "]=" + context.getArgs()[i]); } context.out.println("\ncontext.getEnv():"); <START> TreeSet keys = new TreeSet(context.getEnv().keySet()); <END> for (Iterator i = keys.iterator(); i.hasNext(); ) { String key = (String) i.next(); context.out.println(" env[\"" + key + "\"]=" + context.getEnv().getProperty(key)); } }</code><technical_language>generics</technical_language>

Target:
public static void nailMain(NGContext context) { context.out.println(); context.out.println(" context.getCommand(): " + context.getCommand()); context.out.println(" context.getInetAddress(): " + context.getInetAddress()); context.out.println(" context.getPort(): " + context.getPort()); context.out.println("context.getWorkingDirectory(): " + context.getWorkingDirectory()); context.out.println(" context.getFileSeparator(): " + context.getFileSeparator()); context.out.println(" context.getPathSeparator(): " + context.getPathSeparator()); context.out.println("\ncontext.getArgs():"); for (int i = 0; i < context.getArgs().length; ++i) { context.out.println(" args[" + i + "]=" + context.getArgs()[i]); } context.out.println("\ncontext.getEnv():"); TreeSet keys = new TreeSet(context.getEnv().keySet()); for (Object okey : keys) { String key = (String) okey; context.out.println(" env[\"" + key + "\"]=" + context.getEnv().getProperty(key)); } }
Source:
<code>public void startIndexPopulation( IndexPopulationJob job ) { populationJobs.add( job ); <START> scheduler.schedule( indexPopulation, new IndexPopulationJobWrapper( job, this ) ); <END> }</code><technical_language>I is a race in IndexingService createIndexes shutdown population jobs added IndexPopulationJobController.stop is called. Result leak population jobs. this is guarded for higher in stack. I this guarded for explicitly. in IndexingService</technical_language>

Target:
void startIndexPopulation( IndexPopulationJob job ) { populationJobs.add( job ); scheduler.schedule( indexPopulation, new IndexPopulationJobWrapper( job, this ) ); }
Source:
<code>public String getCloneBaseUrlOrHost() { <START> return StringUtils.isEmpty(cloneBaseUrl) ? host : cloneBaseUrl; <END> }</code><technical_language>Strings.isNullOrEmpty (this guava Strings class is imported here)</technical_language>

Target:
public String getCloneBaseUrlOrHost() { return Strings.isNullOrEmpty(cloneBaseUrl) ? host : cloneBaseUrl; }
Source:
<code>private VariantMetricInformation updateVarianMetricById(PushMessageInformation pmi, final VariantMetricInformation vmi) { return pmi.getVariantInformations().stream() .filter(v -> vmi.getVariantID().equals(v.getVariantID())) .findFirst() <START> .orElse(null); <END> }</code><technical_language>If throwing illegal state exception more consider making return type Optional<VariantMetricInformation></technical_language>

Target:
private VariantMetricInformation updateVarianMetricById(PushMessageInformation pmi, final VariantMetricInformation vmi) { return pmi.getVariantInformations().stream() .filter(v -> vmi.getVariantID().equals(v.getVariantID())) .findFirst() .orElseThrow(() -> new IllegalArgumentException("No variant metric found for given id") ); }
Source:
<code>public void testWithInvalidToken(String opHost, String redirectUrl) throws Exception { DevelopersApi client = Tester.api(); RegisterSiteResponseData setupData = RegisterSiteTest.registerSite(client, opHost, redirectUrl); GetClientTokenResponseData tokenResponse = getGetClientTokenResponseData(opHost, client, setupData); assertNotNull(tokenResponse); final String accessToken = tokenResponse.getAccessToken(); final String validHeader = "Bearer " + accessToken; final String invalidToken = accessToken.concat("BlahBlah"); IntrospectAccessTokenParams iatParams = new IntrospectAccessTokenParams(); iatParams.setAccessToken(invalidToken); iatParams.setOxdId(setupData.getOxdId()); ApiResponse<IntrospectAccessTokenResponse> apiIatResponse = client.introspectAccessTokenWithHttpInfo(validHeader, iatParams); assertEquals(apiIatResponse.getStatusCode(), 200); assertNotNull(apiIatResponse.getData()); IntrospectAccessTokenResponseData responseData = apiIatResponse.getData().getData(); assertNotNull(responseData); <START> assertEquals(responseData.isActive(), Boolean.FALSE); <END> }</code><technical_language>assertFalse(responseData.isActive());</technical_language>

Target:
public void testWithInvalidToken(String opHost, String redirectUrl) throws Exception { DevelopersApi client = Tester.api(); RegisterSiteResponseData setupData = RegisterSiteTest.registerSite(client, opHost, redirectUrl); GetClientTokenResponseData tokenResponse = getGetClientTokenResponseData(opHost, client, setupData); assertNotNull(tokenResponse); final String accessToken = tokenResponse.getAccessToken(); final String validHeader = "Bearer " + accessToken; final String invalidToken = accessToken.concat("BlahBlah"); IntrospectAccessTokenParams iatParams = new IntrospectAccessTokenParams(); iatParams.setAccessToken(invalidToken); iatParams.setOxdId(setupData.getOxdId()); ApiResponse<IntrospectAccessTokenResponse> apiIatResponse = client.introspectAccessTokenWithHttpInfo(validHeader, iatParams); assertEquals(apiIatResponse.getStatusCode(), 200); assertNotNull(apiIatResponse.getData()); IntrospectAccessTokenResponseData responseData = apiIatResponse.getData().getData(); assertNotNull(responseData); assertFalse(responseData.isActive()); }
Source:
<code>public static IpBlock create(String id, Location location, List<PublicIp> publicIps, List<String> ips) { <START> return new AutoValue_IpBlock(id, location, publicIps, ips); <END> }</code><technical_language>enforce immutability of list, if null pass ImmutableList.copyOf(ips) auto constructor</technical_language>

Target:
public static IpBlock create(String id, Location location, List<PublicIp> publicIps, List<String> ips) { return new AutoValue_IpBlock(id, location, publicIps, ips != null ? ImmutableList.copyOf(ips) : ImmutableList.<String>of()); }
Source:
<code>public static <T> QueryRunner<T> makeSearchQueryRunner( Segment adapter ) { final SearchQueryConfig config = new SearchQueryConfig(); <START> QueryRunnerFactory factory = new SearchQueryRunnerFactory( <END> new SearchStrategySelector(new Supplier<SearchQueryConfig>() { @Override public SearchQueryConfig get() { return config; } }), new SearchQueryQueryToolChest( config, QueryRunnerTestHelper.NoopIntervalChunkingQueryRunnerDecorator()), QueryRunnerTestHelper.NOOP_QUERYWATCHER); return new FinalizeResultsQueryRunner<T>( factory.createRunner(adapter), factory.getToolchest() ); }</code><technical_language>This supplier Suppliers.ofInstance(config)</technical_language>

Target:
public static <T> QueryRunner<T> makeSearchQueryRunner( Segment adapter ) { final SearchQueryConfig config = new SearchQueryConfig(); QueryRunnerFactory factory = new SearchQueryRunnerFactory( new SearchStrategySelector(Suppliers.ofInstance(config)), new SearchQueryQueryToolChest( config, QueryRunnerTestHelper.NoopIntervalChunkingQueryRunnerDecorator() ), QueryRunnerTestHelper.NOOP_QUERYWATCHER ); return new FinalizeResultsQueryRunner<T>( factory.createRunner(adapter), factory.getToolchest() ); }
Source:
<code>public void rollback() { mPut = null; mEntityId = null; mHopper = null; mId = null; <START> mLGNames = new HashSet<String>(); <END> }</code><technical_language>nit: do mLGNames = Sets.newHashSet();</technical_language>

Target:
public void rollback() { Preconditions.checkState(mPut != null, "rollback() must be paired with a call to begin()"); reset(); }
Source:
<code>private String getDuplicateStorageDomainId(StorageServerConnections connection, Guid storagePoolId) { List<StorageServerConnections> connections = null; List<StorageDomain> sd; if (connection.getStorageType() == StorageType.LOCALFS) { List<StorageServerConnections> connectionsForPool = storagePoolId == null ? Collections.emptyList() : storageServerConnectionDao.getAllConnectableStorageSeverConnection(storagePoolId); List<StorageServerConnections> connectionsForPath = storageServerConnectionDao.getAllForStorage(connection.getConnection()); connections = (List<StorageServerConnections>) CollectionUtils.intersection(connectionsForPool, connectionsForPath); } else if (connection.getStorageType().isFileDomain()) { String connectionField = connection.getConnection(); connections = storageServerConnectionDao.getAllForStorage(connectionField); } else { StorageServerConnections sameConnection = iscsiStorageHelper.findConnectionWithSameDetails(connection); connections = sameConnection != null ? Collections.singletonList(sameConnection) : Collections.emptyList(); } <START> return connections.get(0).getId(); <END> }</code><technical_language>get IndexOutOfRange I</technical_language>

Target:
private String getDuplicateStorageDomainId(StorageServerConnections connection, Guid storagePoolId) { List<StorageServerConnections> connections = null; List<StorageDomain> sd; if (connection.getStorageType() == StorageType.LOCALFS) { List<StorageServerConnections> connectionsForPool = storagePoolId == null ? Collections.emptyList() : storageServerConnectionDao.getAllConnectableStorageSeverConnection(storagePoolId); List<StorageServerConnections> connectionsForPath = storageServerConnectionDao.getAllForStorage(connection.getConnection()); connections = (List<StorageServerConnections>) CollectionUtils.intersection(connectionsForPool, connectionsForPath); } else if (connection.getStorageType().isFileDomain()) { String connectionField = connection.getConnection(); connections = storageServerConnectionDao.getAllForStorage(connectionField); } else { StorageServerConnections sameConnection = iscsiStorageHelper.findConnectionWithSameDetails(connection); connections = sameConnection != null ? Collections.singletonList(sameConnection) : Collections.emptyList(); } if (connections != null && connections.size() > 0 ) return connections.get(0).getId(); return ""; }
Source:
<code>public void setup() { compactionConfigs = new HashMap<>(); for (int i = 0; i < numDataSources; i++) { final String dataSource = DATA_SOURCE_PREFIX + i; compactionConfigs.put( dataSource, new DataSourceCompactionConfig( dataSource, 0, targetCompactionSizeBytes, targetCompactionSizeBytes, null, null, null, null, null ) ); } dataSources = new HashMap<>(); for (int i = 0; i < numDataSources; i++) { final String dataSource = DATA_SOURCE_PREFIX + i; VersionedIntervalTimeline<String, DataSegment> timeline = new VersionedIntervalTimeline<>( String.CASE_INSENSITIVE_ORDER ); final int startYear = ThreadLocalRandom.current().nextInt(2000, 2040); DateTime date = DateTimes.of(startYear, 1, 1, 0, 0); for (int j = 0; j < numDayIntervalsPerDataSource; j++, date = date.plusDays(1)) { for (int k = 0; k < numPartitionsPerDayInterval; k++) { final ShardSpec shardSpec = new NumberedShardSpec(numPartitionsPerDayInterval, k); final DataSegment segment = new DataSegment( dataSource, new Interval(date, date.plusDays(1)), "version", null, ImmutableList.of(), ImmutableList.of(), shardSpec, 0, segmentSizeBytes ); <START> timeline.add(segment.getInterval(), segment.getMajorVersion(), shardSpec.createChunk(segment)); <END> } } dataSources.put(dataSource, timeline); } }</code><technical_language>a hacks reviewing this PR, starting if renaming getVersion getMajorVersion worth noise in this change. I obvious getVersion is .. more major getMinorVersion? Thoughts? I missing a reason this _needs_ renamed? dramatically reduce footprint of this PR, a lot of changes this method call. If prefer it, rename in a follow-up PR change</technical_language>

Target:
public void setup() { compactionConfigs = new HashMap<>(); for (int i = 0; i < numDataSources; i++) { final String dataSource = DATA_SOURCE_PREFIX + i; compactionConfigs.put( dataSource, new DataSourceCompactionConfig( dataSource, 0, targetCompactionSizeBytes, targetCompactionSizeBytes, null, null, null, null, null ) ); } List<DataSegment> segments = new ArrayList<>(); for (int i = 0; i < numDataSources; i++) { final String dataSource = DATA_SOURCE_PREFIX + i; final int startYear = ThreadLocalRandom.current().nextInt(2000, 2040); DateTime date = DateTimes.of(startYear, 1, 1, 0, 0); for (int j = 0; j < numDayIntervalsPerDataSource; j++, date = date.plusDays(1)) { for (int k = 0; k < numPartitionsPerDayInterval; k++) { final ShardSpec shardSpec = new NumberedShardSpec(numPartitionsPerDayInterval, k); final DataSegment segment = new DataSegment( dataSource, new Interval(date, date.plusDays(1)), "version", null, ImmutableList.of(), ImmutableList.of(), shardSpec, 0, segmentSizeBytes ); segments.add(segment); } } } dataSources = DataSourcesSnapshot.fromUsedSegments(segments, ImmutableMap.of()).getUsedSegmentsTimelinesPerDataSource(); }
Source:
<code>private synchronized boolean updateWeatherData() { try { String data = getWeatherData( "SELECT * FROM weather.forecast WHERE u = 'c' AND woeid = " + location.toPlainString()); if (data != null) { if (data.contains("\"results\":null")) { if (isCurrentDataExpired()) { weatherData = null; logger.trace( "The Yahoo Weather API did not return any data. Omiting the old result because it became too old."); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "The Yahoo Weather API did not return any data."); return false; } else { logger.trace("The Yahoo Weather API did not return any data. Keeping the old result."); return false; } } else { lastUpdateTime = System.currentTimeMillis(); weatherData = data; } <START> updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE, "@text/online"); <END> return true; } } catch (IOException e) { logger.warn("Error accessing Yahoo weather: {}", e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "@text/offline"); } weatherData = null; return false; }</code><technical_language>introduced message details for providing infos problem. I prefer ONLINE status additional texts, simply means "all is fine" end kinds of expressions for bindings</technical_language>

Target:
private synchronized boolean updateWeatherData() { try { String data = getWeatherData( "SELECT * FROM weather.forecast WHERE u = 'c' AND woeid = " + location.toPlainString()); if (data != null) { if (data.contains("\"results\":null")) { if (isCurrentDataExpired()) { weatherData = null; logger.trace( "The Yahoo Weather API did not return any data. Omiting the old result because it became too old."); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "@text/offline.no-data"); return false; } else { logger.trace("The Yahoo Weather API did not return any data. Keeping the old result."); return false; } } else { lastUpdateTime = System.currentTimeMillis(); weatherData = data; } updateStatus(ThingStatus.ONLINE); return true; } } catch (IOException e) { logger.warn("Error accessing Yahoo weather: {}", e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "@text/offline.location [\"" + location.toPlainString() + "\""); } weatherData = null; return false; }
Source:
<code>public void parseArguments(List<String> args) throws Exception { final Map<String, String> substitutions = new HashMap<>(); <START> substitutions.put( <END> "@PROGRAM_NAME@", (String)((Map) context.get(ModuleService.CLI_PARSER_SUBSTITUTIONS)).get("PROGRAM_NAME") ); args.remove(0); Properties props = new Properties(); try ( InputStream in = LoggerServiceImpl.class.getResourceAsStream("arguments.properties"); Reader reader = new InputStreamReader(in); ) { props.load(reader); } ArgumentsParser parser = new ArgumentsParser(props, "module"); parser.getSubstitutions().putAll(substitutions); parser.parse(args); Map<String, Object> moduleArgs = parser.getParsedArgs(); if((Boolean)moduleArgs.get("help")) { System.out.format("Usage: %s", parser.getUsage()); throw new ExitException("Help", 0); } if(!parser.getErrors().isEmpty()) { for(Throwable t : parser.getErrors()) { System.err.format("FATAL: %s%n", t.getMessage()); } throw new ExitException("Parsing error", 1); } if (args.size() < 1) { System.err.println("Action not provided"); throw new ExitException("Action not provided", 1); } try { action = Action.valueOf(args.get(0).toUpperCase().replace("-", "_")); } catch(IllegalArgumentException e) { System.err.printf("Invalid action '%s'%n", args.get(0)); throw new ExitException("Invalid action", 1); } argMap = action.parse(substitutions, props, args); }</code><technical_language>entire point is do care within... final Map<String, String> substitutions = new HashMap<>((Map) context.get(ModuleService.CLI_PARSER_SUBSTITUTIONS));</technical_language>

Target:
public void parseArguments(List<String> args) throws Exception { args.remove(0); Properties props = new Properties(); try ( InputStream in = LoggerServiceImpl.class.getResourceAsStream("arguments.properties"); Reader reader = new InputStreamReader(in, Charset.forName("UTF-8")); ) { props.load(reader); } Map<String, String> substitutions = (Map)context.get(ModuleService.CLI_PARSER_SUBSTITUTIONS); ArgumentsParser parser = new ArgumentsParser(props, "module"); parser.getSubstitutions().putAll(substitutions); parser.parse(args); Map<String, Object> moduleArgs = parser.getParsedArgs(); if((Boolean)moduleArgs.get("help")) { System.out.format("Usage: %s", parser.getUsage()); throw new ExitException("Help", 0); } if(!parser.getErrors().isEmpty()) { for(Throwable t : parser.getErrors()) { System.err.format("FATAL: %s%n", t.getMessage()); } throw new ExitException("Parsing error", 1); } if (args.size() < 1) { System.err.println("Action not provided"); throw new ExitException("Action not provided", 1); } try { action = Action.valueOf(args.get(0).toUpperCase().replace("-", "_")); } catch(IllegalArgumentException e) { System.err.printf("Invalid action '%s'%n", args.get(0)); throw new ExitException("Invalid action", 1); } argMap = action.parse(substitutions, props, args); }
Source:
<code>public File provisionWorkspace(RunConfiguration configuration, GeoJsonDiseaseOccurrenceFeatureCollection modelData) throws IOException { Path workingDirectoryPath = Paths.get( configuration.getBaseDir().getAbsolutePath(), configuration.getRunName() + "-" + UUID.randomUUID().toString()); LOGGER.info("Provisioning workspace at " + workingDirectoryPath.toString()); File workingDirectory = workingDirectoryPath.toFile(); boolean workingDirectoryCreated = workingDirectory.mkdirs(); File modelDirectory = null; if (workingDirectoryCreated) { Path modelDirectoryPath = Paths.get(workingDirectoryPath.toString(), MODEL_CODE_DIRECTORY_NAME); modelDirectory = modelDirectoryPath.toFile(); workingDirectoryCreated = modelDirectory.mkdir(); } File dataDirectory = null; if (workingDirectoryCreated) { Path dataDirectoryPath = Paths.get(workingDirectoryPath.toString(), MODEL_DATA_DIRECTORY_NAME); dataDirectory = dataDirectoryPath.toFile(); workingDirectoryCreated = dataDirectory.mkdir(); } if (!workingDirectoryCreated) { LOGGER.warn(String.format(LOG_DIRECTORY_ERROR, workingDirectoryPath.toString())); throw new IOException("Directory structure could not be created."); } inputDataManager.writeData(modelData, dataDirectory); sourceCodeManager.provisionVersion(configuration.getModelVersion(), modelDirectory); File runScript = scriptGenerator.generateScript(configuration, workingDirectory, false); <START> LOGGER.info("Workspace successfully provisioned at " + workingDirectoryPath.toString()); <END> return runScript; }</code><technical_language>noticed changed... LOG_DIRECTORY_SUCCESS</technical_language>

Target:
public File provisionWorkspace(RunConfiguration configuration, GeoJsonDiseaseOccurrenceFeatureCollection modelData) throws IOException { Path workingDirectoryPath = Paths.get( configuration.getBaseDir().getAbsolutePath(), configuration.getRunName() + "-" + UUID.randomUUID().toString()); LOGGER.info(String.format(LOG_PROVISIONING_WORKSPACE, workingDirectoryPath.toString())); File workingDirectory = workingDirectoryPath.toFile(); boolean workingDirectoryCreated = workingDirectory.mkdirs(); File modelDirectory = null; if (workingDirectoryCreated) { Path modelDirectoryPath = Paths.get(workingDirectoryPath.toString(), MODEL_CODE_DIRECTORY_NAME); modelDirectory = modelDirectoryPath.toFile(); workingDirectoryCreated = modelDirectory.mkdir(); } File dataDirectory = null; if (workingDirectoryCreated) { Path dataDirectoryPath = Paths.get(workingDirectoryPath.toString(), MODEL_DATA_DIRECTORY_NAME); dataDirectory = dataDirectoryPath.toFile(); workingDirectoryCreated = dataDirectory.mkdir(); } if (!workingDirectoryCreated) { LOGGER.warn(String.format(LOG_DIRECTORY_ERROR, workingDirectoryPath.toString())); throw new IOException("Directory structure could not be created."); } inputDataManager.writeData(modelData, dataDirectory); sourceCodeManager.provisionVersion(configuration.getModelVersion(), modelDirectory); File runScript = scriptGenerator.generateScript(configuration, workingDirectory, false); LOGGER.info(String.format(LOG_WORKSPACE_SUCCESSFULLY_PROVISIONED, workingDirectoryPath.toString())); return runScript; }
Source:
<code>void emit(long previousRequested) { <START> if (requested.get() == Long.MAX_VALUE) { <END> if (previousRequested == 0) { try { for (Object value : deque) { if (subscriber.isUnsubscribed()) return; notification.accept(subscriber, value); } } catch (Throwable e) { Exceptions.throwOrReport(e, subscriber); } finally { deque.clear(); } } else { } } else { if (previousRequested == 0) { while (true) { long numToEmit = requested.get(); int emitted = 0; Object o; while (--numToEmit >= 0 && (o = deque.poll()) != null) { if (subscriber.isUnsubscribed()) { return; } if (notification.accept(subscriber, o)) { return; } else { emitted++; } } for (; ; ) { long oldRequested = requested.get(); long newRequested = oldRequested - emitted; if (oldRequested == Long.MAX_VALUE) { break; } if (requested.compareAndSet(oldRequested, newRequested)) { if (newRequested == 0) { return; } break; } } } } } }</code><technical_language>requested field read a local variable</technical_language>

Target:
void emit(long previousRequested) { if (get() == Long.MAX_VALUE) { if (previousRequested == 0) { try { for (Object value : deque) { if (subscriber.isUnsubscribed()) return; notification.accept(subscriber, value); } } catch (Throwable e) { Exceptions.throwOrReport(e, subscriber); } finally { deque.clear(); } } else { } } else { if (previousRequested == 0) { while (true) { long numToEmit = get(); int emitted = 0; Object o; while (--numToEmit >= 0 && (o = deque.poll()) != null) { if (subscriber.isUnsubscribed()) { return; } if (notification.accept(subscriber, o)) { return; } else { emitted++; } } for (; ; ) { long oldRequested = get(); long newRequested = oldRequested - emitted; if (oldRequested == Long.MAX_VALUE) { break; } if (compareAndSet(oldRequested, newRequested)) { if (newRequested == 0) { return; } break; } } } } } }
Source:
<code>protected List<String> initialKnifeParameters() { MutableList<String> result = new MutableList<String>(); SshMachineLocation machine = EffectorTasks.findSshMachine(); result.add("bootstrap"); result.addAll(extraBootstrapParameters); HostAndPort hostAndPort = machine.getSshHostAndPort(); result.add(wrapBash(hostAndPort.getHostText())); <START> result.add("-p "+hostAndPort.getPort()); <END> result.add("-x "+wrapBash(checkNotNull(machine.getUser(), "user"))); File keyfile = ChefServerTasks.extractKeyFile(machine); if (keyfile!=null) result.add("-i "+keyfile.getPath()); else result.add("-P "+checkNotNull(machine.findPassword(), "No password or private key data for "+machine)); if (sudo != Boolean.FALSE) result.add("--sudo"); if (!Strings.isNullOrEmpty(nodeName)) { result.add("--node-name"); result.add(nodeName); } result.add("-r "+wrapBash(runList.apply(entity()))); if (!knifeAttributes.isEmpty()) result.add("-j "+wrapBash(new GsonBuilder().create() .toJson(knifeAttributes))); return result; }</code><technical_language>This loses portOmittedToUseKnifeDefault in knifeWhichPort(machine). I want that, we</technical_language>

Target:
protected List<String> initialKnifeParameters() { MutableList<String> result = new MutableList<String>(); SshMachineLocation machine = EffectorTasks.findSshMachine(); result.add("bootstrap"); result.addAll(extraBootstrapParameters); HostAndPort hostAndPort = machine.getSshHostAndPort(); result.add(wrapBash(hostAndPort.getHostText())); Integer whichPort = knifeWhichPort(hostAndPort); if (whichPort!=null) result.add("-p "+whichPort); result.add("-x "+wrapBash(checkNotNull(machine.getUser(), "user"))); File keyfile = ChefServerTasks.extractKeyFile(machine); if (keyfile!=null) result.add("-i "+keyfile.getPath()); else result.add("-P "+checkNotNull(machine.findPassword(), "No password or private key data for "+machine)); if (sudo != Boolean.FALSE) result.add("--sudo"); if (!Strings.isNullOrEmpty(nodeName)) { result.add("--node-name"); result.add(nodeName); } result.add("-r "+wrapBash(runList.apply(entity()))); if (!knifeAttributes.isEmpty()) result.add("-j "+wrapBash(new GsonBuilder().create() .toJson(knifeAttributes))); return result; }
Source:
<code>private AuthenticationResult createAuthenticationResult() { <START> val mock = mock(AuthenticationResult.class); <END> val authentication = createAuthentication(); when(mock.getAuthentication()).thenReturn(authentication); when(mock.getService()).thenReturn(createService()); return mock; }</code><technical_language>remove, similar functionality in CoreAuthenticationTestUtils</technical_language>

Target:
private AuthenticationResult createAuthenticationResult() { val authentication = createAuthentication(); val mock = CoreAuthenticationTestUtils.getAuthenticationResult(authentication); return mock; }
Source:
<code>public void MinimalWordCountTest() { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); MinimalWordCount app = new MinimalWordCount(); try { lma.prepareDAG(app, conf); } catch (Exception e) { e.printStackTrace(); } LocalMode.Controller lc = lma.getController(); <START> lc.run(10000); <END> }</code><technical_language>This testing anything. Please implement proper result verification</technical_language>

Target:
public void MinimalWordCountTest() throws Exception { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); MinimalWordCount app = new MinimalWordCount(); lma.prepareDAG(app, conf); LocalMode.Controller lc = lma.getController(); ((StramLocalCluster)lc).setExitCondition(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return MinimalWordCount.Collector.isDone(); } }); lc.run(10000); Assert.assertTrue(MinimalWordCount.Collector.result.get("error") == 7); Assert.assertTrue(MinimalWordCount.Collector.result.get("word") == 119); Assert.assertTrue(MinimalWordCount.Collector.result.get("bye") == 1); }
Source:
<code>public void testGetPublicKeyPairNullInput1() { try{ KeyGenUtils.getPublicKeyPair(null, truePublicKeys[0]); } catch (UnsupportedTypeException e) { <START> fail("UnsupportedTypeException thrown"); <END> } }</code><technical_language>Is declare function throws UnsupportedTypeException instead of try-catch? (Other functions do similarly.) JUnit fail if throw</technical_language>

Target:
public void testGetPublicKeyPairNullInput1() { KeyGenUtils.getPublicKeyPair(null, truePublicKeys[0]); }
Source:
<code>public boolean addOffHeapResource(OffHeapResourceIdentifier identifier, long capacityInBytes) { boolean wasAdded = addToResources(identifier, capacityInBytes); if (wasAdded) { for (EntityManagementRegistry registry : registries) { OffHeapResourceBinding managementBinding = getOffHeapResource(identifier).getManagementBinding(); registry.register(managementBinding); <START> registry.refresh(); <END> } } return wasAdded; }</code><technical_language>registerAndRefresh() registration done async in monitoring server depending voltron is calling us</technical_language>

Target:
public boolean addOffHeapResource(OffHeapResourceIdentifier identifier, long capacityInBytes) { boolean wasAdded = addToResources(identifier, capacityInBytes); if (wasAdded) { for (EntityManagementRegistry registry : registries) { OffHeapResourceBinding managementBinding = getOffHeapResource(identifier).getManagementBinding(); registry.registerAndRefresh(managementBinding); } } return wasAdded; }
Source:
<code>public void open(int taskNumber, int numTasks) throws IOException { super.open(taskNumber, numTasks); DatumWriter<E> datumWriter; Schema schema = null; if (org.apache.avro.specific.SpecificRecordBase.class.isAssignableFrom(avroValueType)) { datumWriter = new SpecificDatumWriter<E>(avroValueType); try { schema = ((org.apache.avro.specific.SpecificRecordBase)avroValueType.newInstance()).getSchema(); } catch (InstantiationException e) { <START> e.printStackTrace(); <END> } catch (IllegalAccessException e) { e.printStackTrace(); } } else { datumWriter = new ReflectDatumWriter<E>(avroValueType); schema = ReflectData.get().getSchema(avroValueType); } dataFileWriter = new DataFileWriter<E>(datumWriter); dataFileWriter.create(schema, this.stream); }</code><technical_language>Please do swallow exceptions. Please rethrow message (using a RuntimeException so)</technical_language>

Target:
public void open(int taskNumber, int numTasks) throws IOException { super.open(taskNumber, numTasks); DatumWriter<E> datumWriter; Schema schema = null; if (org.apache.avro.specific.SpecificRecordBase.class.isAssignableFrom(avroValueType)) { datumWriter = new SpecificDatumWriter<E>(avroValueType); try { schema = ((org.apache.avro.specific.SpecificRecordBase)avroValueType.newInstance()).getSchema(); } catch (InstantiationException e) { throw new RuntimeException(e.getMessage()); } catch (IllegalAccessException e) { throw new RuntimeException(e.getMessage()); } } else { datumWriter = new ReflectDatumWriter<E>(avroValueType); schema = ReflectData.get().getSchema(avroValueType); } dataFileWriter = new DataFileWriter<E>(datumWriter); if (userDefinedSchema == null) { dataFileWriter.create(schema, stream); } else { dataFileWriter.create(userDefinedSchema, stream); } }
Source:
<code>public <T> T transform(Object value, Class<T> type) { Object returnValue = null; if (value == null) { return null; } if (ClassUtils.isAssignable(type, java.time.LocalDateTime.class)) { returnValue = toZonedDateTime((Calendar) value).toLocalDateTime(); } else if (ClassUtils.isAssignable(type, java.time.LocalDate.class)) { returnValue = toZonedDateTime((Calendar) value).toLocalDate(); } else if (ClassUtils.isAssignable(type, java.time.LocalTime.class)) { returnValue = toZonedDateTime((Calendar) value).toLocalTime(); } else if (ClassUtils.isAssignable(type, java.time.OffsetDateTime.class)) { returnValue = toZonedDateTime((Calendar) value).toOffsetDateTime(); } else if (ClassUtils.isAssignable(type, java.time.ZonedDateTime.class)) { returnValue = toZonedDateTime((Calendar) value); } else if (ClassUtils.isAssignable(type, java.time.OffsetTime.class)) { returnValue = toZonedDateTime((Calendar) value).toOffsetDateTime().toOffsetTime(); } else if (ClassUtils.isAssignable(type, java.time.Instant.class)) { returnValue = ((Calendar) value).toInstant(); <START> } else if (ClassUtils.isAssignable(type, java.time.Instant.class)) { <END> returnValue = ((Calendar) value).toInstant(); } else { throw new IllegalArgumentException("Incorrect type for transformer: " + type.getCanonicalName()); } return type.cast(returnValue); }</code><technical_language>This condition is duplicated statement</technical_language>

Target:
public <T> T transform(Object value, Class<T> type) { Object returnValue = null; if (value == null) { return null; } if (ClassUtils.isAssignable(type, java.time.LocalDateTime.class)) { returnValue = toZonedDateTime((Calendar) value).toLocalDateTime(); } else if (ClassUtils.isAssignable(type, java.time.LocalDate.class)) { returnValue = toZonedDateTime((Calendar) value).toLocalDate(); } else if (ClassUtils.isAssignable(type, java.time.LocalTime.class)) { returnValue = toZonedDateTime((Calendar) value).toLocalTime(); } else if (ClassUtils.isAssignable(type, java.time.OffsetDateTime.class)) { returnValue = toZonedDateTime((Calendar) value).toOffsetDateTime(); } else if (ClassUtils.isAssignable(type, java.time.ZonedDateTime.class)) { returnValue = toZonedDateTime((Calendar) value); } else if (ClassUtils.isAssignable(type, java.time.OffsetTime.class)) { returnValue = toZonedDateTime((Calendar) value).toOffsetDateTime().toOffsetTime(); } else if (ClassUtils.isAssignable(type, java.time.Instant.class)) { returnValue = ((Calendar) value).toInstant(); } else { throw new IllegalArgumentException("Incorrect type for transformer: " + type.getCanonicalName()); } return type.cast(returnValue); }
Source:
<code>public String getHumanishName() throws IllegalArgumentException { if ("".equals(getPath()) || getPath() == null) throw new IllegalArgumentException(); String[] elements = getPath().split("/"); if (elements.length == 0) throw new IllegalArgumentException(); String result = elements[elements.length - 1]; if (DOT_GIT.equals(result)) result = elements[elements.length - 2]; else if (result.endsWith(DOT_GIT)) result = result.substring(0, result.length() - DOT_GIT.length()); <START> if ("".equals(result)) <END> throw new IllegalArgumentException(); return result; }</code><technical_language>allow cloning /.git get humanish name of it? C Git allows this $ git clone /.git Initialized empty Git repository in /home/me/tmp/.git/.git/ return "" then? some other combinations C git "workded", sense</technical_language>

Target:
public String getHumanishName() throws IllegalArgumentException { if ("".equals(getPath()) || getPath() == null) throw new IllegalArgumentException(); String[] elements = getPath().split("/"); if (elements.length == 0) throw new IllegalArgumentException(); String result = elements[elements.length - 1]; if (DOT_GIT.equals(result)) result = elements[elements.length - 2]; else if (result.endsWith(DOT_GIT)) result = result.substring(0, result.length() - DOT_GIT.length()); return result; }
Source:
<code><START> protected boolean isAnyVmRunOnVdsInDb(Guid vdsId) { if (!Config.<Boolean>getValue(ConfigValues.MaintenanceVdsIgnoreExternalVms)) { return vmDynamicDao.isAnyVmRunOnVds(vdsId); } return !vmStaticDao.getAllRunningForVds(vdsId) .stream() .filter(vm -> !OriginType.EXTERNAL.equals(vm.getOrigin())) .collect(Collectors.toList()) .isEmpty(); } <END></code><technical_language>reason change this method now, no</technical_language>

Target:
protected boolean isAnyVmRunOnVdsInDb(Guid vdsId) { return vmDynamicDao.isAnyVmRunOnVds(vdsId); }
Source:
<code>private <T extends Metric> T find(String name, Class<T> type) { A.notNull(name, "name"); String[] splited = fromFullName(name); MetricRegistry mreg = registries.get(splited[0]); if (mreg == null) { if (log.isInfoEnabled()) log.info("Metric registry not found[registry=" + splited[0] + ']'); return null; } Metric m = mreg.findMetric(splited[1]); if (m == null) { if (log.isInfoEnabled()) log.info("Metric not found[registry=" + splited[0] + ", metricName=" + splited[1] + ']'); return null; } if (!m.getClass().isAssignableFrom(type)) { <START> log.error("Metric '" + name + "' should be a HitRate[type=" + m.getClass().getSimpleName() + ']'); <END> return null; } return (T) m; }</code><technical_language>HitRate removed log message</technical_language>

Target:
private <T extends Metric> T find(String name, Class<T> type) { A.notNull(name, "name"); T2<String, String> splitted = fromFullName(name); MetricRegistry mreg = registries.get(splitted.get1()); if (mreg == null) { if (log.isInfoEnabled()) log.info("Metric registry not found[registry=" + splitted.get1() + ']'); return null; } Metric m = mreg.findMetric(splitted.get2()); if (m == null) { if (log.isInfoEnabled()) log.info("Metric not found[registry=" + splitted.get1() + ", metricName=" + splitted.get2() + ']'); return null; } if (!m.getClass().isAssignableFrom(type)) { log.error("Metric '" + name + "' has wrong type[type=" + m.getClass().getSimpleName() + ']'); return null; } return (T) m; }
Source:
<code>public void testGetDocument() throws FileNotFoundException, DocumentException { final LabelPaper paper = LabelPaperFactory.generateLabelPaper(3, 9, 1); <START> Document document = this.pdfLabelsFileGenerator.getDocument(new FileOutputStream("temp"), paper, 1); <END> Assert.assertNotNull(document); Assert.assertEquals(PageSize.A4, document.getPageSize()); document = this.pdfLabelsFileGenerator.getDocument(new FileOutputStream("temp"), paper, 2); Assert.assertEquals(PageSize.LETTER, document.getPageSize()); }</code><technical_language>closing new FileOutputStream</technical_language>

Target:
public void testGetDocument() throws DocumentException, IOException { LabelPaper paper = LabelPaper.PAPER_3_BY_7_A4; final FileOutputStream fileOutputStream = new FileOutputStream("temp"); Document document = this.pdfLabelsFileGenerator.getDocument(fileOutputStream, paper, 1); Assert.assertNotNull(document); Assert.assertEquals(PageSize.A4, document.getPageSize()); paper = LabelPaper.PAPER_3_BY_7_LETTER; document = this.pdfLabelsFileGenerator.getDocument(fileOutputStream, paper, 2); Assert.assertEquals(PageSize.LETTER, document.getPageSize()); fileOutputStream.close(); }
Source:
<code>public <START> Collection<Disk> aggregateDiskImagesSnapshots(List<DiskImage> <END> images){ Map<Guid, DiskImage> diskImagesMap = new HashMap<>(); images.forEach(diskImage -> { if (diskImage.getActive()) { diskImage.getSnapshots().add(DiskImage.copyOf(diskImage)); diskImagesMap.put(diskImage.getId(), diskImage); } }); images.forEach(diskImage -> { if (!diskImage.getActive()) { diskImagesMap.get(diskImage.getId()).getSnapshots().add(diskImage); } }); return new ArrayList<>(diskImagesMap.values()); }</code><technical_language>a Collection of DiskImage</technical_language>

Target:
public Collection<DiskImage> aggregateDiskImagesSnapshots(List<DiskImage> images){ Map<Guid, DiskImage> diskImagesMap = new HashMap<>(); images.forEach(diskImage -> { if (diskImage.getActive()) { diskImage.getSnapshots().add(DiskImage.copyOf(diskImage)); diskImagesMap.put(diskImage.getId(), diskImage); } }); images.forEach(diskImage -> { if (!diskImage.getActive()) { diskImagesMap.get(diskImage.getId()).getSnapshots().add(diskImage); } }); return diskImagesMap.values(); }
Source:
<code>private void enforceAttemptTTLs() { Instant creationDeadline = ssm.getStoreTime().minus(attemptTTL); int state = 0; long lastId = 0; List<StoredSessionAttempt> expiredAttempts = ssm.findAttemptsCreatedBeforeWithState(creationDeadline, state, lastId, 100); for (StoredSessionAttempt attempt : expiredAttempts) { AttemptStateFlags stateFlags; try { stateFlags = ssm.getAttemptStateFlags(attempt.getId()); } catch (ResourceNotFoundException e) { logger.debug("Session Attempt not found, ignoring: {}", attempt, e); continue; } <START> if (stateFlags.isCancelRequested()) { <END> logger.debug("Session Attempt already canceled, ignoring: {}", attempt); continue; } logger.info("Session Attempt timed out, canceling: {}", attempt); ssm.requestCancelAttempt(attempt.getId()); } }</code><technical_language>if DatabaseSessionStoreManager state_flags = 0 condition, this checking is unnecessary. if Session Attempt canceled, ignoring message is shown, means attempt canceled selecting list of sessions. totally ok this for a purpose of fail-safe assertion</technical_language>

Target:
private void enforceAttemptTTLs() { Instant creationDeadline = ssm.getStoreTime().minus(attemptTTL); List<StoredSessionAttempt> expiredAttempts = ssm.findActiveAttemptsCreatedBefore(creationDeadline, (long) 0, 100); for (StoredSessionAttempt attempt : expiredAttempts) { AttemptStateFlags stateFlags; try { stateFlags = ssm.getAttemptStateFlags(attempt.getId()); } catch (ResourceNotFoundException e) { logger.debug("Session Attempt not found, ignoring: {}", attempt, e); continue; } if (stateFlags.isCancelRequested()) { logger.debug("Session Attempt already canceled, ignoring: {}", attempt); continue; } logger.info("Session Attempt timed out, canceling: {}", attempt); boolean canceled = ssm.requestCancelAttempt(attempt.getId()); if (canceled) { sendTimeoutNotification("Workflow execution timeout", attempt.getId()); } } }
Source:
<code>public DatabaseMetricsService(DataSourceFactory dataSourceFactory, MetricRegistry metricRegistry, String databaseName) { this.dataSourceFactory = dataSourceFactory; this.databaseName = databaseName; <START> initialiseMetrics(metricRegistry); <END> }</code><technical_language>inline this constructor</technical_language>

Target:
public DatabaseMetricsService(DataSourceFactory dataSourceFactory, MetricRegistry metricRegistry, String databaseName) { this.dataSourceFactory = dataSourceFactory; this.databaseName = databaseName; metrics.forEach(metric -> metric.register(metricRegistry, format("%sdb.", databaseName))); metricRegistry.<Gauge<Integer>>register(format("%sdb.stats_healthy", databaseName), () -> statsHealthy); }
Source:
<code>public ResponseEntity addPrivilegesToAnonymous(@RequestBody @Validated PrivilegeListForm privilegeListForm, BindingResult bindingResult, @RequestHeader(HttpHeaders.ACCEPT) String acceptHeader) { <START> if (privilegeListForm == null) <END> { throw new RequestBodyValidationException("Empty request body", bindingResult); } if (bindingResult.hasErrors()) { String message = "Privileges cannot be saved because the submitted form contains errors!"; throw new RequestBodyValidationException(message, bindingResult); } TypeDescriptor sourceType = TypeDescriptor.valueOf(PrivilegeListForm.class); TypeDescriptor targetType = TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Privilege.class)); List<Privilege> privilegeList = (List<Privilege>) conversionService.convert(privilegeListForm, sourceType, targetType); return processConfig(config -> Objects.requireNonNull(privilegeList).forEach(this::addAnonymousAuthority), () -> SUCCESSFUL_ASSIGN_PRIVILEGES, acceptHeader); }</code><technical_language>above, I null</technical_language>

Target:
public ResponseEntity addPrivilegesToAnonymous(@RequestBody @Validated PrivilegeListForm privilegeListForm, BindingResult bindingResult, @RequestHeader(HttpHeaders.ACCEPT) String acceptHeader) { if (bindingResult.hasErrors()) { throw new RequestBodyValidationException(FAILED_ASSIGN_PRIVILEGES, bindingResult); } TypeDescriptor sourceType = TypeDescriptor.valueOf(PrivilegeListForm.class); TypeDescriptor targetType = TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Privilege.class)); List<Privilege> privilegeList = (List<Privilege>) conversionService.convert(privilegeListForm, sourceType, targetType); return processConfig(config -> Objects.requireNonNull(privilegeList).forEach(this::addAnonymousAuthority), () -> SUCCESSFUL_ASSIGN_PRIVILEGES, acceptHeader); }
Source:
<code><START> public static ForLoadedType of(Class<?> type) { <END> ForLoadedType res = (ForLoadedType) WELLKNOWN_TYPE_MAP.get(type); if (res != null) { return res; } return new ForLoadedType(type); }</code><technical_language>This return a TypeDescription. implementation exposed</technical_language>

Target:
public static TypeDescription of(Class<?> type) { TypeDescription res = TypeDescription.TypeCache.WELLKNOWN_TYPE_MAP.get(type); if (res != null) { return res; } return new ForLoadedType(type); }
Source:
<code>public void logOut() { <START> mutableIdentityStore.logOut(); <END> isLoggedInBehaviorSubject.onNext(false); analytics.record(Events.Identity.UserLogout); }</code><technical_language>Want add a Logger.info(...) item</technical_language>

Target:
public void logOut() { mutableIdentityStore.logOut(); isLoggedInBehaviorSubject.onNext(false); analytics.record(Events.Identity.UserLogout); Logger.info(this, "User logged out"); }
Source:
<code><START> public static List<Optional<ApiResponses>> findApiResponsesAnnotations(AnnotatedElement annotated) { <END> return newArrayList( fromNullable(getAnnotation(annotated, ApiResponses.class)), fromNullable(annotated instanceof Method ? findAnnotation(((Method) annotated).getDeclaringClass(), ApiResponses.class) : (ApiResponses) null ) ); }</code><technical_language>List is monadic in itself, a returning a list of ApiResponses suffice. i.e. add list of getAnnotation method returns a null. sense? consumption in downstream processes easier, for e.g. need a if (apiResponses.isPresent()) {...} block</technical_language>

Target:
public static List<ApiResponses> findApiResponsesAnnotations(AnnotatedElement annotated) { List<ApiResponses> results = newArrayList(); ApiResponses currentLevel = getAnnotation(annotated, ApiResponses.class); if (currentLevel != null) { results.add(currentLevel); } if (annotated instanceof Method) { ApiResponses parentLevel = findAnnotation(((Method)annotated).getDeclaringClass(), ApiResponses.class); if (parentLevel != null) { results.add(parentLevel); } } return results; }
Source:
<code>public void includeSample( IndexEntryUpdate update ) { <START> nativePopulator.includeSample( update ); <END> lucenePopulator.includeSample( update ); }</code><technical_language>sample included populators</technical_language>

Target:
public void includeSample( IndexEntryUpdate update ) { selector.select( nativePopulator, lucenePopulator, update.values() ).includeSample( update ); }
Source:
<code>public void shutdown() { this.interrupt(); <START> LOG.info("Shutdown datastream {}", _datastreamGroup.getName()); <END> }</code><technical_language>rename message "PartitionListenerThread Shutdown called for datastreamgroup"</technical_language>

Target:
public void shutdown() { this.interrupt(); LOG.info("PartitionListenerThread Shutdown called for datastreamgroup {}", _datastreamGroup.getName()); }
Source:
<code>public VisualEditorPageObject closeDialog() { waitForElementClickableByElement(closeButton); closeButton.click(); <START> PageObjectLogging.log("closeDialog", "Closed button on the dialog is clicked", true); <END> waitForElementNotVisibleByElement(dialog); PageObjectLogging.log("closeDialog", "Dialog is closed", true); return new VisualEditorPageObject(driver); }</code><technical_language>Global listener catch click. need log it</technical_language>

Target:
public VisualEditorPageObject closeDialog() { waitForDialogVisible(); waitForElementClickableByElement(closeButton); closeButton.click(); waitForDialogNotVisible(); PageObjectLogging.log("closeDialog", "Dialog is closed", true); return new VisualEditorPageObject(driver); }
Source:
<code>public static void addZKStartStopAuditLog() { if (isAuditEnabled) { <START> ZKAuditLogger.logSuccess(getZKUser(), AuditConstants.OP_START); <END> Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { ZKAuditLogger.logInvoked(getZKUser(), AuditConstants.OP_STOP); } }); } }</code><technical_language>If I right, this is place ZKAuditLogFormatter. String.format() instead of a custom formatter</technical_language>

Target:
public static void addZKStartStopAuditLog() { if (isAuditEnabled()) { ZKAuditLogger.logSuccess(getZKUser(), AuditConstants.OP_START); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { ZKAuditLogger.logInvoked(getZKUser(), AuditConstants.OP_STOP); } }); } }