auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void start(final Stage primaryStage) throws IOException { Runtime.getRuntime().addShutdownHook(MainApplication.CLEAN_SHUTDOWN_PERFORMER); executorService = Executors.newCachedThreadPool(); addShutdownTask(() -> { executorService.shutdown(); }); WebDavServer.getInstance().start(); chooseNativeStylesheet(); final ResourceBundle rb = ResourceBundle.getBundle("localization"); final FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"), rb); final Parent root = loader.load(); final MainController ctrl = loader.getController(); ctrl.setStage(primaryStage); final Scene scene = new Scene(root); primaryStage.setTitle(rb.getString("app.name")); primaryStage.setScene(scene); primaryStage.sizeToScene(); primaryStage.setResizable(false); primaryStage.show(); ActiveWindowStyleSupport.startObservingFocus(primaryStage); TrayIconUtil.init(primaryStage, rb, () -> { quit(); }); for (String arg : getParameters().getUnnamed()) { handleCommandLineArg(ctrl, arg); } if (org.controlsfx.tools.Platform.getCurrent().equals(org.controlsfx.tools.Platform.OSX)) { Main.openFileHandler.complete(file -> handleCommandLineArg(ctrl, file.getAbsolutePath())); } LocalInstance cryptomatorGuiInstance = SingleInstanceManager.startLocalInstance(APPLICATION_KEY, executorService); addShutdownTask(() -> { cryptomatorGuiInstance.close(); }); cryptomatorGuiInstance.registerListener(arg -> handleCommandLineArg(ctrl, arg)); }

Target:
public void start(final Stage primaryStage) throws IOException { Runtime.getRuntime().addShutdownHook(MainApplication.CLEAN_SHUTDOWN_PERFORMER); executorService = Executors.newCachedThreadPool(); addShutdownTask(() -> { executorService.shutdown(); }); WebDavServer.getInstance().start(); chooseNativeStylesheet(); final ResourceBundle rb = ResourceBundle.getBundle("localization"); final FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"), rb); final Parent root = loader.load(); final MainController ctrl = loader.getController(); ctrl.setStage(primaryStage); final Scene scene = new Scene(root); primaryStage.setTitle(rb.getString("app.name")); primaryStage.setScene(scene); primaryStage.sizeToScene(); primaryStage.setResizable(false); primaryStage.show(); ActiveWindowStyleSupport.startObservingFocus(primaryStage); TrayIconUtil.init(primaryStage, rb, () -> { quit(); }); for (String arg : getParameters().getUnnamed()) { handleCommandLineArg(ctrl, arg); } if (org.controlsfx.tools.Platform.getCurrent().equals(org.controlsfx.tools.Platform.OSX)) { Main.OPEN_FILE_HANDLER.complete(file -> handleCommandLineArg(ctrl, file.getAbsolutePath())); } LocalInstance cryptomatorGuiInstance = SingleInstanceManager.startLocalInstance(APPLICATION_KEY, executorService); addShutdownTask(() -> { cryptomatorGuiInstance.close(); }); cryptomatorGuiInstance.registerListener(arg -> handleCommandLineArg(ctrl, arg)); }
Source:
private CircuitBreaker getCircuitBreaker(String circuitBreakerName) { CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker(circuitBreakerName); if (circuitBreaker == null && !circuitBreaker.getName().equalsIgnoreCase(circuitBreakerName)) { new IllegalArgumentException(String .format("circuit breaker with name %s not found", circuitBreakerName)); } return circuitBreaker; }

Target:
private CircuitBreaker getCircuitBreaker(String circuitBreakerName) { return circuitBreakerRegistry.circuitBreaker(circuitBreakerName); }
Source:
private void mockViolations(List<DomainViolation> violations) { violations.stream().forEach(v -> { when(v.getViolationType()).thenReturn(Violation.Type.ERROR); when(v.getUUID()).thenReturn(UUID_1); }); DomainViolation first = violations.get(0); when(first.getUUID()).thenReturn(UUID_0); DomainViolation last1 = violations.get(violations.size() - 2); when(last1.getUUID()).thenReturn("null"); DomainViolation last = violations.get(violations.size() - 1); when(last.getUUID()).thenReturn(null); }

Target:
private void mockViolations(List<DomainViolation> violations) { violations.stream().forEach(v -> { when(v.getViolationType()).thenReturn(Violation.Type.ERROR); when(v.getUUID()).thenReturn(UUID_1); }); DomainViolation first = violations.get(0); when(first.getUUID()).thenReturn(UUID_0); DomainViolation last1 = violations.get(violations.size() - 2); when(last1.getUUID()).thenReturn(null); DomainViolation last = violations.get(violations.size() - 1); when(last.getUUID()).thenReturn("null"); }
Source:
void offer(final UUID client) { if (uniqueClients.contains(client)) { clientsByTaskLoad.remove(client); } clientsByTaskLoad.offer(client); uniqueClients.add(client); }

Target:
void offer(final UUID client) { if (uniqueClients.contains(client)) { clientsByTaskLoad.remove(client); } else { uniqueClients.add(client); } clientsByTaskLoad.offer(client); }
Source:
protected CompletionStage<Collection<Void>> handleMessageAsync(KV<K, V> message, MessageCollector collector, TaskCoordinator coordinator) { return table.putAsync(message.getKey(), message.getValue()) .thenApply(ignored -> Collections.emptyList()); }

Target:
protected CompletionStage<Collection<KV<K, V>>> handleMessageAsync(KV<K, V> message, MessageCollector collector, TaskCoordinator coordinator) { return table.putAsync(message.getKey(), message.getValue(), sendToTableOpSpec.getArgs()) .thenApply(result -> Collections.singleton(message)); }
Source:
private void merge(YamlNode source, YamlNode target) { if (source == null) { return; } YamlMapping sourceAsMapping = asMapping(source); YamlMapping targetAsMapping = asMapping(target); for (YamlNode sourceChild : sourceAsMapping.children()) { YamlNode targetChild = targetAsMapping.child(sourceChild.nodeName()); if (targetChild != null) { merge(sourceChild, targetChild); } else { if (targetAsMapping instanceof MutableYamlMapping) { ((YamlMappingImpl) targetAsMapping).addChild(sourceChild.nodeName(), sourceChild); } } } }

Target:
private void merge(YamlNode source, YamlNode target) { YamlMapping sourceAsMapping = asMapping(source); YamlMapping targetAsMapping = asMapping(target); for (YamlNode sourceChild : sourceAsMapping.children()) { YamlNode targetChild = targetAsMapping.child(sourceChild.nodeName()); if (targetChild != null) { merge(sourceChild, targetChild); } else { ((MutableYamlMapping) targetAsMapping).addChild(sourceChild.nodeName(), sourceChild); } } }
Source:
public static List<String> getTags(JSONObject jo) throws JSONException { if (jo.has(FIELD_TAGS)) { return getStringsFromJSONArray(jo.getJSONArray(FIELD_TAGS)); } else { return Lists.newArrayList(); } }

Target:
public static List<String> getTags(JSONObject jo) throws JSONException { if (jo.has(FIELD_TAGS)) { return getStringsFromJSONArray(jo.getJSONArray(FIELD_TAGS)); } else { return Collections.emptyList(); } }
Source:
public void onFailure(Call<T> call, Throwable t) { Log.e("DefaultCallback", "Nework failure", t); }

Target:
public void onFailure(Call<T> call, Throwable t) { ZLog.logException(t); }
Source:
public final synchronized Subject getSystemSubject() { auditSystemSubjectAccess(); final java.lang.SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkPermission(Security.GET_SYSTEM_SUBJECT_PERMISSION); } if (!javaSubjectHasAdminRole()) { SecurityLogger.audit("Unable to retrieve system subject."); return null; } if (!tokenAboutToExpire(cachedSystemSubject)) { return cachedSystemSubject; } KeyStore keyStore = AccessController.doPrivileged((PrivilegedAction<KeyStore>) this::getSystemKeyStore); String alias = null; Certificate cert = null; try { if (keyStore != null) { if (keyStore.size() == 1) { alias = keyStore.aliases().nextElement(); } else if (keyStore.size() > 1) { alias = getCertificateAlias(); } cert = keyStore.getCertificate(alias); } } catch (KeyStoreException e) { LOGGER.warn("Unable to get certificate for alias [{}]", alias, e); return null; } if (cert == null) { LOGGER.warn("Unable to get certificate for alias [{}]", alias); return null; } AuthenticationTokenFactory tokenFactory = createBasicTokenFactory(); AuthenticationToken token = tokenFactory.fromCertificates(new X509Certificate[] {(X509Certificate) cert}, "127.0.0.1"); if (token != null) { ((BaseAuthenticationToken) token).setAllowGuest(true); SecurityManager securityManager = getSecurityManager(); if (securityManager != null) { try { cachedSystemSubject = securityManager.getSubject(token); } catch (SecurityServiceException sse) { LOGGER.warn("Unable to request subject for system user.", sse); } } } return cachedSystemSubject; }

Target:
public final synchronized Subject getSystemSubject() { auditSystemSubjectAccess(); final java.lang.SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkPermission(Security.GET_SYSTEM_SUBJECT_PERMISSION); } if (!javaSubjectHasAdminRole()) { SecurityLogger.audit("Unable to retrieve system subject."); return null; } if (!tokenAboutToExpire(cachedSystemSubject)) { return cachedSystemSubject; } KeyStore keyStore = AccessController.doPrivileged((PrivilegedAction<KeyStore>) this::getSystemKeyStore); String alias = null; Certificate cert = null; try { if (keyStore != null) { if (keyStore.size() == 1) { alias = keyStore.aliases().nextElement(); } else if (keyStore.size() > 1) { alias = getCertificateAlias(); } cert = keyStore.getCertificate(alias); } } catch (KeyStoreException e) { LOGGER.warn("Unable to get certificate for alias [{}]", alias, e); return null; } if (cert == null) { LOGGER.warn("Unable to get certificate for alias [{}]", alias); return null; } AuthenticationTokenFactory tokenFactory = createBasicTokenFactory(); AuthenticationToken token = tokenFactory.fromCertificates(new X509Certificate[] {(X509Certificate) cert}, "127.0.0.1"); if (token != null) { if (token instanceof BaseAuthenticationToken) { ((BaseAuthenticationToken) token).setAllowGuest(true); } SecurityManager securityManager = getSecurityManager(); if (securityManager != null) { try { cachedSystemSubject = securityManager.getSubject(token); } catch (SecurityServiceException sse) { LOGGER.warn("Unable to request subject for system user.", sse); } } } return cachedSystemSubject; }
Source:
public void validate() { if (enabled()) { if (clustering().cacheMode().isInvalidation()) { throw CONFIG.invalidConfigurationIndexingWithInvalidation(); } if (indexedEntities().isEmpty() && !getBuilder().template()) { CONFIG.noIndexableClassesDefined(); } } else { if (!indexedEntities().isEmpty()) { } } if (attributes.attribute(PROPERTIES).get() .entrySet().stream() .filter(e -> ((String) e.getKey()).endsWith(DIRECTORY_PROVIDER_SUFFIX)) .map(Map.Entry::getValue) .collect(Collectors.toSet()).size() > 1) { throw CONFIG.foundMultipleDirectoryProviders(); } if (attributes.attribute(INDEX).get() == Index.PRIMARY_OWNER) { throw CONFIG.indexModeNotSupported(Index.PRIMARY_OWNER.name()); } }

