auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public EventTypeValidator build(final EventType eventType) { final List<Function<JSONObject, Optional<ValidationError>>> validators = new ArrayList<>(); final Schema schema = SchemaLoader.builder() .schemaJson(loader.effectiveSchema(eventType)) .addFormatValidator(new RFC3339DateTimeValidator()) .build() .load() .build(); validators.add((evt) -> validateSchemaConformance(schema, evt)); if (eventType.getCategory() == EventCategory.DATA || eventType.getCategory() == EventCategory.BUSINESS) { validators.add(this::validateOccurredAt); } return (event) -> validators .stream() .map(validator -> validator.apply(event)) .filter(Optional::isPresent) .findFirst() .orElse(Optional.empty()); }

Target:
public EventTypeValidator build(final EventType eventType) { final List<Function<JSONObject, Optional<ValidationError>>> validators = new ArrayList<>(2); final Schema schema = SchemaLoader.builder() .schemaJson(loader.effectiveSchema(eventType)) .addFormatValidator(new RFC3339DateTimeValidator()) .build() .load() .build(); validators.add((evt) -> validateSchemaConformance(schema, evt)); if (eventType.getCategory() == EventCategory.DATA || eventType.getCategory() == EventCategory.BUSINESS) { validators.add(this::validateOccurredAt); } return (event) -> validators .stream() .map(validator -> validator.apply(event)) .filter(Optional::isPresent) .findFirst() .orElse(Optional.empty()); }
Source:
public BytecodeNode visitCall(CallExpression call, Context context) { BytecodeGeneratorContext generatorContext = new BytecodeGeneratorContext( RowExpressionCompiler.this, context.getScope(), callSiteBinder, cachedInstanceBinder, functionManager); if (call.getSignature().getName().equals(CAST)) { return (new CastCodeGenerator()).generateExpression(generatorContext, call.getType(), call.getArguments(), context.getOutputBlockVariable()); } else { return (new FunctionCallCodeGenerator()).generateCall(call.getSignature(), generatorContext, call.getType(), call.getArguments(), context.getOutputBlockVariable()); } }

Target:
public BytecodeNode visitCall(CallExpression call, Context context) { BytecodeGeneratorContext generatorContext = new BytecodeGeneratorContext( RowExpressionCompiler.this, context.getScope(), callSiteBinder, cachedInstanceBinder, functionManager); return (new FunctionCallCodeGenerator()).generateCall(call.getFunctionHandle().getSignature(), generatorContext, call.getType(), call.getArguments(), context.getOutputBlockVariable()); }
Source:
public void shouldAutoDeployScriptAndForms() throws IOException { InputStream formFile = AutoDeploymentIT.class.getClassLoader().getResourceAsStream("deployment/form.html"); InputStream scriptFile = AutoDeploymentIT.class.getClassLoader().getResourceAsStream("deployment/script.js"); File resourcesDirectory = Paths.get(baseDirectory, "configuration", "resources").toFile(); resourcesDirectory.mkdirs(); Files.copy(formFile, Paths.get(resourcesDirectory.getAbsolutePath(), "form.html")); Files.copy(scriptFile, Paths.get(resourcesDirectory.getAbsolutePath(), "script.js")); runStartScript(); Response definitionResponse = when().get(container.getBaseUrl() + DEPLOYMENT_ENDPOINT); definitionResponse.then() .body("size()", is(1)); String deploymentId = definitionResponse.then().extract().path("[0].id"); Response resourcesResponse = when().get(container.getBaseUrl() + DEPLOYMENT_ENDPOINT + "/" + deploymentId + "/resources"); List<String> resourceNames = extractResourceNames(resourcesResponse); assertThat(resourceNames, contains("/form.html", "/script.js")); }

Target:
public void shouldAutoDeployScriptAndForms() throws IOException { InputStream formFile = AutoDeploymentIT.class.getClassLoader().getResourceAsStream("deployment/form.html"); InputStream scriptFile = AutoDeploymentIT.class.getClassLoader().getResourceAsStream("deployment/script.js"); File resourcesDirectory = Paths.get(baseDirectory, "configuration", "resources").toFile(); resourcesDirectory.mkdirs(); Files.copy(formFile, Paths.get(resourcesDirectory.getAbsolutePath(), "form.html")); Files.copy(scriptFile, Paths.get(resourcesDirectory.getAbsolutePath(), "script.js")); runStartScript(); Response definitionResponse = when().get(container.getBaseUrl() + DEPLOYMENT_ENDPOINT); definitionResponse.then() .body("size()", is(1)); String deploymentId = definitionResponse.then().extract().path("[0].id"); Response resourcesResponse = when().get(container.getBaseUrl() + DEPLOYMENT_ENDPOINT + "/" + deploymentId + "/resources"); List<String> resourceNames = extractResourceNames(resourcesResponse); assertThat(resourceNames).contains("/form.html", "/script.js"); }
Source:
protected BaseRuleTest() { this(TpchConnectorFactory.DEFAULT_PREDICATE_PUSHDOWN_ENABLED); }

Target:
protected BaseRuleTest() { this(false); }
Source:
private FilePath createSshKeyFile(SSHUserPrivateKey sshUser) throws IOException, InterruptedException { FilePath key = workspace.createTempFile("ssh", "key"); List<String> privateKeys = sshUser.getPrivateKeys(); key.write(StringUtils.join(privateKeys, "\n"), null); key.chmod(0400); return key; }

Target:
private FilePath createSshKeyFile(SSHUserPrivateKey sshUser) throws IOException, InterruptedException { List<String> privateKeys = sshUser.getPrivateKeys(); FilePath key = workspace.createTextTempFile("ssh", "key", StringUtils.join(privateKeys, "\n"), false); key.chmod(0400); return key; }
Source:
protected void execute() { if (!bindingsExist()) { logger.debug("There is no existing Sonance binding configuration => refresh cycle aborted!"); return; } logger.info("Refreshing all items"); List<String> offlineEndPoints = new ArrayList<String>(); for (SonanceBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String group = provider.getGroup(itemName); String ip = provider.getIP(itemName); int port = provider.getPort(itemName); String key = ip + ":" + port; if (!offlineEndPoints.contains(key)) { try { if (!socketCache.containsKey(key)) { socketCache.put(key, new Socket(ip, port)); outputStreamCache.put(key, new DataOutputStream( socketCache.get(key).getOutputStream())); bufferedReaderCache.put(key, new BufferedReader( new InputStreamReader(socketCache.get(key) .getInputStream()))); logger.debug("New socket created"); } if (provider.isMute(itemName)) sendMuteCommand(itemName, "FF550212" + group, outputStreamCache.get(key), bufferedReaderCache.get(key)); else if (provider.isVolume(itemName)) sendVolumeCommand(itemName, "FF550210" + group, outputStreamCache.get(key), bufferedReaderCache.get(key)); } catch (UnknownHostException e) { logger.error("UnknownHostException occured."); } catch (IOException e) { logger.debug("Amplifier is offline, status can't be updated at this moment."); try { socketCache.get(key).close(); } catch (Exception ex) { } socketCache.remove(key); outputStreamCache.remove(key); bufferedReaderCache.remove(key); offlineEndPoints.add(key); } } } } }

