auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run(final ActionContext context) throws Exception { Connection connection = new Connection(config.host); try { connection.connect(); String password = Strings.isNullOrEmpty(config.password) ? null : config.password; if (!connection.authenticateWithPublicKey(config.user, new File(config.privateKeyFile), password)) { throw new IOException(String.format("SSH authentication error when connecting to %s@%s on port %d", config.user, config.host, config.port)); } LOG.debug("Connection established with the host {}", config.host); Session session = connection.openSession(); session.execCommand(config.command); InputStream stdout = new StreamGobbler(session.getStdout()); BufferedReader outBuffer = new BufferedReader(new InputStreamReader(stdout, Charsets.UTF_8)); InputStream stderr = new StreamGobbler(session.getStderr()); BufferedReader errBuffer = new BufferedReader(new InputStreamReader(stderr, Charsets.UTF_8)); String out = CharStreams.toString(outBuffer); String err = CharStreams.toString(errBuffer); LOG.debug("Output: {}", out); if (err.length() > 0) { LOG.error("Errors: {}", err); } Integer exitCode = session.getExitStatus(); if (exitCode != null && exitCode != 0) { throw new IOException(String.format("Error: command %s running on hostname %s finished with exit code: %d", config.command, config.host, exitCode)); } if (config.output != null) { out = out.endsWith("\n") ? out.substring(0, out.length() - 1) : out; context.getArguments().set(config.output, out); } } finally { connection.close(); } }

Target:
public void run(final ActionContext context) throws Exception { Connection connection = new Connection(config.host); try { connection.connect(); String password = Strings.isNullOrEmpty(config.password) ? null : config.password; if (!connection.authenticateWithPublicKey(config.user, new File(config.privateKeyFile), password)) { throw new IOException(String.format("SSH authentication error when connecting to %s@%s on port %d", config.user, config.host, config.port)); } LOG.debug("Connection established with the host {}", config.host); Session session = connection.openSession(); session.execCommand(config.command); InputStream stdout = new StreamGobbler(session.getStdout()); BufferedReader outBuffer = new BufferedReader(new InputStreamReader(stdout, Charsets.UTF_8)); InputStream stderr = new StreamGobbler(session.getStderr()); BufferedReader errBuffer = new BufferedReader(new InputStreamReader(stderr, Charsets.UTF_8)); String out = CharStreams.toString(outBuffer); String err = CharStreams.toString(errBuffer); if (out.length() > 0) { LOG.debug("Stdout: {}", out); } if (err.length() > 0) { LOG.error("Stderr: {}", err); } Integer exitCode = session.getExitStatus(); if (exitCode != null && exitCode != 0) { throw new IOException(String.format("Error: command %s running on hostname %s finished with exit code: %d", config.command, config.host, exitCode)); } if (config.output != null) { out = out.endsWith("\n") ? out.substring(0, out.length() - 1) : out; context.getArguments().set(config.output, out); } } finally { connection.close(); } }
Source:
protected void onEndTransaction(boolean callerIsSyncAdapter) { super.onEndTransaction(callerIsSyncAdapter); Intent providerChangedIntent = new Intent(Intent.ACTION_PROVIDER_CHANGED, TaskContract.getContentUri(mAuthority)); if (mChanged) { updateNotifications(); } if (Build.VERSION.SDK_INT >= 26) { providerChangedIntent.setPackage(getContext().getPackageName()); } getContext().sendBroadcast(providerChangedIntent); if (Boolean.TRUE.equals(mStaleListCreated.get())) { Intent visbilityRequest = new Intent("org.dmfs.tasks.action.STALE_LIST_BROADCAST").setPackage(getContext().getPackageName()); getContext().sendBroadcast(visbilityRequest); } }

Target:
protected void onEndTransaction(boolean callerIsSyncAdapter) { super.onEndTransaction(callerIsSyncAdapter); Intent providerChangedIntent = new Intent(Intent.ACTION_PROVIDER_CHANGED, TaskContract.getContentUri(mAuthority)); if (mChanged) { updateNotifications(); mChanged = false; } if (Build.VERSION.SDK_INT >= 26) { providerChangedIntent.setPackage(getContext().getPackageName()); } getContext().sendBroadcast(providerChangedIntent); if (Boolean.TRUE.equals(mStaleListCreated.get())) { Intent visbilityRequest = new Intent("org.dmfs.tasks.action.STALE_LIST_BROADCAST").setPackage(getContext().getPackageName()); getContext().sendBroadcast(visbilityRequest); } }
Source:
protected void onCreate(Bundle savedInstanceState) { context = this; ButterKnife.setDebug(true); fragmentManager = getSupportFragmentManager(); setTheme(R.style.AppTheme_NoActionBar_MainTheme); super.onCreate(savedInstanceState); SharedPreferencesUtil.putInt(ConstantStrings.SESSION_MAP_ID, -1); isTwoPane = drawerLayout == null; Utils.twoPane = isTwoPane; setSupportActionBar(toolbar); setUpNavDrawer(); setUpCustomTab(); setupEvent(); completeHandler = DownloadCompleteHandler.with(context); if(!SharedPreferencesUtil.getBoolean(ConstantStrings.IS_DOWNLOAD_DONE, false)) { if(Utils.isBaseUrlEmpty()) { downloadFromAssets(); } else { downloadData(); } } else { completeHandler.hide(); } if (savedInstanceState == null) { currentMenuItemId = R.id.nav_home; } else { currentMenuItemId = savedInstanceState.getInt(STATE_FRAGMENT); } if (getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_HOME) == null && getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_REST) == null) { doMenuAction(currentMenuItemId); } }

Target:
protected void onCreate(Bundle savedInstanceState) { context = this; ButterKnife.setDebug(true); fragmentManager = getSupportFragmentManager(); setTheme(R.style.AppTheme_NoActionBar_MainTheme); super.onCreate(savedInstanceState); SharedPreferencesUtil.putInt(ConstantStrings.SESSION_MAP_ID, -1); isTwoPane = drawerLayout == null; Utils.setTwoPane(isTwoPane); setSupportActionBar(toolbar); setUpNavDrawer(); setUpCustomTab(); setupEvent(); completeHandler = DownloadCompleteHandler.with(context); if(!SharedPreferencesUtil.getBoolean(ConstantStrings.IS_DOWNLOAD_DONE, false)) { if(Utils.isBaseUrlEmpty()) { downloadFromAssets(); } else { downloadData(); } } else { completeHandler.hide(); } if (savedInstanceState == null) { currentMenuItemId = R.id.nav_home; } else { currentMenuItemId = savedInstanceState.getInt(STATE_FRAGMENT); } if (getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_HOME) == null && getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_REST) == null) { doMenuAction(currentMenuItemId); } }
Source:
public TxnContext txn(@Nonnull final String namespace, IsolationLevel isolationLevel) { return new TxnContext( this.runtime.getObjectsView(), this.runtime.getTableRegistry(), namespace, isolationLevel, false); }

