auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void close(final boolean clean) { final AtomicReference<RuntimeException> firstException = new AtomicReference<>(null); final List<T> nonSuspendedTasks = new ArrayList<>(); nonSuspendedTasks.addAll(created.values()); nonSuspendedTasks.addAll(running.values()); for (final T task : nonSuspendedTasks) { closeTask(clean, false, task, firstException); } for (final T task : suspended.values()) { closeTask(clean, true, task, firstException); } clear(); final RuntimeException fatalException = firstException.get(); if (fatalException != null) { throw fatalException; } }

Target:
void close(final boolean clean) { final AtomicReference<RuntimeException> firstException = new AtomicReference<>(null); for (final T task: allTasks()) { try { if (suspended.containsKey(task.id())) { task.closeSuspended(clean, false, null); } else { task.close(clean, false); } } catch (final TaskMigratedException e) { log.info("Failed to close since it got migrated to another thread already. " + "Closing it as zombie and move on.", taskTypeName, task.id()); firstException.compareAndSet(null, closeZombieTask(task)); } catch (final RuntimeException t) { log.error("Failed while closing due to the following error:", task.getClass().getSimpleName(), task.id(), t); if (clean) { if (!closeUnclean(task)) { firstException.compareAndSet(null, t); } } else { firstException.compareAndSet(null, t); } } } clear(); final RuntimeException fatalException = firstException.get(); if (fatalException != null) { throw fatalException; } }
Source:
public void testCreationTimeout(int poolSize, int concurrency) throws Exception { ObjectCreatorThatNeverCreates objectCreatorThatNeverCreates = new ObjectCreatorThatNeverCreates(); ClockedExecutor clockedExecutor = new ClockedExecutor(); ExponentialBackOffRateLimiter rateLimiter = new ExponentialBackOffRateLimiter(0, 5000, 10, clockedExecutor, concurrency); final AsyncPool<Object> pool = new AsyncPoolImpl<Object>("object pool", objectCreatorThatNeverCreates, poolSize, Integer.MAX_VALUE, Integer.MAX_VALUE, clockedExecutor, Integer.MAX_VALUE, AsyncPoolImpl.Strategy.MRU, 0, rateLimiter, clockedExecutor, new LongTracking() ); pool.start(); List<FutureCallback<Object>> checkoutCallbacks = new ArrayList<>(); for (int i = 0; i < poolSize * 2 ; i++) { FutureCallback<Object> cb = new FutureCallback<>(); checkoutCallbacks.add(cb); rateLimiter.setPeriod(0); pool.get(cb); clockedExecutor.runFor(10000); } clockedExecutor.runFor(10000); for(FutureCallback<Object> cb : checkoutCallbacks) { try { cb.get(100, TimeUnit.MILLISECONDS); } catch (Exception ex) { Assert.assertTrue(ex.getCause() instanceof ObjectCreationTimeoutException); } } PoolStats stats = pool.getStats(); Assert.assertEquals(stats.getTotalCreateErrors(), poolSize * 2); Assert.assertEquals(stats.getCheckedOut(), 0); Assert.assertEquals(stats.getIdleCount(), 0); Assert.assertEquals(stats.getPoolSize(), 0); Assert.assertEquals(stats.getMaxPoolSize(), poolSize); Assert.assertEquals(stats.getIdleCount(), 0); }

Target:
public void testCreationTimeout(int poolSize, int concurrency) throws Exception { ObjectCreatorThatNeverCreates objectCreatorThatNeverCreates = new ObjectCreatorThatNeverCreates(); ClockedExecutor clockedExecutor = new ClockedExecutor(); ExponentialBackOffRateLimiter rateLimiter = new ExponentialBackOffRateLimiter(0, 5000, 10, clockedExecutor, concurrency); final AsyncPool<Object> pool = new AsyncPoolImpl<Object>("object pool", objectCreatorThatNeverCreates, poolSize, Integer.MAX_VALUE, Integer.MAX_VALUE, clockedExecutor, Integer.MAX_VALUE, AsyncPoolImpl.Strategy.MRU, 0, rateLimiter, clockedExecutor, new LongTracking() ); pool.start(); List<FutureCallback<Object>> checkoutCallbacks = new ArrayList<>(); for (int i = 0; i < poolSize * 2 ; i++) { FutureCallback<Object> cb = new FutureCallback<>(); checkoutCallbacks.add(cb); rateLimiter.setPeriod(0); pool.get(cb); clockedExecutor.runFor(AsyncPoolImpl.DEFAULT_OBJECT_CREATION_TIMEOUT); } clockedExecutor.runFor(AsyncPoolImpl.DEFAULT_OBJECT_CREATION_TIMEOUT); for(FutureCallback<Object> cb : checkoutCallbacks) { try { cb.get(100, TimeUnit.MILLISECONDS); } catch (Exception ex) { Assert.assertTrue(ex.getCause() instanceof ObjectCreationTimeoutException); } } PoolStats stats = pool.getStats(); Assert.assertEquals(stats.getTotalCreateErrors(), poolSize * 2); Assert.assertEquals(stats.getCheckedOut(), 0); Assert.assertEquals(stats.getIdleCount(), 0); Assert.assertEquals(stats.getPoolSize(), 0); Assert.assertEquals(stats.getMaxPoolSize(), poolSize); Assert.assertEquals(stats.getIdleCount(), 0); }
Source:
private boolean validateBacklinks() { boolean allValid = true; Map<String, ClassMetaData> realmClasses = new HashMap<String, ClassMetaData>(classesToValidate.size()); for (ClassMetaData classData: classesToValidate) { realmClasses.put(classData.getFullyQualifiedClassName(), classData); } for (Backlink backlink: backlinksToValidate) { ClassMetaData klass = realmClasses.get(backlink.getSourceClass()); if (klass == null) { continue; } if (!backlink.validateTarget(klass) && allValid) { allValid = false; } } return allValid; }