Target:
protected void execute() { if (!bindingsExist()) { logger.debug("There is no existing Sonance binding configuration => refresh cycle aborted!"); return; } logger.info("Refreshing all items"); List<String> offlineEndPoints = new ArrayList<String>(); for (SonanceBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String group = provider.getGroup(itemName); String ip = provider.getIP(itemName); int port = provider.getPort(itemName); String key = ip + ":" + port; if (!offlineEndPoints.contains(key)) { try { if (!socketCache.containsKey(key)) { socketCache.put(key, new Socket(ip, port)); outputStreamCache.put(key, new DataOutputStream( socketCache.get(key).getOutputStream())); bufferedReaderCache.put(key, new BufferedReader( new InputStreamReader(socketCache.get(key) .getInputStream()))); logger.debug("New socket created ({}:{})", ip, port); } if (provider.isMute(itemName)) { sendMuteCommand(itemName, SonanceConsts.MUTE_QUERY + group, outputStreamCache.get(key), bufferedReaderCache.get(key)); } else if (provider.isVolume(itemName)) { sendVolumeCommand(itemName, SonanceConsts.VOLUME_QUERY + group, outputStreamCache.get(key), bufferedReaderCache.get(key)); } } catch (UnknownHostException e) { logger.error( "UnknownHostException occured when connecting to amplifier {}:{}.", ip, port); } catch (IOException e) { logger.debug( "Amplifier ({},{}) is offline, status can't be updated at this moment.", ip, port); try { socketCache.get(key).close(); } catch (Exception ex) { } socketCache.remove(key); outputStreamCache.remove(key); bufferedReaderCache.remove(key); offlineEndPoints.add(key); } } } } }
Source:
protected boolean validate() { if (getParameters().getSchedule() == null || (getParameters().getSchedule().getFrequency() != StorageSyncSchedule.Frequency.NONE && getParameters().getSchedule().getCronExpression().isEmpty())) { return failValidation(EngineMessage.VALIDATION_INVALID_SCHEDULE); } if (getParameters().getStorageDomainId() == null || getStorageDomain() == null) { return failValidation(EngineMessage.STORAGE_DOMAIN_DOES_NOT_EXIST); } if (getParameters().getGeoRepSessionId() == null || getGeoRepSession() == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_GEOREP_SESSION_INVALID); } return super.validate(); }

Target:
protected boolean validate() { if (getParameters().getSchedule() == null || (getParameters().getSchedule().getFrequency() != StorageSyncSchedule.Frequency.NONE && StringUtils.isEmpty(getParameters().getSchedule().getCronExpression()))) { return failValidation(EngineMessage.VALIDATION_INVALID_SCHEDULE); } if (getStorageDomainId() == null || getStorageDomain() == null) { return failValidation(EngineMessage.STORAGE_DOMAIN_DOES_NOT_EXIST); } if (getGeoRepSession() == null) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_GEOREP_SESSION_INVALID); } return super.validate(); }
Source:
public ResultScanner<FlatRow> readFlatRows(ReadRowsRequest request) { if (shouldOverrideAppProfile(request.getAppProfileId())) { request = request.toBuilder().setAppProfileId(clientDefaultAppProfileId).build(); } final ResponseQueueReader reader = new ResponseQueueReader(retryOptions.getReadPartialRowTimeoutMillis()); final StreamObserver<ReadRowsResponse> responseObserver = new StreamObserver<ReadRowsResponse>() { @Override public void onNext(ReadRowsResponse value) { reader.addRequestResultMarker(); } @Override public void onError(Throwable t) { } @Override public void onCompleted() { } }; RetryingReadRowsOperation operation = createReadRowsRetryListener(request, reader, responseObserver); operation.getAsyncResult(); return new ResumingStreamingResultScanner(reader, operation); }

Target:
public ResultScanner<FlatRow> readFlatRows(ReadRowsRequest request) { if (shouldOverrideAppProfile(request.getAppProfileId())) { request = request.toBuilder().setAppProfileId(clientDefaultAppProfileId).build(); } final ResponseQueueReader reader = new ResponseQueueReader(retryOptions.getReadPartialRowTimeoutMillis()); RetryingReadRowsOperation operation = createReadRowsOperation(request, reader); return new ResumingStreamingResultScanner(reader, operation); }
Source:
public void setJwtValidator(OAuth2TokenValidator<Jwt> jwtValidator) { this.jwtValidator = jwtValidator; }

Target:
public void setJwtValidator(OAuth2TokenValidator<Jwt> jwtValidator) { Assert.notNull(jwtValidator, "jwtValidator cannot be null"); this.jwtValidator = jwtValidator; }
Source:
public static List<ScenarioResult> verifyConditions(SimulationDescriptor simulationDescriptor, List<ScenarioInput> inputData, List<ScenarioOutput> outputData) { List<ScenarioResult> scenarioResult = new ArrayList<>(); for (ScenarioInput input : inputData) { FactIdentifier factIdentifier = input.getFactIdentifier(); List<ScenarioOutput> assertionOnFact = outputData.stream().filter(elem -> elem.getFactIdentifier().equals(factIdentifier)).collect(toList()); if (assertionOnFact.size() < 1) { continue; } scenarioResult.addAll(getScenarioResults(simulationDescriptor, assertionOnFact, input)); } return scenarioResult; }