Target:
public TxnContext txn(@Nonnull final String namespace, IsolationLevel isolationLevel) { return new TxnContext( this.runtime.getObjectsView(), this.runtime.getTableRegistry(), namespace, isolationLevel); }
Source:
private FeedbackSessionsForm buildBasicForm(List<CourseAttributes> courses, String courseIdForNewSession, Map<String, InstructorAttributes> instructors, FeedbackSessionAttributes newFeedbackSession, String feedbackSessionType, String feedbackSessionNameForSessionList, List<String> courseIds, FeedbackSessionsAdditionalSettingsFormSegment additionalSettings) { List<ElementTag> courseIdOptions = getCourseIdOptions(courses, courseIdForNewSession, instructors, newFeedbackSession); boolean isSubmitButtonDisabled = courseIdOptions.isEmpty(); if (courseIdOptions.isEmpty()) { if (courses.isEmpty()) addPlaceholder(courseIdOptions, Const.StatusMessages.INSTRUCTOR_NO_ACTIVE_COURSES); else { addPlaceholder(courseIdOptions, Const.StatusMessages.INSTRUCTOR_NO_MODIFY_COURSES_SESSION_PERMISSION); } } return FeedbackSessionsForm.getFormForNewFs( newFeedbackSession, getFeedbackSessionTypeOptions(feedbackSessionType), courseIdForNewSession, courseIds, courseIdOptions, instructors, additionalSettings, isSubmitButtonDisabled); }

Target:
private FeedbackSessionsForm buildBasicForm(List<CourseAttributes> courses, String courseIdForNewSession, Map<String, InstructorAttributes> instructors, FeedbackSessionAttributes newFeedbackSession, String feedbackSessionType, String feedbackSessionNameForSessionList, List<String> courseIds, FeedbackSessionsAdditionalSettingsFormSegment additionalSettings) { List<ElementTag> courseIdOptions = getCourseIdOptions(courses, courseIdForNewSession, instructors, newFeedbackSession); boolean isSubmitButtonDisabled = courseIdOptions.isEmpty(); addPlaceholderIfEmpty(courseIdOptions, determinePlaceholderMessage(!courses.isEmpty())); return FeedbackSessionsForm.getFormForNewFs( newFeedbackSession, getFeedbackSessionTypeOptions(feedbackSessionType), courseIdForNewSession, courseIds, courseIdOptions, instructors, additionalSettings, isSubmitButtonDisabled); }
Source:
public void testServiceCheckWarning() throws Exception { SimpleTestJavaApp testApp = new SimpleTestJavaApp(); testApp.populateHashMap(400); registerMBean(testApp, "org.datadog.jmxfetch.test:type=ServiceCheckTest"); initApplication("too_many_metrics.yaml"); run(); LinkedList<HashMap<String, Object>> serviceChecks = getServiceChecks(); LinkedList<HashMap<String, Object>> metrics = getMetrics(); assertTrue(metrics.size() >= 350 ); assertEquals(1, serviceChecks.size()); HashMap<String, Object> sc = serviceChecks.getFirst(); assertNotNull(sc.get("name")); assertNotNull(sc.get("status")); assertNotNull(sc.get("message")); assertNotNull(sc.get("tags")); String scName = (String) (sc.get("name")); String scStatus = (String) (sc.get("status")); String[] scTags = (String[]) (sc.get("tags")); assertEquals(Reporter.formatServiceCheckPrefix("too_many_metrics"), scName); assertEquals(Status.STATUS_OK, scStatus); assertEquals(scTags.length, 3); assertTrue(Arrays.asList(scTags).contains("instance:jmx_test_instance")); }

Target:
public void testServiceCheckWarning() throws Exception { SimpleTestJavaApp testApp = new SimpleTestJavaApp(); testApp.populateHashMap(400); registerMBean(testApp, "org.datadog.jmxfetch.test:type=ServiceCheckTest"); initApplication("too_many_metrics.yaml"); run(); LinkedList<HashMap<String, Object>> serviceChecks = getServiceChecks(); LinkedList<HashMap<String, Object>> metrics = getMetrics(); assertTrue(metrics.size() >= 350 ); assertEquals(1, serviceChecks.size()); HashMap<String, Object> sc = serviceChecks.getFirst(); assertNotNull(sc.get("name")); assertNotNull(sc.get("status")); assertNotNull(sc.get("message")); assertNotNull(sc.get("tags")); String scName = (String) (sc.get("name")); String scStatus = (String) (sc.get("status")); String[] scTags = (String[]) (sc.get("tags")); assertEquals(Reporter.formatServiceCheckPrefix("too_many_metrics"), scName); assertEquals(Status.STATUS_OK, scStatus); assertEquals(scTags.length, 3); assertTrue(Arrays.asList(scTags).contains("instance:jmx_test_instance")); assertTrue(Arrays.asList(scTags).contains("env:stage")); assertTrue(Arrays.asList(scTags).contains("newTag:test")); }
Source:
private static void doJsonQuery(Prologue prologue, QueryExecution queryExecution, ResultsFormat outputFormat) { JsonArray results = queryExecution.execJson();; JSON.write(System.out, results); }

Target:
private static void doJsonQuery(Prologue prologue, QueryExecution queryExecution, ResultsFormat outputFormat) { JsonArray results = queryExecution.execJson(); JSON.write(System.out, results); }
Source:
List<Double> calculateHitProbabilities(final RollData rollData) { if (rollData.totalRolls == 0) { return List.of(); } final List<Integer> dicePowersList = new ArrayList<>(rollData.rollsByDicePower.keySet()); Collections.sort(dicePowersList); final int maxPower = dicePowersList.get(dicePowersList.size() - 1); final int[] dicePowers = new int[dicePowersList.size()]; final Map<Integer, double[]> calculatedProbabilityCache = this.calculatedProbabilityCache.computeIfAbsent( rollData.maxDiceSides, key -> new HashMap<>(rollData.maxDiceSides * rollData.totalRolls)); final int[] diceAvailableGroupedByPower = new int[maxPower + 1]; for (int dicePowerIndex = 0; dicePowerIndex < dicePowersList.size(); dicePowerIndex++) { final int dicePower = dicePowersList.get(dicePowerIndex); dicePowers[dicePowerIndex] = dicePower; diceAvailableGroupedByPower[dicePower] = rollData.rollsByDicePower.get(dicePower); } final double[] probabilities = new double[rollData.totalRolls + 1]; calculateHitProbabilitiesWorker( 0, dicePowersList.size() - 1, probabilities, 1.0, rollData.maxDiceSides, dicePowers, diceAvailableGroupedByPower, calculatedProbabilityCache); final List<Double> probabilitiesList = new ArrayList<>(); for (final double probability : probabilities) { probabilitiesList.add(probability); } return probabilitiesList; }