Target:
private boolean validateBacklinks() { boolean allValid = true; Map<String, ClassMetaData> realmClasses = new HashMap<String, ClassMetaData>(classesToValidate.size()); for (ClassMetaData classData: classesToValidate) { realmClasses.put(classData.getFullyQualifiedClassName(), classData); } for (Backlink backlink: backlinksToValidate) { ClassMetaData clazz = realmClasses.get(backlink.getSourceClass()); if (clazz == null) { continue; } if (!backlink.validateTarget(clazz) && allValid) { allValid = false; } } return allValid; }
Source:
public void testExpressionWithPhoenixRowTimestamp() throws Exception { ParseNode parseNode = SQLParser.parseCondition("(PHOENIX_ROW_TIMESTAMP() = PK2)"); boolean hasPhoenixRowTimestampParseNode = false; for (ParseNode childNode : parseNode.getChildren()) { if (childNode.getClass().isAssignableFrom(PhoenixRowTimestampParseNode.class)) { assertEquals("", childNode.getChildren().size(), 0); hasPhoenixRowTimestampParseNode = true; } } assertTrue(hasPhoenixRowTimestampParseNode); }

Target:
public void testExpressionWithPhoenixRowTimestamp() throws Exception { ParseNode parseNode = SQLParser.parseCondition("(PHOENIX_ROW_TIMESTAMP() = PK2)"); boolean hasPhoenixRowTimestampParseNode = false; for (ParseNode childNode : parseNode.getChildren()) { if (childNode.getClass().isAssignableFrom(PhoenixRowTimestampParseNode.class)) { assertEquals(0, childNode.getChildren().size()); hasPhoenixRowTimestampParseNode = true; } } assertTrue(hasPhoenixRowTimestampParseNode); }
Source:
public DefaultKieCompilationResponse(DefaultKieCompilationResponseOffProcess res) { this.defaultResponse = new DefaultCompilationResponse(res.isSuccessful(), res.getMavenOutput(), getWorkingDir(res.getWorkingDir()), res.getTargetContent(), res.getDependencies(), res.getRequestUUID()); if (res.getKieModuleMetaInfo().isPresent()) { this.kieModuleMetaInfo = res.getKieModuleMetaInfo().get(); } if (res.getKieModule().isPresent()) { this.kieModule = res.getKieModule().get(); } if(res.getProjectClassLoaderStore() != null && !res.getProjectClassLoaderStore().isEmpty()){ this.projectClassLoaderStore = res.getProjectClassLoaderStore(); }else{ this.projectClassLoaderStore = Collections.emptyMap(); } if(res.getEventTypeClasses()!= null && !res.getEventTypeClasses().isEmpty()) { this.eventsTypeClasses = res.getEventTypeClasses(); }else{ this.eventsTypeClasses = Collections.emptySet(); } }

Target:
public DefaultKieCompilationResponse(DefaultKieCompilationResponseOffProcess res) { this.defaultResponse = new DefaultCompilationResponse(res.isSuccessful(), res.getMavenOutput(), getWorkingDir(res.getWorkingDir()), res.getTargetContent(), res.getDependencies(), res.getRequestUUID()); this.kieModuleMetaInfo = res.getKieModuleMetaInfo().orElse(null); this.kieModule = res.getKieModule().orElse(null); this.projectClassLoaderStore = Optional.ofNullable(res.getProjectClassLoaderStore()).orElse(Collections.emptyMap()); this.eventsTypeClasses = Optional.ofNullable(res.getEventTypeClasses()).orElse(Collections.emptySet()); }
Source:
void pinCertificate(OkHttpClient.Builder builder) { Log.d(Constants.TAG, "Pinning certificate for " + url); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); byte[] certificate = sCertificatePins.get(url.getHost()); Certificate ca = cf.generateCertificate(new ByteArrayInputStream(certificate)); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } X509TrustManager trustManager = (X509TrustManager) trustManagers[0]; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{trustManager}, null); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); builder.sslSocketFactory(sslSocketFactory, trustManager); } catch (CertificateException | KeyStoreException | KeyManagementException | NoSuchAlgorithmException | IOException e) { throw new IllegalStateException(e); } }

Target:
void pinCertificate(OkHttpClient.Builder builder) { Log.d(Constants.TAG, "Pinning certificate for " + url); try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); byte[] certificate = sCertificatePins.get(url.getHost()); Certificate ca = cf.generateCertificate(new ByteArrayInputStream(certificate)); KeyStore keyStore = createSingleCertificateKeyStore(ca); X509TrustManager trustManager = createTrustManager(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{trustManager}, null); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); builder.sslSocketFactory(sslSocketFactory, trustManager); } catch (CertificateException | KeyStoreException | KeyManagementException | NoSuchAlgorithmException | IOException e) { throw new IllegalStateException(e); } }
Source:
public List<EmailWrapper> generateFeedbackSessionClosedEmails(FeedbackSessionAttributes session) { if (session.isPrivateSession()) { return new ArrayList<>(); } CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); boolean isEmailNeededForStudents = false; try { isEmailNeededForStudents = fsLogic.isFeedbackSessionHasQuestionForStudents( session.getFeedbackSessionName(), session.getCourseId()); } catch (EntityDoesNotExistException e) { log.severe("Course " + session.getCourseId() + " does not exist or " + "session " + session.getFeedbackSessionName() + " does not exist"); } List<InstructorAttributes> instructors = isEmailNeededForStudents ? instructorsLogic.getInstructorsForCourse(session.getCourseId()) : new ArrayList<InstructorAttributes>(); List<StudentAttributes> students = isEmailNeededForStudents ? studentsLogic.getStudentsForCourse(session.getCourseId()) : new ArrayList<StudentAttributes>(); String template = EmailTemplates.USER_FEEDBACK_SESSION.replace("${status}", FEEDBACK_STATUS_SESSION_CLOSED); String additionalContactInformation = getAdditionalContactInformationFragment(course); return generateFeedbackSessionEmailBases(course, session, students, instructors, template, EmailType.FEEDBACK_CLOSED.getSubject(), FEEDBACK_ACTION_VIEW, additionalContactInformation); }