Target:
public static List<ScenarioResult> verifyConditions(SimulationDescriptor simulationDescriptor, List<ScenarioInput> inputData, List<ScenarioOutput> outputData) { List<ScenarioResult> scenarioResult = new ArrayList<>(); for (ScenarioInput input : inputData) { FactIdentifier factIdentifier = input.getFactIdentifier(); List<ScenarioOutput> assertionOnFact = outputData.stream().filter(elem -> Objects.equals(elem.getFactIdentifier(), factIdentifier)).collect(toList()); if (assertionOnFact.size() < 1) { continue; } scenarioResult.addAll(getScenarioResults(simulationDescriptor, assertionOnFact, input)); } return scenarioResult; }
Source:
private void configureQueryParameters(Request request) { try { Config queryParameters = params.parseNestedOrGetEmpty("query"); for (String name : queryParameters.getKeys()) { request.param(name, queryParameters.get(name, String.class)); } } catch (ConfigException e) { Optional<String> query = params.getOptional("query", String.class); if (query.isPresent()) { List<NameValuePair> parameters = URLEncodedUtils.parse(query.get(), StandardCharsets.UTF_8); for (NameValuePair parameter : parameters) { request.param(parameter.getName(), parameter.getValue()); } } } }

Target:
private void configureQueryParameters(Request request) { try { Config queryParameters = params.parseNestedOrGetEmpty("query"); for (String name : queryParameters.getKeys()) { request.param(name, queryParameters.get(name, String.class)); } } catch (ConfigException e) { Optional<String> query = params.getOptional("query", String.class); if (query.isPresent()) { List<NameValuePair> parameters = URLEncodedUtils.parse(query.get(), UTF_8); for (NameValuePair parameter : parameters) { request.param(parameter.getName(), parameter.getValue()); } } } }
Source:
private boolean restore(MigrationReport report, Optional<InputStream> ois) throws IOException { final InputStream is = ois.orElse(null); if (is == null) { throw new MigrationException("Import error: missing exported profile information."); } final JsonProfile jprofile = JsonUtils.fromJson(IOUtils.toString(is, StandardCharsets.UTF_8), JsonProfile.class); for (int i = 1; i < ProfileMigratable.RETRY_COUNT; i++) { LOGGER.debug( "importing system profile (attempt out of {})", i, ProfileMigratable.RETRY_COUNT); final Boolean result = restore(report, jprofile, false); if (result != null) { return result; } } LOGGER.debug( "verifying system profile", ProfileMigratable.RETRY_COUNT, ProfileMigratable.RETRY_COUNT); final Boolean result = restore(report, jprofile, true); if (result != null) { return result; } throw new IllegalStateException("too many attempts to import profile"); }

Target:
private boolean restore(MigrationReport report, Optional<InputStream> ois) throws IOException { final InputStream is = ois.orElse(null); if (is == null) { throw new MigrationException("Import error: missing exported profile information."); } final JsonProfile jprofile = JsonUtils.fromJson(IOUtils.toString(is, StandardCharsets.UTF_8), JsonProfile.class); for (int i = 1; i < ProfileMigratable.ATTEMPT_COUNT; i++) { LOGGER.debug( "importing system profile (attempt out of {})", i, ProfileMigratable.ATTEMPT_COUNT); final Boolean result = restore(report, jprofile, false); if (result != null) { return result; } } LOGGER.debug( "verifying system profile", ProfileMigratable.ATTEMPT_COUNT, ProfileMigratable.ATTEMPT_COUNT); final Boolean result = restore(report, jprofile, true); if (result != null) { return result; } throw new IllegalStateException("too many attempts to import profile"); }
Source:
private ProtocolRequestMessage createProtocolRequestMessage(final Device device) { final String deviceIdentification = device.getDeviceIdentification(); final String organisation = "LianderNetManagement"; final String correlationUid = ""; final DeviceFunction deviceFunction = DeviceFunction.GET_STATUS; final String domain = "CORE"; final String domainVersion = "1.0"; final DeviceMessageMetadata deviceMessageMetadata = new DeviceMessageMetadata(deviceIdentification, organisation, correlationUid, deviceFunction.toString(), 0); String ipAddress = null; if (device.getNetworkAddress() == null) { LOGGER.warn("Unable to create protocol request message because the IP address is empty for device: {}", deviceIdentification); return null; } else { ipAddress = device.getNetworkAddress().getHostAddress(); } final RequestMessage requestMessage = new RequestMessage(correlationUid, organisation, deviceIdentification, null); return new ProtocolRequestMessage.Builder().deviceMessageMetadata(deviceMessageMetadata).domain(domain) .domainVersion(domainVersion).ipAddress(ipAddress).request(requestMessage).build(); }

Target:
private ProtocolRequestMessage createProtocolRequestMessage(final Device device) { final String deviceIdentification = device.getDeviceIdentification(); final String organisation = device.getOwner() == null ? "" : device.getOwner().getOrganisationIdentification(); final String correlationUid = ""; final DeviceFunction deviceFunction = DeviceFunction.GET_STATUS; final String domain = "CORE"; final String domainVersion = "1.0"; final DeviceMessageMetadata deviceMessageMetadata = new DeviceMessageMetadata(deviceIdentification, organisation, correlationUid, deviceFunction.toString(), 0); String ipAddress = null; if (device.getNetworkAddress() == null) { LOGGER.warn("Unable to create protocol request message because the IP address is empty for device: {}", deviceIdentification); return null; } else { ipAddress = device.getNetworkAddress().getHostAddress(); } final RequestMessage requestMessage = new RequestMessage(correlationUid, organisation, deviceIdentification, null); return new ProtocolRequestMessage.Builder().deviceMessageMetadata(deviceMessageMetadata).domain(domain) .domainVersion(domainVersion).ipAddress(ipAddress).request(requestMessage).build(); }
Source:
private void parseCanonicalTranscriptPerHugoSymbolTSV() { this.indexByHugoSymbol = new HashMap<>(); CsvParserSettings parserSettings = new CsvParserSettings(); parserSettings.setHeaderExtractionEnabled(true); parserSettings.getFormat().setDelimiter('\t'); parserSettings.setRowProcessor( new BeanProcessor<HugoSymbolRecord>(HugoSymbolRecord.class) { @Override public void beanProcessed(HugoSymbolRecord hugoSymbolRecord, ParsingContext context) { Map<String, List<EnsemblTranscript>> canonicalMap = indexByHugoSymbol.get(hugoSymbolRecord.getHugoSymbol()); if (canonicalMap == null) { canonicalMap = new HashMap(); } else { System.err.println("Hugo Symbols should be unique"); } canonicalMap.put("ensembl", indexByTranscript.get(hugoSymbolRecord.getEnsemblCanonicalTranscript())); canonicalMap.put("genomeNexus", indexByTranscript.get(hugoSymbolRecord.getGenomeNexusCanonicalTranscript())); canonicalMap.put("uniprot", indexByTranscript.get(hugoSymbolRecord.getUniprotCanonicalTranscript())); canonicalMap.put("mskcc", indexByTranscript.get(hugoSymbolRecord.getMskccCanonicalTranscript())); indexByHugoSymbol.put(hugoSymbolRecord.getHugoSymbol(), canonicalMap); } } ); CsvParser parser = new CsvParser(parserSettings); parser.parse(getReader(this.canonicalTranscriptPerHugoSymbolResourceURI)); }

