auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Set<Template> collectAvailableTemplates(EObject eObject, EReference eReference) { final Set<Template> templates = new TreeSet<Template>(new Comparator<Template>() { @Override public int compare(Template left, Template right) { if (!left.getPriority().equals(right.getPriority())) { return left.getPriority().compareTo(right.getPriority()); } return -1; } }); if (templateProviders.isEmpty()) { return templates; } for (final TemplateProvider provider : templateProviders) { if (!provider.canProvide(eObject, eReference)) { continue; } for (final Template template : provider.provide(eObject, eReference)) { if (template.getInstance() == null) { reportError("Ignoring template '{0}', as it does not contain a valid EObject instance", null, template.getName()); continue; } templates.add(template); } } return templates; }

Target:
protected Set<Template> collectAvailableTemplates(EObject eObject, EReference eReference) { final Set<Template> templates = new TreeSet<Template>(new Comparator<Template>() { @Override public int compare(Template left, Template right) { if (!left.getPriority().equals(right.getPriority())) { return left.getPriority().compareTo(right.getPriority()); } return -1; } }); if (templateProviders.isEmpty()) { return templates; } for (final TemplateProvider provider : templateProviders) { if (!provider.canProvide(eObject, eReference)) { continue; } for (final Template template : provider.provide(eObject, eReference)) { if (template.getInstance() == null) { reportError("Ignoring template '{0}', as it does not contain a valid EObject instance", null, template.getName()); continue; } templates.add(template); } } return templates; }
Source:
void display(final PluginMap plugins) { while (1 < table.getRowCount()) table.removeRow(table.getRowCount() - 1); List<PluginInfo> list = plugins.values().asList(); for (final PluginInfo p : list) { final int row = table.getRowCount(); table.insertRow(row); applyDataRowStyle(row); populate(row, p); } }

Target:
void display(final PluginMap plugins) { while (1 < table.getRowCount()) { table.removeRow(table.getRowCount() - 1); } for (final PluginInfo p : plugins.values().asList()) { final int row = table.getRowCount(); table.insertRow(row); applyDataRowStyle(row); populate(row, p); } }
Source:
private String getHashKeyForDuet(HashingAlgorithm hashingAlgorithm, Boolean shouldEncodeHashKey, Integer maxDigestBytes, Integer maxHashLength, String encoder) { if (null == hashingAlgorithm) { return null; } final String key = hashingAlgorithm.toString()+ maxDigestBytes != null ? maxDigestBytes.toString() : "-" + maxHashLength != null ? maxHashLength.toString() : "-" + encoder != null ? encoder : "-"; String val = hashedKeysByAlgorithmForDuet.get(key); if(val == null) { val = KeyHasher.getHashedKeyEncoded(getCanonicalKeyForDuet(), hashingAlgorithm, maxDigestBytes, maxHashLength, encoder); hashedKeysByAlgorithmForDuet.put(key , val); } return null; }

Target:
private String getHashKeyForDuet(HashingAlgorithm hashingAlgorithm, Boolean shouldEncodeHashKey, Integer maxDigestBytes, Integer maxHashLength, String encoder) { if (null == hashingAlgorithm) { return null; } final String key = hashingAlgorithm.toString()+ maxDigestBytes != null ? maxDigestBytes.toString() : "-" + maxHashLength != null ? maxHashLength.toString() : "-" + encoder != null ? encoder : "-"; String val = hashedKeysByAlgorithmForDuet.get(key); if(val == null) { val = KeyHasher.getHashedKeyEncoded(getCanonicalKeyForDuet(), hashingAlgorithm, maxDigestBytes, maxHashLength, encoder); hashedKeysByAlgorithmForDuet.put(key , val); } return val; }
Source:
public static <T> Call<List<T>> emptyList() { return (Call<List<T>>) CALL_EMPTY_LIST.clone(); }

Target:
public static <T> Call<List<T>> emptyList() { return Call.create(Collections.emptyList()); }
Source:
public CompletableFuture<Long> tryReadLastAddConfirmed() { CompletableFuture<Long> counter = new CompletableFuture<>(); ReadLastConfirmedCallback callback = (int rc, long lastConfirmed, Object ctx) -> { SyncCallbackUtils.finish(rc, lastConfirmed, counter); }; asyncTryReadLastConfirmed(callback, counter); return counter; }

Target:
public CompletableFuture<Long> tryReadLastAddConfirmed() { FutureReadLastConfirmed result = new FutureReadLastConfirmed(); asyncTryReadLastConfirmed(result, null); return result; }
Source:
private void enforceTaskTTLs() { Instant startDeadline = ssm.getStoreTime().minus(taskTTL); long lastId = 0; List<TaskAttemptSummary> expiredTasks = ssm.findTasksStartedBeforeWithStateAndType(TaskType.of(0), TaskStateCode.notDoneStates(), startDeadline, lastId, 100); for (TaskAttemptSummary task : expiredTasks) { AttemptStateFlags stateFlags; try { stateFlags = ssm.getAttemptStateFlags(task.getAttemptId()); } catch (ResourceNotFoundException e) { logger.debug("Session Attempt not found, ignoring: {}", task, e); continue; } if (stateFlags.isCancelRequested()) { logger.debug("Session Attempt already canceled, ignoring: {}", task); continue; } logger.info("Task timed out, canceling Session Attempt: {}", task); ssm.requestCancelAttempt(task.getAttemptId()); } }

Target:
private void enforceTaskTTLs() { Instant startDeadline = ssm.getStoreTime().minus(taskTTL); List<TaskAttemptSummary> expiredTasks = ssm.findTasksStartedBeforeWithState(TaskStateCode.notDoneStates(), startDeadline, (long) 0, 100); Map<Long, List<TaskAttemptSummary>> attempts = expiredTasks.stream() .collect(groupingBy(TaskAttemptSummary::getAttemptId)); for (Map.Entry<Long, List<TaskAttemptSummary>> entry : attempts.entrySet()) { logger.info("Task(s) timed out, canceling Session Attempt: {}, tasks={}", entry.getKey(), entry.getValue()); boolean canceled = ssm.requestCancelAttempt(entry.getKey()); String taskIds = entry.getValue().stream().mapToLong(TaskAttemptSummary::getId).mapToObj(Long::toString).collect(joining(",")); if (canceled) { sendTimeoutNotification("Task execution timeout: " + taskIds, entry.getKey()); } } }
Source:
public void doSubmit() { if (!checkCanSubmit(IMessageProvider.ERROR)) { return; } super.doSubmit(); }

