auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void setCache(String lastModified, String cacheControl, String expires, String etag, String url, String date, Pair<String, String> varyHeader) { if (log.isDebugEnabled()){ log.debug("setCache(" + lastModified + "," + cacheControl + "," + expires + "," + etag + "," + url + "," + date + ")"); } Date expiresDate = null; if (useExpires) { final String maxAge = "max-age="; if(cacheControl != null && cacheControl.contains("no-store")) { return; } if (expires != null) { expiresDate = extractExpiresDateFromExpires(expires); } if(cacheControl != null && !cacheControl.contains("no-cache")) { expiresDate = extractExpiresDateFromCacheControl(lastModified, cacheControl, expires, etag, url, date, maxAge); } } if (varyHeader != null) { log.debug("Set entry into cache for url and vary ({})", url, varyHeader, varyUrl(url, varyHeader.getLeft(), varyHeader.getRight())); getCache().put(url, new CacheEntry(lastModified, expiresDate, etag, varyHeader.getLeft())); getCache().put(varyUrl(url, varyHeader.getLeft(), varyHeader.getRight()), new CacheEntry(lastModified, expiresDate, etag, null)); } else { getCache().put(url, new CacheEntry(lastModified, expiresDate, etag, null)); } }

Target:
private void setCache(String lastModified, String cacheControl, String expires, String etag, String url, String date, Pair<String, String> varyHeader) { if (log.isDebugEnabled()){ log.debug("setCache(" + lastModified + "," + cacheControl + "," + expires + "," + etag + "," + url + "," + date + ")"); } Date expiresDate = null; if (useExpires) { final String maxAge = "max-age="; if(cacheControl != null && cacheControl.contains("no-store")) { return; } if (expires != null) { expiresDate = extractExpiresDateFromExpires(expires); } if(cacheControl != null && !cacheControl.contains("no-cache")) { expiresDate = extractExpiresDateFromCacheControl(lastModified, cacheControl, expires, etag, url, date, maxAge, expiresDate); } } if (varyHeader != null) { if (log.isDebugEnabled()) { log.debug("Set entry into cache for url and vary ({})", url, varyHeader, varyUrl(url, varyHeader.getLeft(), varyHeader.getRight())); } getCache().put(url, new CacheEntry(lastModified, expiresDate, etag, varyHeader.getLeft())); getCache().put(varyUrl(url, varyHeader.getLeft(), varyHeader.getRight()), new CacheEntry(lastModified, expiresDate, etag, null)); } else { getCache().put(url, new CacheEntry(lastModified, expiresDate, etag, null)); } }
Source:
public void testPathRegexDoesntMatchPartially() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportControlCheck.class); checkConfig.addAttribute("file", getResourcePath("import-control_one.xml")); checkConfig.addAttribute("path", "main"); final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; verify(checkConfig, getPath("InputImportControl.java"), expected); }

Target:
public void testPathRegexDoesntMatchPartially() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(ImportControlCheck.class); checkConfig.addAttribute("file", getResourcePath("import-control_one.xml")); checkConfig.addAttribute("path", "[\\\\/]NoMatch\\.java"); final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; verify(checkConfig, getPath("InputImportControl.java"), expected); }
Source:
public void shouldConflictIfImmutableTimestampLockExpiresEvenIfNoWritesOnThoroughSweptTable() { TimelockService timelock = mock(TimelockService.class); LockService mockLockService = mock(LockService.class); TransactionManager txnManagerWithMocks = new SerializableTransactionManager(metricsManager, keyValueService, timelock, mockLockService, transactionService, () -> AtlasDbConstraintCheckingMode.FULL_CONSTRAINT_CHECKING_THROWS_EXCEPTIONS, conflictDetectionManager, sweepStrategyManager, NoOpCleaner.INSTANCE, () -> AtlasDbConstants.DEFAULT_TIMESTAMP_CACHE_SIZE, false, () -> AtlasDbConstants.DEFAULT_TRANSACTION_LOCK_ACQUIRE_TIMEOUT_MS, AbstractTransactionTest.GET_RANGES_THREAD_POOL_SIZE, AbstractTransactionTest.DEFAULT_GET_RANGES_CONCURRENCY, MultiTableSweepQueueWriter.NO_OP, MoreExecutors.newDirectExecutorService()); setupTimeLock(timelock); assertThatThrownBy(() -> txnManagerWithMocks.runTaskThrowOnConflict(txn -> { get(txn, TEST_TABLE_THOROUGH, "row1", "col1"); return null; })) .isInstanceOf(TransactionFailedRetriableException.class); }

Target:
public void shouldConflictIfImmutableTimestampLockExpiresEvenIfNoWritesOnThoroughSweptTable() { TransactionManager txnManagerWithMocks = setupTransactionManager(); assertThatThrownBy(() -> txnManagerWithMocks.runTaskThrowOnConflict(txn -> { get(txn, TEST_TABLE_THOROUGH, "row1", "col1"); return null; })) .isInstanceOf(TransactionFailedRetriableException.class); }
Source:
private void internalTryBasic(CuratorFramework client) throws Exception { WatcherRemoveCuratorFramework removerClient = client.newWatcherRemoveCuratorFramework(); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { } }; removerClient.checkExists().usingWatcher(watcher).forPath("/hey"); List<String> existWatches = WatchersDebug.getExistWatches(client.getZookeeperClient().getZooKeeper()); Assert.assertEquals(existWatches.size(), 1); removerClient.removeWatchers(); new Timing().sleepABit(); existWatches = WatchersDebug.getExistWatches(client.getZookeeperClient().getZooKeeper()); Assert.assertEquals(existWatches.size(), 0); }