Target:
private Map<String, Map<String, List<EnsemblTranscript>>> parseCanonicalTranscriptPerHugoSymbolTSV() { final Map<String, Map<String, List<EnsemblTranscript>>> indexByHugoSymbol = new HashMap<>(); CsvParserSettings parserSettings = new CsvParserSettings(); parserSettings.setHeaderExtractionEnabled(true); parserSettings.getFormat().setDelimiter('\t'); parserSettings.setRowProcessor( new BeanProcessor<HugoSymbolRecord>(HugoSymbolRecord.class) { @Override public void beanProcessed(HugoSymbolRecord hugoSymbolRecord, ParsingContext context) { Map<String, List<EnsemblTranscript>> canonicalMap = indexByHugoSymbol.get(hugoSymbolRecord.getHugoSymbol()); if (canonicalMap == null) { canonicalMap = new HashMap(); } else { System.err.println("Hugo Symbols should be unique"); } canonicalMap.put("ensembl", indexByTranscript.get(hugoSymbolRecord.getEnsemblCanonicalTranscript())); canonicalMap.put("genomeNexus", indexByTranscript.get(hugoSymbolRecord.getGenomeNexusCanonicalTranscript())); canonicalMap.put("uniprot", indexByTranscript.get(hugoSymbolRecord.getUniprotCanonicalTranscript())); canonicalMap.put("mskcc", indexByTranscript.get(hugoSymbolRecord.getMskccCanonicalTranscript())); indexByHugoSymbol.put(hugoSymbolRecord.getHugoSymbol(), canonicalMap); } } ); CsvParser parser = new CsvParser(parserSettings); parser.parse(getReader(this.canonicalTranscriptPerHugoSymbolResourceURI)); return indexByHugoSymbol; }
Source:
boolean joinGroupIfNeeded(final Timer timer) { while (rejoinNeededOrPending()) { if (!ensureCoordinatorReady(timer)) { return false; } if (needsJoinPrepare) { needsJoinPrepare = false; onJoinPrepare(generation.generationId, generation.memberId); } final RequestFuture<ByteBuffer> future = initiateJoinGroup(); client.poll(future, timer); if (!future.isDone()) { return false; } if (future.succeeded()) { Generation generationSnapshot; synchronized (AbstractCoordinator.this) { generationSnapshot = this.generation; } if (generationSnapshot != Generation.NO_GENERATION) { ByteBuffer memberAssignment = future.value().duplicate(); onJoinComplete(generationSnapshot.generationId, generationSnapshot.memberId, generationSnapshot.protocol, memberAssignment); resetJoinGroupFuture(); needsJoinPrepare = true; } else { log.info("Generation data was cleared by heartbeat thread. Initiating rejoin."); synchronized (AbstractCoordinator.this) { resetStateAndRejoin(); } resetJoinGroupFuture(); return false; } } else { resetJoinGroupFuture(); final RuntimeException exception = future.exception(); if (exception instanceof UnknownMemberIdException || exception instanceof RebalanceInProgressException || exception instanceof IllegalGenerationException || exception instanceof MemberIdRequiredException) continue; else if (!future.isRetriable()) throw exception; timer.sleep(rebalanceConfig.retryBackoffMs); } } return true; }

Target:
boolean joinGroupIfNeeded(final Timer timer) { while (rejoinNeededOrPending()) { if (!ensureCoordinatorReady(timer)) { return false; } if (needsJoinPrepare) { needsJoinPrepare = false; onJoinPrepare(generation.generationId, generation.memberId); } final RequestFuture<ByteBuffer> future = initiateJoinGroup(); client.poll(future, timer); if (!future.isDone()) { return false; } if (future.succeeded()) { Generation generationSnapshot; synchronized (AbstractCoordinator.this) { generationSnapshot = this.generation; } if (generationSnapshot != Generation.NO_GENERATION) { ByteBuffer memberAssignment = future.value().duplicate(); onJoinComplete(generationSnapshot.generationId, generationSnapshot.memberId, generationSnapshot.protocol, memberAssignment); resetJoinGroupFuture(); needsJoinPrepare = true; } else { log.info("Generation data was cleared by heartbeat thread. Initiating rejoin."); resetStateAndRejoin(); resetJoinGroupFuture(); return false; } } else { resetJoinGroupFuture(); final RuntimeException exception = future.exception(); if (exception instanceof UnknownMemberIdException || exception instanceof RebalanceInProgressException || exception instanceof IllegalGenerationException || exception instanceof MemberIdRequiredException) continue; else if (!future.isRetriable()) throw exception; timer.sleep(rebalanceConfig.retryBackoffMs); } } return true; }
Source:
public LocalMemoryManager(NodeMemoryConfig config) { requireNonNull(config, "config is null"); configureMemoryPools(config, Runtime.getRuntime().maxMemory()); }

Target:
public LocalMemoryManager(NodeMemoryConfig config) { this(config, Runtime.getRuntime().maxMemory()); }
Source:
public void testHeaderVersion() throws Exception { final String oldVersionHeader = "@HD\tVN:1.3\tSO:unsorted"; final File inputSam = File.createTempFile("ViewSamTest.input.", ".sam"); inputSam.deleteOnExit(); final AsciiWriter writer = new AsciiWriter(new FileOutputStream(inputSam)); writer.write(oldVersionHeader); writer.write("\n"); writer.close(); final File viewSamOutputFile = File.createTempFile("ViewSamTest.output.", ".sam"); viewSamOutputFile.deleteOnExit(); final ViewSam viewSam = new ViewSam(); viewSam.INPUT = inputSam.getAbsolutePath(); final PrintStream viewSamPrintStream = new PrintStream(viewSamOutputFile); Assert.assertEquals(viewSam.writeSamText(viewSamPrintStream), 0); viewSamPrintStream.close(); viewSamPrintStream.close(); final LineReader viewSamInputReader = new BufferedLineReader(new FileInputStream(viewSamOutputFile)); Assert.assertEquals(viewSamInputReader.readLine(), oldVersionHeader); }