Target:
public void doSubmit() { if (!checkCanSubmit(IMessageProvider.ERROR)) return; super.doSubmit(); }
Source:
public void testGetForVdsFilteredWithPermissions() { storage_pool result = dao.get(vds, PRIVILEGED_USER_ID, true); assertGetResult(result); }

Target:
public void testGetForVdsFilteredWithPermissions() { storage_pool result = dao.getForVds(vds, PRIVILEGED_USER_ID, true); assertGetResult(result); }
Source:
public void testUpperCamelCase() throws IOException { String[] command = { inputFile.getPath() }; addExpectMsg(Messages.CLASS_NAME, 3, 7, "error"); addExpectMsg(Messages.CLASS_NAME, 7, 7, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 24, 8, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 25, 8, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 26, 8, "error"); addExpectMsg(Messages.ENUM_NAME, 42, 6, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 43, 8, "error"); addExpectMsg(Messages.ENUM_NAME, 46, 6, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 47, 8, "error"); addExpectMsg(Messages.ENUM_NAME, 50, 6, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 55, 8, "error"); addExpectMsg(Messages.ENUM_CASE_NAME, 63, 8, "error"); addExpectMsg(Messages.STRUCT_NAME, 72, 8, "error"); addExpectMsg(Messages.STRUCT_NAME, 76, 8, "error"); addExpectMsg(Messages.PROTOCOL_NAME, 90, 10, "error"); addExpectMsg(Messages.PROTOCOL_NAME, 94, 10, "error"); addExpectMsg(Messages.PROTOCOL_NAME, 98, 10, "error"); Tailor.main(command); for(String msg : outContent.toString().split(NEWLINE_REGEX)) { String truncatedMsg = msg.substring(msg.indexOf(inputFile.getName())); assertTrue(expectedMessages.contains(truncatedMsg)); } }

Target:
public void testUpperCamelCase() throws IOException { String[] command = { inputFile.getPath() }; addExpectedMsg(Messages.CLASS_NAME, 3, 7, "error"); addExpectedMsg(Messages.CLASS_NAME, 7, 7, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 24, 8, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 25, 8, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 26, 8, "error"); addExpectedMsg(Messages.ENUM_NAME, 42, 6, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 43, 8, "error"); addExpectedMsg(Messages.ENUM_NAME, 46, 6, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 47, 8, "error"); addExpectedMsg(Messages.ENUM_NAME, 50, 6, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 55, 8, "error"); addExpectedMsg(Messages.ENUM_CASE_NAME, 63, 8, "error"); addExpectedMsg(Messages.STRUCT_NAME, 72, 8, "error"); addExpectedMsg(Messages.STRUCT_NAME, 76, 8, "error"); addExpectedMsg(Messages.PROTOCOL_NAME, 90, 10, "error"); addExpectedMsg(Messages.PROTOCOL_NAME, 94, 10, "error"); addExpectedMsg(Messages.PROTOCOL_NAME, 98, 10, "error"); Tailor.main(command); Set<String> actualOutput = new HashSet<>(); for (String msg : outContent.toString().split(NEWLINE_REGEX)) { String truncatedMsg = msg.substring(msg.indexOf(inputFile.getName())); actualOutput.add(truncatedMsg); } assertTrue(actualOutput.size() == expectedMessages.size()); assertTrue(actualOutput.containsAll(expectedMessages)); }
Source:
public void run() { FileInputStream inputStream; try { inputStream = new FileInputStream("/proc/net/dev"); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); try { String line = br.readLine(); while (line != null) { line = line.trim(); if (line.startsWith(iface)) { String[] vals = line.split(":")[1].trim().split("\\s+"); if (initialValue == null) { initialValue = new BigDecimal(vals[valueIndex]); timeline.addValue(getCategory(), new Timeline.Value(0)); } else { timeline.addValue(getCategory(), new Timeline.Value(new BigDecimal(vals[valueIndex]).subtract(initialValue))); } break; } line = br.readLine(); } br.close(); } catch (Exception e) { log.error("Exception occurred while reading /proc/net/dev.", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.error("Exception occurred while closing /proc/net/dev.", e); } } } } catch (FileNotFoundException e) { log.error("File /proc/net/dev was not found!", e); } }

Target:
public void run() { FileInputStream inputStream; try { inputStream = new FileInputStream("/proc/net/dev"); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); try { String line = br.readLine(); while (line != null) { line = line.trim(); if (line.startsWith(iface)) { String[] vals = line.split(":")[1].trim().split("\\s+"); if (initialValue == null) { initialValue = new BigDecimal(vals[valueIndex]); timeline.addValue(getCategory(), new Timeline.Value(0)); } else { timeline.addValue(getCategory(), new Timeline.Value(new BigDecimal(vals[valueIndex]).subtract(initialValue))); } break; } line = br.readLine(); } } catch (Exception e) { log.error("Exception occurred while reading /proc/net/dev.", e); } finally { try { if (br != null) br.close(); if (inputStream != null) inputStream.close(); } catch (IOException e) { log.error("Exception occurred while closing /proc/net/dev.", e); } } } catch (FileNotFoundException e) { log.error("File /proc/net/dev was not found!", e); } }
Source:
public void testWriteByteArrays() throws Throwable { describe("Write byte arrays to a file and verify" + " the stream statistics are updated"); Path path = methodPath(); FileSystem fs = getFileSystem(); fs.mkdirs(path.getParent()); try (FSDataOutputStream out = fs.create(path, true)) { final byte[] bytes = ContractTestUtils.toAsciiByteArray( "statistically-speaking"); final int len = bytes.length; out.write(bytes); IOStatistics statistics = extractStatistics(out); verifyStatisticValue(statistics, STREAM_WRITE_BYTES, len); out.write(bytes); verifyStatisticValue(statistics, STREAM_WRITE_BYTES, len * 2); out.close(); statistics = extractStatistics(out); verifyStatisticValue(statistics, STREAM_WRITE_BYTES, len * 2); } finally { fs.delete(path, false); } }