Target:
private void internalTryBasic(CuratorFramework client) throws Exception { WatcherRemoveCuratorFramework removerClient = client.newWatcherRemoveCuratorFramework(); final CountDownLatch latch = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { if ( event.getType() == Event.EventType.DataWatchRemoved ) { latch.countDown(); } } }; removerClient.checkExists().usingWatcher(watcher).forPath("/hey"); List<String> existWatches = WatchersDebug.getExistWatches(client.getZookeeperClient().getZooKeeper()); Assert.assertEquals(existWatches.size(), 1); removerClient.removeWatchers(); Assert.assertTrue(new Timing().awaitLatch(latch)); existWatches = WatchersDebug.getExistWatches(client.getZookeeperClient().getZooKeeper()); Assert.assertEquals(existWatches.size(), 0); }
Source:
public void onCreate(Bundle savedInstanceState) { Log.i("SalesforceDroidGapActivity.onCreate", "onCreate called"); super.onCreate(savedInstanceState); bootconfig = BootConfig.getBootConfig(this); LoginOptions loginOptions = new LoginOptions( null, ForceApp.APP.getPasscodeHash(), bootconfig.getOauthRedirectURI(), bootconfig.getRemoteAccessConsumerKey(), bootconfig.getOauthScopes()); Log.i("SalesforceDroidGapActivity.onCreate", "loginOptions:" + loginOptions.toString()); clientManager = new ClientManager(this, ForceApp.APP.getAccountType(), loginOptions); try { client = clientManager.peekRestClient(); } catch (AccountInfoNotFoundException e) { client = null; } passcodeManager = ForceApp.APP.getPasscodeManager(); CookieSyncManager.createInstance(this); if (bootconfig.autoRefreshPeriodically()) { periodicAutoRefreshHandler = new Handler(); periodicAutoRefresher = new PeriodicAutoRefresher(); } EventsObservable.get().notifyEvent(EventType.MainActivityCreateComplete, this); }

Target:
public void onCreate(Bundle savedInstanceState) { Log.i("SalesforceDroidGapActivity.onCreate", "onCreate called"); super.onCreate(savedInstanceState); bootconfig = BootConfig.getBootConfig(this); LoginOptions loginOptions = new LoginOptions( null, ForceApp.APP.getPasscodeHash(), bootconfig.getOauthRedirectURI(), bootconfig.getRemoteAccessConsumerKey(), bootconfig.getOauthScopes()); clientManager = new ClientManager(this, ForceApp.APP.getAccountType(), loginOptions); try { client = clientManager.peekRestClient(); } catch (AccountInfoNotFoundException e) { client = null; } passcodeManager = ForceApp.APP.getPasscodeManager(); CookieSyncManager.createInstance(this); if (bootconfig.autoRefreshPeriodically()) { periodicAutoRefreshHandler = new Handler(); periodicAutoRefresher = new PeriodicAutoRefresher(); } EventsObservable.get().notifyEvent(EventType.MainActivityCreateComplete, this); }
Source:
public void display(DashboardMap dashes) { while (1 < table.getRowCount()) { table.removeRow(table.getRowCount() - 1); } List<DashboardInfo> list = dashes.values().asList(); Collections.sort(list, new Comparator<DashboardInfo>() { @Override public int compare(DashboardInfo a, DashboardInfo b) { return a.name().compareTo(b.name()); } }); String section = null; for(DashboardInfo d : list) { if (!d.refName().equals(section)) { section = d.refName(); insertTitleRow(table.getRowCount(), section); } insert(table.getRowCount(), d); } finishDisplay(); }

Target:
public void display(DashboardMap dashes) { while (1 < table.getRowCount()) { table.removeRow(table.getRowCount() - 1); } List<DashboardInfo> list = dashes.values().asList(); Collections.sort(list, new Comparator<DashboardInfo>() { @Override public int compare(DashboardInfo a, DashboardInfo b) { return a.id().compareTo(b.id()); } }); String section = null; for(DashboardInfo d : list) { if (!d.refName().equals(section)) { section = d.refName(); insertTitleRow(table.getRowCount(), section); } insert(table.getRowCount(), d); } finishDisplay(); }
Source:
private ValueType getTypeFromDimVal(Object dimVal) { Object singleVal; if (dimVal instanceof List) { List dimValList = (List) dimVal; singleVal = dimValList.size() == 0 ? null : dimValList.get(0); } else { singleVal = dimVal; } if (singleVal == null) { return null; } ValueType valType = TYPE_MAP.get(singleVal.getClass().getSimpleName()); return valType; }

Target:
private ValueType getTypeFromDimVal(Object dimVal) { Object singleVal; if (dimVal instanceof List) { List dimValList = (List) dimVal; singleVal = dimValList.size() == 0 ? null : dimValList.get(0); } else { singleVal = dimVal; } if (singleVal == null) { return null; } return TYPE_MAP.get(singleVal.getClass().getSimpleName()); }
Source:
private void visitConnect(IProject project, final Map<IProject, File> projects) throws CoreException { if (RepositoryMapping.getMapping(project) != null) { return; } RepositoryProvider provider = RepositoryProvider .getProvider(project); if (provider != null) { return; } RepositoryFinder f = new RepositoryFinder(project); f.setFindInChildren(false); List<RepositoryMapping> mappings = f .find(new NullProgressMonitor()); if (mappings.isEmpty()) { return; } RepositoryMapping m = mappings.get(0); IPath gitDirPath = m.getGitDirAbsolutePath(); if (gitDirPath == null || !isValidRepositoryPath(gitDirPath)) { return; } File repositoryDir = gitDirPath.toFile(); projects.put(project, repositoryDir); int nofMappings = mappings.size(); if (nofMappings > 1) { Set<String> configured = Activator.getDefault() .getRepositoryUtil().getRepositories(); if (!configured.contains(gitDirPath.toString())) { IPath lastPath = gitDirPath; for (int i = 1; i < nofMappings; i++) { IPath nextPath = mappings.get(i) .getGitDirAbsolutePath(); if (nextPath == null) { continue; } if (configured.contains(nextPath.toString())) { return; } else if (!isValidRepositoryPath(nextPath)) { break; } lastPath = nextPath; } repositoryDir = lastPath.toFile(); } } try { Activator.getDefault().getRepositoryUtil() .addConfiguredRepository(repositoryDir); } catch (IllegalArgumentException e) { logError(CoreText.Activator_AutoSharingFailed, e); } }