Target:
List<Double> calculateHitProbabilities(final RollData rollData) { if (rollData.totalRolls == 0) { return List.of(); } final List<Integer> dicePowersList = new ArrayList<>(rollData.rollsByDicePower.keySet()); Collections.sort(dicePowersList); final int maxPower = dicePowersList.get(dicePowersList.size() - 1); final int[] dicePowers = new int[dicePowersList.size()]; final Map<Integer, double[]> calculatedProbabilityCache = this.calculatedProbabilityCache.computeIfAbsent( rollData.maxDiceSides, key -> new HashMap<>(rollData.maxDiceSides * rollData.totalRolls)); final int[] diceAvailableGroupedByPower = new int[maxPower + 1]; for (int dicePowerIndex = 0; dicePowerIndex < dicePowersList.size(); dicePowerIndex++) { final int dicePower = dicePowersList.get(dicePowerIndex); dicePowers[dicePowerIndex] = dicePower; diceAvailableGroupedByPower[dicePower] = rollData.rollsByDicePower.get(dicePower); } final double[] probabilities = new double[rollData.totalRolls + 1]; calculateHitProbabilitiesWorker( 0, dicePowersList.size() - 1, probabilities, 1.0, rollData.maxDiceSides, dicePowers, diceAvailableGroupedByPower, calculatedProbabilityCache); return Arrays.stream(probabilities).boxed().collect(Collectors.toList()); }
Source:
public void writeToParcel(Parcel dest, int flags) { dest.writeString(mTag); dest.writeInt(mDrawerIconResId); dest.writeInt(mTitleResId); dest.writeInt(mDescriptionResId); dest.writeInt(mDefaultIconResId); dest.writeInt(mLogoResId); dest.writeInt(mSpecialEventTheme); dest.writeInt(mDrawerId); dest.writeInt(mGreetingsResId); dest.writeInt(mGreetingsTitleResId); dest.writeLong(mStartDateInMillis.getMillis()); dest.writeLong(mEndDateInMillis.getMillis()); }

Target:
public void writeToParcel(Parcel dest, int flags) { dest.writeString(mTag); dest.writeInt(mDrawerIconResId); dest.writeInt(mTitleResId); dest.writeInt(mDescriptionResId); dest.writeInt(mDefaultIconResId); dest.writeInt(mLogoResId); dest.writeInt(mSpecialEventTheme); dest.writeInt(mDrawerId); dest.writeInt(mGreetingsResId); dest.writeInt(mGreetingsTitleResId); dest.writeLong(mStartDate.getMillis()); dest.writeLong(mEndDateIn.getMillis()); }
Source:
public void testParametersAreSetForRevisedNodeSourceRequest() throws IOException { when(this.catalogObjectAction.isRevised()).thenReturn(true); HttpPost httpPost = this.catalogRequestBuilder.buildCatalogRequest("http://localhost:8080/catalog"); String string = getMultipartEntityString(httpPost); checkThatRequestContainsRegularParameters(string); assertThat("Request contains the " + CatalogConstants.KIND_PARAM + " parameter whereas it shouldn't", !string.contains(CatalogConstants.KIND_PARAM)); assertThat("Request contains the " + CatalogConstants.OBJECT_CONTENT_TYPE_PARAM + " parameter whereas it shouldn't", !string.contains(CatalogConstants.OBJECT_CONTENT_TYPE_PARAM)); }

Target:
public void testParametersAreSetForRevisedNodeSourceRequest() throws IOException { when(this.catalogObjectAction.isRevised()).thenReturn(true); HttpPost httpPost = this.catalogRequestBuilder.buildCatalogRequest("http://localhost:8080/catalog"); String entityStringContent = getMultipartEntityString(httpPost); checkThatRequestContainsRegularParameters(entityStringContent); assertThat("Request contains the " + CatalogConstants.KIND_PARAM + " parameter whereas it shouldn't", CoreMatchers.not(entityStringContent.contains(CatalogConstants.KIND_PARAM))); assertThat("Request contains the " + CatalogConstants.OBJECT_CONTENT_TYPE_PARAM + " parameter whereas it shouldn't", CoreMatchers.not(entityStringContent.contains(CatalogConstants.OBJECT_CONTENT_TYPE_PARAM))); }
Source:
protected void serviceInit(Configuration conf) throws Exception { super.serviceInit(conf); LOG.debug("Creating plugin dispatch queue with size {}", qsize); blockingQueue = new ArrayBlockingQueue<>(qsize); RejectedExecutionHandler handler = new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { blockingQueue.remove(); executor.submit(r); } catch (NoSuchElementException ex) { } } }; executorService = new ThreadPoolExecutor(1, NUM_MAX_THREADS, 60L, TimeUnit.SECONDS, blockingQueue, new NameableThreadFactory("PluginExecutor-"), handler); }

Target:
protected void serviceInit(Configuration conf) throws Exception { super.serviceInit(conf); LOG.debug("Creating plugin dispatch queue with size {}", qsize); blockingQueue = new ArrayBlockingQueue<>(qsize); RejectedExecutionHandler rejectionHandler = new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { blockingQueue.remove(); executor.submit(r); } catch (NoSuchElementException ex) { } } }; executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, blockingQueue, new NameableThreadFactory("PluginExecutorThread"), rejectionHandler); }
Source:
public LoggedUserDto getLoggedUserInfo() { LoggedUserDto loggedUserDto=new LoggedUserDto(); List<String> roles = new ArrayList<>(); String userLogin = SecurityContextHolder.getContext().getAuthentication().getName(); if (userLogin!="anonymousUser"){ for (Role role:userService.findByLogin(userLogin).getRoles()){ roles.add(role.getName()); } loggedUserDto.setLogin(SecurityContextHolder.getContext().getAuthentication().getName()); } loggedUserDto.setRoles(roles); return loggedUserDto; }