Target:
public void testWriteByteArrays() throws Throwable { describe("Write byte arrays to a file and verify" + " the stream statistics are updated"); Path path = methodPath(); FileSystem fs = getFileSystem(); fs.mkdirs(path.getParent()); boolean writesInBlocks = streamWritesInBlocks(); try (FSDataOutputStream out = fs.create(path, true)) { Object demandStatsString = demandStringify(out); final byte[] bytes = ContractTestUtils.toAsciiByteArray( "statistically-speaking"); final long len = bytes.length; out.write(bytes); out.flush(); IOStatistics statistics = extractStatistics(out); verifyStatisticCounterValue(statistics, STREAM_WRITE_BYTES, writesInBlocks ? 0 : len); out.write(bytes); out.flush(); verifyStatisticCounterValue(statistics, STREAM_WRITE_BYTES, writesInBlocks ? 0 : len * 2); out.close(); statistics = extractStatistics(out); verifyStatisticCounterValue(statistics, STREAM_WRITE_BYTES, len * 2); Assertions.assertThat(demandStatsString.toString()) .contains(Long.toString(len * 2)); } finally { fs.delete(path, false); } }
Source:
private void apply(PacketContext context, UUID ownerId, boolean isPortFilter, RuleResult res, int depth, List<UUID> traversedChains) { context.jlog().debug("Processing chain with name and ID {}", name, id); if (depth > 10) { throw new IllegalStateException("Deep recursion when processing " + "chain " + traversedChains.get(0)); } context.addFlowTag(flowInvTag); traversedChains.add(id); Iterator<Rule> iter = rules.iterator(); res.action = Action.CONTINUE; while (iter.hasNext() && res.action == Action.CONTINUE) { Rule r = iter.next(); r.process(context, res, ownerId, isPortFilter); if (res.action == Action.TRACE) { throw TraceRequiredException.instance(); } if (res.action == Action.JUMP) { Chain jumpChain = getJumpTarget(res.jumpToChain); if (null == jumpChain) { context.jlog().error("ignoring jump to chain : not found.", res.jumpToChain, context); res.action = Action.CONTINUE; } else if (traversedChains.contains(jumpChain.id)) { context.jlog().warn( "cannot jump from chain to chain -- already visited", this, jumpChain, context); res.action = Action.CONTINUE; } else { jumpChain.apply(context, ownerId, isPortFilter, res, depth + 1, traversedChains); if (res.action == Action.RETURN) res.action = Action.CONTINUE; } } } assert res.action != Action.JUMP; }

Target:
private void apply(PacketContext context, UUID ownerId, boolean isPortFilter, RuleResult res, int depth, List<UUID> traversedChains) { context.jlog().debug("Processing chain with name and ID {}", name, id); if (depth > 10) { throw new IllegalStateException("Deep recursion when processing " + "chain " + traversedChains.get(0)); } context.addFlowTag(flowInvTag); traversedChains.add(id); Iterator<Rule> iter = rules.iterator(); res.action = Action.CONTINUE; while (iter.hasNext() && res.action == Action.CONTINUE) { Rule r = iter.next(); r.process(context, res, ownerId, isPortFilter); if (res.action == Action.JUMP) { Chain jumpChain = getJumpTarget(res.jumpToChain); if (null == jumpChain) { context.jlog().error("ignoring jump to chain : not found.", res.jumpToChain, context); res.action = Action.CONTINUE; } else if (traversedChains.contains(jumpChain.id)) { context.jlog().warn( "cannot jump from chain to chain -- already visited", this, jumpChain, context); res.action = Action.CONTINUE; } else { jumpChain.apply(context, ownerId, isPortFilter, res, depth + 1, traversedChains); if (res.action == Action.RETURN) res.action = Action.CONTINUE; } } } assert res.action != Action.JUMP; }
Source:
public void testRestoreUserFromPrefs() { Client client = new Client(getContext(), "api-key"); client.clearUser(); SharedPreferences sharedPref = getContext().getSharedPreferences("com.bugsnag.android", Context.MODE_PRIVATE); sharedPref.edit() .putString("user.id", "123456") .putString("user.email", "mr.test@email.com") .putString("user.name", "Mr Test") .commit(); client = new Client(getContext(), "api-key"); final User user = new User(); client.beforeNotify(new BeforeNotify() { @Override public boolean run(Error error) { user.setId(error.getUser().getId()); user.setEmail(error.getUser().getEmail()); user.setName(error.getUser().getName()); return true; } }); client.notify(new RuntimeException("Testing")); assertEquals("123456", user.getId()); assertEquals("mr.test@email.com", user.getEmail()); assertEquals("Mr Test", user.getName()); client.clearUser(); }

Target:
public void testRestoreUserFromPrefs() { SharedPreferences sharedPref = getContext().getSharedPreferences("com.bugsnag.android", Context.MODE_PRIVATE); sharedPref.edit() .putString("user.id", "123456") .putString("user.email", "mr.test@email.com") .putString("user.name", "Mr Test") .commit(); Configuration config = new Configuration("api-key"); config.setPersistUserBetweenSessions(true); Client client = new Client(getContext(), config); final User user = new User(); client.beforeNotify(new BeforeNotify() { @Override public boolean run(Error error) { user.setId(error.getUser().getId()); user.setEmail(error.getUser().getEmail()); user.setName(error.getUser().getName()); return true; } }); client.notify(new RuntimeException("Testing")); assertEquals("123456", user.getId()); assertEquals("mr.test@email.com", user.getEmail()); assertEquals("Mr Test", user.getName()); }
Source:
private NamespaceDescriptor ensureNamespaceCreated(String schemaName) throws SQLException { SQLException sqlE = null; try (HBaseAdmin admin = getAdmin()) { final String quorum = ZKConfig.getZKQuorumServersString(config); final String znode = this.props.get(HConstants.ZOOKEEPER_ZNODE_PARENT); logger.debug("Found quorum: " + quorum + ":" + znode); boolean nameSpaceExists = true; NamespaceDescriptor namespaceDescriptor = null; try { namespaceDescriptor = admin.getNamespaceDescriptor(schemaName); } catch (org.apache.hadoop.hbase.NamespaceNotFoundException e) { nameSpaceExists = false; } if (!nameSpaceExists) { namespaceDescriptor = NamespaceDescriptor.create(schemaName).build(); admin.createNamespace(namespaceDescriptor); } return namespaceDescriptor; } catch (IOException e) { sqlE = ServerUtil.parseServerException(e); } finally { if (sqlE != null) { throw sqlE; } } return null; }