Target:
public void testHeaderVersion() throws Exception { final String oldVersionHeader = "@HD\tVN:1.3\tSO:unsorted"; final File inputSam = File.createTempFile("ViewSamTest.input.", ".sam"); inputSam.deleteOnExit(); final AsciiWriter writer = new AsciiWriter(new FileOutputStream(inputSam)); writer.write(oldVersionHeader); writer.write("\n"); writer.close(); final File viewSamOutputFile = File.createTempFile("ViewSamTest.output.", ".sam"); viewSamOutputFile.deleteOnExit(); final ViewSam viewSam = new ViewSam(); viewSam.INPUT = inputSam.getAbsolutePath(); final PrintStream viewSamPrintStream = new PrintStream(viewSamOutputFile); Assert.assertEquals(viewSam.writeSamText(viewSamPrintStream), 0); viewSamPrintStream.close(); final LineReader viewSamInputReader = new BufferedLineReader(new FileInputStream(viewSamOutputFile)); Assert.assertEquals(viewSamInputReader.readLine(), oldVersionHeader); }
Source:
public void snapViewIfNeeded(View child) { mSwipeHelper.snapChildIfNeeded(child, mIsExpanded ); }

Target:
public void snapViewIfNeeded(View child) { boolean animate = mIsExpanded || isPinnedHeadsUp(child); mSwipeHelper.snapChildIfNeeded(child, animate); }
Source:
default String getName() { return getMetadata().getName(); }

Target:
default String getName() { return getMetadata() == null ? null : getMetadata().getName(); }
Source:
public void massClearNetworkFromNicsTest() { VdsNetworkInterface nic1 = dao.get(FixturesTool.VDS_NETWORK_INTERFACE); VdsNetworkInterface nic2 = dao.get(FixturesTool.VDS_NETWORK_INTERFACE_WITHOUT_QOS); VdsNetworkInterface nic3 = dao.get(FixturesTool.VDS_NETWORK_INTERFACE2); assertNotNull(nic1.getNetworkName()); assertNotNull(nic2.getNetworkName()); assertNotNull(nic3.getNetworkName()); dao.massClearNetworkFromNics(new ArrayList<>(Arrays.asList(nic1.getId(), nic2.getId()))); nic1 = dao.get(nic1.getId()); nic2 = dao.get(nic2.getId()); nic3 = dao.get(nic3.getId()); assertNull(nic1.getNetworkName()); assertNull(nic2.getNetworkName()); assertNotNull(nic3.getNetworkName()); }

Target:
public void massClearNetworkFromNicsTest() { VdsNetworkInterface nic1 = dao.get(FixturesTool.VDS_NETWORK_INTERFACE); VdsNetworkInterface nic2 = dao.get(FixturesTool.VDS_NETWORK_INTERFACE_WITHOUT_QOS); VdsNetworkInterface nic3 = dao.get(FixturesTool.VDS_NETWORK_INTERFACE2); assertNotNull(nic1.getNetworkName()); assertNotNull(nic2.getNetworkName()); assertNotNull(nic3.getNetworkName()); dao.massClearNetworkFromNics(Arrays.asList(nic1.getId(), nic2.getId())); nic1 = dao.get(nic1.getId()); nic2 = dao.get(nic2.getId()); nic3 = dao.get(nic3.getId()); assertNull(nic1.getNetworkName()); assertNull(nic2.getNetworkName()); assertNotNull(nic3.getNetworkName()); }
Source:
public void serialize(T object, Output output) { Class type = object.getClass(); if (clazz == null) { clazz = type; } Serde serde = getDefaultSerde(type); if (serde != null) { serde.serialize(object, output); return; } if (clazz == null) { kryo.writeClassAndObject(output, object); } else { kryo.writeObject(output, object); } }

Target:
public void serialize(T object, Output output) { Class type = object.getClass(); Serde serde = null; if (clazz == type) { serde = getDefaultSerde(type); } if (serde != null) { serde.serialize(object, output); return; } if (clazz == null) { kryo.writeClassAndObject(output, object); } else { kryo.writeObject(output, object); } }
Source:
void resolveColumnIndexesUsingSchema(NodeSchema inputSchema) { int difftor = 0; for (SchemaColumn col : m_outputSchema) { col.setDifferentiator(difftor); ++difftor; Collection<TupleValueExpression> allTves = ExpressionUtil.getTupleValueExpressions(col.getExpression()); for (TupleValueExpression tve : allTves) { tve.setColumnIndexUsingSchema(inputSchema); assert (tve.getColumnIndex() >= 0 || tve.getColumnIndex() < inputSchema.size()); } } }

Target:
void resolveColumnIndexesUsingSchema(NodeSchema inputSchema) { int difftor = 0; for (SchemaColumn col : m_outputSchema) { col.setDifferentiator(difftor); ++difftor; Collection<TupleValueExpression> allTves = ExpressionUtil.getTupleValueExpressions(col.getExpression()); for (TupleValueExpression tve : allTves) { tve.setColumnIndexUsingSchema(inputSchema); assert (tve.getColumnIndex() >= 0 && tve.getColumnIndex() < inputSchema.size()); } } }
Source:
protected void displayTopControl() { if (null != preferenceStore && null != preferenceStore.getString(MultiplicityConstants.MULTIPLICITY_EDITOR_MODE)) { stackLayout.topControl = preferenceStore.getString(MultiplicityConstants.MULTIPLICITY_EDITOR_MODE).equals(MultiplicityConstants.ADVANCED_MODE) ? doubleEditorsComposite : stringComboEditor; } else { if (null == stackLayout.topControl) { stackLayout.topControl = stringComboEditor; } } if (!stackLayoutComposite.isDisposed()) { stackLayoutComposite.layout(); } setReadOnly(readOnly); updateLabels(); }

Target:
protected void displayTopControl() { final String multiplicityEditorMode = preferenceStore.getString(MultiplicityConstants.MULTIPLICITY_EDITOR_MODE); if (null != preferenceStore && null != multiplicityEditorMode) { stackLayout.topControl = multiplicityEditorMode.equals(MultiplicityConstants.ADVANCED_MODE) ? doubleEditorsComposite : stringComboEditor; } else { if (null == stackLayout.topControl) { stackLayout.topControl = stringComboEditor; } } if (!stackLayoutComposite.isDisposed()) { stackLayoutComposite.layout(); } setReadOnly(readOnly); updateLabels(); }
Source:
boolean containsUpdate(TreePath path) { if (getElementPath().equals(path)) { return true; } else if (fBatchedRequests != null) { for (ViewerUpdateMonitor fBatchedRequest : fBatchedRequests) { if (fBatchedRequest.getElementPath().equals(path)) { return true; } } } return false; }