Target:
private void visitConnect(IProject project, final Map<IProject, File> projects) throws CoreException { if (RepositoryMapping.getMapping(project) != null) { return; } RepositoryProvider provider = RepositoryProvider .getProvider(project); if (provider != null) { return; } RepositoryFinder f = new RepositoryFinder(project); f.setFindInChildren(false); List<RepositoryMapping> mappings = f .find(new NullProgressMonitor()); if (mappings.isEmpty()) { return; } RepositoryMapping m = mappings.get(0); IPath gitDirPath = m.getGitDirAbsolutePath(); if (gitDirPath == null || !isValidRepositoryPath(gitDirPath)) { return; } File repositoryDir = gitDirPath.toFile(); projects.put(project, repositoryDir); Set<String> configured = Activator.getDefault().getRepositoryUtil() .getRepositories(); if (configured.contains(gitDirPath.toString())) { return; } int nofMappings = mappings.size(); if (nofMappings > 1) { IPath lastPath = gitDirPath; for (int i = 1; i < nofMappings; i++) { IPath nextPath = mappings.get(i).getGitDirAbsolutePath(); if (nextPath == null) { continue; } if (configured.contains(nextPath.toString())) { return; } else if (!isValidRepositoryPath(nextPath)) { break; } lastPath = nextPath; } repositoryDir = lastPath.toFile(); } try { Activator.getDefault().getRepositoryUtil() .addConfiguredRepository(repositoryDir); } catch (IllegalArgumentException e) { logError(CoreText.Activator_AutoSharingFailed, e); } }
Source:
private String createThresholdExceededMessage(Category category, Double totalAmountSpent) { String defaultCurrency = userUtil.extractLoggedAppUserFromDatabase().getDefaultCurrency().getCurrencyCode(); String thresholdAmount = category.getThreshold() + " " + defaultCurrency; String message = "The threshold of \"" + thresholdAmount + "\" for the category \"" + category.getName() + "\" " + " have been exceeded. Total amount spent on this category this month is \"" + totalAmountSpent + " " + defaultCurrency + "\"!"; return message; }

Target:
private String createThresholdExceededMessage(Category category, Double totalAmountSpent) { String defaultCurrency = userUtil.extractLoggedAppUserFromDatabase().getDefaultCurrency().getCurrencyCode(); String thresholdAmount = category.getThreshold() + " " + defaultCurrency; String message = "Threshold of value " + thresholdAmount + " for category " + category.getName() + " has been exceeded!\n" + "Current amount spent: " + totalAmountSpent + " " + defaultCurrency + "."; return message; }
Source:
public void replaceRecipients(Properties recipientMappings) { Assert.notNull(recipientMappings, "'recipientMappings' must not be null"); Set<String> keys = recipientMappings.stringPropertyNames(); ConcurrentLinkedQueue<Recipient> originalRecipients = this.recipients; this.recipients.clear(); for (String key : keys) { Assert.notNull(key, "channelName can't be null."); if(StringUtils.hasText(recipientMappings.getProperty(key))) { this.addRecipient(key, recipientMappings.getProperty(key)); } else { this.addRecipient(key); } } if (logger.isDebugEnabled()) { logger.debug("Channel Recipients:" + originalRecipients + " replaced with:" + this.recipients); } }

Target:
public void replaceRecipients(Properties recipientMappings) { Assert.notNull(recipientMappings, "'recipientMappings' must not be null"); Assert.notEmpty(recipientMappings, "'recipientMappings' must not be empty"); Set<String> keys = recipientMappings.stringPropertyNames(); ConcurrentLinkedQueue<Recipient> originalRecipients = this.recipients; this.recipients.clear(); for (String key : keys) { Assert.notNull(key, "channelName can't be null."); if(StringUtils.hasText(recipientMappings.getProperty(key))) { this.addRecipient(key, recipientMappings.getProperty(key)); } else { this.addRecipient(key); } } if (logger.isDebugEnabled()) { logger.debug("Channel Recipients:" + originalRecipients + " replaced with:" + this.recipients); } }
Source:
public String toString() { return new ToStringBuilder(this) .append("slowLogResponseRequest", slowLogResponseRequest) .append("namedQueueEvent", namedQueueEvent) .append("balancerDecisionRequest", balancerDecisionRequest) .toString(); }

Target:
public String toString() { return new ToStringBuilder(this) .append("slowLogResponseRequest", slowLogResponseRequest) .append("namedQueueEvent", namedQueueEvent) .append("balancerDecisionsRequest", balancerDecisionsRequest) .toString(); }
Source:
public void checkinAssignments(List<Assignment> assignments) { EKBCommit commit = getEKBCommit(); preparePersistenceAccess(); for (Assignment assignment : assignments) { String query = "userName:\"" + assignment.getUserName() + "\" and projectName:\"" + assignment.getProjectName() + "\""; List<Assignment> result = queryService.queryByString(Assignment.class, query); if (result.size() == 0) { commit.addInsert(assignment); } else { commit.addUpdate(assignment); } } persistService.commit(commit); revokePersistenceAccess(); }

Target:
public void checkinAssignments(List<Assignment> assignments) { EKBCommit commit = getEKBCommit(); preparePersistenceAccess(); for (Assignment assignment : assignments) { QueryRequest request = QueryRequest.create(); request.addParameter("userName", assignment.getUserName()); request.addParameter("projectName", assignment.getProjectName()); List<Assignment> result = queryService.query(Assignment.class, request); if (result.size() == 0) { commit.addInsert(assignment); } else { commit.addUpdate(assignment); } } persistService.commit(commit); revokePersistenceAccess(); }
Source:
public void iccOpenLogicalChannel(String AID, byte p2, Message response) { RILRequest rr = RILRequest.obtain(RIL_REQUEST_SIM_OPEN_CHANNEL, response); rr.mParcel.writeByte(p2); rr.mParcel.writeString(AID); if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); send(rr); }

Target:
public void iccOpenLogicalChannel(String AID, byte p2, Message response) { RILRequest rr = RILRequest.obtain(RIL_REQUEST_SIM_OPEN_CHANNEL, response); rr.mParcel.writeString(AID); rr.mParcel.writeByte(p2); if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); send(rr); }
Source:
public SecretProperties setEnabled(Boolean enabled) { this.enabled = enabled; return this; }

Target:
public SecretProperties setEnabled(Boolean enabled) { Objects.requireNonNull(enabled); this.enabled = enabled; return this; }
Source:
public String getPosTag(ConlluTagset tagset) { if (ConlluTagset.U.equals(tagset)) { return uPosTag; } else if (ConlluTagset.X.equals(tagset)) { return xPosTag; } else { throw new IllegalStateException("Unexpected tagset value: " + tagset); } }