Target:
private NamespaceDescriptor ensureNamespaceCreated(String schemaName) throws SQLException { SQLException sqlE = null; try (HBaseAdmin admin = getAdmin()) { NamespaceDescriptor namespaceDescriptor = null; try { namespaceDescriptor = NamespaceDescriptor.create(schemaName).build(); admin.createNamespace(namespaceDescriptor); } catch (org.apache.hadoop.hbase.NamespaceExistException e) return namespaceDescriptor; } catch (IOException e) { sqlE = ServerUtil.parseServerException(e); } finally { if (sqlE != null) { throw sqlE; } } return null; }
Source:
public void testGetCollectionPage() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); buyClient.getCollections(1, new Callback<List<Collection>>() { @Override public void success(List<Collection> collections) { assertNotNull(collections); assertFalse(collections.isEmpty()); boolean found = false; for (Collection collection : collections) { if ("frontpage".equals(collection.getHandle())) { found = true; break; } } assertTrue(found); latch.countDown(); } @Override public void failure(BuyClientError error) { fail(); } }); latch.await(); }

Target:
public void testGetCollectionPage() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); buyClient.getCollections(1, new Callback<List<Collection>>() { @Override public void success(List<Collection> collections) { assertNotNull(collections); assertFalse(collections.isEmpty()); boolean found = false; for (Collection collection : collections) { if (data.getCollectionHandle().equals(collection.getHandle())) { found = true; break; } } assertTrue(found); latch.countDown(); } @Override public void failure(BuyClientError error) { fail(); } }); latch.await(); }
Source:
private void writeStringToFile(File file, String str) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(file.toString()))) { bw.write(str); } }

Target:
private void writeStringToFile(File file, String str) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { bw.write(str); } }
Source:
public void afterTest() { new TransactionTemplate(this.transactionManager).execute(status -> { final int deletedGroupToMessageRows = jdbcTemplate.update("delete from INT_GROUP_TO_MESSAGE"); final int deletedMessages = jdbcTemplate.update("delete from INT_MESSAGE"); final int deletedMessageGroups = jdbcTemplate.update("delete from INT_MESSAGE_GROUP"); LOG.info(String.format("Cleaning Database - Deleted Messages: %s, " + "Deleted GroupToMessage Rows: %s, Deleted Message Groups: %s", deletedMessages, deletedGroupToMessageRows, deletedMessageGroups)); return null; }); }

Target:
public void afterTest() { new TransactionTemplate(this.transactionManager).execute(status -> { this.jdbcTemplate.update("delete from INT_GROUP_TO_MESSAGE"); this.jdbcTemplate.update("delete from INT_MESSAGE"); this.jdbcTemplate.update("delete from INT_MESSAGE_GROUP"); return null; }); }
Source:
public ResultSet extract(PreparedStatement statement) { long executeStart = 0; if ( this.sqlStatementLogger.getLogSlowQuery() > 0 ) { executeStart = System.currentTimeMillis(); } try { final ResultSet rs; try { jdbcExecuteStatementStart(); rs = statement.executeQuery(); } finally { jdbcExecuteStatementEnd(); sqlStatementLogger.logSlowQuery( statement.toString(), executeStart ); } postExtract( rs, statement ); return rs; } catch (SQLException e) { throw sqlExceptionHelper.convert( e, "could not extract ResultSet" ); } }

Target:
public ResultSet extract(PreparedStatement statement) { long executeStart = 0; if ( this.sqlStatementLogger.getLogSlowQuery() > 0 ) { executeStart = System.currentTimeMillis(); } try { final ResultSet rs; try { jdbcExecuteStatementStart(); rs = statement.executeQuery(); } finally { jdbcExecuteStatementEnd(); sqlStatementLogger.logSlowQuery( statement, executeStart ); } postExtract( rs, statement ); return rs; } catch (SQLException e) { throw sqlExceptionHelper.convert( e, "could not extract ResultSet" ); } }
Source:
public void configure(final MapperFactory mapperFactory) { mapperFactory .classMap(com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.AmrProfileStatusCode.class, AmrProfileStatusCode.class).field("amrProfileStatusCodeFlag", "amrProfileStatusCodeFlags") .byDefault().register(); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsRequestConverter()); mapperFactory.getConverterFactory().registerConverter(new PushNotificationsAlarmConverter()); mapperFactory.getConverterFactory().registerConverter(new MeterValueConverter()); mapperFactory.getConverterFactory().registerConverter(new XsdDateTimeToLongConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicReadsRequestGasQueryConverter()); mapperFactory.getConverterFactory().registerConverter(new ObisCodeValuesConverter()); mapperFactory.getConverterFactory().registerConverter(new ProfileEntryValueVoConverter()); }

Target:
public void configure(final MapperFactory mapperFactory) { mapperFactory .classMap(com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.AmrProfileStatusCode.class, AmrProfileStatusCode.class).field("amrProfileStatusCodeFlag", "amrProfileStatusCodeFlags") .byDefault().register(); mapperFactory.getConverterFactory().registerConverter(new PeriodicMeterReadsRequestConverter()); mapperFactory.getConverterFactory().registerConverter(new PushNotificationsAlarmConverter()); mapperFactory.getConverterFactory().registerConverter(new MeterValueConverter()); mapperFactory.getConverterFactory().registerConverter(new XsdDateTimeToLongConverter()); mapperFactory.getConverterFactory().registerConverter(new PeriodicReadsRequestGasQueryConverter()); mapperFactory.getConverterFactory().registerConverter(new ObisCodeValuesConverter()); mapperFactory.getConverterFactory().registerConverter(new ProfileEntryValueConverter()); mapperFactory.getConverterFactory().registerConverter(new ProfileGenericDataResponseConverter()); }
Source:
public void shouldAcceptAndApplyValidDiscountCode() throws Exception { withCartDiscountAndDiscountCode(sphereClient, discountCode -> { withTaxedAndFilledCart(sphereClient, cart -> { when(cartInSession.findCartId()).thenReturn(Optional.of(cart.getId())); final Map<String, String> bodyForm = new HashMap<>(); bodyForm.put("code", discountCode.getCode()); final Result result = route(new Http.RequestBuilder() .uri("/en/cart/discount/add") .method(POST) .bodyForm(bodyForm)); assertThat(result.status()).isEqualTo(SEE_OTHER); return cart; }); return discountCode; }); }