Target:
public List<EmailWrapper> generateFeedbackSessionClosedEmails(FeedbackSessionAttributes session) { if (session.isPrivateSession()) { return new ArrayList<>(); } CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); boolean isEmailNeededForStudents = false; try { isEmailNeededForStudents = fsLogic.isFeedbackSessionHasQuestionForStudents( session.getFeedbackSessionName(), session.getCourseId()); } catch (EntityDoesNotExistException e) { log.severe("Course " + session.getCourseId() + " does not exist or " + "session " + session.getFeedbackSessionName() + " does not exist"); } List<InstructorAttributes> instructors = isEmailNeededForStudents ? instructorsLogic.getInstructorsForCourse(session.getCourseId()) : new ArrayList<>(); List<StudentAttributes> students = isEmailNeededForStudents ? studentsLogic.getStudentsForCourse(session.getCourseId()) : new ArrayList<>(); String template = EmailTemplates.USER_FEEDBACK_SESSION.replace("${status}", FEEDBACK_STATUS_SESSION_CLOSED); String additionalContactInformation = getAdditionalContactInformationFragment(course); return generateFeedbackSessionEmailBases(course, session, students, instructors, template, EmailType.FEEDBACK_CLOSED.getSubject(), FEEDBACK_ACTION_VIEW, additionalContactInformation); }
Source:
public void copySupplementaryFolder(String newName) { IFolder oldSupplFolder = getTraceSupplementaryFolder(getResourceName()); IFolder newSupplFolder = getTraceSupplementaryFolder(newName + getSuffix()); if (oldSupplFolder.exists()) { try { oldSupplFolder.copy(newSupplFolder.getFullPath(), true, new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().logError("Error renaming supplementary folder " + oldSupplFolder, e); } } }

Target:
public void copySupplementaryFolder(String newName) { IFolder oldSupplFolder = getTraceSupplementaryFolder(getResourceName()); IFolder newSupplFolder = getTraceSupplementaryFolder(newName + getSuffix()); if (oldSupplFolder.exists()) { try { oldSupplFolder.copy(newSupplFolder.getFullPath(), true, new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().logError(Messages.TmfCommonProjectElement_ErrorCopyingSF + oldSupplFolder, e); } } }
Source:
public Iterable<Task> open() { return Iterables.transform( this.region.table(DyTask.TBL) .frame() .through( new QueryValve() .withSelect(Select.ALL_PROJECTED_ATTRIBUTES) ) .where( new Conditions().with( DyTask.ATTR_OPEN, Conditions.equalTo(String.valueOf(true)) ).with( DyTask.ATTR_REPO_URN, Conditions.equalTo(this.repo.name()) ) ) , new Function<Item, Task>() { @Override public Task apply(final Item input) { return new DyTask(input); } } ); }

Target:
public Iterable<Task> open() { return Iterables.transform( this.region.table(DyTask.TBL) .frame() .through( new QueryValve() .withSelect(Select.ALL_PROJECTED_ATTRIBUTES) ) .where( new Conditions().with( DyTask.ATTR_OPEN, String.valueOf(true) ).with( DyTask.ATTR_REPO_URN, this.repo.name() ) ), new Function<Item, Task>() { @Override public Task apply(final Item input) { return new DyTask(input); } } ); }
Source:
final protected void initialize() { if (!previous.isCanceled()) { previous.cancel(); } onInitialize(); }

Target:
final protected void initialize() { if (previous != null && (previous.isRunning() || !previous.isCanceled())) { previous.cancel(); } onInitialize(); }
Source:
public NodeConditionalBreakpointAction(IWorkbenchPart part) { super(part); setId(ID); setImageDescriptor(DesignerPlugin.getImageDescriptor("icons/breakpoint.png")); setText("Conditional breakpoint"); }

Target:
public NodeConditionalBreakpointAction(IWorkbenchPart part) { super(part); setId(ID); setImageDescriptor(DesignerPlugin.getImageDescriptor("icons/breakpoint.png")); setText(Messages.getString("NodeConditionalBreakpointAction.conditionalBreakpoint")); }
Source:
synchronized void responseComplete() { if (METRICS_ENABLED && metrics != null) { reportBytesWritten(bytesWritten); bytesWritten = 0; if (requestFailed) { metrics.requestReset(requestMetric); requestFailed = false; } else { metrics.responseEnd(requestMetric, pendingResponse); } } pendingResponse = null; checkNextTick(); }

Target:
synchronized void responseComplete() { if (METRICS_ENABLED && metrics != null) { reportBytesWritten(bytesWritten); bytesWritten = 0; if (requestFailed) { metrics.requestReset(requestMetric); requestFailed = false; } else { metrics.responseEnd(requestMetric, pendingResponse); } } pendingResponse = null; if (queueing) { queueing = paused; } checkNextTick(); }
Source:
private static ExecutorService createBoundedExecutor(MetricRegistry metricRegistry, String useCase) { return new InstrumentedExecutorService( PTExecutors.newThreadPoolExecutor( 1, MAXIMUM_POOL_SIZE, THREAD_KEEP_ALIVE.toMillis(), TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new ThreadFactoryBuilder() .setNameFormat("timelock-executors-" + useCase + "-%d") .setDaemon(true) .build()), metricRegistry, MetricRegistry.name(TimeLockPaxosExecutors.class, useCase, "executor")); }

Target:
private static ExecutorService createBoundedExecutor(MetricRegistry metricRegistry, String useCase) { return new InstrumentedExecutorService( PTExecutors.newThreadPoolExecutor( SINGLE_THREAD_FOR_MOSTLY_AUTOBATCHED_OPERATIONS, MAXIMUM_POOL_SIZE, THREAD_KEEP_ALIVE.toMillis(), TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new ThreadFactoryBuilder() .setNameFormat("timelock-executors-" + useCase + "-%d") .setDaemon(true) .build()), metricRegistry, MetricRegistry.name(TimeLockPaxosExecutors.class, useCase, "executor")); }
Source:
public void request_without_forward_url_should_fail() throws Exception { try{ mockMvc.perform(get(Path.PROXY_CONTEXT+"/"+BINDING_ID).accept(MediaType.ALL)) .andExpect(status().is5xxServerError()); Assert.fail("Shouldn't work"); } catch (Exception e){ Assert.assertNotNull(e); } }

Target:
public void request_without_forward_url_should_fail() throws Exception { verifyThrown( () -> mockMvc.perform(get(Path.PROXY_CONTEXT+"/"+BINDING_ID) .accept(MediaType.ALL)) .andExpect(status().is5xxServerError()), Exception.class); }
Source:
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case 1: { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d("Scanner Message", "coarse location permission granted"); ((DemoApplication) getApplication()).setScannerStatus(SensorbergService.MSG_LOCATION_SET); } else { ((DemoApplication) getApplication()).setScannerStatus(SensorbergService.MSG_LOCATION_NOT_SET_WHEN_NEEDED); } return; } } }