Target:
public String getPosTag(ConlluTagset tagset) { switch (tagset) { case U: return uPosTag; case X: return xPosTag; default: throw new IllegalStateException("Unexpected tagset value: " + tagset); } }
Source:
public AbstractAsyncProducer(MaxwellContext context) { super(context); this.inflightMessages = new InflightMessageList(); Metrics metrics = context.getMetrics(); MetricRegistry metricRegistry = metrics.getRegistry(); String gaugeName = metrics.metricName("inflightmessages", "count"); metricRegistry.register(gaugeName, (Gauge<Long>) () -> (long) inflightMessages.size()); this.succeededMessageCount = metricRegistry.counter(metrics.metricName("messages", "succeeded")); this.succeededMessageMeter = metricRegistry.meter(metrics.metricName("messages", "succeeded", "meter")); this.failedMessageCount = metricRegistry.counter(metrics.metricName("messages", "failed")); this.failedMessageMeter = metricRegistry.meter(metrics.metricName("messages", "failed", "meter")); }

Target:
public AbstractAsyncProducer(MaxwellContext context) { super(context); this.inflightMessages = new InflightMessageList(); Metrics metrics = context.getMetrics(); MetricRegistry metricRegistry = metrics.getRegistry(); String gaugeName = metrics.metricName("inflightmessages", "count"); metrics.register(gaugeName, (Gauge<Long>) () -> (long) inflightMessages.size()); this.succeededMessageCount = metricRegistry.counter(metrics.metricName("messages", "succeeded")); this.succeededMessageMeter = metricRegistry.meter(metrics.metricName("messages", "succeeded", "meter")); this.failedMessageCount = metricRegistry.counter(metrics.metricName("messages", "failed")); this.failedMessageMeter = metricRegistry.meter(metrics.metricName("messages", "failed", "meter")); }
Source:
private DateTime getTaskStartTime(final String id) { if (taskInfoProvider.getTaskLocation(id) != null) { DateTime startTime = taskClient.getStartTime(id, false); log.debug("Received start time of [%s] from task [%s]", startTime, id); return startTime; } return null; }

Target:
private DateTime getTaskStartTime(final String id) { if (!taskInfoProvider.getTaskLocation(id).equals(TaskLocation.unknown())) { DateTime startTime = taskClient.getStartTime(id, false); log.debug("Received start time of [%s] from task [%s]", startTime, id); return startTime; } return null; }
Source:
@Test public void symlinkInTar() throws Exception { assumeTrue(!Functions.isWindows()); FilePath tmp = new FilePath(temp.getRoot()); FilePath in = tmp.child("in"); in.mkdirs(); in.child("c").touch(0); in.child("b").symlinkTo("c", TaskListener.NULL); FilePath tar = tmp.child("test.tar"); in.tar(tar.write(), "**/*"); FilePath dst = in.child("dst"); tar.untar(dst, TarCompression.NONE); assertEquals("c",dst.child("b").readLink()); }

Target:
@Test public void symlinkInTar() throws Exception { assumeFalse("can't test on Windows", Functions.isWindows()); FilePath tmp = new FilePath(temp.getRoot()); FilePath in = tmp.child("in"); in.mkdirs(); in.child("c").touch(0); in.child("b").symlinkTo("c", TaskListener.NULL); FilePath tar = tmp.child("test.tar"); in.tar(tar.write(), "**/*"); FilePath dst = in.child("dst"); tar.untar(dst, TarCompression.NONE); assertEquals("c",dst.child("b").readLink()); }
Source:
public static String getTestScreenshotsLink() { String link = ""; try { if (FileUtils.listFiles(ReportContext.getTestDir(), new String[] { "png" }, false).isEmpty()) { return link; } } catch (Exception e) { LOGGER.error("Exception during report directory scanning", e); e.printStackTrace(); } String test = testDirectory.get().getName().replaceAll("[^a-zA-Z0-9.-]", "_"); if (!Configuration.get(Parameter.REPORT_URL).isEmpty()) { link = String.format("%s/%d/%s/report.html", Configuration.get(Parameter.REPORT_URL), rootID, test); } else { link = String.format("./%d/%s/report.html", rootID, test); } return link; }

Target:
public static String getTestScreenshotsLink() { String link = ""; try { if (FileUtils.listFiles(ReportContext.getTestDir(), new String[] { "png" }, false).isEmpty()) { return link; } } catch (Exception e) { LOGGER.error("Exception during report directory scanning", e); } String test = testDirectory.get().getName().replaceAll("[^a-zA-Z0-9.-]", "_"); if (!Configuration.get(Parameter.REPORT_URL).isEmpty()) { link = String.format("%s/%d/%s/report.html", Configuration.get(Parameter.REPORT_URL), rootID, test); } else { link = String.format("./%d/%s/report.html", rootID, test); } return link; }
Source:
private List<String> getSelectedRepositories(ExecutionEvent event) throws ExecutionException { List<String> repoDirs = new ArrayList<>(); List<RepositoryTreeNode> elements = getSelectedNodes(event); for (Object element : elements) { if (element instanceof RepositoryNode) { File dir = ((RepositoryNode) element).getRepository() .getDirectory(); repoDirs.add(dir.toString()); } } return repoDirs; }

Target:
private List<File> getSelectedRepositories(ExecutionEvent event) throws ExecutionException { return getSelectedNodes(event).stream() .filter(node -> node instanceof RepositoryNode) .map(e -> e.getRepository().getDirectory()) .collect(Collectors.toList()); }
Source:
public static EC2HardwareBuilder t2_xlarge() { return new EC2HardwareBuilder(InstanceType.T2_XLARGE).t2() .ram(16384) .processors(ImmutableList.of(new Processor(2.0, 0.4))).rootDeviceType(RootDeviceType.EBS); }

Target:
public static EC2HardwareBuilder t2_xlarge() { return new EC2HardwareBuilder(InstanceType.T2_XLARGE).t2() .ram(16384) .processors(ImmutableList.of(new Processor(4.0, 3.0))).rootDeviceType(RootDeviceType.EBS); }
Source:
public <E extends Throwable> E expectError(Class<E> clazz, long timeoutMillis, String errorMsg) throws Exception { Thread.sleep(timeoutMillis); if (env.asyncErrors.isEmpty()) { String msg = String.format("%s within %d ms", errorMsg, timeoutMillis); return env.flopAndFail(msg); } else { Throwable thrown = env.asyncErrors.remove(0); if (clazz.isInstance(thrown)) { return (E) thrown; } else { String msg = String.format("%s within %d ms; Got %s but expected %s", errorMsg, timeoutMillis, thrown.getClass().getCanonicalName(), clazz.getCanonicalName()); return env.flopAndFail(msg); } } }