Target:
public void validate() { if (enabled()) { if (clustering().cacheMode().isInvalidation()) { throw CONFIG.invalidConfigurationIndexingWithInvalidation(); } if (indexedEntities().isEmpty() && !getBuilder().template()) { CONFIG.noIndexableClassesDefined(); } } else { if (!indexedEntities().isEmpty()) { } } ensureSingleIndexingProvider(); if (attributes.attribute(INDEX).get() == Index.PRIMARY_OWNER) { throw CONFIG.indexModeNotSupported(Index.PRIMARY_OWNER.name()); } }
Source:
static <T, R> WorkProcessor<R> flatTransform(WorkProcessor<T> processor, Transformation<T, WorkProcessor<R>> transformation) { return processor.transform(new Transformation<T, R>() { WorkProcessor<R> processor; boolean needsMoreData; @Override public ProcessorState<R> process(Optional<T> elementOptional) { while (true) { if (processor == null) { ProcessorState<WorkProcessor<R>> state = transformation.process(elementOptional); if (state.type != ProcessorState.Type.RESULT) { return new ProcessorState<>(state.type, state.needsMoreData, Optional.empty(), state.blocked); } processor = state.result.get(); needsMoreData = state.needsMoreData; } if (processor.process()) { if (!processor.isFinished()) { return ProcessorState.ofResult(processor.getResult(), false); } processor = null; if (needsMoreData) { return ProcessorState.needsMoreData(); } } else if (processor.isBlocked()) { return ProcessorState.blocked(processor.getBlockedFuture()); } else { return ProcessorState.yield(); } } } }); }