Target:
public LoggedUserDto getLoggedUserInfo() { LoggedUserDto loggedUserDto=new LoggedUserDto(); List<String> roles = new ArrayList<>(); String userLogin = getUserLogin(); if (!userLogin.equals(Constants.UNKNOWN_USER)){ for (Role role:userService.findByLogin(userLogin).getRoles()){ roles.add(role.getName()); } loggedUserDto.setLogin(userLogin); } loggedUserDto.setRoles(roles); return loggedUserDto; }
Source:
private void createMenu() { popupMenu = new JBPopupMenu(); popupMenu.setForeground(FOREGROUND_COLOR); popupMenu.setBackground(BACKGROUND_COLOR); menuItemPrefix = "Follow "; ISarosSession currentSession = session; FollowModeManager currentFollowModeManager = followModeManager; if (currentSession == null || currentFollowModeManager == null) { return; } for (User user : currentSession.getRemoteUsers()) { JMenuItem menuItem = createItemForUser(user); popupMenu.add(menuItem); } popupMenu.addSeparator(); JMenuItem leaveItem = new JMenuItem("Leave follow mode"); leaveItem.setForeground(FOREGROUND_COLOR); leaveItem.setBackground(BACKGROUND_COLOR); leaveItem.addActionListener(e -> followModeAction.execute(null)); leaveItem.setEnabled(currentFollowModeManager.getFollowedUser() != null); popupMenu.add(leaveItem); }

Target:
private void createMenu() { popupMenu = new JBPopupMenu(); popupMenu.setForeground(FOREGROUND_COLOR); popupMenu.setBackground(BACKGROUND_COLOR); menuItemPrefix = "Follow "; ISarosSession currentSession = session; FollowModeManager currentFollowModeManager = followModeManager; if (currentSession == null || currentFollowModeManager == null) { return; } for (User user : currentSession.getRemoteUsers()) { JMenuItem menuItem = createItemForUser(user); popupMenu.add(menuItem); } popupMenu.addSeparator(); JMenuItem leaveItem = new JBMenuItem("Leave follow mode"); leaveItem.setForeground(FOREGROUND_COLOR); leaveItem.setBackground(BACKGROUND_COLOR); leaveItem.addActionListener(e -> followModeAction.execute(null)); leaveItem.setEnabled(currentFollowModeManager.getFollowedUser() != null); popupMenu.add(leaveItem); }
Source:
public void testKieSessionsPoolInMultithreadEnv() throws InterruptedException, ExecutionException { KieContainerSessionsPool pool = getKieContainer().newKieSessionsPool( 4 ); final int THREAD_NR = 10; final ExecutorService executor = Executors.newFixedThreadPool(THREAD_NR, r -> { final Thread t = new Thread(r); t.setDaemon(true); return t; }); final CompletionService<Boolean> ecs = new ExecutorCompletionService<>(executor); for (int i = 0; i < THREAD_NR; i++) { ecs.submit(() -> { try { KieSession ksession = pool.newKieSession(); checkKieSession( ksession ); ksession.dispose(); try { ksession.insert( "test2" ); fail("it shouldn't be possible to operate on a disposed session even if created from a pool"); } catch (Exception e) { } return true; } catch (final Exception e) { return false; } }); } boolean success = true; for (int i = 0; i < THREAD_NR; i++) { success = ecs.take().get() && success; } assertTrue( success ); pool.shutdown(); try { pool.newKieSession(); fail("after pool shutdown it shouldn't be possible to get sessions from it"); } catch (Exception e) { } }

Target:
public void testKieSessionsPoolInMultithreadEnv() throws InterruptedException, ExecutionException { KieContainerSessionsPool pool = getKieContainer().newKieSessionsPool( 4 ); final int THREAD_NR = 10; ExecutorService executor = Executors.newFixedThreadPool(THREAD_NR, r -> { final Thread t = new Thread(r); t.setDaemon(true); return t; }); try { CompletionService<Boolean> ecs = new ExecutorCompletionService<>( executor ); for (int i = 0; i < THREAD_NR; i++) { ecs.submit( () -> { try { KieSession ksession = pool.newKieSession(); try { checkKieSession( ksession ); } finally { ksession.dispose(); } try { ksession.insert( "test2" ); fail( "it shouldn't be possible to operate on a disposed session even if created from a pool" ); } catch (IllegalStateException e) { } return true; } catch (final Exception e) { return false; } } ); } boolean success = true; for (int i = 0; i < THREAD_NR; i++) { success = ecs.take().get() && success; } assertTrue( success ); } finally { executor.shutdown(); } pool.shutdown(); try { pool.newKieSession(); fail("after pool shutdown it shouldn't be possible to get sessions from it"); } catch (IllegalStateException e) { } }
Source:
private void scheduleExpiredLockReaper() { reaperExecutor.scheduleAtFixedRate(() -> heldLocks.removeExpired(), 0, LeaseExpirationTimer.LEASE_TIMEOUT_MILLIS / 2, TimeUnit.MILLISECONDS); }

Target:
private void scheduleExpiredLockReaper() { reaperExecutor.scheduleAtFixedRate(() -> { try { heldLocks.removeExpired(); } catch (Throwable t) { log.warn("Error while removing expired lock requests. Trying again on next iteration.", t); } }, 0, LeaseExpirationTimer.LEASE_TIMEOUT_MILLIS / 2, TimeUnit.MILLISECONDS); }
Source:
public void judgmentReindexingJob() throws Exception { JobExecution jobExecution = jobLauncher.run(judgmentReindexingJob, new JobParameters()); JobExecutionAssertUtils.assertJobExecution(jobExecution, 0, ALL_JUDGMENTS_COUNT); solrJudgmentsServer.commit(); assertAllMarkedAsIndexed(); assertAllInIndex(ALL_JUDGMENTS_COUNT); }

Target:
public void judgmentReindexingJob() throws Exception { JobExecution jobExecution = jobLauncher.run(judgmentReindexingJob, new JobParameters()); solrJudgmentsServer.commit(); JobExecutionAssertUtils.assertJobExecution(jobExecution, 0, ALL_JUDGMENTS_COUNT); assertAllMarkedAsIndexed(); assertAllInIndex(ALL_JUDGMENTS_COUNT); }
Source:
public FieldLayout getRows(final ContentType contentType) { try { fixFields(fields, contentType.id()); final String rowsString = MAPPER.writeValueAsString(fields); return new FieldLayout(contentType, new JsonFieldTransformer(rowsString).asList()); } catch (IOException e) { throw new DotRuntimeException(e); } }