Target:
public <E extends Throwable> E expectError(Class<E> clazz, long timeoutMillis, String errorMsg) throws Exception { Thread.sleep(timeoutMillis); if (env.asyncErrors.isEmpty()) { return env.flopAndFail(String.format("%s within %d ms", errorMsg, timeoutMillis)); } else { Throwable thrown = env.asyncErrors.remove(0); if (clazz.isInstance(thrown)) { return (E) thrown; } else { return env.flopAndFail(String.format("%s within %d ms; Got %s but expected %s", errorMsg, timeoutMillis, thrown.getClass().getCanonicalName(), clazz.getCanonicalName())); } } }
Source:
public void testCompare() { Task taskA = new Task(null, "task", "Build", StatusFactory.success(0, 20, false, Collections.<PromotionStatus>emptyList()), null, null, null, true, ""); List<Task> tasksA = new ArrayList<Task>(); tasksA.add(taskA); Stage stageA = new Stage("Build", tasksA); List<Stage> stagesA = new ArrayList<Stage>(); stagesA.add(stageA); Pipeline pipelineA = new Pipeline("Pipeline A", null, null, "1.0.0.1", null, null, null, stagesA, false); List<Pipeline> pipelinesA = new ArrayList<Pipeline>(); pipelinesA.add(pipelineA); Task taskB = new Task(null, "task", "Build", StatusFactory.success(10, 20, false, Collections.<PromotionStatus>emptyList()), null, null, null, true, ""); List<Task> tasksB = new ArrayList<Task>(); tasksB.add(taskB); Stage stageB = new Stage("Build", tasksB); List<Stage> stagesB = new ArrayList<Stage>(); stagesB.add(stageB); Pipeline pipelineB = new Pipeline("Pipeline B", null, null, "1.0.0.1", null, null, null, stagesB, false); List<Pipeline> pipelinesB = new ArrayList<Pipeline>(); pipelinesB.add(pipelineB); Component componentB = new Component("B", "B", "job/A", false, pipelinesB,3,false); Component componentA = new Component("A", "A", "job/B", false, pipelinesA,3,false); List<Component> list = new ArrayList<Component>(); list.add(componentB); list.add(componentA); Collections.sort(list, new LatestActivityComparator.DescriptorImpl().createInstance()); assertEquals(componentB, list.get(0)); assertEquals(componentA, list.get(1)); }

Target:
public void testCompare() { Task taskA = new Task(null, "task", "Build", StatusFactory.success(0, 20, false, Collections.<PromotionStatus>emptyList()), null, null, null, true, ""); List<Task> tasksA = new ArrayList<Task>(); tasksA.add(taskA); Stage stageA = new Stage("Build", tasksA); List<Stage> stagesA = new ArrayList<Stage>(); stagesA.add(stageA); Pipeline pipelineA = new Pipeline("Pipeline A", null, null, "1.0.0.1", null, null, null, stagesA, false); List<Pipeline> pipelinesA = new ArrayList<Pipeline>(); pipelinesA.add(pipelineA); Task taskB = new Task(null, "task", "Build", StatusFactory.success(10, 20, false, Collections.<PromotionStatus>emptyList()), null, null, null, true, ""); List<Task> tasksB = new ArrayList<Task>(); tasksB.add(taskB); Stage stageB = new Stage("Build", tasksB); List<Stage> stagesB = new ArrayList<Stage>(); stagesB.add(stageB); Pipeline pipelineB = new Pipeline("Pipeline B", null, null, "1.0.0.1", null, null, null, stagesB, false); List<Pipeline> pipelinesB = new ArrayList<Pipeline>(); pipelinesB.add(pipelineB); Component componentB = new Component("B", "B", "job/A", false, pipelinesB, 3, pagingEnabledFalse); Component componentA = new Component("A", "A", "job/B", false, pipelinesA, 3, pagingEnabledFalse); List<Component> list = new ArrayList<Component>(); list.add(componentB); list.add(componentA); Collections.sort(list, new LatestActivityComparator.DescriptorImpl().createInstance()); assertEquals(componentB, list.get(0)); assertEquals(componentA, list.get(1)); }
Source:
public static VirtualMachineScaleSetOSProfile create(final String computerNamePrefix, final String adminUsername, final String adminPassword, final LinuxConfiguration linuxConfiguration, final WindowsConfiguration windowsConfiguration, final List<Secrets> secrets) { return builder() .computerNamePrefix(computerNamePrefix) .adminUsername(adminUsername) .adminPassword(adminPassword) .linuxConfiguration(linuxConfiguration) .windowsConfiguration(windowsConfiguration) .secrets(secrets == null ? ImmutableList.<Secrets>of() : ImmutableList.copyOf(secrets) ) .build(); }

Target:
public static VirtualMachineScaleSetOSProfile create(final String computerNamePrefix, final String adminUsername, final String adminPassword, final LinuxConfiguration linuxConfiguration, final WindowsConfiguration windowsConfiguration, final List<Secrets> secrets) { return builder() .computerNamePrefix(computerNamePrefix) .adminUsername(adminUsername) .adminPassword(adminPassword) .linuxConfiguration(linuxConfiguration) .windowsConfiguration(windowsConfiguration) ._secrets(secrets) .build(); }
Source:
private OncotreeMappingsResp extractOncotreeMappings(MSKConcept mskConcept) { OncotreeMappingsResp rsp = new OncotreeMappingsResp(); if (mskConcept == null) { return rsp; } if (mskConcept.getCrosswalks() != null && mskConcept.getCrosswalks().size() > 0) { if (mskConcept.getCrosswalks().containsKey("ONCOTREE")) { logger.info("Oncotree mskConcept found for concept id " + mskConcept.getConceptIds().get(0)); rsp.setOncotreeCode( mskConcept.getCrosswalks().get("ONCOTREE")); } } else if (mskConcept.getOncotreeCodes() != null && mskConcept.getOncotreeCodes().size() > 0) { logger.info("Oncotree mskConcept found for concept id " + mskConcept.getOncotreeCodes().toString()); rsp.setOncotreeCode(mskConcept.getOncotreeCodes()); } if (rsp.getOncotreeCode() == null || rsp.getOncotreeCode().isEmpty()) { throw new OncotreeMappingsNotFound("There is no oncotree code mapped to the query"); } return rsp; }