Target:
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSION_REQUEST_LOCATION_SERVICES: { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d("Scanner Message", "coarse location permission granted"); ((DemoApplication) getApplication()).setLocationPermissionGranted(SensorbergServiceMessage.MSG_LOCATION_SET); } else { ((DemoApplication) getApplication()).setLocationPermissionGranted(SensorbergServiceMessage.MSG_LOCATION_NOT_SET_WHEN_NEEDED); } return; } } }
Source:
public void testWithNullArrays() { final byte[] authenthicationKey = null; final byte[] encryptionKey = null; final KeySet keySet = new KeySet(authenthicationKey, encryptionKey); final KeySetDto keySetDto = this.configurationMapper.map(keySet, KeySetDto.class); assertNotNull(keySet); assertNotNull(keySetDto); assertNull(keySetDto.getAuthenticationKey()); assertNull(keySetDto.getEncryptionKey()); }

Target:
public void testWithNullArrays() { final byte[] authenthicationKey = null; final byte[] encryptionKey = null; final KeySet keySet = new KeySet(authenthicationKey, encryptionKey); final KeySetDto keySetDto = this.configurationMapper.map(keySet, KeySetDto.class); assertNotNull(keySetDto); assertNull(keySetDto.getAuthenticationKey()); assertNull(keySetDto.getEncryptionKey()); }
Source:
public static void main(String... args) throws Exception { try { new RequestBodyCompression().run(); } catch (IOException ioe) { } }

Target:
public static void main(String... args) throws Exception { new RequestBodyCompression().run(); }
Source:
public boolean isSuggestionListDisplayed() { try { waitForElementByElement(searchSuggestions.get(0)); return searchSuggestions.get(0).isDisplayed(); } catch (NoSuchElementException|IndexOutOfBoundsException e) return false; }

Target:
public boolean isSuggestionListDisplayed() { try { if (searchSuggestions.size() > 0) { waitForElementByElement(searchSuggestions.get(0)); return searchSuggestions.get(0).isDisplayed(); } } catch (NoSuchElementException e) return false; }
Source:
default <M extends Externalizable> LogTailer<M> createTailer(String group, String name, Codec<M> codec) { int partitions = size(name); if (partitions <= 0) { System.out.println(this); throw new IllegalArgumentException("Log name: " + name + " not found"); } return createTailer(group, IntStream.range(0, partitions).boxed().map(partition -> new LogPartition(name, partition)).collect( Collectors.toList()), codec); }

Target:
default <M extends Externalizable> LogTailer<M> createTailer(String group, String name, Codec<M> codec) { int partitions = size(name); if (partitions <= 0) { throw new IllegalArgumentException("Log name: " + name + " not found"); } return createTailer(group, IntStream.range(0, partitions).boxed().map(partition -> new LogPartition(name, partition)).collect( Collectors.toList()), codec); }
Source:
FixedDoubleHistogram(FixedDoubleHistogram other) { this(other.bucketCount, other.min, other.max); for (int i = 0; i < bucketCount; ++i) { weights[i] = other.weights[i]; } }

Target:
protected FixedDoubleHistogram(FixedDoubleHistogram other) { this(other.bucketCount, other.min, other.max); for (int i = 0; i < bucketCount; ++i) { weights[i] = other.weights[i]; } }
Source:
public ValidationResult validate(Object value) { Long longValue = null; ValidationResult res = new ValidationResult(); if (value instanceof Long) { longValue = (Long) value; } else if (value instanceof String && !((String) value).trim().isEmpty()) { try { longValue = Long.valueOf((String) value); } catch (NumberFormatException e) { } } if (longValue != null && longValue == 0) { return ValidationResult.ok(); } if (getMaximum() <= 0) { String msg = ConstantsManager.getInstance().getConstants().diskMaxSizeReached(); res.setSuccess(false); res.setReasons(Collections.singletonList(msg)); } return super.validate(value); }

Target:
public ValidationResult validate(Object value) { Long longValue = LongValidation.tryParseLong(value); if (longValue != null && longValue == 0) { return ValidationResult.ok(); } if (getMaximum() <= 0) { String msg = ConstantsManager.getInstance().getConstants().diskMaxSizeReached(); return ValidationResult.fail(msg); } return super.validate(value); }
Source:
public void testShowHindiNumberFormatAsEngNumberFormat() throws Exception { createProject(AR_ONE_TO_ZERO); baseActivityTestRule.launchActivity(null); onView(withId(R.id.button_play)) .perform(click()); onView(isRoot()) .perform(CustomActions.wait(500)); Bitmap bitmap = Screenshot.capture().getBitmap(); TessOCR tessocr = new TessOCR("eng"); final String srcText = tessocr.getOCRResult(bitmap); assertFalse("stage screenshot contains a text which is :" + srcText, srcText.isEmpty()); assertEquals(String.valueOf(ONE_TO_ZERO), srcText); tessocr.onDestroy(); }

Target:
public void testShowHindiNumberFormatAsEngNumberFormat() throws Exception { createProject(AR_ONE_TO_ZERO); baseActivityTestRule.launchActivity(null); lastBrickInScript.waitUntilEvaluated(3000); onView(isRoot()) .perform(CustomActions.wait(1000)); Bitmap bitmap = Screenshot.capture().getBitmap(); TessOCR tessocr = new TessOCR("eng"); final String srcText = tessocr.getOCRResult(bitmap); assertFalse("stage screenshot contains a text which is :" + srcText, srcText.isEmpty()); assertEquals(String.valueOf(ONE_TO_ZERO), srcText); tessocr.onDestroy(); }
Source:
public PayloadValidatingInterceptor payloadValidatingInterceptor() { final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor(); final Resource[] resources = new Resource[] { new ClassPathResource("schemas/common.xsd"), new ClassPathResource("schemas/devicemonitoring.xsd"), new ClassPathResource("schemas/pl-adhocmanagement.xsd"), new ClassPathResource("schemas/pl-schedulemanagement.xsd") }; payloadValidatingInterceptor.setSchemas(resources); return payloadValidatingInterceptor; }