Target:
boolean containsUpdate(TreePath path) { if (getElementPath().equals(path)) { return true; } else if (fBatchedRequests != null) { for (ViewerUpdateMonitor request : fBatchedRequests) { if (request.getElementPath().equals(path)) { return true; } } } return false; }
Source:
private void handleResourceChange(GitResourceVariantTreeSubscriber subscriber, Repository which, Collection<IFile> resources) { for (GitSynchronizeData gsd : gsds) { if (which.equals(gsd.getRepository())) { if (!resources.isEmpty()) refreshResources(subscriber, resources); else refreshRepository(subscriber); } } }

Target:
private void handleResourceChange(GitResourceVariantTreeSubscriber subscriber, Repository which, Collection<IFile> resources) { for (GitSynchronizeData gsd : gsds) { if (which.equals(gsd.getRepository()) && resources != null && !resources.isEmpty()) refreshResources(subscriber, resources); } }
Source:
private ByteBuffer objectToBuffer(Object o, int estimatedSize) { if (o == null) return null; try { boolean wrapped = isPersistenceClass(o); o = wrap(o, wrapped); int size = estimatedSize < 0 ? sizeEstimate(o, true) : estimatedSize; ByteArrayOutputStream baos = new ByteArrayOutputStream(size); ProtobufUtil.toWrappedStream(serializationContext, baos, o, size); byte[] bytes = baos.toByteArray(); return new ByteBufferImpl(bytes, 0, bytes.length); } catch (Throwable t) { log.warnf(t, "Cannot marshall %s", o.getClass().getName()); throw new MarshallingException(t.getMessage(), t.getCause()); } }

Target:
private ByteBuffer objectToBuffer(Object o, int estimatedSize) { if (o == null) return null; try { boolean requiresWrapping = !isPersistenceClass(o); if (requiresWrapping) o = wrapUserObject(o); int size = estimatedSize < 0 ? sizeEstimate(o, true) : estimatedSize; ByteArrayOutputStream baos = new ByteArrayOutputStream(size); ProtobufUtil.toWrappedStream(serializationContext, baos, o, size); byte[] bytes = baos.toByteArray(); return new ByteBufferImpl(bytes, 0, bytes.length); } catch (Throwable t) { log.warnf(t, "Cannot marshall %s", o.getClass().getName()); throw new MarshallingException(t.getMessage(), t.getCause()); } }
Source:
private void saveProfiles(final String sessionId, final String taskId) throws IOException { String dir; dir = sessionId + "/" + taskId + "/" + MonitorProcess.PROFILER_MARKER; Set<String> fileNameList = fileStorage.getFileNameList(dir); if (fileNameList.isEmpty()) { log.debug("Directory is empty.", dir); return; } final TaskData taskData = getTaskData(taskId, sessionId); if (taskData == null) { log.error("TaskData not found by taskId: {}", taskId); return; } for (final String fileName : fileNameList) { LogReader.FileReader reader; try { reader = logReader.read(fileName, Object.class); } catch (IllegalArgumentException e) { log.warn(e.getMessage(), e); return; } final ProfileDTO profileDTO = SerializationUtils.fromString(reader.iterator().next().toString()); getHibernateTemplate().execute(new HibernateCallback<Void>() { @Override public Void doInHibernate(Session session) throws HibernateException, SQLException { String prefix = "Agent on (" + profileDTO.getHostAddress() + ") : "; for (Map.Entry<String, RuntimeGraph> runtimeGraphEntry : profileDTO.getRuntimeGraphs().entrySet()) { String context = SerializationUtils.toString(runtimeGraphEntry.getValue()); session.persist(new ProfilingSuT(prefix + runtimeGraphEntry.getKey(), sessionId, taskData, context)); } session.flush(); return null; } }); } }

Target:
private void saveProfiles(final String sessionId, final String taskId) throws IOException { String dir; dir = sessionId + "/" + taskId + "/" + MonitorProcess.PROFILER_MARKER; Set<String> fileNameList = fileStorage.getFileNameList(dir); if (fileNameList.isEmpty()) { log.debug("Directory is empty.", dir); return; } final TaskData taskData = getTaskData(taskId, sessionId); if (taskData == null) { log.error("TaskData not found by sessionId: and taskId: {}", sessionId, taskId); return; } for (final String fileName : fileNameList) { LogReader.FileReader reader; try { reader = logReader.read(fileName, Object.class); } catch (IllegalArgumentException e) { log.warn(e.getMessage(), e); return; } final ProfileDTO profileDTO = SerializationUtils.fromString(reader.iterator().next().toString()); getHibernateTemplate().execute(new HibernateCallback<Void>() { @Override public Void doInHibernate(Session session) throws HibernateException, SQLException { String prefix = "Agent on (" + profileDTO.getHostAddress() + ") : "; for (Map.Entry<String, RuntimeGraph> runtimeGraphEntry : profileDTO.getRuntimeGraphs().entrySet()) { String context = SerializationUtils.toString(runtimeGraphEntry.getValue()); session.persist(new ProfilingSuT(prefix + runtimeGraphEntry.getKey(), sessionId, taskData, context)); } session.flush(); return null; } }); } }
Source:
private Page replacePage(CursorPos path, Page replacement, IntValueHolder unsavedMemoryHolder) { int unsavedMemory = replacement.getMemory(); while (path != null) { Page child = replacement; replacement = path.page.copy(); replacement.setChild(path.index, child); unsavedMemory += replacement.getMemory(); path = path.parent; } unsavedMemoryHolder.value += unsavedMemory; return replacement; }

Target:
private static Page replacePage(CursorPos path, Page replacement, IntValueHolder unsavedMemoryHolder) { int unsavedMemory = replacement.getMemory(); while (path != null) { Page child = replacement; replacement = path.page.copy(); replacement.setChild(path.index, child); unsavedMemory += replacement.getMemory(); path = path.parent; } unsavedMemoryHolder.value += unsavedMemory; return replacement; }
Source:
protected HookResult runHook() { Repository repo = null; HookResult result = null; try { final List<String> argv = new ArrayList<String>(1 + args.size()); argv.add(hook.getAbsolutePath()); argv.addAll(args); final ProcessBuilder pb = new ProcessBuilder(argv); pb.redirectErrorStream(true); if(project != null) repo = openRepository(project); if (repo != null) { pb.directory(repo.getDirectory()); final Map<String, String> env = pb.environment(); env.put("GIT_DIR", repo.getDirectory().getAbsolutePath()); } Process ps = pb.start(); ps.getOutputStream().close(); InputStream is = ps.getInputStream(); String output = null; try { output = readOutput(is); } finally { try { is.close(); } catch (IOException closeErr) { } ps.waitFor(); result = new HookResult(ps.exitValue(), output); } } catch (InterruptedException iex) { } catch (Throwable err) { log.error("Error running hook " + hook.getAbsolutePath(), err); } finally { if (repo != null) { repo.close(); } } log.info("hook[" + getName() + "] exitValue:" + result.getExitValue()); BufferedReader br = new BufferedReader(new StringReader(result.getOutput())); try { String line; while ((line = br.readLine()) != null) { log.info("hook[" + getName() + "] output: " + line); } } catch(IOException iox) { log.error("Error writing hook output", iox); } return result; }