Target:
public void shouldAcceptAndApplyValidDiscountCode() throws Exception { withCartDiscountAndDiscountCode(sphereClient, discountCode -> { withTaxedAndFilledCart(sphereClient, cart -> { when(cartInSession.findCartId()).thenReturn(Optional.of(cart.getId())); final Map<String, String> bodyForm = new HashMap<>(); bodyForm.put("code", discountCode.getCode()); final Result result = route(new Http.RequestBuilder() .uri("/en/cart/discount/add") .method(POST) .bodyForm(bodyForm)); assertThat(result.status()).isEqualTo(SEE_OTHER); assertThat(result.redirectLocation()) .isPresent() .hasValue("/en/cart"); return cart; }); return discountCode; }); }
Source:
public void stop() { this.cache.removeListener(this); PrivilegedAction<List<Runnable>> action = () -> this.executor.shutdownNow(); WildFlySecurityManager.doUnchecked(action); try { this.executor.awaitTermination(this.cache.getCacheConfiguration().transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } this.dispatcher.close(); this.scheduler.close(); this.identifierFactory.stop(); }

Target:
public void stop() { this.cache.removeListener(this); PrivilegedAction<List<Runnable>> action = () -> this.executor.shutdownNow(); WildFlySecurityManager.doUnchecked(action); try { this.executor.awaitTermination(this.cache.getCacheConfiguration().transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { this.dispatcher.close(); this.scheduler.close(); this.identifierFactory.stop(); } }
Source:
protected int getStreamingFetchSize() { return 50; }

Target:
protected int getStreamingFetchSize() { return DEFAULT_STREAMING_RESULT_SIZE; }
Source:
protected void validatePlan(String SQL, int numberOfFragments, Object ...types) { List<AbstractPlanNode> fragments = compileToFragments(SQL); assertEquals(String.format("Expected %d fragments, not %d", numberOfFragments, fragments.size()), numberOfFragments, fragments.size()); int idx = 0; int fragment = 1; int nchildren = types.length; System.out.printf("Plan for <%s>\n", SQL); for (AbstractPlanNode plan : fragments) { printPlanNodes(plan, fragment, numberOfFragments); if (fragment > 1) { assertEquals("Expected a fragment to start here", PlanNodeType.INVALID, types[idx]); idx += 1; } fragment += 1; for (;plan != null; idx += 1) { if (types.length <= idx) { fail(String.format("Expected %d plan nodes, but found more.", types.length)); } if (types[idx] instanceof PlanNodeType) { assertEquals(String.format("Expected %s plan node by found %s", types[idx], plan.getPlanNodeType()), types[idx], plan.getPlanNodeType()); } else if (types[idx] instanceof PlanWithInlineNodes) { PlanWithInlineNodes branch = (PlanWithInlineNodes)types[idx]; String error = branch.match(plan); if (error != null) { fail(error); } } else { fail("Expected a PlanNodeType or an array of PlanNodeTypes here."); } plan = (plan.getChildCount() > 0) ? plan.getChild(0) : null; } } assertEquals(nchildren, idx); }

Target:
protected void validatePlan(String SQL, int numberOfFragments, Object ...types) { List<AbstractPlanNode> fragments = compileToFragments(SQL); assertEquals(String.format("Expected %d fragments, not %d", numberOfFragments, fragments.size()), numberOfFragments, fragments.size()); int idx = 0; int fragment = 1; int nchildren = types.length; System.out.printf("Plan for <%s>\n", SQL); for (AbstractPlanNode plan : fragments) { printPlanNodes(plan, fragment, numberOfFragments); if (fragment > 1) { assertEquals("Expected a fragment to start here", PlanNodeType.INVALID, types[idx]); idx += 1; } fragment += 1; for (;plan != null; idx += 1) { if (types.length <= idx) { fail(String.format("Expected %d plan nodes, but found more.", types.length)); } if (types[idx] instanceof PlanNodeType) { assertEquals(String.format("Expected %s plan node but found %s", types[idx], plan.getPlanNodeType()), types[idx], plan.getPlanNodeType()); } else if (types[idx] instanceof PlanWithInlineNodes) { PlanWithInlineNodes branch = (PlanWithInlineNodes)types[idx]; String error = branch.match(plan); if (error != null) { fail(error); } } else { fail("Expected a PlanNodeType or an array of PlanNodeTypes here."); } plan = (plan.getChildCount() > 0) ? plan.getChild(0) : null; } } assertEquals(nchildren, idx); }
Source:
public static Map<String, List<String>> getAvailableNamesSpaces(SSOExtensionsManager extensionsManager) { Map<String, List<String>> namespacesMap = new HashMap<>(); for (ExtensionProxy authz : extensionsManager.getExtensionsByService(Authz.class.getName())) { String authzName = authz.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME); for (String namespace : authz.getContext().<Collection<String>>get(Authz.ContextKeys.AVAILABLE_NAMESPACES, Collections.<String>emptyList())) { if (!namespacesMap.containsKey(authzName)) { namespacesMap.put(authzName, new ArrayList<>()); } namespacesMap.get(authzName).add(namespace); } } for (List<String> entry : namespacesMap.values()) { Collections.sort(entry); } return namespacesMap; }

Target:
public static Map<String, List<String>> getAvailableNamesSpaces(SSOExtensionsManager extensionsManager) { Map<String, List<String>> namespacesMap = new HashMap<>(); extensionsManager.getExtensionsByService(Authz.class.getName()) .forEach(authz -> { String authzName = authz.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME); authz.getContext().<Collection<String>>get(Authz.ContextKeys.AVAILABLE_NAMESPACES, Collections.<String>emptyList()) .forEach(namespace -> { if (!namespacesMap.containsKey(authzName)) { namespacesMap.put(authzName, new ArrayList<>()); } namespacesMap.get(authzName).add(namespace); }); }); namespacesMap.values().forEach(Collections::sort); return namespacesMap; }
Source:
private static Value buildPortInfo( InputPortInfo portInfo, ProgramInspector inspector, Set< String > referredTypesSet ) { Value result = Value.create(); result.setFirstChild( PortInfoType.NAME, portInfo.id() ); if( portInfo.location() != null ) { result.setFirstChild( PortInfoType.LOCATION, portInfo.location().toString() ); } if( portInfo.protocol() != null ) { result.setFirstChild( PortInfoType.PROTOCOL, portInfo.protocol().toString() ); } if( portInfo.getDocumentation() != null ) { result.setFirstChild( PortInfoType.DOCUMENTATION, portInfo.getDocumentation() ); } ValueVector interfaces = result.getChildren( PortInfoType.INTERFACE ); portInfo.getInterfaceList().forEach( i -> interfaces.add( buildInterfaceInfo( i, referredTypesSet ) ) ); getAggregatedInterfaces( portInfo, inspector ) .forEach( i -> interfaces.add( buildInterfaceInfo( i, referredTypesSet ) ) ); return result; }

Target:
private static Value buildPortInfo( InputPortInfo portInfo, ProgramInspector inspector, Set< String > referredTypesSet ) { Value result = Value.create(); result.setFirstChild( PortInfoType.NAME, portInfo.id() ); if( portInfo.location() != null ) { result.setFirstChild( PortInfoType.LOCATION, portInfo.location().toString() ); } if( portInfo.protocol() != null ) { result.setFirstChild( PortInfoType.PROTOCOL, portInfo.protocolId() ); } if( portInfo.getDocumentation() != null ) { result.setFirstChild( PortInfoType.DOCUMENTATION, portInfo.getDocumentation() ); } ValueVector interfaces = result.getChildren( PortInfoType.INTERFACE ); portInfo.getInterfaceList().forEach( i -> interfaces.add( buildInterfaceInfo( i, referredTypesSet ) ) ); getAggregatedInterfaces( portInfo, inspector ) .forEach( i -> interfaces.add( buildInterfaceInfo( i, referredTypesSet ) ) ); return result; }
Source:
public Date parse(String source) throws ParseException { if (source.matches(".+\\.\\d\\d\\d\\d\\d\\d\\d\\d\\dZ$")) { source = source.replaceAll("\\d\\d\\d\\d\\d\\dZ$", "Z"); } return super.parse(source); }

Target:
public Date parse(String source) throws ParseException { if (source.matches(".+\\.\\d{9}Z$")) { source = source.replaceAll("\\d{6}Z$", "Z"); } return super.parse(source); }
Source:
private Optional<String> getDockerHubToolAsString(Tool tool) { final String repo = tool.getNamespace() + '/' + tool.getName(); final String repoUrl = DOCKERHUB_URL + "repositories/" + repo + "/tags"; String command = "curl " + repoUrl; Optional<String> response; try { Process process = Runtime.getRuntime().exec(command.split(" ")); InputStream inputStream = process.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line); } response = Optional.of(sb.toString()); inputStreamReader.close(); bufferedReader.close(); if (response.isPresent()) { return response; } } catch (IOException ex) { LOG.info("Unable to get DockerHub response for " + repo); } return Optional.empty(); }