Target:
public FieldLayout getRows(final ContentType contentType) { try { fixFields(fields, contentType.id()); final String rowsString = MAPPER.writeValueAsString(fields); return new FieldLayout(contentType, new JsonFieldTransformer(rowsString).asList()); } catch (IOException e) { Logger.error(MoveFieldsForm.class, String.format("Error moving fields to Content Type %s: %s", contentType.name(), e.getMessage())); throw new DotRuntimeException(e); } }
Source:
protected void run() throws Exception { PackConfig packConfig = new PackConfig(); StoredConfig cfg; if (configFile == null) { cfg = getUserConfig(); } else { if (!configFile.exists()) { throw die(MessageFormat.format( CLIText.get().configFileNotFound, configFile.getAbsolutePath())); } cfg = new FileBasedConfig(getUserConfig(), configFile, FS.DETECTED); } cfg.load(); new WindowCacheConfig().fromConfig(cfg).install(); packConfig.fromConfig(cfg); int threads = packConfig.getThreads(); if (threads <= 0) threads = Runtime.getRuntime().availableProcessors(); if (1 < threads) packConfig.setExecutor(Executors.newFixedThreadPool(threads)); final FileResolver<DaemonClient> resolver = new FileResolver<>(); for (File f : directory) { outw.println(MessageFormat.format(CLIText.get().exporting, f.getAbsolutePath())); resolver.exportDirectory(f); } resolver.setExportAll(exportAll); final org.eclipse.jgit.transport.Daemon d; d = new org.eclipse.jgit.transport.Daemon( host != null ? new InetSocketAddress(host, port) : new InetSocketAddress(port)); d.setPackConfig(packConfig); d.setRepositoryResolver(resolver); if (0 <= timeout) d.setTimeout(timeout); for (String n : enable) service(d, n).setEnabled(true); for (String n : disable) service(d, n).setEnabled(false); for (String n : canOverride) service(d, n).setOverridable(true); for (String n : forbidOverride) service(d, n).setOverridable(false); if (ketchServerType == KetchServerType.LEADER) { startKetchLeader(d); } d.start(); outw.println(MessageFormat.format(CLIText.get().listeningOn, d.getAddress())); }

Target:
protected void run() throws Exception { PackConfig packConfig = new PackConfig(); StoredConfig cfg; if (configFile == null) { cfg = getUserConfig(); } else { if (!configFile.exists()) { throw die(MessageFormat.format( CLIText.get().configFileNotFound, configFile.getAbsolutePath())); } cfg = new FileBasedConfig(configFile, FS.DETECTED); } cfg.load(); new WindowCacheConfig().fromConfig(cfg).install(); packConfig.fromConfig(cfg); int threads = packConfig.getThreads(); if (threads <= 0) threads = Runtime.getRuntime().availableProcessors(); if (1 < threads) packConfig.setExecutor(Executors.newFixedThreadPool(threads)); final FileResolver<DaemonClient> resolver = new FileResolver<>(); for (File f : directory) { outw.println(MessageFormat.format(CLIText.get().exporting, f.getAbsolutePath())); resolver.exportDirectory(f); } resolver.setExportAll(exportAll); final org.eclipse.jgit.transport.Daemon d; d = new org.eclipse.jgit.transport.Daemon( host != null ? new InetSocketAddress(host, port) : new InetSocketAddress(port)); d.setPackConfig(packConfig); d.setRepositoryResolver(resolver); if (0 <= timeout) d.setTimeout(timeout); for (String n : enable) service(d, n).setEnabled(true); for (String n : disable) service(d, n).setEnabled(false); for (String n : canOverride) service(d, n).setOverridable(true); for (String n : forbidOverride) service(d, n).setOverridable(false); if (ketchServerType == KetchServerType.LEADER) { startKetchLeader(d); } d.start(); outw.println(MessageFormat.format(CLIText.get().listeningOn, d.getAddress())); }
Source:
public boolean execute(ArenaMaster am, CommandSender sender, String... args) { if (!Commands.isPlayer(sender)) { am.getGlobalMessenger().tell(sender, Msg.MISC_NOT_FROM_CONSOLE); return true; } Player p = Commands.unwrap(sender); Arena arena = am.getArenaWithPlayer(p); if (arena == null) { am.getGlobalMessenger().tell(p, Msg.NOT_IN_LOBBY); return true; } else if (arena.inArena(p)) { arena.getMessenger().tell(p, Msg.JOIN_ALREADY_PLAYING); return true; } else if (!arena.inLobby(p)) { arena.getMessenger().tell(p, Msg.NOT_IN_LOBBY); return true; } if (arena.getArenaPlayer(p).getArenaClass() != null) { arena.getMessenger().tell(p, Msg.LOBBY_PLAYER_READY); arena.playerReady(p); } else { arena.getMessenger().tell(p, Msg.LOBBY_PICK_CLASS); } return true; }

Target:
public boolean execute(ArenaMaster am, CommandSender sender, String... args) { if (!Commands.isPlayer(sender)) { am.getGlobalMessenger().tell(sender, Msg.MISC_NOT_FROM_CONSOLE); return true; } Player p = Commands.unwrap(sender); Arena arena = am.getArenaWithPlayer(p); if (arena == null) { am.getGlobalMessenger().tell(p, Msg.NOT_IN_LOBBY); } else if (!arena.inLobby(p)) { arena.getMessenger().tell(p, Msg.NOT_IN_LOBBY); } else if (arena.getArenaPlayer(p).getArenaClass() != null) { arena.getMessenger().tell(p, Msg.LOBBY_PLAYER_READY); arena.playerReady(p); } else { arena.getMessenger().tell(p, Msg.LOBBY_PICK_CLASS); } return true; }
Source:
public void populateClan(ChatChannelUser chatChannelUser) { if (chatChannelUser.isDisplayed()) { if (chatChannelUser.getClan().isEmpty()) { chatChannelUser.getPlayer().ifPresent(player -> { if (player.getClan() != null) { clanService.getClanByTag(player.getClan()) .thenAccept(optionalClan -> Platform.runLater(() -> { if (optionalClan.isPresent()) { chatChannelUser.setClan(optionalClan.get()); } else { chatChannelUser.setClan(null); } }) ); } else { chatChannelUser.setClan(null); } }); } } else { chatChannelUser.setClan(null); } }