Target:
private Iterable<String> extractOncotreeMappings(MSKConcept mskConcept) { List<String> oncotreeCodes = null; if (mskConcept != null) { if (mskConcept.getCrosswalks() != null && mskConcept.getCrosswalks().size() > 0) { if (mskConcept.getCrosswalks().containsKey("ONCOTREE")) { logger.info("Oncotree mskConcept found for concept id " + mskConcept.getConceptIds().get(0)); oncotreeCodes = mskConcept.getCrosswalks().get("ONCOTREE"); } } else if (mskConcept.getOncotreeCodes() != null && mskConcept.getOncotreeCodes().size() > 0) { logger.info("Oncotree mskConcept found for concept id " + mskConcept.getOncotreeCodes().toString()); oncotreeCodes = mskConcept.getOncotreeCodes(); } } if (oncotreeCodes == null || oncotreeCodes.isEmpty()) { throw new OncotreeMappingsNotFound("There is no oncotree code mapped to the query"); } return oncotreeCodes; }
Source:
private static SegueJobService getSegueJobService(final PostgresSqlDb database) { if (null == segueJobService) { SegueScheduledJob PIISQLJob = new SegueScheduledDatabaseScriptJob( "PIIDeleteScheduledJob", "SQLMaintenance", "SQL scheduled job that deletes PII", "0 0 2 * * ?", "db_scripts/scheduled/pii-delete-task.sql"); SegueScheduledJob cleanUpOldAnonymousUsers = new SegueScheduledDatabaseScriptJob( "cleanAnonymousUsers", "SQLMaintenance", "SQL scheduled job that deletes old AnonymousUsers", "0 30 2 * * ?", "db_scripts/scheduled/anonymous-user-clean-up.sql"); SegueScheduledJob cleanUpExpiredReservations = new SegueScheduledDatabaseScriptJob( "cleanUpExpiredReservations", "SQLMaintenence", "SQL scheduled job that deletes expired reservations for the event booking system", "0 0 2 * * ?", "db_scripts/scheduled/expired-reservations-clean-up.sql"); segueJobService = new SegueJobService(Arrays.asList(PIISQLJob, cleanUpOldAnonymousUsers, cleanUpExpiredReservations)); log.info("Created Segue Job Manager for scheduled jobs"); } return segueJobService; }

Target:
private static SegueJobService getSegueJobService(final PostgresSqlDb database) { if (null == segueJobService) { SegueScheduledJob PIISQLJob = new SegueScheduledDatabaseScriptJob( "PIIDeleteScheduledJob", "SQLMaintenance", "SQL scheduled job that deletes PII", "0 0 2 * * ?", "db_scripts/scheduled/pii-delete-task.sql"); SegueScheduledJob cleanUpOldAnonymousUsers = new SegueScheduledDatabaseScriptJob( "cleanAnonymousUsers", "SQLMaintenance", "SQL scheduled job that deletes old AnonymousUsers", "0 30 2 * * ?", "db_scripts/scheduled/anonymous-user-clean-up.sql"); SegueScheduledJob cleanUpExpiredReservations = new SegueScheduledDatabaseScriptJob( "cleanUpExpiredReservations", "SQLMaintenence", "SQL scheduled job that deletes expired reservations for the event booking system", "0 0 7 * * ?", "db_scripts/scheduled/expired-reservations-clean-up.sql"); segueJobService = new SegueJobService(Arrays.asList(PIISQLJob, cleanUpOldAnonymousUsers, cleanUpExpiredReservations)); log.info("Created Segue Job Manager for scheduled jobs"); } return segueJobService; }
Source:
public void testNoReferrer() { mIntent.putExtra("Bananas", "utm_source=should no appear"); mReceiver.onReceive(getContext(), mIntent); SharedPreferences stored = getContext().getSharedPreferences(MPConfig.REFERRER_PREFS_NAME, Context.MODE_PRIVATE); System.out.println("FOUND REFERRER " + stored.getString("referrer", "(didnt find a referrer)")); assertFalse(stored.contains("referrer")); assertFalse(stored.contains("utm_source")); assertFalse(stored.contains("utm_medium")); assertFalse(stored.contains("utm_campaign")); assertFalse(stored.contains("utm_content")); assertFalse(stored.contains("utm_term")); }

Target:
public void testNoReferrer() { mIntent.putExtra("Bananas", "utm_source=should no appear"); mReceiver.onReceive(getContext(), mIntent); SharedPreferences stored = getContext().getSharedPreferences(MPConfig.REFERRER_PREFS_NAME, Context.MODE_PRIVATE); assertFalse(stored.contains("referrer")); assertFalse(stored.contains("utm_source")); assertFalse(stored.contains("utm_medium")); assertFalse(stored.contains("utm_campaign")); assertFalse(stored.contains("utm_content")); assertFalse(stored.contains("utm_term")); }
Source:
public void testSpuriousWakeup() throws Exception { Pipelining<String> pipelining = new Pipelining<String>(1); pipelining.add(mock(ICompletableFuture.class)); TestThread t = new TestThread() { @Override public void doRun() throws Throwable { pipelining.add(mock(ICompletableFuture.class)); } }; t.start(); for (int k = 0; k < 100; k++) { Thread.sleep(5); LockSupport.unpark(t); } t.interrupt(); t.assertFailsEventually(InterruptedException.class); }

Target:
public void testSpuriousWakeup() throws Exception { final Pipelining<String> pipelining = new Pipelining<String>(1); pipelining.add(mock(ICompletableFuture.class)); TestThread t = new TestThread() { @Override public void doRun() throws Throwable { pipelining.add(mock(ICompletableFuture.class)); } }; t.start(); for (int k = 0; k < 100; k++) { Thread.sleep(5); LockSupport.unpark(t); } t.interrupt(); t.assertFailsEventually(InterruptedException.class); }
Source:
public Release tagged(final String name) throws IOException { final Iterator<Release> itRelease = this.iterate().iterator(); while (itRelease.hasNext()) { final Release release = itRelease.next(); if (name.equals(new Release.Smart(release).tag())) { return release; } } return null; }

Target:
public Release tagged(final String name) throws IOException { Release tagged = null; for (final Release release: this.iterate()) { if (name.equals(this.smart(release).tag())) { tagged = release; break; } } return tagged; }
Source:
public GString plus(GString that) { Object[] v1 = this instanceof GStringImpl ? ((GStringImpl)this).getValueList().toArray(new Object[0]) : getValues(); Object[] v2 = that instanceof GStringImpl ? ((GStringImpl)that).getValueList().toArray(new Object[0]) : that.getValues(); String[] s1 = this instanceof GStringImpl ? ((GStringImpl)this).getStringList().toArray(new String[0]) : getStrings(); String[] s2 = that instanceof GStringImpl ? ((GStringImpl)that).getStringList().toArray(new String[0]) : that.getStrings(); return new GStringImpl(appendValues(v1, v2), appendStrings(s1, s2, v1.length)); }