Target:
static <T, R> WorkProcessor<R> flatTransform(WorkProcessor<T> processor, Transformation<T, WorkProcessor<R>> transformation) { return processor.transform(new Transformation<T, R>() { WorkProcessor<R> processor; boolean needsMoreData; @Override public ProcessorState<R> process(Optional<T> elementOptional) { while (true) { if (processor == null) { ProcessorState<WorkProcessor<R>> state = transformation.process(elementOptional); if (state.getType() != ProcessorState.Type.RESULT) { return new ProcessorState<>(state.getType(), state.isNeedsMoreData(), Optional.empty(), state.getBlocked()); } processor = state.getResult().get(); needsMoreData = state.isNeedsMoreData(); } if (processor.process()) { if (!processor.isFinished()) { return ProcessorState.ofResult(processor.getResult(), false); } processor = null; if (needsMoreData) { return ProcessorState.needsMoreData(); } } else if (processor.isBlocked()) { return ProcessorState.blocked(processor.getBlockedFuture()); } else { return ProcessorState.yield(); } } } }); }
Source:
public void testProcessSpecialSoftwareCapabilities() { VDS vds = new VDS(); vds.setSupportedEmulatedMachines("pc-1.0"); vds.setStatus(VDSStatus.Up); virtStrategy.processSoftwareCapabilities(vds); Assert.assertEquals(VDSStatus.Up, vds.getStatus()); vds.setKvmEnabled(Boolean.TRUE); virtStrategy.processSoftwareCapabilities(vds); Assert.assertEquals(VDSStatus.Up, vds.getStatus()); vds.setKvmEnabled(Boolean.FALSE); virtStrategy.processSoftwareCapabilities(vds); assertEquals(VDSStatus.NonOperational, vds.getStatus()); }

Target:
public void testProcessSpecialSoftwareCapabilities() { VDS vds = new VDS(); vds.setSupportedEmulatedMachines("pc-1.0"); vds.setStatus(VDSStatus.Up); virtStrategy.processSoftwareCapabilities(vds); assertEquals(VDSStatus.Up, vds.getStatus()); vds.setKvmEnabled(Boolean.TRUE); virtStrategy.processSoftwareCapabilities(vds); assertEquals(VDSStatus.Up, vds.getStatus()); vds.setKvmEnabled(Boolean.FALSE); virtStrategy.processSoftwareCapabilities(vds); assertEquals(VDSStatus.NonOperational, vds.getStatus()); }
Source:
public Optional<?> getProperty(T pojo, String propertyName) { return ReflectionAdapterUtils.getFields(pojo.getClass()).stream() .filter(f -> Objects.equals(propertyName, f.getName())) .map(field -> Exceptions.swallow(() -> field.get(pojo), null)) .findFirst(); }

Target:
public Optional<?> getProperty(T pojo, String propertyName) { return ReflectionAdapterUtils.getFields(pojo.getClass()).stream() .filter(field -> Objects.equals(propertyName, field.getName())) .map(field -> Exceptions.swallow(() -> field.get(pojo), null)) .findFirst(); }
Source:
private CompletableFuture<Location> calculateRandomLocation(Location center, double minRange, double maxRange) { CompletableFuture<Location> future = new CompletableFuture<>(); double[] offset = getRandXySquare(minRange, maxRange); Location location = new Location( center.getWorld(), center.getX() + offset[0], center.getWorld().getMaxHeight(), center.getZ() + offset[1], 360 * RANDOM.nextFloat() - 180, 0 ); PaperLib.getChunkAtAsync(location).thenAccept(chunk -> { if (World.Environment.NETHER.equals(center.getWorld().getEnvironment())) { location.setY(getNetherYAt(location)); } else { location.setY(center.getWorld().getHighestBlockYAt(location) + HIGHEST_BLOCK_Y_OFFSET); } future.complete(location); }); return future; }

Target:
private CompletableFuture<Location> calculateRandomLocation(Location center, double minRange, double maxRange) { CompletableFuture<Location> future = new CompletableFuture<>(); double rectX = RANDOM.nextDouble() * (maxRange - minRange) + minRange; double rectZ = RANDOM.nextDouble() * (maxRange + minRange) - minRange; double offsetX, offsetZ; int transform = RANDOM.nextInt(4); if (transform == 0) { offsetX = rectX; offsetZ = rectZ; } else if (transform == 1) { offsetX = -rectZ; offsetZ = rectX; } else if (transform == 2) { offsetX = -rectX; offsetZ = -rectZ; } else { offsetX = rectZ; offsetZ = -rectX; } Location location = new Location( center.getWorld(), center.getX() + offsetX, center.getWorld().getMaxHeight(), center.getZ() + offsetZ, 360 * RANDOM.nextFloat() - 180, 0 ); PaperLib.getChunkAtAsync(location).thenAccept(chunk -> { if (World.Environment.NETHER.equals(center.getWorld().getEnvironment())) { location.setY(getNetherYAt(location)); } else { location.setY(center.getWorld().getHighestBlockYAt(location) + HIGHEST_BLOCK_Y_OFFSET); } future.complete(location); }); return future; }
Source:
public void makeHeaderVisible() { waitForElementByElement(titleLink); executeScript("$('.LightboxHeader').css('opacity', 'initial')"); }