Target:
protected HookResult runHook() { Repository repo = null; HookResult result = null; try { final List<String> argv = new ArrayList<String>(1 + args.size()); argv.add(hook.getAbsolutePath()); argv.addAll(args); final ProcessBuilder pb = new ProcessBuilder(argv); pb.redirectErrorStream(true); if(project != null) { repo = openRepository(project); } if (repo != null) { pb.directory(repo.getDirectory()); final Map<String, String> env = pb.environment(); env.put("GIT_DIR", repo.getDirectory().getAbsolutePath()); } ps = pb.start(); ps.getOutputStream().close(); InputStream is = ps.getInputStream(); String output = null; try { output = readOutput(is); } finally { try { is.close(); } catch (IOException closeErr) { } ps.waitFor(); result = new HookResult(ps.exitValue(), output); } } catch (InterruptedException iex) { } catch (Throwable err) { log.error("Error running hook " + hook.getAbsolutePath(), err); } finally { if (repo != null) { repo.close(); } } log.info("hook[" + getName() + "] exitValue:" + result.getExitValue()); BufferedReader br = new BufferedReader(new StringReader(result.getOutput())); try { String line; while ((line = br.readLine()) != null) { log.info("hook[" + getName() + "] output: " + line); } } catch(IOException iox) { log.error("Error writing hook output", iox); } return result; }
Source:
public VirtConsumerMap getGuestConsumersMap(Owner owner, Set<String> guestIds) { VirtConsumerMap guestConsumersMap = new VirtConsumerMap(); if (guestIds.size() == 0) { return guestConsumersMap; } List<String> possibleGuestIds = Util.getPossibleUuids(guestIds.toArray( new String [guestIds.size()])); String sql = "select cp_consumer.uuid from cp_consumer " + "inner join cp_consumer_facts " + "on cp_consumer.id = cp_consumer_facts.cp_consumer_id " + "where cp_consumer_facts.mapkey = 'virt.uuid' and " + "lower(cp_consumer_facts.element) in (:guestids) " + "and cp_consumer.owner_id = :ownerid " + "order by cp_consumer.updated desc"; Query q = currentSession().createSQLQuery(sql); List<String> consumerUuids = new ArrayList<String>(); int fromIndex = 0; int toIndex = fromIndex + MAX_IN_QUERY_LENGTH; int count = 0; while (fromIndex < possibleGuestIds.size()) { if (toIndex > possibleGuestIds.size()) { toIndex = possibleGuestIds.size(); } List<String> subList = possibleGuestIds.subList(fromIndex, toIndex); q.setParameterList("guestids", subList); q.setParameter("ownerid", owner.getId()); consumerUuids.addAll(q.list()); fromIndex = toIndex; toIndex += MAX_IN_QUERY_LENGTH; } if (consumerUuids == null || consumerUuids.size() == 0) { return guestConsumersMap; } List<Consumer> guestConsumersWithDupes = findByUuidsAndOwner(consumerUuids, owner); for (Consumer c : guestConsumersWithDupes) { String virtUuid = c.getFact("virt.uuid").toLowerCase(); if (guestConsumersMap.get(virtUuid) == null) { guestConsumersMap.add(virtUuid, c); } } return guestConsumersMap; }

Target:
public VirtConsumerMap getGuestConsumersMap(Owner owner, Set<String> guestIds) { VirtConsumerMap guestConsumersMap = new VirtConsumerMap(); if (guestIds.size() == 0) { return guestConsumersMap; } List<String> possibleGuestIds = Util.getPossibleUuids(guestIds.toArray( new String [guestIds.size()])); String sql = "select cp_consumer.uuid from cp_consumer " + "inner join cp_consumer_facts " + "on cp_consumer.id = cp_consumer_facts.cp_consumer_id " + "where cp_consumer_facts.mapkey = 'virt.uuid' and " + "lower(cp_consumer_facts.element) in (:guestids) " + "and cp_consumer.owner_id = :ownerid " + "order by cp_consumer.updated desc"; Query q = currentSession().createSQLQuery(sql); List<String> consumerUuids = new ArrayList<String>(); int fromIndex = 0; int toIndex = fromIndex + MAX_IN_QUERY_LENGTH; while (fromIndex < possibleGuestIds.size()) { if (toIndex > possibleGuestIds.size()) { toIndex = possibleGuestIds.size(); } List<String> subList = possibleGuestIds.subList(fromIndex, toIndex); q.setParameterList("guestids", subList); q.setParameter("ownerid", owner.getId()); consumerUuids.addAll(q.list()); fromIndex = toIndex; toIndex += MAX_IN_QUERY_LENGTH; } if (consumerUuids == null || consumerUuids.size() == 0) { return guestConsumersMap; } List<Consumer> guestConsumersWithDupes = findByUuidsAndOwner(consumerUuids, owner); for (Consumer c : guestConsumersWithDupes) { String virtUuid = c.getFact("virt.uuid").toLowerCase(); if (guestConsumersMap.get(virtUuid) == null) { guestConsumersMap.add(virtUuid, c); } } return guestConsumersMap; }
Source:
public void createContractFork() throws Exception { String contractSrc = "contract Child {" + " int a;" + " int b;" + " int public c;" + " function Child(int i) {" + " a = 333 + i;" + " b = 444 + i;" + " }" + " function sum() {" + " c = a + b;" + " }" + "}" + "contract Parent {" + " address public child;" + " function createChild(int a) returns (address) {" + " child = new Child(a);" + " return child;" + " }" + "}"; StandaloneBlockchain bc = new StandaloneBlockchain(); SolidityContract parent = bc.submitNewContract(contractSrc, "<stdin>:Parent"); Block b1 = bc.createBlock(); Block b2 = bc.createBlock(); parent.callFunction("createChild", 100); Block b3 = bc.createBlock(); byte[] childAddress = (byte[]) parent.callConstFunction("child")[0]; parent.callFunction("createChild", 200); Block b2_ = bc.createForkBlock(b1); SolidityContract child = bc.createExistingContractFromSrc(contractSrc, "<stdin>:Child", childAddress); child.callFunction("sum"); Block b4 = bc.createBlock(); Assert.assertEquals(BigInteger.valueOf(100 + 333 + 100 + 444), child.callConstFunction("c")[0]); }