Target:
public void populateClan(ChatChannelUser chatChannelUser) { if (chatChannelUser.isDisplayed()) { if (!chatChannelUser.getClan().isEmpty()) { return; } chatChannelUser.getPlayer().ifPresent(player -> { if (player.getClan() != null) { clanService.getClanByTag(player.getClan()) .thenAccept(optionalClan -> Platform.runLater(() -> { Clan clan = optionalClan.orElse(null); chatChannelUser.setClan(clan); }) ); } else { chatChannelUser.setClan(null); } }); } else { chatChannelUser.setClan(null); } }
Source:
public void checkTriggers(final Calendar cal) { for (ComputedFolder<?> p : Jenkins.getInstance().getAllItems(ComputedFolder.class)) { for (Trigger<?> t : p.getTriggers().values()) { LOGGER.log(Level.FINE, "cron checking {0}", p.getName()); CronTabList tabs; try { tabs = (CronTabList) this.tabsField.get(t); } catch (IllegalAccessException e) { continue; } if (tabs.check(cal)) { LOGGER.log(Level.CONFIG, "cron triggered {0}", p.getName()); try { t.run(); } catch (Throwable e) { LOGGER.log(Level.WARNING, t.getClass().getName() + ".run() failed for " + p.getName(), e); } } } } }

Target:
public void checkTriggers(final Calendar cal) { for (ComputedFolder<?> p : Jenkins.getInstance().allItems(ComputedFolder.class)) { for (Trigger<?> t : p.getTriggers().values()) { LOGGER.log(Level.FINE, "cron checking {0}", p.getName()); CronTabList tabs; try { tabs = (CronTabList) this.tabsField.get(t); } catch (IllegalAccessException e) { continue; } if (tabs.check(cal)) { LOGGER.log(Level.CONFIG, "cron triggered {0}", p.getName()); try { t.run(); } catch (Throwable e) { LOGGER.log(Level.WARNING, t.getClass().getName() + ".run() failed for " + p.getName(), e); } } } } }
Source:
public void should_expose_warnings_on_execution_info() { final String query = String.format( "BEGIN UNLOGGED BATCH\n" + "INSERT INTO test (k, v) VALUES (1, '%s')\n" + "INSERT INTO test (k, v) VALUES (2, '%s')\n" + "APPLY BATCH", Strings.repeat("1", 2 * 1024), Strings.repeat("1", 3 * 1024)); Statement<?> st = SimpleStatement.builder(String.format(query)).build(); ResultSet result = sessionRule.session().execute(st); ExecutionInfo executionInfo = result.getExecutionInfo(); assertThat(executionInfo).isNotNull(); List<String> warnings = executionInfo.getWarnings(); assertThat(warnings).isNotEmpty(); verify(appender, after(500).atLeast(1)).doAppend(loggingEventCaptor.capture()); assertThat(loggingEventCaptor.getValue().getMessage()).isNotNull(); boolean testPassed = false; for (ILoggingEvent log : loggingEventCaptor.getAllValues()) { String logMessage = log.getFormattedMessage(); assertThat(logMessage) .startsWith("Query '") .contains(query.substring(0, RequestLogger.DEFAULT_REQUEST_LOGGER_MAX_QUERY_LENGTH)) .contains("' generated server side warning(s): "); if (logMessage.contains("Batch")) { assertThat(logMessage) .contains(String.format("for [%s.test] is of size", sessionRule.keyspace().asCql(true))) .contains("exceeding specified threshold"); testPassed = true; break; } } assertThat(testPassed).isTrue(); }

Target:
public void should_expose_warnings_on_execution_info() { final String query = String.format( "BEGIN UNLOGGED BATCH\n" + "INSERT INTO test (k, v) VALUES (1, '%s')\n" + "INSERT INTO test (k, v) VALUES (2, '%s')\n" + "APPLY BATCH", Strings.repeat("1", 2 * 1024), Strings.repeat("1", 3 * 1024)); Statement<?> st = SimpleStatement.builder(query).build(); ResultSet result = sessionRule.session().execute(st); ExecutionInfo executionInfo = result.getExecutionInfo(); assertThat(executionInfo).isNotNull(); List<String> warnings = executionInfo.getWarnings(); assertThat(warnings).isNotEmpty(); verify(appender, timeout(500).atLeast(1)).doAppend(loggingEventCaptor.capture()); List<String> logMessages = loggingEventCaptor .getAllValues() .stream() .map(ILoggingEvent::getFormattedMessage) .collect(Collectors.toList()); assertThat(logMessages) .anySatisfy( logMessage -> assertThat(logMessage) .startsWith("Query '") .contains( query.substring(0, RequestLogger.DEFAULT_REQUEST_LOGGER_MAX_QUERY_LENGTH)) .contains("' generated server side warning(s): ") .contains("Batch") .contains( String.format( "for [%s.test] is of size", sessionRule.keyspace().asCql(true))) .contains("exceeding specified threshold")); }
Source:
protected Item createRssItem(FeedMetadata feedMetadata, Map<String, Object> article) { Item item = new Item(); item.setTitle(Strings.isNullOrEmpty((String) article.get("title_display")) ? (String) article.get("title") : (String) article.get("title_display")); item.setLink(getArticleLink(feedMetadata, article)); Guid guid = new Guid(); guid.setValue((String) article.get("id")); guid.setPermaLink(false); item.setGuid(guid); item.setPubDate(getPubDate(feedMetadata, article)); List<String> authorList = (List<String>) article.get("author_display"); if (authorList != null) { item.setAuthor(AUTHOR_JOINER.join(authorList)); } item.setDescription(buildRssDescription(article)); return item; }

Target:
protected Item createRssItem(FeedMetadata feedMetadata, Map<String, Object> article) { Item item = new Item(); item.setTitle(getArticleTitle(article)); item.setLink(getArticleLink(feedMetadata, article)); Guid guid = new Guid(); guid.setValue((String) article.get("id")); guid.setPermaLink(false); item.setGuid(guid); item.setPubDate(getPubDate(feedMetadata, article)); List<String> authorList = (List<String>) article.get("author_display"); if (authorList != null) { item.setAuthor(AUTHOR_JOINER.join(authorList)); } item.setDescription(buildRssDescription(article)); return item; }
Source:
public void run() { if(blobStore.get() == null) { System.out.println("Creating connection for thread " + Thread.currentThread()); resetBlobstore(username, password, provider, region); } if(container.get() == null) { container.set(UUID.randomUUID().toString()); Location location = getOnlyElement(blobStore.get().listAssignableLocations()); blobStore.get().createContainerInLocation(location, container.get()); System.out.println("Created container " + container.get() + " for thread " + Thread.currentThread() + " in " + location.toString()); } String md5Local, md5Remote; Blob blob = null; FileInputStream fis = null; try { fis = new FileInputStream(file); md5Local = DigestUtils.md5Hex(fis); fis.close(); } catch (java.io.IOException e) { e.printStackTrace(); return; } do { System.out.println("Uploading " + file.getName() + " ; " + FileUtils.sizeOf(file)); try { blob = blobStore.get().blobBuilder(file.getName()) .payload(Payloads.newInputStreamPayload(new BufferedInputStream(new FileInputStream(file)))) .build(); } catch (FileNotFoundException e) { e.printStackTrace(); return; } md5Remote = blobStore.get().putBlob(container.get(), blob); if(md5Local.equals(md5Remote)) { long total = BlobUploaderMain.bytesUploaded.addAndGet(FileUtils.sizeOf(file)); System.out.println("Uploaded MB: " + (int)total / FileUtils.ONE_MB + "MB ; " + (int)((float)BlobUploaderMain.bytesUploaded.get()/BlobUploaderMain.totalBytes)*100 +"%"); return; } else { System.out.println("Retrying " + file.getName()); } } while(true); }