Target:
public void makeHeaderVisible() { waitForElementByElement(titleLink); executeScript("$('.LightboxHeader').css('opacity', '1')"); }
Source:
private String getIdForEvent(MuleEvent event) throws Exception { if (useSecureHash) { MuleMessage message = event.getMessage(); Object payload = message.getPayload(); byte[] payloadBytes = (byte[]) objectToByteArray.transform(payload); byte[] bytes = Bytes.concat(payloadBytes, message.getUniqueId().getBytes()); if (payload instanceof InputStream) { event.getMessage().setPayload(bytes); } MessageDigest md = MessageDigest.getInstance(messageDigestAlgorithm); byte[] digestedBytes = md.digest(bytes); return (String)byteArrayToHexString.transform(digestedBytes); } else { return event.getMuleContext().getExpressionManager().parse(idExpression, event, true); } }

Target:
private String getIdForEvent(MuleEvent event) throws Exception { if (useSecureHash) { MuleMessage message = event.getMessage(); Object payload = message.getPayload(); byte[] payloadBytes = (byte[]) objectToByteArray.transform(payload); byte[] bytes = concat(payloadBytes, message.getUniqueId().getBytes()); if (payload instanceof InputStream) { event.getMessage().setPayload(bytes); } MessageDigest md = MessageDigest.getInstance(messageDigestAlgorithm); byte[] digestedBytes = md.digest(bytes); return (String)byteArrayToHexString.transform(digestedBytes); } else { return event.getMuleContext().getExpressionManager().parse(idExpression, event, true); } }
Source:
static String checkNotEmpty(String value, String name) { if (value == null) { throw new NullPointerException(name + " is null"); } if (value.isEmpty()) { throw new PrestoException(GENERIC_USER_ERROR, name + " is empty"); } return value; }

Target:
static String checkNotEmpty(String value, String name) { if (value == null) { throw new NullPointerException(name + " is null"); } if (value.isEmpty()) { throw new IllegalArgumentException(name + " is empty"); } return value; }
Source:
default Tuple2<Iterator<T>, Iterator<T>> partition(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); if (!hasNext()) { return Tuple.of(empty(), empty()); } else { Stream<T> first = Stream.empty(); Stream<T> second = Stream.empty(); for (T t : this) { if (predicate.test(t)) { first = first.append(t); } else { second = second.append(t); } } return Tuple.of(first.iterator(), second.iterator()); } }

Target:
default Tuple2<Iterator<T>, Iterator<T>> partition(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); if (!hasNext()) { return Tuple.of(empty(), empty()); } else { final Tuple2<Iterator<T>, Iterator<T>> dup = IteratorModule.duplicate(this); return Tuple.of(dup._1.filter(predicate), dup._2.filterNot(predicate)); } }
Source:
protected FileLock lock(final long lockPosition) throws Exception { long start = System.currentTimeMillis(); boolean isRecurringFailure = false; while (!interrupted) { try { FileLock lock = tryLock(lockPosition); isRecurringFailure = false; if (lock == null) { logger.debug("lock is null"); try { Thread.sleep(500); } catch (InterruptedException e) { return null; } if (lockAcquisitionTimeout != -1 && (System.currentTimeMillis() - start) > lockAcquisitionTimeout) { throw new Exception("timed out waiting for lock"); } } else { return lock; } } catch (IOException e) { logger.log(isRecurringFailure ? Logger.Level.DEBUG : Logger.Level.WARN, "Failure when accessing a lock file", e); isRecurringFailure = true; Thread.sleep(LOCK_ACCESS_FAILURE_WAIT_TIME); } } FileLock lock = null; do { try { lock = tryLock(lockPosition); isRecurringFailure = false; if (lock == null) { try { Thread.sleep(500); } catch (InterruptedException e1) { } } } catch (IOException e) { logger.log(isRecurringFailure ? Logger.Level.DEBUG : Logger.Level.WARN, "Failure when accessing a lock file", e); isRecurringFailure = true; Thread.sleep(LOCK_ACCESS_FAILURE_WAIT_TIME); } if (interrupted) { interrupted = false; throw new IOException("Lock was interrupted"); } } while (lock == null); return lock; }

Target:
protected FileLock lock(final long lockPosition) throws Exception { long start = System.currentTimeMillis(); boolean isRecurringFailure = false; while (!interrupted) { try { FileLock lock = tryLock(lockPosition); isRecurringFailure = false; if (lock == null) { try { Thread.sleep(500); } catch (InterruptedException e) { return null; } if (lockAcquisitionTimeout != -1 && (System.currentTimeMillis() - start) > lockAcquisitionTimeout) { throw new ActiveMQLockAcquisitionTimeoutException("timed out waiting for lock"); } } else { return lock; } } catch (IOException e) { logger.log(isRecurringFailure ? Logger.Level.DEBUG : Logger.Level.WARN, "Failure when accessing a lock file", e); isRecurringFailure = true; long waitTime = LOCK_ACCESS_FAILURE_WAIT_TIME; if (lockAcquisitionTimeout != -1) { final long remainingTime = lockAcquisitionTimeout - (System.currentTimeMillis() - start); if (remainingTime <= 0) { throw new ActiveMQLockAcquisitionTimeoutException("timed out waiting for lock"); } waitTime = Math.min(waitTime, remainingTime); } try { Thread.sleep(waitTime); } catch (InterruptedException interrupt) { return null; } } } return null; }
Source:
public Object execute() throws Exception { EventBuilder eventBuilder = new EventBuilder(EventConstants.RELOAD_IMPORT_UEI, EVENT_SOURCE); if((!Strings.isNullOrEmpty(requisition)) && (!Strings.isNullOrEmpty(type)) && requisition.contains("=")) { String url = String.format("requisition://%s?%s", type, requisition); eventBuilder.addParam("url", url); eventForwarder.sendNow(eventBuilder.getEvent()); System.out.printf("Import Requisition Event sent with URL : %s \n ", url); } else { System.out.printf("No valid requisition specified, It should be specified in 'name=myServer' format \n"); } return null; }