Target:
private Optional<String> getDockerHubToolAsString(Tool tool) { final String repo = tool.getNamespace() + '/' + tool.getName(); final String repoUrl = DOCKERHUB_URL + "repositories/" + repo + "/tags"; Optional<String> response; try { URL url = new URL(repoUrl); response = Optional.of(IOUtils.toString(url, "UTF-8")); if (response.isPresent()) { return response; } } catch (IOException ex) { LOG.info("Unable to get DockerHub response for " + repo); } return Optional.empty(); }
Source:
protected Void doInBackground(Void... params) { try { UserSubscriptions.syncMultiReddits(MainActivity.this); } catch (final Exception e) { runOnUiThread(new Runnable() { @Override public void run() { new AlertDialogWrapper.Builder(MainActivity.this) .setTitle(R.string.err_title) .setMessage(e instanceof ApiException ? getString(R.string.misc_err) + ": " + ((ApiException) e).getExplanation() + "\n" + getString(R.string.misc_retry) : getString(R.string.misc_err)) .setNeutralButton(R.string.btn_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }).create().show(); } }); e.printStackTrace(); } return null; }

Target:
protected Void doInBackground(Void... params) { UserSubscriptions.syncMultiReddits(MainActivity.this); return null; }
Source:
public String[] getAllSchemaNames( long milliSeconds ) { class TempThread extends Thread { private List<String> names = new ArrayList<String>( ); @Override public void run( ) { ResultSet rs = JdbcMetaDataProvider.this.getAllSchemas( ); String odaDriver = JdbcMetaDataProvider.this.driverClass.toLowerCase(); boolean isCassandra = ( odaDriver !=null && odaDriver.indexOf("cassandra") != -1 ); String otscpfKeyspace = null; if (isCassandra) { String odaUrl = JdbcMetaDataProvider.this.url; StringTokenizer st = new StringTokenizer(odaUrl, ";"); while (st.hasMoreTokens()) { String key = st.nextToken().toUpperCase(); if (key.indexOf(OT_SCHEMA_PREFIX) == 0) { int equalIndex = key.indexOf("="); if (equalIndex != -1) { otscpfKeyspace = key.substring(equalIndex + 1); } break; } } } if ( rs != null ) { try { while ( rs.next( ) ) { String schemaName = rs.getString( "TABLE_SCHEM" ); if ( isCassandra && otscpfKeyspace != null ) { if ( !schemaName.equalsIgnoreCase( otscpfKeyspace ) ) { schemaName = null; } } if ( schemaName != null ) { names.add( schemaName ); } } } catch ( SQLException e ) { logger.log( Level.WARNING, e.getMessage( ), e ); } } } public String[] getResult( ) { return names.toArray( new String[0] ); } } TempThread tt = new TempThread( ); tt.start( ); try { tt.join( milliSeconds ); } catch ( InterruptedException e ) { } return tt.getResult( ); }