Target:
public GString plus(GString that) { Object[] thisValues = getValuesInternal(this); return new GStringImpl( appendValues(thisValues, getValuesInternal(that)), appendStrings(getStringsInternal(this), getStringsInternal(that), thisValues.length)); }
Source:
private static int getMaxReplicas(CrateClient client) { int maxReplicas = 0; try { SQLResponse response = client.sql("SELECT number_of_replicas FROM information_schema.tables GROUP BY number_of_replicas").actionGet(); for (Object[] objects : response.rows()) { List<String> replicas = Splitter.on("-").splitToList((String) objects[0]); String val = replicas.get(replicas.size()-1); if (replicas.size() == 2 && val.equals("all")) { val = replicas.get(0); } maxReplicas = Math.max(maxReplicas, Integer.parseInt(val)); } } catch (NoNodeAvailableException e) { LOGGER.warn("No Crate node available.", e); } catch (SQLActionException e) { LOGGER.warn("An error occurred while trying to get max replicas", e); } return maxReplicas; }

Target:
private static int getMaxReplicas(CrateClient client) { int maxReplicas = 0; try { SQLResponse response = client.sql(SQL_MAX_REPLICAS).actionGet(); for (Object[] objects : response.rows()) { List<String> replicas = Splitter.on("-").splitToList((String) objects[0]); String val = replicas.get(replicas.size()-1); if (replicas.size() == 2 && val.equals("all")) { val = replicas.get(0); } maxReplicas = Math.max(maxReplicas, Integer.parseInt(val)); } } catch (NoNodeAvailableException e) { LOGGER.warn("No Crate node available.", e); } catch (SQLActionException e) { LOGGER.warn("An error occurred while trying to get max replicas", e); } return maxReplicas; }
Source:
public void moveBackward() { if (formController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) { try { int event = formController.stepToPreviousScreenEvent(); if (event == FormEntryController.EVENT_BEGINNING_OF_FORM) { event = formController.stepToNextScreenEvent(); if (event != EVENT_PROMPT_NEW_REPEAT) { return; } } } catch (JavaRosaException e) { error.setValue(e.getCause().getMessage()); return; } formController.getAuditEventLogger().flush(); } }

Target:
public void moveBackward() { try { int event = formController.stepToPreviousScreenEvent(); if (event == FormEntryController.EVENT_BEGINNING_OF_FORM) { formController.stepToNextScreenEvent(); } } catch (JavaRosaException e) { error.setValue(e.getCause().getMessage()); return; } formController.getAuditEventLogger().flush(); }
Source:
private void collectExpectedIssues(String comment, int line) { if (comment.startsWith(TRIGGER)) { String cleanedComment = StringUtils.remove(comment, TRIGGER); String expectedMessage = StringUtils.substringBetween(cleanedComment, "{{", "}}"); int expectedLine = line; cleanedComment = StringUtils.stripEnd(StringUtils.remove(cleanedComment, "{{" + expectedMessage + "}}"), " \t"); if (StringUtils.startsWith(cleanedComment, "@")) { final int lineAdjustment; final char firstChar = cleanedComment.charAt(1); final int endIndex = cleanedComment.indexOf(' '); if (endIndex == -1) { lineAdjustment = Integer.parseInt(cleanedComment.substring(2)); cleanedComment = ""; } else { lineAdjustment = Integer.parseInt(cleanedComment.substring(2, endIndex)); cleanedComment = cleanedComment.substring(endIndex + 1).trim(); } if (firstChar == '+') { expectedLine += lineAdjustment; } else if (firstChar == '-') { expectedLine -= lineAdjustment; } } cleanedComment = StringUtils.trim(cleanedComment); int times = StringUtils.isEmpty(cleanedComment) ? 1 : Integer.parseInt(cleanedComment); for (int i = 0; i < times; i++) { expected.put(expectedLine, expectedMessage); } } }

Target:
private void collectExpectedIssues(String comment, int line) { if (comment.startsWith(TRIGGER)) { String cleanedComment = StringUtils.remove(comment, TRIGGER); String expectedMessage = StringUtils.substringBetween(cleanedComment, "{{", "}}"); int expectedLine = line; cleanedComment = StringUtils.stripEnd(StringUtils.remove(cleanedComment, "{{" + expectedMessage + "}}"), " \t"); if (StringUtils.startsWith(cleanedComment, "@")) { final int lineAdjustment; final char firstChar = cleanedComment.charAt(1); final int endIndex = cleanedComment.indexOf(' '); if (endIndex == -1) { lineAdjustment = Integer.parseInt(cleanedComment.substring(2)); cleanedComment = ""; } else { lineAdjustment = Integer.parseInt(cleanedComment.substring(2, endIndex)); cleanedComment = cleanedComment.substring(endIndex + 1).trim(); } if (firstChar == '+') { expectedLine += lineAdjustment; } else if (firstChar == '-') { expectedLine -= lineAdjustment; } else { throw Fail.fail("Use only '@+N' or '@-N' to shifts messages."); } } cleanedComment = StringUtils.trim(cleanedComment); int times = StringUtils.isEmpty(cleanedComment) ? 1 : Integer.parseInt(cleanedComment); for (int i = 0; i < times; i++) { expected.put(expectedLine, expectedMessage); } } }
Source:
private static Target lookupTarget(StructDefinition streamPacketContextDef, boolean hasDevice, Long cpuId) { Target ret = new Target(); if (hasDevice) { IDefinition def = streamPacketContextDef.lookupDefinition(CTFStrings.DEVICE); if (def instanceof SimpleDatatypeDefinition) { SimpleDatatypeDefinition simpleDefinition = (SimpleDatatypeDefinition) def; ret.string = simpleDefinition.getStringValue(); ret.number = simpleDefinition.getIntegerValue(); } else if (def instanceof StringDefinition) { StringDefinition stringDefinition = (StringDefinition) def; ret.string = stringDefinition.getValue(); final Matcher matcher = NUMBER_PATTERN.matcher(ret.string); if(matcher.find()){ String number = matcher.group(0); ret.number = Integer.parseInt(number); } } } else if (cpuId != null) { ret.string = ("CPU" + cpuId.toString()); ret.number = cpuId; } return ret; }