Target:
public void createContractFork() throws Exception { String contractSrc = "contract Child {" + " int a;" + " int b;" + " int public c;" + " function Child(int i) {" + " a = 333 + i;" + " b = 444 + i;" + " }" + " function sum() {" + " c = a + b;" + " }" + "}" + "contract Parent {" + " address public child;" + " function createChild(int a) returns (address) {" + " child = new Child(a);" + " return child;" + " }" + "}"; StandaloneBlockchain bc = new StandaloneBlockchain(); SolidityContract parent = bc.submitNewContract(contractSrc, "Parent"); Block b1 = bc.createBlock(); Block b2 = bc.createBlock(); parent.callFunction("createChild", 100); Block b3 = bc.createBlock(); byte[] childAddress = (byte[]) parent.callConstFunction("child")[0]; parent.callFunction("createChild", 200); Block b2_ = bc.createForkBlock(b1); SolidityContract child = bc.createExistingContractFromSrc(contractSrc, "Child", childAddress); child.callFunction("sum"); Block b4 = bc.createBlock(); Assert.assertEquals(BigInteger.valueOf(100 + 333 + 100 + 444), child.callConstFunction("c")[0]); }
Source:
public void testForValidProgramId() throws MiddlewareQueryException { final BindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), "Program"); final Integer attributeById = 1; final Attribute attribute = new Attribute(); attribute.setAid(1); Mockito.doReturn(attribute).when(this.germplasmDataManager).getAttributeById(attributeById); this.attributeValidator.validateAttributeIds(bindingResult, Lists.newArrayList(String.valueOf(attributeById))); Assert.assertFalse(bindingResult.hasErrors()); }

Target:
public void testForValidProgramId() throws MiddlewareQueryException { final BindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), "Program"); final Integer attributeById = Integer.valueOf(RandomStringUtils.randomNumeric(1)); final Attribute attribute = new Attribute(); attribute.setAid(attributeById); List<Attribute> attributeLists = Lists.newArrayList(attribute); Mockito.doReturn(attributeLists).when(this.germplasmDataManager).getAttributeByIds(Lists.newArrayList(attributeById)); this.attributeValidator.validateAttributeIds(bindingResult, Lists.newArrayList(String.valueOf(attributeById))); Assert.assertFalse(bindingResult.hasErrors()); }
Source:
public ClusterServiceModule(Configuration configuration){ this.configuration = configuration; checkNotNull(configuration); String className = configuration.getString("provider.classname"); checkNotNull(className); implClass = getImplClassForName(className); checkNotNull(implClass); }

Target:
public ClusterServiceModule(Configuration configuration) throws ClassNotFoundException{ this.configuration = checkNotNull(configuration); implClass = Class.forName(configuration.getString("provider.classname")); }
Source:
public final void test() throws EdisonException { log.debug("Corlex Feature Extractor"); TextAnnotation ta = tas.get(1); View TOKENS = ta.getView("TOKENS"); log.debug("Got tokens FROM TextAnnotation"); CorlexFeatureExtractor testInstance = new CorlexFeatureExtractor(true); Set<Feature> feats = testInstance.getWordFeatures(ta,1); String[] expected_outputs = {"atr"}; if (feats == null) { log.debug("Feats are returning NULL."); } log.debug("Printing Set of Features"); for (Feature f : feats) { log.debug(f.getName()); assert (ArrayUtils.contains(expected_outputs, f.getName())); } }

Target:
public final void test() throws EdisonException { log.debug("Corlex Feature Extractor"); TextAnnotation ta = tas.get(1); View TOKENS = ta.getView("TOKENS"); log.debug("Got tokens FROM TextAnnotation"); CorlexFeatureExtractor testInstance = new CorlexFeatureExtractor(true); Set<Feature> feats = testInstance.getWordFeatures(ta,1); String[] expected_outputs = {"atr"}; if (feats == null) { log.debug("Feats are returning NULL."); } log.debug("Printing Set of Features"); for (Feature f : feats) { log.debug(f.getName()); assertTrue(ArrayUtils.contains(expected_outputs, f.getName())); } }
Source:
void startPeriodRebalance(long period, HelixManager manager) { if (period != _timerPeriod) { logger.info("Controller starting periodical rebalance timer at period " + period); ScheduledFuture lastScheduledFuture = null; synchronized (_lock) { if (_periodicRebalancerFutureTasks!=null && !_periodicRebalancerFutureTasks.isCancelled()) { lastScheduledFuture = _periodicRebalancerFutureTasks; } _timerPeriod = period; _periodicRebalancerFutureTasks = _periodicalRebalanceExecutor .scheduleAtFixedRate(new RebalanceTask(manager, ClusterEventType.PeriodicalRebalance), _timerPeriod, _timerPeriod, TimeUnit.MILLISECONDS); } if (lastScheduledFuture != null) { lastScheduledFuture.cancel(true ); } } else { logger.info("Controller already has periodical rebalance timer at period " + _timerPeriod); } }

Target:
void startPeriodRebalance(long period, HelixManager manager) { if (period != _timerPeriod) { logger.info("Controller starting periodical rebalance timer at period " + period); ScheduledFuture lastScheduledFuture; synchronized (_periodicalRebalanceExecutor) { lastScheduledFuture = _periodicRebalanceFutureTask; _timerPeriod = period; _periodicRebalanceFutureTask = _periodicalRebalanceExecutor .scheduleAtFixedRate(new RebalanceTask(manager, ClusterEventType.PeriodicalRebalance), _timerPeriod, _timerPeriod, TimeUnit.MILLISECONDS); } if (lastScheduledFuture != null && !lastScheduledFuture.isCancelled()) { lastScheduledFuture.cancel(false ); } } else { logger.info("Controller already has periodical rebalance timer at period " + _timerPeriod); } }
Source:
public List<User> getUsersByRole(Role role) throws APIException { List<Role> roles = new ArrayList<>(); roles.add(role); return removeDaemonUsers(Context.getUserService().getUsers(null, roles, false)); }

Target:
public List<User> getUsersByRole(Role role) throws APIException { List<Role> roles = new ArrayList<>(); roles.add(role); return Context.getUserService().getUsers(null, roles, false); }