Target:
public PayloadValidatingInterceptor payloadValidatingInterceptor() { final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor(); final Resource[] resources = new Resource[] { new ClassPathResource(COMMON_XSD_PATH), new ClassPathResource(DEVICE_MONITORING_XSD_PATH), new ClassPathResource(PL_ADHOCMANAGEMENT_XSD_PATH), new ClassPathResource(PL_SCHEDULEMANAGEMENT_XSD_PATH) }; payloadValidatingInterceptor.setSchemas(resources); return payloadValidatingInterceptor; }
Source:
public void delete(final Integer formulaId) { final BindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), FormulaDto.class.getName()); final Optional<FormulaDto> formula = this.formulaService.getById(formulaId); if (!formula.isPresent()) { bindingResult.reject("variable.formula.not.exist", new Integer[] {formulaId}, ""); throw new ApiRequestValidationException(bindingResult.getAllErrors()); } this.formulaValidator.validateDelete(formula.get(), bindingResult); if (bindingResult.hasErrors()) { throw new ApiRequestValidationException(bindingResult.getAllErrors()); } VariableCache.removeFromCache(formula.get().getTarget().getTargetTermId()); this.formulaService.delete(formulaId); }

Target:
public void delete(final Integer formulaId) { final BindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), FormulaDto.class.getName()); final Optional<FormulaDto> formula = this.formulaService.getById(formulaId); if (!formula.isPresent()) { bindingResult.reject("variable.formula.not.exist", new Integer[] {formulaId}, ""); throw new ApiRequestValidationException(bindingResult.getAllErrors()); } this.formulaValidator.validateDelete(formula.get(), bindingResult); if (bindingResult.hasErrors()) { throw new ApiRequestValidationException(bindingResult.getAllErrors()); } VariableCache.removeFromCache(formula.get().getTarget().getId()); this.formulaService.delete(formulaId); }
Source:
public void testGetContent_whenAllTestsPassedShouldGiveMeaningfulMessage() throws Exception { AbstractTestResultAction testResults = mock( AbstractTestResultAction.class ); when( build.getAction(AbstractTestResultAction.class) ).thenReturn( testResults ); String content = failedTestContent.evaluate( build, listener, FailedTestsContent.MACRO_NAME ); assertEquals( "All tests passed", content ); }

Target:
public void testGetContent_whenAllTestsPassedShouldGiveMeaningfulMessage() throws Exception { AbstractTestResultAction testResults = mock( AbstractTestResultAction.class ); when( testResults.getFailCount() ).thenReturn( 0 ); when( build.getAction(AbstractTestResultAction.class) ).thenReturn( testResults ); String content = failedTestContent.evaluate( build, listener, FailedTestsContent.MACRO_NAME ); assertEquals( "All tests passed", content ); }
Source:
public static VmNetworkInterface map(NIC model, VmNetworkInterface template) { VmNetworkInterface entity = template != null ? template : new VmNetworkInterface(); if (model.isSetVm() && model.getVm().isSetId()) { entity.setVmId(new Guid(model.getVm().getId())); } if (model.isSetId()) { entity.setId(new Guid(model.getId())); } if (model.isSetName()) { entity.setName(model.getName()); } if (model.isSetMac() && model.getMac().isSetAddress()) { entity.setMacAddress(model.getMac().getAddress()); } if (model.isSetNetwork() && model.getNetwork().isSetName()) { entity.setNetworkName(model.getNetwork().getName()); } if (model.isSetInterface()) { NicInterface nicType = NicInterface.fromValue(model.getInterface()); if (nicType != null) { entity.setType(map(nicType)); } } if (model.isSetActive()) { entity.setActive(model.isActive()); } return entity; }

Target:
public static VmNetworkInterface map(NIC model, VmNetworkInterface template) { VmNetworkInterface entity = template != null ? template : new VmNetworkInterface(); if (model.isSetVm() && model.getVm().isSetId()) { entity.setVmId(new Guid(model.getVm().getId())); } if (model.isSetId()) { entity.setId(new Guid(model.getId())); } if (model.isSetName()) { entity.setName(model.getName()); } if (model.isSetMac() && model.getMac().isSetAddress()) { entity.setMacAddress(model.getMac().getAddress()); } if (model.isSetNetwork() && model.getNetwork().isSetName()) { entity.setNetworkName(model.getNetwork().getName()); } if (model.isSetInterface()) { NicInterface nicType = NicInterface.fromValue(model.getInterface()); if (nicType != null) { entity.setType(map(nicType)); } } return entity; }
Source:
public GetBlobPropertiesOperation(String datacenterName, ConnectionPool connectionPool, ExecutorService requesterPool, OperationContext oc, BlobId blobId, long operationTimeoutMs, ClusterMap clusterMap) throws CoordinatorException { super(datacenterName, connectionPool, requesterPool, oc, blobId, operationTimeoutMs, clusterMap, MessageFormatFlags.BlobProperties); logger.trace( "DatacenterNAme " + datacenterName + " Connection pool " + connectionPool + ", requestorPool " + requesterPool + ", Operation context " + oc + ", blobId " + blobId + ", timeout " + operationTimeoutMs + ", clustermap " + clusterMap); this.blobProperties = null; }

Target:
public GetBlobPropertiesOperation(String datacenterName, ConnectionPool connectionPool, ExecutorService requesterPool, OperationContext oc, BlobId blobId, long operationTimeoutMs, ClusterMap clusterMap) throws CoordinatorException { super(datacenterName, connectionPool, requesterPool, oc, blobId, operationTimeoutMs, clusterMap, MessageFormatFlags.BlobProperties); logger.trace("GetBlobProperties: Datacenter name " + datacenterName + " Connection pool " + (connectionPool != null) + ", requester pool " + (requesterPool != null) + ", Operation context " + oc + ", blobId " + blobId + ", timeout " + operationTimeoutMs + ", clustermap " + (clusterMap != null)); this.blobProperties = null; }
Source:
public void testDefaultParam() { assertEarlyReferenceError("function f(x=a) { let a; }"); assertEarlyReferenceError(LINE_JOINER.join( "function f(x=a) { let a; }", "function g(x=1) { var a; }")); assertEarlyReferenceError("function f(x=a) { var a; }"); assertEarlyReferenceError("function f(x=a()) { function a() }"); assertEarlyReferenceError("function f(x=[a]) { var a; }"); assertEarlyReferenceError("function f(x=y, y=2) {}"); assertNoWarning("function f(x=a) {}"); assertNoWarning("function f(x=a) var a;"); assertNoWarning("let b; function f(x=b) { var b; }"); assertNoWarning("function f(y = () => x, x = 5) { return y(); }"); }