Target:
public Object execute() throws Exception { return sendImportRequisitionEvent(eventForwarder, type, parameters, rescanExisting); }
Source:
public StrangeCANSpeedControllerModeRuntimeException() { super("One of " + getName() + "'s CustomSpeedControllers is a CANSpeedController with a non-zero mode. This might mess up it's .get(), so Motor cannot verify safety."); }

Target:
public StrangeCANSpeedControllerModeRuntimeException() { super("One of " + getName() + "'s SpeedControllers is a CANSpeedController with a non-zero mode. This might mess up it's .get(), so Motor cannot verify safety."); }
Source:
public RosActivity(String notificationTicker, String notificationTitle) { super(); rosActivityComponent = new RosActivityComponent(notificationTicker, notificationTitle, this); }

Target:
public RosActivity(String notificationTicker, String notificationTitle) { rosActivityComponent = new RosActivityComponent(this, notificationTicker, notificationTitle, new RosActivityEventsHandler()); }
Source:
public ClosableIterator<RowResult<Set<Long>>> getRangeOfTimestamps( TableReference tableRef, RangeRequest rangeRequest, long timestamp) { return new RangeOfTimestampsIterator(this, tableRef, rangeRequest, timestamp); }

Target:
public ClosableIterator<RowResult<Set<Long>>> getRangeOfTimestamps( TableReference tableRef, RangeRequest rangeRequest, long timestamp) { CandidateCellForSweepingRequest request = ImmutableCandidateCellForSweepingRequest.builder() .startRowInclusive(rangeRequest.getStartInclusive()) .maxTimestampExclusive(timestamp) .addTimestampsToIgnore() .shouldCheckIfLatestValueIsEmpty(false) .build(); return getCandidateRowsForSweeping(tableRef, request) .flatMap(rows -> rows) .map(row -> row.toRowResult()) .stopWhen(rowResult -> !rangeRequest.inRange(rowResult.getRowName())); }
Source:
public synchronized void addWarnings(List<PrestoWarning> warnings) { for (; warningsSeen < warnings.size(); warningsSeen++) { addWarning(warnings.get(warningsSeen)); } }

Target:
public synchronized void addWarnings(List<PrestoWarning> warnings) { for (PrestoWarning warning : warnings) { if (warningsSeen.add(warning.getWarningCode())) { addWarning(warning); } } }
Source:
default boolean knowablySemanticallyEquivalent(VersionedInternalSchemaMetadata other) { if (version() != other.version()) { return false; } return underlyingData().isPresent() && other.underlyingData().isPresent() && underlyingData().get().equals(other.underlyingData().get()); }

Target:
default boolean knowablySemanticallyEquivalent(VersionedInternalSchemaMetadata other) { if (other == null || version() != other.version()) { return false; } return underlyingData().isPresent() && other.underlyingData().isPresent() && underlyingData().get().equals(other.underlyingData().get()); }
Source:
public TestingService(ProjectManager projectManager, TestFrameworkRegistry frameworkRegistry, TestClasspathRegistry classpathRegistry) { this.projectManager = projectManager; this.frameworkRegistry = frameworkRegistry; this.classpathRegistry = classpathRegistry; System.out.println("inititilaized TestingService"); }

Target:
public TestingService(ProjectManager projectManager, TestFrameworkRegistry frameworkRegistry, TestClasspathRegistry classpathRegistry) { this.projectManager = projectManager; this.frameworkRegistry = frameworkRegistry; this.classpathRegistry = classpathRegistry; }
Source:
public IToHex getInstance(DiscreteElement<?> elementType){ if(elementType instanceof EnumeratedElement){ return new EnumToHex(); } else if (elementType instanceof NumericElement<?>){ return new NumericToHex(); }else if (elementType instanceof EmptyEnum_Element){ return new EmptyEnumToHex(); }else if (elementType instanceof StringElement){ return new StringToHex(); }else{ return new CharToHex(); } }

Target:
public IToHex getInstance(DiscreteElement<?> elementType){ if(elementType instanceof EnumeratedElement){ return new EnumToHex(); } else if (elementType instanceof NumericElement<?>){ return new NumericToHex(); }else if (elementType instanceof EmptyEnum_Element){ return new EmptyEnumToHex(); }else if (elementType instanceof StringElement){ return new StringToHex(); }else if (elementType instanceof CharElement){ return new CharToHex(); }else{ OseeLog.log(ToHexFactory.class, Level.SEVERE, "ERROR: " + elementType.getDescriptiveName() + " was not handled correctly"); return new InaccessibleToHex(); } }
Source:
private BuilderInfo findBuilderInfoFromInnerBuilderClass(TypeElement typeElement) { if (shouldIgnore( typeElement )) { return null; } List<TypeElement> types = ElementFilter.typesIn( typeElement.getEnclosedElements() ); List<BuilderInfo> builderInfo = new ArrayList<>(); types.stream() .filter( innerType -> isPossibleInnerBuilder( innerType, typeElement ) ) .forEach( innerBuilderClass -> { Collection<ExecutableElement> buildMethods = findBuildMethods( innerBuilderClass, typeElement ); if (!buildMethods.isEmpty()) { ElementFilter.constructorsIn( innerBuilderClass.getEnclosedElements() ) .stream() .filter( constructor -> constructor.getParameters().isEmpty() && constructor.getModifiers().contains( Modifier.PUBLIC ) ) .findAny() .ifPresent( defaultConstructor -> builderInfo.add( new BuilderInfo.Builder() .builderCreationMethod( defaultConstructor ) .buildMethod( buildMethods ) .build() ) ); } } ); if (builderInfo.size() == 1) { return builderInfo.get( 0 ); } else if (builderInfo.size() > 1) { throw new MoreThanOneBuilderCreationMethodException(typeElement.asType(), builderInfo); } return null; }