Target:
public String[] getAllSchemaNames( long milliSeconds ) { class TempThread extends Thread { private List<String> names = new ArrayList<String>( ); @Override public void run( ) { ResultSet rs = JdbcMetaDataProvider.this.getAllSchemas( ); if ( rs != null ) { try { while ( rs.next( ) ) { names.add( rs.getString( "TABLE_SCHEM" ) ); } } catch ( SQLException e ) { logger.log( Level.WARNING, e.getMessage( ), e ); } } } public String[] getResult( ) { return names.toArray( new String[0] ); } } TempThread tt = new TempThread( ); tt.start( ); try { tt.join( milliSeconds ); } catch ( InterruptedException e ) { } return tt.getResult( ); }
Source:
public long writeTo(int index, WritableByteChannel channel, long relativeOffset, long maxSize) throws IOException { validateIndex(index); long written = 0; BlobReadInfo blobReadInfo = blobReadInfoList.get(index); String blobIdStr = blobReadInfo.getBlobId().getID(); try { if (!blobReadInfo.isPrefetched()) { blobReadInfo.prefetchBlob(blobStore); } ByteBuffer outputBuffer = blobReadInfo.getPrefetchedBuffer(); long sizeToRead = Math.min(maxSize, blobReadInfo.getBlobSize() - relativeOffset); outputBuffer.limit((int) (relativeOffset + sizeToRead)); outputBuffer.position((int) (relativeOffset)); written = channel.write(outputBuffer); } catch (StoreException ex) { throw new IOException("Write of cloud blob " + blobIdStr + " failed"); } logger.trace("Downloaded bytes to the write channel from the cloud blob : {}", written, blobIdStr); return written; }

Target:
public long writeTo(int index, WritableByteChannel channel, long relativeOffset, long maxSize) throws IOException { validateIndex(index); long written = 0; BlobReadInfo blobReadInfo = blobReadInfoList.get(index); String blobIdStr = blobReadInfo.getBlobId().getID(); try { if (!blobReadInfo.isPrefetched()) { blobReadInfo.prefetchBlob(blobStore); } ByteBuffer outputBuffer = blobReadInfo.getPrefetchedBuffer(); long sizeToRead = Math.min(maxSize, blobReadInfo.getBlobSize() - relativeOffset); outputBuffer.limit((int) (relativeOffset + sizeToRead)); outputBuffer.position((int) (relativeOffset)); written = channel.write(outputBuffer); } catch (StoreException ex) { throw new IOException("Write of cloud blob " + blobIdStr + " failed", ex); } logger.trace("Downloaded bytes to the write channel from the cloud blob : {}", written, blobIdStr); return written; }
Source:
public void workerCount_can_be_controlled_via_plugin() throws IOException { String workerCount = "5"; OrchestratorBuilder builder = Orchestrator.builderEnv() .setZipFile(FileLocation.byWildcardMavenFilename(new File("../sonar-application/target"), "sonar*.zip").getFile()) .addPlugin(pluginArtifact("fake-governance-plugin")) .setServerProperty("fakeGovernance.workerCount", workerCount); orchestrator = builder.build(); orchestrator.start(); Set<String> line = Files.lines(orchestrator.getServer().getCeLogs().toPath()) .filter(s -> s.contains("Compute Engine will use ")) .collect(Collectors.toSet()); assertThat(line) .hasSize(1); assertThat(line.iterator().next()).contains(workerCount); }

Target:
public void workerCount_can_be_controlled_via_plugin() throws IOException { String workerCount = "5"; OrchestratorBuilder builder = Orchestrator.builderEnv() .addPlugin(pluginArtifact("fake-governance-plugin")) .setServerProperty("fakeGovernance.workerCount", workerCount); orchestrator = builder.build(); orchestrator.start(); Set<String> line = Files.lines(orchestrator.getServer().getCeLogs().toPath()) .filter(s -> s.contains("Compute Engine will use ")) .collect(Collectors.toSet()); assertThat(line) .hasSize(1); assertThat(line.iterator().next()).contains(workerCount); }
Source:
public static ICPPFunction[] instantiateForFunctionCall(ICPPFunction[] fns, ICPPTemplateArgument[] tmplArgs, List<IType> fnArgs, List<ValueCategory> argCats, boolean withImpliedObjectArg) { boolean requireTemplate = tmplArgs != null; boolean haveTemplate = false; for (final ICPPFunction func : fns) { if (func instanceof ICPPConstructor || (func instanceof ICPPMethod && ((ICPPMethod) func).isDestructor())) requireTemplate = false; if (func instanceof ICPPFunctionTemplate) { if (containsDependentType(fnArgs)) return new ICPPFunction[] { CPPDeferredFunction.createForCandidates(fns) }; if (requireTemplate && hasDependentArgument(tmplArgs)) return new ICPPFunction[] { CPPDeferredFunction.createForCandidates(fns) }; haveTemplate = true; break; } } if (!haveTemplate && !requireTemplate) return fns; final List<ICPPFunction> result = new ArrayList<>(fns.length); for (ICPPFunction fn : fns) { if (fn != null) { if (fn instanceof ICPPFunctionTemplate) { ICPPFunctionTemplate fnTmpl = (ICPPFunctionTemplate) fn; ICPPFunction inst = instantiateForFunctionCall(fnTmpl, tmplArgs, fnArgs, argCats, withImpliedObjectArg); if (inst != null) result.add(inst); } else if (!requireTemplate || fn instanceof ICPPUnknownBinding) { result.add(fn); } } } return result.toArray(new ICPPFunction[result.size()]); }

Target:
static ICPPFunction[] instantiateForFunctionCall(ICPPFunction[] fns, ICPPTemplateArgument[] tmplArgs, List<IType> fnArgs, List<ValueCategory> argCats, boolean withImpliedObjectArg) { boolean requireTemplate = tmplArgs != null; boolean haveTemplate = false; for (final ICPPFunction func : fns) { if (func instanceof ICPPConstructor || (func instanceof ICPPMethod && ((ICPPMethod) func).isDestructor())) requireTemplate = false; if (func instanceof ICPPFunctionTemplate) { if (containsDependentType(fnArgs)) return new ICPPFunction[] { CPPDeferredFunction.createForCandidates(fns) }; if (requireTemplate && hasDependentArgument(tmplArgs)) return new ICPPFunction[] { CPPDeferredFunction.createForCandidates(fns) }; haveTemplate = true; break; } } if (!haveTemplate && !requireTemplate) return fns; final List<ICPPFunction> result = new ArrayList<>(fns.length); for (ICPPFunction fn : fns) { if (fn != null) { if (fn instanceof ICPPFunctionTemplate) { ICPPFunctionTemplate fnTmpl = (ICPPFunctionTemplate) fn; ICPPFunction inst = instantiateForFunctionCall(fnTmpl, tmplArgs, fnArgs, argCats, withImpliedObjectArg); if (inst != null) result.add(inst); } else if (!requireTemplate || fn instanceof ICPPUnknownBinding) { result.add(fn); } } } return result.toArray(new ICPPFunction[result.size()]); }
Source:
public final Entity getSource() { if (source == null || !source.isValid()) { return null; } else { return source; } }