Target:
public void testDefaultParam() { assertEarlyReferenceError("function f(x=a) { let a; }"); assertEarlyReferenceError(LINE_JOINER.join( "function f(x=a) { let a; }", "function g(x=1) { var a; }")); assertEarlyReferenceError("function f(x=a) { var a; }"); assertEarlyReferenceError("function f(x=a()) { function a() }"); assertEarlyReferenceError("function f(x=[a]) { var a; }"); assertEarlyReferenceError("function f(x=y, y=2) {}"); assertNoWarning("function f(x=a) {}"); assertNoWarning("function f(x=a) var a;"); assertNoWarning("let b; function f(x=b) { var b; }"); assertNoWarning("function f(y = () => x, x = 5) { return y(); }"); assertNoWarning("function f(x = new foo.bar()) {}"); assertNoWarning("var foo = {}; foo.bar = class {}; function f(x = new foo.bar()) {}"); }
Source:
private static Date parseDate(List<String> parameters) { DateFormat df = new SimpleDateFormat("dd-MMM-yyyy"); try { Date d = df.parse(parameters.get(0)); LOGGER.debug("Using date '{}'.", d); return d; } catch (ParseException e) { throw new RuntimeException(e); } }

Target:
private static Date parseDate(List<String> parameters) { DateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH); String date = parameters.get(0); try { Date d = df.parse(date); LOGGER.debug("Using date '{}'.", d); return d; } catch (ParseException e) { throw new IllegalArgumentException("Unable to parse date '" + date+"'",e); } }
Source:
public static TimeZone getTimezone(long userId) { String timezone = Context.getPermissionsManager().getUser(userId).getTimezone(); if (timezone == null) { timezone = Context.getPermissionsManager().getServer().getTimezone(); } return timezone != null ? TimeZone.getTimeZone(timezone) : TimeZone.getDefault(); }

Target:
public static TimeZone getTimezone(long userId) { String timezone = (String) Context.getPermissionsManager().lookupPreference(userId, "timezone", null); return timezone != null ? TimeZone.getTimeZone(timezone) : TimeZone.getDefault(); }
Source:
private static void updateMemoryFuture(ListenableFuture<?> memoryPoolFuture, AtomicReference<SettableFuture<?>> targetFutureReference) { if (!memoryPoolFuture.isDone()) { SettableFuture<?> currentMemoryFuture = targetFutureReference.get(); while (currentMemoryFuture.isDone()) { SettableFuture<?> settableFuture = SettableFuture.create(); if (targetFutureReference.compareAndSet(currentMemoryFuture, settableFuture)) { currentMemoryFuture = settableFuture; } else { currentMemoryFuture = targetFutureReference.get(); } } SettableFuture<?> finalMemoryFuture = currentMemoryFuture; Futures.addCallback(memoryPoolFuture, new FutureCallback<Object>() { @Override public void onSuccess(Object result) { finalMemoryFuture.set(null); } @Override public void onFailure(Throwable t) { finalMemoryFuture.set(null); } }, directExecutor()); } }

Target:
private static void updateMemoryFuture(ListenableFuture<?> memoryPoolFuture, AtomicReference<SettableFuture<?>> targetFutureReference) { if (!memoryPoolFuture.isDone()) { SettableFuture<?> currentMemoryFuture = targetFutureReference.get(); while (currentMemoryFuture.isDone()) { SettableFuture<?> settableFuture = SettableFuture.create(); if (targetFutureReference.compareAndSet(currentMemoryFuture, settableFuture)) { currentMemoryFuture = settableFuture; } else { currentMemoryFuture = targetFutureReference.get(); } } SettableFuture<?> finalMemoryFuture = currentMemoryFuture; memoryPoolFuture.addListener(() -> finalMemoryFuture.set(null), directExecutor()); } }
Source:
public static void exportToStream(FileOutputStream outFileStream, Context context) throws IOException { FileChannel src = null; FileChannel dst = null; try { File currentDB = context.getDatabasePath(PodDBAdapter.DATABASE_NAME); if (currentDB.exists()) { src = new FileInputStream(currentDB).getChannel(); dst = outFileStream.getChannel(); long srcSize = src.size(); long oldDstSize = dst.size(); dst.transferFrom(src, 0, srcSize); long newDstSize = dst.size(); long expected = srcSize + oldDstSize; if (newDstSize < expected) { throw new IOException(String.format( "Unable to write entire database. Expected to write %s, but wrote %s.", Formatter.formatShortFileSize(context, expected), Formatter.formatShortFileSize(context, newDstSize - oldDstSize))); } } else { throw new IOException("Can not access current database"); } } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); throw e; } finally { IOUtils.closeQuietly(src); IOUtils.closeQuietly(dst); } }