Target:
private BuilderInfo findBuilderInfoFromInnerBuilderClass(TypeElement typeElement) { if (shouldIgnore( typeElement )) { return null; } List<TypeElement> innerTypes = ElementFilter.typesIn( typeElement.getEnclosedElements() ); ExecutableElement defaultConstructor = innerTypes.stream() .filter( this::isBuilderCandidate ) .map( this::getEmptyArgPublicConstructor ) .filter( Objects::nonNull ) .findAny() .orElse( null ); if ( defaultConstructor != null ) { return new BuilderInfo.Builder() .builderCreationMethod( defaultConstructor ) .buildMethod( findBuildMethods( (TypeElement) defaultConstructor.getEnclosingElement(), typeElement ) ) .build(); } return null; }
Source:
boolean verify() throws Exception; } public static boolean verify(Verifier verifier, long timeout) throws Exception { long start = System.currentTimeMillis(); do { boolean result = verifier.verify(); long now = System.currentTimeMillis(); if (result || (now - start) > timeout) { if ((now -start) > timeout && !result) { LOG.error("verifier time out, consider try longer timeout, stack trace{}", Arrays.asList(Thread.currentThread().getStackTrace())); } return result; } Thread.sleep(50); } while (true); }

Target:
boolean verify() throws Exception; } public static boolean verify(Verifier verifier, long timeout) throws Exception { long start = System.currentTimeMillis(); do { boolean result = verifier.verify(); boolean isTimedout = (System.currentTimeMillis() - start) > timeout; if (result || isTimedout) { if (isTimedout && !result) { LOG.error("verifier time out, consider try longer timeout, stack trace{}", Arrays.asList(Thread.currentThread().getStackTrace())); } return result; } Thread.sleep(50); } while (true); }
Source:
private void checkManifestContent(IProject project) throws IOException { InputStream is = null; try { is = project.getFile("META-INF/MANIFEST.MF").getContents(); } catch (CoreException e) { fail("Cannot read the Manifest content"); } BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; Boolean findJse = false; try { while ((line = reader.readLine()) != null && !findJse) { findJse = line.contains("Bundle-RequiredExecutionEnvironment:"); if (findJse) { assertEquals("The JSE name should be the name of the default environment execution.", "Bundle-RequiredExecutionEnvironment: JavaSE-" + System.getProperty("java.version").substring(0, 3), line); } } } finally { is.close(); } }

Target:
private void checkManifestContent(IProject project) throws IOException { InputStream is = null; try { is = project.getFile("META-INF/MANIFEST.MF").getContents(); try { Manifest manifest = new Manifest(is); Attributes attributes = manifest.getMainAttributes(); String currentJseId = attributes.getValue("Bundle-RequiredExecutionEnvironment"); assertEquals("The JSE name should be the name of the default environment execution.", ViewpointSpecificationProject.getDefaultJseId(), currentJseId); } catch (IOException ex) { fail("Error while reading Bundle-RequiredExecutionEnvironment: " + ex.getMessage()); } } catch (CoreException e) { fail("Cannot read the Manifest content"); } finally { is.close(); } }
Source:
protected void executeVmCommand() { lockImageInDb(); List<UpdateDiskParameters.Phase> phaseList = new ArrayList<>(); ImagesHandler.setDiskAlias(getParameters().getDiskInfo(), getVm()); if (resizeDiskImageRequested()) { phaseList.add(UpdateDiskParameters.Phase.EXTEND_DISK); } if (getOldDisk().getDiskStorageType() == DiskStorageType.IMAGE && amendDiskRequested()) { phaseList.add(UpdateDiskParameters.Phase.AMEND_DISK); } phaseList.add(UpdateDiskParameters.Phase.UPDATE_DISK); getParameters().setDiskUpdatePhases(phaseList); setSucceeded(true); }

Target:
protected void executeVmCommand() { lockImageInDb(); List<UpdateDiskParameters.Phase> phaseList = new ArrayList<>(); ImagesHandler.setDiskAlias(getParameters().getDiskInfo(), getVm()); if (resizeDiskImageRequested()) { phaseList.add(UpdateDiskParameters.Phase.EXTEND_DISK); } if (getOldDisk().getDiskStorageType() == DiskStorageType.IMAGE && amendDiskRequested()) { phaseList.add(UpdateDiskParameters.Phase.AMEND_DISK); } phaseList.add(UpdateDiskParameters.Phase.UPDATE_DISK); getParameters().setDiskUpdatePhases(phaseList); persistCommandIfNeeded(); setSucceeded(true); }
Source:
createDataStore(Class<K> keyClass, Class<T> persistentClass) throws GoraException { Properties properties = DataStoreFactory.createProps(); DataStore<K,T> dataStore = DataStoreFactory.createDataStore( (Class<? extends DataStore<K,T>>)dataStoreClass, keyClass, persistentClass, conf, properties); dataStores.add(dataStore); log.info("Datastore for "+persistentClass+" was added."); return dataStore; }

Target:
createDataStore(Class<K> keyClass, Class<T> persistentClass) throws GoraException { final Properties properties = DataStoreFactory.createProps(); final DataStore<K, T> dataStore = DataStoreFactory.createDataStore( (Class<? extends DataStore<K, T>>) dataStoreClass, keyClass, persistentClass, conf, properties); dataStores.add(dataStore); log.info("Datastore for was added.", persistentClass); return dataStore; }
Source:
public RowRanges visit(Not not) { throw new IllegalArgumentException( "This predicate contains a not! Did you forget to run this predicate through LogicalInverseRewriter? " + not); }