Target:
public void run() { if (blobStore.get() == null) { System.out.println("Creating connection for thread " + Thread.currentThread()); resetBlobstore(username, password, provider, region); } if (container.get() == null) { container.set(UUID.randomUUID().toString()); Location location = getOnlyElement(blobStore.get().listAssignableLocations()); blobStore.get().createContainerInLocation(location, container.get()); System.out.println("Created container " + container.get() + " for thread " + Thread.currentThread() + " in " + location.toString()); } String md5Local; String md5Remote; Blob blob; try { md5Local = BaseEncoding.base16().encode(Files.hash(file, Hashing.md5()).asBytes()).toLowerCase(); } catch (java.io.IOException e) { e.printStackTrace(); return; } ByteSourcePayload bsp = new ByteSourcePayload(Files.asByteSource(file)); do { System.out.println("Uploading " + file.getName() + " ; " + FileUtils.sizeOf(file)); blob = blobStore.get().blobBuilder(file.getName()) .payload(bsp) .build(); md5Remote = blobStore.get().putBlob(container.get(), blob).toLowerCase(); if (md5Local.equals(md5Remote)) { long total = BlobUploaderMain.bytesUploaded.addAndGet(FileUtils.sizeOf(file)); System.out.println("Uploaded MB: " + (int)total / FileUtils.ONE_MB + "MB ; " + (int)((float)BlobUploaderMain.bytesUploaded.get() / BlobUploaderMain.totalBytes) * 100 + "%"); bsp.release(); return; } else { System.out.printf("md5 mismatch %s vs %s, retrying %s", md5Local, md5Remote, file.getName()); } } while(true); }
Source:
public void onNotification(Notification notification) { if (!(notification.getType() instanceof CoreNotificationType)) return; CoreNotificationType type = (CoreNotificationType) notification.getType(); if (type != CONSUMER_CREATED) return; TypedProperties props = notification.getProperties(); SimpleString protocolName = props.getSimpleStringProperty(ManagementHelper.HDR_PROTOCOL_NAME); if (protocolName == null || !protocolName.toString().equals(MQTTProtocolManagerFactory.MQTT_PROTOCOL_NAME)) return; int distance = props.getIntProperty(ManagementHelper.HDR_DISTANCE); if (distance > 0) { SimpleString queueName = props.getSimpleStringProperty(ManagementHelper.HDR_ROUTING_NAME); Binding binding = server.getPostOffice().getBinding(queueName); if (binding != null) { Queue queue = (Queue) binding.getBindable(); String clientId = props.getSimpleStringProperty(ManagementHelper.HDR_CLIENT_ID).toString(); Collection<Consumer> consumersSet = queue.getConsumers(); for (Consumer consumer : consumersSet) { ServerConsumerImpl serverConsumer = (ServerConsumerImpl) consumer; if (clientId.equals(serverConsumer.getConnectionClientID())) serverConsumer.getRemotingConnection().destroy(); } } } }

Target:
public void onNotification(Notification notification) { if (!(notification.getType() instanceof CoreNotificationType)) return; CoreNotificationType type = (CoreNotificationType) notification.getType(); if (type != CoreNotificationType.SESSION_CREATED) return; TypedProperties props = notification.getProperties(); SimpleString protocolName = props.getSimpleStringProperty(ManagementHelper.HDR_PROTOCOL_NAME); if (protocolName == null || !protocolName.toString().equals(MQTTProtocolManagerFactory.MQTT_PROTOCOL_NAME)) return; int distance = props.getIntProperty(ManagementHelper.HDR_DISTANCE); if (distance > 0) { String clientId = props.getSimpleStringProperty(ManagementHelper.HDR_CLIENT_ID).toString(); MQTTConnection mqttConnection = connectedClients.get(clientId); if (mqttConnection != null) { mqttConnection.destroy(); } } }
Source:
public Builder baseUrl(URL val) { return baseUri(UrlFunctions.URI_FROM_STRING.apply(val.toString())); }

Target:
public Builder baseUrl(URL val) { return baseUri(Urls.URI_FROM_STRING.apply(val.toString())); }
Source:
@Override public String toString () { return "DataNode[" + getHostname() + ":" + getPort() + "]"; }

Target:
public String toString() { return "DataNode[" + getHostname() + ":" + getPort() + "]"; }
Source:
private void logStaleCheckBatchResults(StaleCheckBatchProcessResults staleCheckBatchProcessResults) { LOG.info("processStaleCheckBatchFiles: =============================================="); LOG.info("processStaleCheckBatchFiles: ==== Summary of Stale Check Batch ===="); LOG.info("processStaleCheckBatchFiles: =============================================="); LOG.info("processStaleCheckBatchFiles: Files loaded successfully: " + staleCheckBatchProcessResults.getNumSuccessFiles()); LOG.info("processStaleCheckBatchFiles: Files loaded with one or more failed rows: " + staleCheckBatchProcessResults.getNumPartialFiles()); if (!staleCheckBatchProcessResults.getPartialProcessingSummary().isEmpty()) { for (String failingFileName : staleCheckBatchProcessResults.getPartialProcessingSummary().keySet()) { List<String> errorsEncountered = staleCheckBatchProcessResults.getPartialProcessingSummary().get(failingFileName); LOG.error("processStaleCheckBatchFiles: Stale Check Batch input file contained "+ errorsEncountered.size() + " rows that could not be processed. (" + failingFileName + ")"); for (String dataError : errorsEncountered) { LOG.error("processStaleCheckBatchFiles: " + dataError); } } } LOG.info("processStaleCheckBatchFiles: Files with errors: " + staleCheckBatchProcessResults.getNumErrorFiles()); LOG.info("processStaleCheckBatchFiles: ====================="); LOG.info("processStaleCheckBatchFiles: ==== End Summary ===="); }