Target:
public static void exportToStream(FileOutputStream outFileStream, Context context) throws IOException { FileChannel src = null; FileChannel dst = null; try { File currentDB = context.getDatabasePath(PodDBAdapter.DATABASE_NAME); if (currentDB.exists()) { src = new FileInputStream(currentDB).getChannel(); dst = outFileStream.getChannel(); long srcSize = src.size(); dst.transferFrom(src, 0, srcSize); long newDstSize = dst.size(); if (newDstSize != srcSize) { throw new IOException(String.format( "Unable to write entire database. Expected to write %s, but wrote %s.", Formatter.formatShortFileSize(context, srcSize), Formatter.formatShortFileSize(context, newDstSize))); } } else { throw new IOException("Can not access current database"); } } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); throw e; } finally { IOUtils.closeQuietly(src); IOUtils.closeQuietly(dst); } }
Source:
public final Response toResponse(T exception) { String message = Objects.toString(exception.getMessage()); String errorString = message; StatusType status = this.getStatus(exception); ResponseBuilder builder = Response.status(status); try { final SerializableError error; if (includeStackTrace) { StackTraceElement[] stackTrace = exception.getStackTrace(); error = SerializableError.of(message, exception.getClass(), Arrays.asList(stackTrace)); } else { String errorId = UUID.randomUUID().toString(); errorString = String.format("Error %s: %s", errorId, message); error = SerializableError.of(errorId, exception.getClass()); } builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json: {}", e.getMessage(), e); builder = Response.status(status); builder.type(MediaType.TEXT_PLAIN); builder.entity(message); } finally { log.error(errorString, exception); } return builder.build(); }

Target:
public final Response toResponse(T exception) { String exceptionMessage = Objects.toString(exception.getMessage()); String logMessage = exceptionMessage; StatusType status = this.getStatus(exception); ResponseBuilder builder = Response.status(status); try { final SerializableError error; if (includeStackTrace) { StackTraceElement[] stackTrace = exception.getStackTrace(); error = SerializableError.of(exceptionMessage, exception.getClass(), Arrays.asList(stackTrace)); } else { String errorId = UUID.randomUUID().toString(); logMessage = String.format("Error %s: %s", errorId, exceptionMessage); error = SerializableError.of(errorId, exception.getClass()); } builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json: {}", e.getMessage(), e); builder = Response.status(status); builder.type(MediaType.TEXT_PLAIN); builder.entity(exceptionMessage); } finally { log.error(logMessage, exception); } return builder.build(); }
Source:
public void iteratesUserOrganizations() throws Exception { final String login = "orgTestIterate"; final MkOrganizations orgs = new MkOrganizations( new MkStorage.InFile(), login ); orgs.get(login); MatcherAssert.assertThat( orgs.iterate(login), Matchers.not(Matchers.emptyIterable()) ); }

Target:
public void iteratesUserOrganizations() throws Exception { final String login = "orgTestIterate"; final MkOrganizations orgs = new MkOrganizations( new MkStorage.InFile(), login ); final Organization org = orgs.get(login); MatcherAssert.assertThat( orgs.iterate(org.login()), Matchers.not(Matchers.emptyIterable()) ); }
Source:
public ColumnSortList reloadColumnSortList() { ColumnSortList columnSortList = getListGrid().getColumnSortList(); GridPreferencesStore gridPreferencesStore = getListGrid().getGridPreferencesStore(); if (gridPreferencesStore != null) { GridSortedColumnPreference gridSortedColumnPreference = gridPreferencesStore.getGridSortedColumnPreference(); if (gridSortedColumnPreference != null && columnSortList.size() <= 1) { Optional<ColumnMeta<T>> optional = getListGrid().getColumnMetaList().stream().filter( tColumnMeta -> tColumnMeta.getColumn().getDataStoreName().equals(gridSortedColumnPreference.getDataStoreName())) .findFirst(); if (optional.isPresent()) { Column col = optional.get().getColumn(); String dataStoreName = gridSortedColumnPreference.getDataStoreName(); col.setDataStoreName(dataStoreName); Scheduler.get().scheduleDeferred(new Command() { public void execute () { columnSortList.push(new ColumnSortList.ColumnSortInfo(col, gridSortedColumnPreference.isAscending())); } }); } } } return columnSortList; }

Target:
public ColumnSortList reloadColumnSortList() { ColumnSortList columnSortList = getListGrid().getColumnSortList(); GridPreferencesStore gridPreferencesStore = getListGrid().getGridPreferencesStore(); if (gridPreferencesStore != null) { GridSortedColumnPreference gridSortedColumnPreference = gridPreferencesStore.getGridSortedColumnPreference(); if (gridSortedColumnPreference != null && columnSortList.size() <= 1) { Optional<ColumnMeta<T>> optional = getListGrid().getColumnMetaList().stream().filter( tColumnMeta -> tColumnMeta.getColumn().getDataStoreName().equals(gridSortedColumnPreference.getDataStoreName())) .findFirst(); if (optional.isPresent()) { if (columnSortList.get(0).getColumn().getDataStoreName().equals(gridSortedColumnPreference.getDataStoreName())) { columnSortList.push(getSecondSortColumn()); } Column col = optional.get().getColumn(); col.setDataStoreName(gridSortedColumnPreference.getDataStoreName()); columnSortList.push(new ColumnSortList.ColumnSortInfo(col, gridSortedColumnPreference.isAscending())); } } } return columnSortList; }
Source:
public void execute(TupleWindow inputWindow) { I reducedValue = null; for (Tuple tuple : inputWindow.get()) { I tup = (I) tuple.getValue(0); if (reducedValue == null) { reducedValue = tup; } else { reducedValue = reduceFn.apply(reducedValue, tup); } } long startWindow; long endWindow; if (inputWindow.getStartTimestamp() == null) { startWindow = 0; } else { startWindow = inputWindow.getStartTimestamp(); } if (inputWindow.getEndTimestamp() == null) { endWindow = 0; } else { endWindow = inputWindow.getEndTimestamp(); } Window window = new Window(startWindow, endWindow); collector.emit(new Values(new KeyValue<>(window, reducedValue))); }

Target:
public void execute(TupleWindow inputWindow) { I reducedValue = null; for (Tuple tuple : inputWindow.get()) { I tup = (I) tuple.getValue(0); if (reducedValue == null) { reducedValue = tup; } else { reducedValue = reduceFn.apply(reducedValue, tup); } } long startWindow; long endWindow; if (inputWindow.getStartTimestamp() == null) { startWindow = 0; } else { startWindow = inputWindow.getStartTimestamp(); } if (inputWindow.getEndTimestamp() == null) { endWindow = 0; } else { endWindow = inputWindow.getEndTimestamp(); } Window window = new Window(startWindow, endWindow, inputWindow.get().size()); collector.emit(new Values(new KeyValue<>(window, reducedValue))); }
Source:
void startConsumer() { if (topicPartitionsToOffset.size() <= 0) { LOG.error ("{}: Consumer is not subscribed to any SSPs", this); } topicPartitionToStartpointMap.forEach((topicPartition, startpoint) -> { Partition partition = new Partition(topicPartition.partition()); SystemStreamPartition systemStreamPartition = new SystemStreamPartition(systemName, topicPartition.topic(), partition); startpoint.apply(systemStreamPartition, kafkaStartpointRegistrationHandler); proxy.addTopicPartition(topicPartitionsToSSP.get(topicPartition), kafkaConsumer.position(topicPartition)); }); topicPartitionsToOffset.forEach((topicPartition, startingOffsetString) -> { if (!topicPartitionToStartpointMap.containsKey(topicPartition)) { long startingOffset = Long.valueOf(startingOffsetString); try { synchronized (kafkaConsumer) { kafkaConsumer.seek(topicPartition, startingOffset); } LOG.info("{}: Changing consumer's starting offset for topicPartition = to {}", this, topicPartition, startingOffsetString); } catch (Exception e) { String msg = String.format("%s: Got Exception while seeking to %s for partition %s", this, startingOffsetString, topicPartition); LOG.error(msg, e); throw new SamzaException(msg, e); } proxy.addTopicPartition(topicPartitionsToSSP.get(topicPartition), kafkaConsumer.position(topicPartition)); } }); if (proxy != null && !proxy.isRunning()) { LOG.info("{}: Starting proxy {}", this, proxy); proxy.start(); } }

Target:
void startConsumer() { if (topicPartitionToStartpointMap.size() <= 0) { LOG.error ("{}: Consumer is not subscribed to any SSPs", this); } topicPartitionToStartpointMap.forEach((topicPartition, startpoint) -> { Partition partition = new Partition(topicPartition.partition()); SystemStreamPartition systemStreamPartition = new SystemStreamPartition(systemName, topicPartition.topic(), partition); startpoint.apply(systemStreamPartition, kafkaStartpointRegistrationHandler); }); if (proxy != null && !proxy.isRunning()) { LOG.info("{}: Starting proxy {}", this, proxy); proxy.start(); } }
Source:
public void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) throws SignalFxMetricsException { if (dataPoints.isEmpty()) { return; } try { CloseableHttpResponse resp = null; try { resp = postToEndpoint(auth, getEntityForVersion(dataPoints), getEndpointForAddDatapoints(), !Boolean.getBoolean(DISABLE_COMPRESSION_PROPERTY)); int code = resp.getStatusLine().getStatusCode(); if (code != HttpStatus.SC_OK) { throw new SignalFxMetricsException("Invalid status code " + code); } } finally { if (resp != null) { resp.close(); } } } catch (IOException e) { throw new SignalFxMetricsException("Exception posting to addDataPoints", e); } }

Target:
public void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) throws SignalFxMetricsException { if (dataPoints.isEmpty()) { return; } try { CloseableHttpResponse resp = null; try { resp = postToEndpoint(auth, getEntityForVersion(dataPoints), getEndpointForAddDatapoints(), compress); int code = resp.getStatusLine().getStatusCode(); if (code != HttpStatus.SC_OK) { throw new SignalFxMetricsException("Invalid status code " + code); } } finally { if (resp != null) { resp.close(); } } } catch (IOException e) { throw new SignalFxMetricsException("Exception posting to addDataPoints", e); } }
Source:
public void updateDominantLocks( String path, UnlockStatus unlockStatus ) { assert true; }

Target:
public void updateDominantLocks( String path, UnlockStatus unlockStatus ) { }
Source:
public void fieldMissing(Object object, String fieldName, Object value) { if (!DeserializeDeletedFieldHandler.class.isAssignableFrom(object.getClass())) { return; } Object deserialized = value; if (value instanceof JsonObject) { deserialized = new com.cedarsoftware.util.io.JsonReader().jsonObjectsToJava((JsonObject) value); if (deserialized instanceof JsonObject) { deserialized = null; } } Boolean migrated = ((DeserializeDeletedFieldHandler) object).deletedField(fieldName, deserialized); if (migrated) { migratedDeleted[0] = true; } }

Target:
public void fieldMissing(Object object, String fieldName, Object value) { if (!DeserializeDeletedFieldHandler.class.isAssignableFrom(object.getClass())) { return; } Object deserialized = value; if (value instanceof JsonObject) { deserialized = new com.cedarsoftware.util.io.JsonReader().jsonObjectsToJava((JsonObject) value); if (deserialized instanceof JsonObject) { deserialized = null; } } Boolean migrated = ((DeserializeDeletedFieldHandler) object).deletedField(fieldName, deserialized); if (migrated) { migratedDeleted.set(true); } }
Source:
private String startUserDialog() throws IOException { log.debug("starting user dialog."); String user; while (true) { System.out.println("Please enter user:"); user = System.console().readLine(); if (StringUtils.isNotEmpty(user)) { break; } } return user; }

Target:
private String startUserDialog() throws IOException { log.debug("starting user dialog."); String user = null; while(StringUtils.isBlank(user)) { System.out.println("Please enter user:"); user = System.console().readLine(); } return user; }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { IReplicationController rc = getSelectedElement(event, IReplicationController.class); if(rc == null) { rc = getSelectedElement(event, IDeploymentConfig.class); } if(rc != null) { scaleUsing(event, rc, rc.getName()); return null; } Deployment deployment = getSelectedElement(event, Deployment.class); if(deployment != null) { Collection<IResourceUIModel> rcs = deployment.getReplicationControllers(); if(!rcs.isEmpty()) { rc = (IReplicationController) rcs.iterator().next().getResource(); scaleUsing(event, rc, deployment.getResource().getName()); } } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IReplicationController rc = getSelectedElement(event, IReplicationController.class); if(rc != null) { scaleUsing(event, rc, rc.getName()); return null; } Deployment deployment = getSelectedElement(event, Deployment.class); if(deployment != null) { Collection<IResourceUIModel> rcs = deployment.getReplicationControllers(); if(!rcs.isEmpty()) { rc = (IReplicationController) rcs.iterator().next().getResource(); scaleUsing(event, rc, deployment.getResource().getName()); } } return null; }
Source:
public boolean getSwipeArticles() { return getBoolean(R.string.pref_key_ui_swipeArticles, true); }

Target:
public boolean getSwipeArticles() { return getBoolean(R.string.pref_key_ui_swipeArticles, false); }
Source:
public String getConfigFile() { return configFile; }

Target:
public File getConfigFile() { return configFile; }