Target:
public RowRanges visit(Not not) { throw new IllegalArgumentException( "Predicates containing a NOT must be run through LogicalInverseRewriter. " + not); }
Source:
public void testConfigurePythonExecution() throws IllegalAccessException, NoSuchFieldException, CliArgsException, ProgramInvocationException, IOException { String[] args = { "--python", "xxx.py", "--pyModule", "xxx", "--pyFiles", "/absolute/a.py,relative/b.py,relative/c.py", "--pyRequirements", "d.txt#e_dir", "--pyExecutable", "/usr/bin/python", "--pyArchives", "g.zip,h.zip#data,h.zip#data2", "userarg1", "userarg2" }; final File[] dummyJobJar = {null}; Files.walkFileTree(FileSystems.getDefault().getPath("target/dummy-job-jar"), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { FileVisitResult result = super.visitFile(file, attrs); if (file.getFileName().toString().startsWith("flink-python")) { dummyJobJar[0] = file.toFile(); } return result; } }); PackagedProgram packagedProgram = PackagedProgram.newBuilder() .setArguments(args).setJarFile(dummyJobJar[0]) .build(); Configuration configuration = new Configuration(); ProgramOptionsUtils.configurePythonExecution(configuration, packagedProgram); assertEquals("/absolute/a.py,relative/b.py,relative/c.py", configuration.get(PythonOptions.PYTHON_FILES)); assertEquals("d.txt#e_dir", configuration.get(PYTHON_REQUIREMENTS)); assertEquals("g.zip,h.zip#data,h.zip#data2", configuration.get(PythonOptions.PYTHON_ARCHIVES)); assertEquals("/usr/bin/python", configuration.get(PYTHON_EXECUTABLE)); assertArrayEquals( new String[] {"--python", "xxx.py", "--pyModule", "xxx", "userarg1", "userarg2"}, packagedProgram.getArguments()); }

Target:
public void testConfigurePythonExecution() throws IllegalAccessException, NoSuchFieldException, CliArgsException, ProgramInvocationException, IOException { final String[] args = { "--python", "xxx.py", "--pyModule", "xxx", "--pyFiles", "/absolute/a.py,relative/b.py,relative/c.py", "--pyRequirements", "d.txt#e_dir", "--pyExecutable", "/usr/bin/python", "--pyArchives", "g.zip,h.zip#data,h.zip#data2", "userarg1", "userarg2" }; final File[] dummyJobJar = {null}; Files.walkFileTree(FileSystems.getDefault().getPath("target/dummy-job-jar"), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { FileVisitResult result = super.visitFile(file, attrs); if (file.getFileName().toString().startsWith("flink-python")) { dummyJobJar[0] = file.toFile(); } return result; } }); PackagedProgram packagedProgram = PackagedProgram.newBuilder() .setArguments(args).setJarFile(dummyJobJar[0]) .build(); Configuration configuration = new Configuration(); ProgramOptionsUtils.configurePythonExecution(configuration, packagedProgram); assertEquals("/absolute/a.py,relative/b.py,relative/c.py", configuration.get(PythonOptions.PYTHON_FILES)); assertEquals("d.txt#e_dir", configuration.get(PYTHON_REQUIREMENTS)); assertEquals("g.zip,h.zip#data,h.zip#data2", configuration.get(PythonOptions.PYTHON_ARCHIVES)); assertEquals("/usr/bin/python", configuration.get(PYTHON_EXECUTABLE)); assertArrayEquals( new String[] {"--python", "xxx.py", "--pyModule", "xxx", "userarg1", "userarg2"}, packagedProgram.getArguments()); }
Source:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); FailureCollector collector = pipelineConfigurer.getStageConfigurer().getFailureCollector(); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { if (inputSchema.getField(config.inputField) == null) { collector.addFailure(String.format("Field '%s' must be present in input schema.", config.inputField), null) .withConfigProperty(INPUT_FIELD); } else if (inputSchema.getField(config.inputField).getSchema().getType() != Schema.Type.STRING) { collector.addFailure(String.format("Field '%s' must be of type string.", config.inputField), null) .withConfigProperty(INPUT_FIELD).withInputSchemaField(config.inputField); } } }

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); FailureCollector collector = pipelineConfigurer.getStageConfigurer().getFailureCollector(); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { Schema.Field field = inputSchema.getField(config.inputField); if (field == null) { collector.addFailure(String.format("Field '%s' must be present in input schema.", config.inputField), null) .withConfigProperty(INPUT_FIELD); } else if (field.getSchema().getType() != Schema.Type.STRING) { collector.addFailure(String.format("Field '%s' must be of type string.", config.inputField), null) .withConfigProperty(INPUT_FIELD).withInputSchemaField(config.inputField); } } }
Source:
private InputStreamContinuator constructContinuatorForCompatibleRequest(final HttpUriRequest request, final CloseableHttpResponse response) { if (this.maxDownloadContinuations == DOWNLOAD_CONTINUATIONS_DISABLED || !HttpGet.METHOD_NAME.equalsIgnoreCase(request.getMethod()) || !(this.connectionContext instanceof MantaApacheHttpClientContext) || !(request instanceof HttpGet)) { return null; } final HttpGet get = (HttpGet) request; final ResumableDownloadMarker marker; try { marker = validateInitialExchange( extractDownloadRequestFingerprint(get), response.getStatusLine().getStatusCode(), extractDownloadResponseFingerprint(response, true)); } catch (final ProtocolException pe) { return null; } try { return new ApacheHttpGetResponseEntityContentContinuator( (MantaApacheHttpClientContext) this.connectionContext, get, marker, this.maxDownloadContinuations); } catch (final ResumableDownloadException rde) { LOGGER.debug( String.format( "Expected to build a continuator but an exception occurred: %s", rde.getMessage())); } return null; }

Target:
private InputStreamContinuator constructContinuatorForCompatibleRequest(final HttpUriRequest request, final CloseableHttpResponse response) { if (this.maxDownloadContinuations == DOWNLOAD_CONTINUATIONS_DISABLED || !HttpGet.METHOD_NAME.equalsIgnoreCase(request.getMethod()) || !(this.connectionContext instanceof MantaApacheHttpClientContext) || !(request instanceof HttpGet)) { return null; } final HttpGet get = (HttpGet) request; final HttpDownloadContinuationMarker marker; try { marker = validateInitialExchange(extractDownloadRequestFingerprint(get), response.getStatusLine().getStatusCode(), extractDownloadResponseFingerprint(response, true)); } catch (final ProtocolException pe) { LOGGER.debug("HTTP download cannot be automatically continued: {}", pe.getMessage()); return null; } try { return new ApacheHttpGetResponseEntityContentContinuator( (MantaApacheHttpClientContext) this.connectionContext, get, marker, this.maxDownloadContinuations); } catch (final HttpDownloadContinuationException rde) { LOGGER.debug( String.format( "Expected to build a continuator but an exception occurred: %s", rde.getMessage())); } return null; }
Source:
private void discoverRegistryPressed(Shell shell) { String ret = RegistryProviderModel.getDefault().getRegistryURL(pageModel.getSelectedConnection()); if( ret != null ) { registryURLObservable.setValue(ret); } else { MessageBox messageBox = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); messageBox.setMessage("No registry provider found for the given connection."); int rc = messageBox.open(); } }