Target:
private static Target lookupTarget(StructDefinition streamPacketContextDef, boolean hasDevice, Long cpuId) { Target ret = new Target(); if (hasDevice) { IDefinition def = streamPacketContextDef.lookupDefinition(CTFStrings.DEVICE); if (def instanceof SimpleDatatypeDefinition) { SimpleDatatypeDefinition simpleDefinition = (SimpleDatatypeDefinition) def; ret.string = simpleDefinition.getStringValue(); ret.number = simpleDefinition.getIntegerValue(); } else if (def instanceof StringDefinition) { StringDefinition stringDefinition = (StringDefinition) def; ret.string = stringDefinition.getValue(); final Matcher matcher = NUMBER_PATTERN.matcher(ret.string); if (matcher.matches()) { String number = matcher.group(1); ret.number = Integer.parseInt(number); } } } else if (cpuId != null) { ret.string = ("CPU" + cpuId.toString()); ret.number = cpuId; } return ret; }
Source:
public void should_match_set_routing_key_vararg() { Random random = new Random(); ByteBuffer buff1 = randomBuffer(random); ByteBuffer buff2 = randomBuffer(random); Statement<?> expectedStmt = SimpleStatement.builder("select * from system.peers").build().setRoutingKey(buff1, buff2); MockSimpleStatementBuilder builder = new MockSimpleStatementBuilder(); Statement<?> builderStmt = builder.setRoutingKey(buff1, buff2).build(); assertThat(expectedStmt.getRoutingKey()).isEqualTo(builderStmt.getRoutingKey()); builderStmt = builder.setRoutingKey(buff2, buff1).build(); assertThat(expectedStmt.getRoutingKey()).isNotEqualTo(builderStmt.getRoutingKey()); }

Target:
public void should_match_set_routing_key_vararg() { ByteBuffer buff1 = ByteBuffer.wrap("the quick brown fox".getBytes(Charsets.UTF_8)); ByteBuffer buff2 = ByteBuffer.wrap("jumped over the lazy dog".getBytes(Charsets.UTF_8)); Statement<?> expectedStmt = SimpleStatement.builder("select * from system.peers").build().setRoutingKey(buff1, buff2); MockSimpleStatementBuilder builder = new MockSimpleStatementBuilder(); Statement<?> builderStmt = builder.setRoutingKey(buff1, buff2).build(); assertThat(expectedStmt.getRoutingKey()).isEqualTo(builderStmt.getRoutingKey()); builderStmt = builder.setRoutingKey(buff2, buff1).build(); assertThat(expectedStmt.getRoutingKey()).isNotEqualTo(builderStmt.getRoutingKey()); }
Source:
public Map<String, Object> getSpecificEventStyle(ITimeEvent event) { if (event instanceof ClusterMarkerEvent) { ClusterMarkerEvent clusterEvent = (ClusterMarkerEvent)event; return clusterEvent.getSpecificEventStyle(); } return Collections.emptyMap(); }

Target:
public Map<String, Object> getSpecificEventStyle(ITimeEvent event) { Map<String, Object> styleMap = new HashMap<>(super.getSpecificEventStyle(event)); if (event instanceof ClusterMarkerEvent) { ClusterMarkerEvent clusterEvent = (ClusterMarkerEvent)event; styleMap.put(ITimeEventStyleStrings.symbolStyle(), IYAppearance.SymbolStyle.DIAMOND); styleMap.put(ITimeEventStyleStrings.fillColor(), RGBAUtil.fromRGBA(clusterEvent.getColor()) | 0xFF); styleMap.put(ITimeEventStyleStrings.heightFactor(), 0.25f); } return styleMap; }
Source:
public void startGrid() throws IOException, InterruptedException { final String remoteEnabled = PropertyLoader.getProperty("remote.enabled"); if (remoteEnabled.equals("true")) { final double vmWait = Double.parseDouble(PropertyLoader.getProperty("vm.start.timeout.min", "virtualbox.properties")) * 60000; VirtualBoxUtil.startVirtualMachine(); Thread.sleep((int)vmWait); VirtualBoxUtil.startHub(); Thread.sleep(5000); VirtualBoxUtil.startNode(); Thread.sleep(5000); } }

Target:
public void startGrid() throws IOException, InterruptedException { final String remoteEnabled = PropertyLoader.getProperty("remote.enabled"); if (remoteEnabled.equals("true")) { final double vmWait = Double.parseDouble(PropertyLoader.getProperty("vm.start.timeout.min", "virtualbox.properties")) * 60000; final int gridStartUpTime = Integer.parseInt(PropertyLoader.getProperty("grid.startup.time.sec", "virtualbox.properties")) * 1000; VirtualBoxUtil.startVirtualMachine(); Thread.sleep((int) vmWait); VirtualBoxUtil.startHub(); Thread.sleep(gridStartUpTime); VirtualBoxUtil.startNode(); Thread.sleep(gridStartUpTime); } }
Source:
private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) { String eol = System.getProperty("line.separator", "\n"); StringBuilder expected = new StringBuilder(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } expected.append(eol).append(" "); } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += " " + tokenImage[tok.kind]; retval += " \""; retval += add_escapes(tok.image); retval += " \""; tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected.toString(); return retval; }

Target:
private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) { StringBuilder expected = new StringBuilder(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected.append("..."); } expected.append(EOL).append(" "); } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += " " + tokenImage[tok.kind]; retval += " \""; retval += add_escapes(tok.image); retval += " \""; tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + EOL; if (expectedTokenSequences.length == 0) { } else { if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + EOL + " "; } else { retval += "Was expecting one of:" + EOL + " "; } retval += expected.toString(); } return retval; }
Source:
private void updateThumbnailUrl() { String newThumbnailUrl; if(!itemListAdapter.getItemsList().isEmpty()){ newThumbnailUrl = ((PlaylistStreamEntry)itemListAdapter.getItemsList().get(0)).thumbnailUrl; } else newThumbnailUrl = "<LINK_0>"; changeThumbnailUrl(newThumbnailUrl); }

Target:
private void updateThumbnailUrl() { String newThumbnailUrl; if (!itemListAdapter.getItemsList().isEmpty()) { newThumbnailUrl = ((PlaylistStreamEntry) itemListAdapter.getItemsList().get(0)).thumbnailUrl; } else { newThumbnailUrl = "drawable://" + R.drawable.dummy_thumbnail_playlist; } changeThumbnailUrl(newThumbnailUrl); }