Target:
private void logStaleCheckBatchResults(StaleCheckBatchProcessResults staleCheckBatchProcessResults) { LOG.info("logStaleCheckBatchResults: =============================================="); LOG.info("logStaleCheckBatchResults: ==== Summary of Stale Check Batch ===="); LOG.info("logStaleCheckBatchResults: =============================================="); LOG.info("logStaleCheckBatchResults: Files loaded successfully: " + staleCheckBatchProcessResults.getNumSuccessFiles()); LOG.info("logStaleCheckBatchResults: Files loaded with one or more failed rows: " + staleCheckBatchProcessResults.getNumPartialFiles()); if (!staleCheckBatchProcessResults.getPartialProcessingSummary().isEmpty()) { for (String failingFileName : staleCheckBatchProcessResults.getPartialProcessingSummary().keySet()) { List<String> errorsEncountered = staleCheckBatchProcessResults.getPartialProcessingSummary().get(failingFileName); LOG.error("logStaleCheckBatchResults: Stale Check Batch input file contained "+ errorsEncountered.size() + " rows that could not be processed. (" + failingFileName + ")"); for (String dataError : errorsEncountered) { LOG.error("logStaleCheckBatchResults: " + dataError); } } } LOG.info("logStaleCheckBatchResults: Files with errors: " + staleCheckBatchProcessResults.getNumErrorFiles()); LOG.info("logStaleCheckBatchResults: ====================="); LOG.info("logStaleCheckBatchResults: ==== End Summary ===="); }
Source:
public boolean isDeviceOnline() { NetworkInfo networkInfo = getConnectivityNetwork(); return networkInfo!=null && networkInfo.isConnected(); }

Target:
public boolean isDeviceOnline() { ConnectivityType connectivityType = getConnectivityType(); return connectivityType == ConnectivityType.MOBILE || connectivityType == ConnectivityType.WIFI; }
Source:
private void revealDiskPanel(final AbstractDiskModel disk) { boolean isInVm = disk.getVm() != null; diskTypePanel.setVisible(isNewLunDiskEnabled); externalDiskPanel.setVisible(isNewLunDiskEnabled && disk.getDiskStorageType().getEntity() == DiskStorageType.LUN); diskErrorPolicyEditor.setVisible(disk.getDiskStorageType().getEntity() != DiskStorageType.LUN); aliasEditor.setFocus(!isInVm); }

Target:
private void revealDiskPanel(final AbstractDiskModel disk) { boolean isInVm = disk.getVm() != null; diskTypePanel.setVisible(isNewLunDiskEnabled); externalDiskPanel.setVisible(isNewLunDiskEnabled && disk.getDiskStorageType().getEntity() == DiskStorageType.LUN); aliasEditor.setFocus(!isInVm); }
Source:
public final void testGetBoxScanWithReadErrorsReturnsError() throws Exception { final long id = 1L; final JSONObject error = new JSONObject(); final JSONObject errorComponents = new JSONObject(); errorComponents.put("errorPositions", "[]"); errorComponents.put("successPositions", "[]"); errorComponents.put("message", "The scanner can not read some positions. Please remove or fix and then rescan: "); errorComponents.put("type", "Read Error"); error.put("errors", errorComponents); Box box = makeEmptyBox(); when(scan.getRowCount()).thenReturn(box.getSize().getRows()); when(scan.getColumnCount()).thenReturn(box.getSize().getColumns()); when(boxScanner.getScan()).thenReturn(scan); when(scan.getReadErrorPositions()).thenReturn(Arrays.asList("A01")); when(requestManager.getBoxById(1L)).thenReturn(box); JSONObject json = new JSONObject(); json.put("boxId", id); assertTrue(boxControllerHelperService.getBoxScan(null, json).getJSONArray("errors").size() > 0); }

Target:
public final void testGetBoxScanWithReadErrorsReturnsError() throws Exception { final long id = 1L; Box box = makeEmptyBox(); when(scan.getRowCount()).thenReturn(box.getSize().getRows()); when(scan.getColumnCount()).thenReturn(box.getSize().getColumns()); when(boxScanner.getScan()).thenReturn(scan); when(scan.getReadErrorPositions()).thenReturn(Arrays.asList("A01")); when(requestManager.getBoxById(1L)).thenReturn(box); JSONObject json = new JSONObject(); json.put("boxId", id); assertTrue(boxControllerHelperService.getBoxScan(null, json).getJSONArray("errors").size() > 0); }
Source:
public Example<Instance> nextInstance() { InstancesHeader header = getHeader(); Instance inst = new DenseInstance(header.numAttributes()); String kafkaString = getNextInstanceFromKafka(); String[] KeyValueString = kafkaString.split(":"); String[] attributes = KeyValueString[1].split(","); for (int i = 0; i < attributes.length - 1; i++) { if (i < numAttrOption.getValue()) { inst.setValue(i, Double.parseDouble(attributes[i])); } } inst.setDataset(header); inst.setClassValue(Double .parseDouble(attributes[attributes.length - 1])); try { Thread.sleep(timeDelayOption.getValue()); } catch (InterruptedException e) { e.printStackTrace(); } return new InstanceExample(inst); }

Target:
public Example<Instance> nextInstance() { InstancesHeader header = getHeader(); Instance inst; String kafkaString = getNextInstanceFromKafka(); inst = mapper.getInstance(kafkaString, keyValueSeparator.getValue(), valuesSeparator.getValue(), instanceType.getValue(), numAttrOption.getValue(), header); try { Thread.sleep(timeDelayOption.getValue()); } catch (InterruptedException e) { e.printStackTrace(); } return new InstanceExample(inst); }
Source:
public void test() throws SQLException { Statement s = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = null; try { s.executeUpdate("INSERT INTO table1(" + columnName + ") VALUES(" + originalValue + ")"); rs = s.executeQuery(TestUtil.selectSQL("table1", "table1_id, " + columnName)); rs.next(); rs.updateObject(2, newValue); rs.updateRow(); rs.close(); rs = s.executeQuery(TestUtil.selectSQL("table1", columnName)); rs.next(); assertEquals(newValue, rs.getObject(1, newValue.getClass())); } finally { if (rs != null) { rs.close(); } s.close(); } }

Target:
public void test() throws SQLException { Statement s = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = null; try { s.executeUpdate("INSERT INTO table1(" + columnName + ") VALUES(" + originalValue + ")"); rs = s.executeQuery(TestUtil.selectSQL("table1", "table1_id, " + columnName)); rs.next(); rs.updateObject(2, newValue); rs.updateRow(); rs.close(); rs = s.executeQuery(TestUtil.selectSQL("table1", columnName)); rs.next(); assertEquals("Object wasn't identical when it got read back from the database", newValue, rs.getObject(1, newValueClass)); } finally { TestUtil.closeQuietly(rs); TestUtil.closeQuietly(s); } }