Target:
public final Entity getSource() { return (source != null && source.isValid()) ? source : null; }
Source:
protected void doClose() throws Exception { Queue<AbstractMap.SimpleEntry<Object, ChannelPromise>> queue = tempInboundMessages(); if (isNotEmpty(queue)) { queue.clear(); } state = State.CLOSED; }

Target:
protected void doClose() throws Exception { state = State.CLOSED; if (isNotEmpty(tempInboundMessages)) { ClosedChannelException exception = null; for (;;) { AbstractMap.SimpleEntry<Object, ChannelPromise> entry = tempInboundMessages.poll(); if (entry == null) { break; } Object value = entry.getKey(); if (value != null) { ReferenceCountUtil.release(value); } ChannelPromise promise = entry.getValue(); if (promise != null) { if (exception == null) { exception = new ClosedChannelException(); } promise.tryFailure(exception); } } } }
Source:
private CompletableFuture<?> index(PojoSessionWorkExecutor workExecutor, Object entity) throws InterruptedException { if ( Thread.currentThread().isInterrupted() ) { throw new InterruptedException(); } CompletableFuture<?> task = null; try { task = workExecutor.add( entity ); } catch (Throwable e) { handleException( entity, e ); } return task; }

Target:
private CompletableFuture<?> index(PojoSessionWorkExecutor workExecutor, Object entity) throws InterruptedException { if ( Thread.currentThread().isInterrupted() ) { throw new InterruptedException(); } CompletableFuture<?> future = Futures.create( () -> workExecutor.add( entity ) .exceptionally( exception -> { handleException( entity, exception ); return null; } ) ); monitor.documentsBuilt( 1 ); return future; }
Source:
private Menu createUpdateMenu() { Menu update = new Menu("Update"); MenuItem checkProgress = new MenuItem("Check progress..."); if (ui.updateManager == null) { checkProgress.setDisable(true); } else { checkProgress.setOnAction(e -> { Platform.runLater(() -> ui.updateProgressWindow.showWindow()); }); } update.getItems().addAll(checkProgress); return update; }

Target:
private Menu createUpdateMenu() { Menu update = new Menu("Update"); MenuItem checkProgress = new MenuItem("Check progress..."); checkProgress.setOnAction(e -> { ui.showUpdateProgressWindow(); }); update.getItems().addAll(checkProgress); return update; }
Source:
public static ITimeEvent findEvent(ITimeGraphEntry entry, long time, int n) { if (null == entry || ! entry.hasTimeEvents()) { return null; } Iterator<ITimeEvent> iterator = entry.getTimeEventsIterator(); if (iterator == null) { return null; } ITimeEvent nextEvent = null; ITimeEvent currEvent = null; ITimeEvent prevEvent = null; while (iterator.hasNext()) { nextEvent = iterator.next(); long nextStartTime = nextEvent.getTime(); if (nextStartTime > time) { break; } if (currEvent == null || currEvent.getTime() != nextStartTime || (nextStartTime != time && currEvent.getDuration() != nextEvent.getDuration())) { prevEvent = currEvent; currEvent = nextEvent; } } if (n == -1) { if (currEvent != null && currEvent.getTime() + currEvent.getDuration() >= time) { return prevEvent; } return currEvent; } else if (n == 0) { if (currEvent != null && currEvent.getTime() + currEvent.getDuration() >= time) { return currEvent; } return null; } else if (n == 1) { if (nextEvent != null && nextEvent.getTime() > time) { return nextEvent; } return null; } else if (n == 2) { return currEvent; } return null; }

Target:
static ITimeEvent findEvent(ITimeGraphEntry entry, long time, int n) { if (null == entry || ! entry.hasTimeEvents()) { return null; } Iterator<ITimeEvent> iterator = entry.getTimeEventsIterator(); if (iterator == null) { return null; } ITimeEvent nextEvent = null; ITimeEvent currEvent = null; ITimeEvent prevEvent = null; while (iterator.hasNext()) { nextEvent = iterator.next(); long nextStartTime = nextEvent.getTime(); if (nextStartTime > time) { break; } if (currEvent == null || currEvent.getTime() != nextStartTime || (nextStartTime != time && currEvent.getDuration() != nextEvent.getDuration())) { prevEvent = currEvent; currEvent = nextEvent; } } if (n == -1) { if (currEvent != null && currEvent.getTime() + currEvent.getDuration() >= time) { return prevEvent; } return currEvent; } else if (n == 0) { if (currEvent != null && currEvent.getTime() + currEvent.getDuration() >= time) { return currEvent; } return null; } else if (n == 1) { if (nextEvent != null && nextEvent.getTime() > time) { return nextEvent; } return null; } else if (n == 2) { return currEvent; } return null; }
Source:
public String toString() { StringBuilder b = new StringBuilder(); long elapsed = getElapsedTime(); int day = (int) (elapsed / 86400000); elapsed -= day * 86400000; int hour = (int) (elapsed / 3600000); elapsed -= hour * 3600000; int minute = (int) (elapsed / 60000); elapsed -= minute * 60000; int second = (int) (elapsed / 1000); if (day > 0) { b.append(day < 10 ? "0" : "").append(day).append("d:"); } b.append(hour < 10 ? "0" : "").append(hour).append(":"); b.append(minute < 10 ? "0" : "").append(minute).append(":"); b.append(second < 10 ? "0" : "").append(second); return new String(b); }

Target:
public String toString() { StringBuilder b = new StringBuilder(); long elapsed = getElapsedTime(); int day = (int) (elapsed / 86400000); elapsed -= day * 86400000; int hour = (int) (elapsed / 3600000); elapsed -= hour * 3600000; int minute = (int) (elapsed / 60000); elapsed -= minute * 60000; int second = (int) (elapsed / 1000); if (day > 0) { b.append(day).append("d:"); } b.append(hour < 10 ? "0" : "").append(hour).append(":"); b.append(minute < 10 ? "0" : "").append(minute).append(":"); b.append(second < 10 ? "0" : "").append(second); return new String(b); }