Target:
private void discoverRegistryPressed(Shell shell) { String ret = RegistryProviderModel.getDefault().getRegistryURL(pageModel.getSelectedConnection()); if( ret != null ) { registryURLObservable.setValue(ret); } else { MessageBox messageBox = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); messageBox.setText("Registry URL not found"); messageBox.setMessage("No registry provider found for the given connection. If your Openshift connection is backed by a CDK or minishift installation, please ensure the CDK is running."); int rc = messageBox.open(); } }
Source:
private static long getChunkCacheSize(IEclipsePreferences node) { double maxSizeMb = node.getDouble(CHUNK_CACHE_SIZE_MB, CHUNK_CACHE_SIZE_MB_DEFAULT); double maxSizePercent = node.getDouble(CHUNK_CACHE_SIZE_PERCENT, CHUNK_CACHE_SIZE_PERCENT_DEFAULT); maxSizePercent = Math.max(1.0, Math.min(50.0, maxSizePercent)); maxSizeMb = Math.max(maxSizeMb, 1.0); long m1= (long)(Runtime.getRuntime().maxMemory() / 100.0 * maxSizePercent); return Math.min(m1, (long)(maxSizeMb * 1024.0 * 1024.0)); }

Target:
private static long getChunkCacheSize(IEclipsePreferences node) { double maxSizeMb = node.getDouble(CHUNK_CACHE_SIZE_MB, CHUNK_CACHE_SIZE_MB_DEFAULT); double maxSizePercent = node.getDouble(CHUNK_CACHE_SIZE_PERCENT, CHUNK_CACHE_SIZE_PERCENT_DEFAULT); maxSizePercent = Math.max(1.0, Math.min(100.0, maxSizePercent)); maxSizeMb = Math.max(maxSizeMb, 1.0); long m1= (long) (Runtime.getRuntime().maxMemory() / 100.0 * maxSizePercent); return Math.min(m1, (long) (maxSizeMb * 1024.0 * 1024.0)); }
Source:
public void run(){ try{ ContextManager cm=ContextService.getFactory().newContextManager(); cm.pushContext(ec); ContextService.getFactory().setCurrentContextManager(cm); TabInfoImpl ti=coreInfo[coreCtr]; String version = catalogVersions.get(coreCtr); Properties heapProperties=new Properties(); heapProperties.setProperty("tableDisplayName", ti.getTableName()); heapProperties.setProperty("catalogVersion", version); ExecRow rowTemplate=ti.getCatalogRowFactory().makeEmptyRowForLatestVersion(); long conglomerate=createConglomerate(tc,rowTemplate,heapProperties, 100); ti.setHeapConglomerate(conglomerate); }catch(Exception e){ e.printStackTrace(); StringBuilder strbuf = new StringBuilder("Dictionary Table Failure - exiting "); strbuf.append(coreCtr); SanityManager.THROWASSERT(strbuf.toString()); } }

Target:
public void run(){ try{ ContextManager cm=ContextService.getFactory().newContextManager(); cm.pushContext(ec); ContextService.getFactory().setCurrentContextManager(cm); TabInfoImpl ti=coreInfo[coreCtr]; String version = catalogVersions.get(coreCtr); Properties heapProperties=new Properties(); heapProperties.setProperty("tableDisplayName", ti.getTableName()); heapProperties.setProperty("catalogVersion", version); ExecRow rowTemplate=ti.getCatalogRowFactory().makeEmptyRowForLatestVersion(); long conglomerate=createConglomerate(tc,rowTemplate,heapProperties, Conglomerate.Priority.HIGH); ti.setHeapConglomerate(conglomerate); }catch(Exception e){ e.printStackTrace(); StringBuilder strbuf = new StringBuilder("Dictionary Table Failure - exiting "); strbuf.append(coreCtr); SanityManager.THROWASSERT(strbuf.toString()); } }
Source:
private String getLegalNoticeMessage() { ClassLoader classLoader = this.getClass().getClassLoader(); InputStream stream = classLoader.getResourceAsStream(KODEBEAGLE_NOTICE_FILENAME); StringBuilder legalNoticeMessage = new StringBuilder(); BufferedReader reader = null; try { String line; reader = new BufferedReader(new InputStreamReader(stream, ESUtils.UTF_8)); while ((line = reader.readLine()) != null) { legalNoticeMessage.append(line); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (Throwable e) { e.printStackTrace(); } } return String.format(legalNoticeMessage.toString()); }

Target:
private String getLegalNoticeMessage() { ClassLoader classLoader = this.getClass().getClassLoader(); InputStream stream = classLoader.getResourceAsStream(KODEBEAGLE_NOTICE_FILENAME); StringBuilder legalNoticeMessage = new StringBuilder(); try { String line; BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); if (stream != null) { while ((line = reader.readLine()) != null) { legalNoticeMessage.append(line); } } } catch (IOException e) { e.printStackTrace(); } finally { try { stream.close(); } catch (Throwable e) { e.printStackTrace(); } } return String.format(legalNoticeMessage.toString()); }
Source:
public static boolean isGenotypeInTransitionWithComplement(final Genotype g, final Transition transition) { Utils.nonNull(g, "Genotype cannot be null"); Utils.nonNull(transition, "Transition cannot be null"); final boolean isInTransition = isGenotypeInTransition(g, transition); if (isInTransition) { return true; } final Transition transitionComplement = transition.complement(); return isGenotypeInTransition(g, transitionComplement); }

Target:
public static boolean isGenotypeInTransitionWithComplement(final Genotype g, final Transition transition) { Utils.nonNull(g, "Genotype cannot be null"); Utils.nonNull(transition, "Transition cannot be null"); return isGenotypeInTransition(g, transition) || isGenotypeInTransition(g, transition.complement()); }