auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public final void write(String path) { final Path savepointPath = new Path(path); List<BootstrapTransformationWithID<?>> newOperatorTransformations = metadata.getNewOperators(); DataSet<OperatorState> newOperatorStates = writeOperatorStates(newOperatorTransformations, savepointPath); List<OperatorState> existingOperatorStateList = metadata.getExistingOperators(); DataSet<OperatorState> finalOperatorStates; if (existingOperatorStateList.isEmpty()) { finalOperatorStates = newOperatorStates; } else { DataSet<OperatorState> existingOperatorStates = newOperatorStates.getExecutionEnvironment() .fromCollection(existingOperatorStateList); existingOperatorStates <START> .map(new OperatorState2PathSetMapFunction()) .flatMap(new FlatMapFunction<Set<Optional<Path>>, Optional<Path>>() { @Override public void flatMap(Set<Optional<Path>> value, Collector<Optional<Path>> out) throws Exception { for (Optional<Path> path : value) { out.collect(path); } } }) .filter(Optional<Path>::isPresent) .map(Optional<Path>::get) .returns(TypeInformation.of(new TypeHint<Path>(){})) <END> .map(new MapFunction<Path, Path>() { @Override public Path map(Path existingStateFile) throws IOException { savepointPath.getFileSystem().mkdirs(savepointPath); Files.copy( Paths.get(existingStateFile.getPath()), Paths.get(path + "/" + existingStateFile.getName()) ); return existingStateFile; } }) .output(new DiscardingOutputFormat<>()); finalOperatorStates = newOperatorStates.union(existingOperatorStates); } finalOperatorStates .reduceGroup(new MergeOperatorStates(metadata.getMasterStates())) .name("reduce(OperatorState)") .output(new SavepointOutputFormat(savepointPath)) .name(path); }</code><technical_language>other change this away. suggestion .flatMap(new StatePathExtractor())</technical_language>

Target:
public final void write(String path) { final Path savepointPath = new Path(path); List<BootstrapTransformationWithID<?>> newOperatorTransformations = metadata.getNewOperators(); DataSet<OperatorState> newOperatorStates = writeOperatorStates(newOperatorTransformations, savepointPath); List<OperatorState> existingOperators = metadata.getExistingOperators(); DataSet<OperatorState> finalOperatorStates; if (existingOperators.isEmpty()) { finalOperatorStates = newOperatorStates; } else { DataSet<OperatorState> existingOperatorStates = newOperatorStates.getExecutionEnvironment() .fromCollection(existingOperators); existingOperatorStates .flatMap(new StatePathExtractor()) .setParallelism(1) .map(new FileCopyMapFunction(path)) .output(new DiscardingOutputFormat<>()); finalOperatorStates = newOperatorStates.union(existingOperatorStates); } finalOperatorStates .reduceGroup(new MergeOperatorStates(metadata.getMasterStates())) .name("reduce(OperatorState)") .output(new SavepointOutputFormat(savepointPath)) .name(path); }
Source:
<code>public void testPlaceOrderTypeText() throws Exception { Axis2BackEndServerController axis2Server = getAxis2Server(); if (axis2Server == null) { fail("Failed to load the Axis2BackEndServerController"); } assertEquals(0, axis2Server.getMessageCount("SimpleStockQuoteService", "placeOrder")); JMSSampleClient client = new JMSSampleClient(); client.connect("dynamicQueues/JMSTextProxy"); client.sendTextMessage("12.33 1000 ACP"); Thread.sleep(2000); assertEquals(1, axis2Server.getMessageCount("SimpleStockQuoteService", "placeOrder")); <START> client.shutdown(); <END> }</code><technical_language>Shutdown client in a finally block? happened if exception occurred</technical_language>

Target:
public void testPlaceOrderTypeText() throws Exception { JMSSampleClient client = new JMSSampleClient(); Axis2BackEndServerController axis2Server = getAxis2Server(); if (axis2Server == null) { fail("Failed to load the Axis2BackEndServerController"); } assertEquals(0, axis2Server.getMessageCount("SimpleStockQuoteService", "placeOrder")); try { client.connect("dynamicQueues/JMSTextProxy"); client.sendTextMessage("12.33 1000 ACP"); boolean expectedMessageCountReceived = SynapseTestUtils.waitForMessageCount(axis2Server, "SimpleStockQuoteService", "placeOrder", 1, 2000); assertTrue("Backend service not received the expected message count", expectedMessageCountReceived); } finally { client.shutdown(); } }
Source:
<code>public Map<String, Template> parseTemplateFile(File file) throws IOException, SAXException, ParserConfigurationException{ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(true); dbf.setNamespaceAware(true); dbf.setFeature("<LINK_0>", false); dbf.setFeature("<LINK_1>", false); DocumentBuilder bd = dbf.newDocumentBuilder(); bd.setEntityResolver(new DefaultEntityResolver()); <START> LoggingErrorHandler errorHandler = new LoggingErrorHandler(log); <END> bd.setErrorHandler(errorHandler); Document document = bd.parse(file.getAbsolutePath()); document.getDocumentElement().normalize(); Map<String, Template> templates = new TreeMap<>(); NodeList templateNodes = document.getElementsByTagName("template"); for (int i = 0; i < templateNodes.getLength(); i++) { Node node = templateNodes.item(i); parseTemplateNode(templates, node); } return templates; }</code><technical_language>hand filename error handler, in error messages</technical_language>

Target:
public Map<String, Template> parseTemplateFile(File file) throws IOException, SAXException, ParserConfigurationException{ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(true); dbf.setNamespaceAware(true); dbf.setFeature("<LINK_0>", false); dbf.setFeature("<LINK_1>", false); DocumentBuilder bd = dbf.newDocumentBuilder(); bd.setEntityResolver(new DefaultEntityResolver()); LoggingErrorHandler errorHandler = new LoggingErrorHandler(log, file); bd.setErrorHandler(errorHandler); Document document = bd.parse(file.getAbsolutePath()); document.getDocumentElement().normalize(); Map<String, Template> templates = new TreeMap<>(); NodeList templateNodes = document.getElementsByTagName("template"); for (int i = 0; i < templateNodes.getLength(); i++) { Node node = templateNodes.item(i); parseTemplateNode(templates, node); } return templates; }
Source:
<code>public synchronized TmfExperiment getExperiment(boolean deleteSuppFiles) { Set<@NonNull ITmfTrace> traces = new HashSet<>(); for (VmTraces trace : fTraces) { ITmfTrace tmfTrace = trace.getTrace(); if (tmfTrace != null) { traces.add(tmfTrace); } } <START> String expName = this.name(); <END> VirtualMachineExperiment experiment = new VirtualMachineExperiment(expName, traces); if (deleteSuppFiles) { File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(experiment)); for (File file : suppDir.listFiles()) { file.delete(); } } return experiment; }</code><technical_language>While here, remove this</technical_language>

Target:
public synchronized TmfExperiment getExperiment(boolean deleteSuppFiles) { Set<@NonNull ITmfTrace> traces = new HashSet<>(); for (VmTraces trace : fTraces) { ITmfTrace tmfTrace = trace.getTrace(); if (tmfTrace != null) { traces.add(tmfTrace); } } String expName = name(); VirtualMachineExperiment experiment = new VirtualMachineExperiment(expName, traces); if (deleteSuppFiles) { File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(experiment)); for (File file : suppDir.listFiles()) { file.delete(); } } return experiment; }
Source:
<code>public @ResponseBody List<UnitDto> sortUnits(@PathVariable("tenderId") Integer tenderId, @RequestParam("direction") String direction, @RequestParam("field") String field) { Sort sort = new Sort(Sort.Direction.fromString(direction), field); <START> Pageable pageRequest = new PageRequest(0, 100, sort); <END> return tenderFacade.findUnitsByTenderId(tenderId, pageRequest); }</code><technical_language>if more 100 units</technical_language>

Target:
public @ResponseBody List<UnitDto> sortUnits(@PathVariable("tenderId") Integer tenderId, @RequestParam("direction") String direction, @RequestParam("field") String field) { Sort sort = new Sort(Sort.Direction.fromString(direction), field); Pageable pageRequest = new PageRequest(0, Integer.MAX_VALUE, sort); return tenderFacade.findUnitsByTenderId(tenderId, pageRequest); }
Source:
<code>public CompletableFuture<FileWrapper> overwriteFileJS(AsyncReader fileData, int endHigh, int endLow, NetworkAccess network, Crypto crypto, ProgressConsumer<Long> monitor) { long size = getSize(); long newSize = LongUtil.intsToLong(endHigh, endLow); return network.synchronizer.applyComplexUpdate(owner(), signingPair(), (s, committer) -> clean(s, committer, network, crypto) .thenCompose(u -> u.left.overwriteSection(u.right, committer, fileData, 0L, newSize, network, crypto, monitor) .thenCompose(v -> newSize >= size ? Futures.of(v) : getUpdated(v, network) <START> .thenCompose(f -> f.truncate(v, committer, newSize, network, crypto))))) <END> .thenCompose(v -> getUpdated(v, network)); }</code><technical_language>close scope soon done reduce indentation hell. here, line 593</technical_language>

Target:
public CompletableFuture<FileWrapper> overwriteFileJS(AsyncReader fileData, int endHigh, int endLow, NetworkAccess network, Crypto crypto, ProgressConsumer<Long> monitor) { long size = getSize(); long newSize = LongUtil.intsToLong(endHigh, endLow); return network.synchronizer.applyComplexUpdate(owner(), signingPair(), (s, committer) -> clean(s, committer, network, crypto) .thenCompose(u -> u.left.overwriteSection(u.right, committer, fileData, 0L, newSize, network, crypto, monitor)) .thenCompose(v -> newSize >= size ? Futures.of(v) : getUpdated(v, network).thenCompose(f -> f.truncate(v, committer, newSize, network, crypto))) ).thenCompose(v -> getUpdated(v, network)); }
Source:
<code>public Map<Integer, Long> pause(final String id, final long timeout) { log.debug("Pause task[%s] timeout[%d]", id, timeout); try { final FullResponseHolder response = submitRequest( id, HttpMethod.POST, "pause", timeout > 0 ? StringUtils.format("timeout=%d", timeout) : null, true ); if (response.getStatus().equals(HttpResponseStatus.OK)) { log.info("Task [%s] paused successfully", id); return jsonMapper.readValue(response.getContent(), new TypeReference<Map<Integer, Long>>() { }); } final RetryPolicy retryPolicy = retryPolicyFactory.makeRetryPolicy(); while (true) { if (getStatus(id) == KafkaIndexTask.Status.PAUSED) { return getCurrentOffsets(id, true); } final Duration delay = retryPolicy.getAndIncrementRetryDelay(); if (delay == null) { log.error("Task [%s] failed to pause, aborting", id); throw new ISE("Task [%s] failed to pause, aborting", id); } else { final long sleepTime = delay.getMillis(); log.info( "Still waiting for task [%s] to pause; will try again in [%s]", id, new Duration(sleepTime).toString() ); Thread.sleep(sleepTime); } } } catch (NoTaskLocationException e) { log.error("Exception [%s] while pausing Task [%s]", e.getMessage(), id); return ImmutableMap.of(); } catch (IOException | InterruptedException e) { log.error("Exception [%s] while pausing Task [%s]", e.getMessage(), id); <START> throw new RuntimeException(e); <END> } }</code><technical_language>is odd log throw. a leads double logging. more sense put log message in RuntimeException</technical_language>

Target:
public Map<Integer, Long> pause(final String id, final long timeout) { log.debug("Pause task[%s] timeout[%d]", id, timeout); try { final FullResponseHolder response = submitRequest( id, HttpMethod.POST, "pause", timeout > 0 ? StringUtils.format("timeout=%d", timeout) : null, true ); if (response.getStatus().equals(HttpResponseStatus.OK)) { log.info("Task [%s] paused successfully", id); return jsonMapper.readValue(response.getContent(), new TypeReference<Map<Integer, Long>>() { }); } final RetryPolicy retryPolicy = retryPolicyFactory.makeRetryPolicy(); while (true) { if (getStatus(id) == KafkaIndexTask.Status.PAUSED) { return getCurrentOffsets(id, true); } final Duration delay = retryPolicy.getAndIncrementRetryDelay(); if (delay == null) { log.error("Task [%s] failed to pause, aborting", id); throw new ISE("Task [%s] failed to pause, aborting", id); } else { final long sleepTime = delay.getMillis(); log.info( "Still waiting for task [%s] to pause; will try again in [%s]", id, new Duration(sleepTime).toString() ); Thread.sleep(sleepTime); } } } catch (NoTaskLocationException e) { log.error("Exception [%s] while pausing Task [%s]", e.getMessage(), id); return ImmutableMap.of(); } catch (IOException | InterruptedException e) { throw new RuntimeException( StringUtils.format("Exception [%s] while pausing Task [%s]", e.getMessage(), id), e ); } }
Source:
<code>public List<String> getFileExtensions(){ <START> ArrayList<String> extensions = new ArrayList(1); <END> extensions.add("blastxml"); return extensions; }</code><technical_language>Missing type</technical_language>

Target:
public List<String> getFileExtensions(){ ArrayList<String> extensions = new ArrayList<String>(1); extensions.add("blastxml"); return extensions; }
Source:
<code>public void testCreateLoadBalancer() { List<String> serverIds = com.google.common.collect.Lists.newArrayList(); serverIds.add("server-ids"); LoadBalancer.Request.CreatePayload payload = LoadBalancer.Request.creatingBuilder() .dataCenterId(dataCenterId) .loadBalancerName("testName") .loadBalancerAlgorithm(LoadbalancerAlgorithm.ROUND_ROBIN) .ip("0.0.0.1") .lanId("1") .serverIds(serverIds) .build(); LoadBalancer loadBalancer = api.loadBalancerApi().createLoadBalancer(payload); <START> System.out.println(loadBalancer); <END> assertNotNull(loadBalancer); }</code><technical_language>Remove this</technical_language>

Target:
public void testCreateLoadBalancer() { List<String> serverIds = com.google.common.collect.Lists.newArrayList(); serverIds.add("server-ids"); LoadBalancer.Request.CreatePayload payload = LoadBalancer.Request.creatingBuilder() .dataCenterId(dataCenterId) .loadBalancerName("testName") .loadBalancerAlgorithm(Algorithm.ROUND_ROBIN) .ip("0.0.0.1") .lanId("1") .serverIds(serverIds) .build(); String requestId = api.loadBalancerApi().createLoadBalancer(payload); assertNotNull(requestId); }
Source:
<code>public void getJobCompletedNotification() throws IOException, SignatureException { UUID notificationUUID = null; try { notificationUUID = client.putJobCompletedNotificationRegistrationSpectraS3( new PutJobCompletedNotificationRegistrationSpectraS3Request("test@test.test")) .getJobCompletedNotificationRegistrationResult().getId(); final GetJobCompletedNotificationRegistrationSpectraS3Response response = client .getJobCompletedNotificationRegistrationSpectraS3( new GetJobCompletedNotificationRegistrationSpectraS3Request(notificationUUID)); assertThat(response.getStatusCode(), is(200)); } finally { <START> client.deleteJobCompletedNotificationRegistrationSpectraS3( <END> new DeleteJobCompletedNotificationRegistrationSpectraS3Request(notificationUUID)); } }</code><technical_language>This check notificationUUID is null attempting delete it</technical_language>

Target:
public void getJobCompletedNotification() throws IOException, SignatureException { UUID notificationUUID = null; try { notificationUUID = client.putJobCompletedNotificationRegistrationSpectraS3( new PutJobCompletedNotificationRegistrationSpectraS3Request("test@test.test")) .getJobCompletedNotificationRegistrationResult().getId(); final GetJobCompletedNotificationRegistrationSpectraS3Response response = client .getJobCompletedNotificationRegistrationSpectraS3( new GetJobCompletedNotificationRegistrationSpectraS3Request(notificationUUID)); assertThat(response.getStatusCode(), is(200)); } finally { if (notificationUUID != null) { client.deleteJobCompletedNotificationRegistrationSpectraS3( new DeleteJobCompletedNotificationRegistrationSpectraS3Request(notificationUUID)); } } }
Source:
<code>public AuthHeader fromString(final String value) { if (value == null) { throw UnauthorizedException.missingCredentials(); <START> } <END> try { return AuthHeader.valueOf(value); } catch (RuntimeException e) { throw UnauthorizedException.malformedCredentials(e); } }</code><technical_language>I this is a break, currently conjure-jersey allows null auth token values. shouldn't, is fixed in conjure-undertow, a projects rely (or point relied) tokens nullable. I generally supportive of reducing friction migrating frameworks, need careful rollout</technical_language>

Target:
public AuthHeader fromString(final String value) { if (value == null) { return null; } try { return AuthHeader.valueOf(value); } catch (RuntimeException e) { throw UnauthorizedException.malformedCredentials(e); } }
Source:
<code>public void unload(Catalog catalog) throws SQLException { conn.setAutoCommit(false); conn.setTransactionIsolation(workConf.getIsolationMode()); Statement st = conn.createStatement(); for (Table catalog_tbl : catalog.getTables()) { LOG.debug(String.format("Deleting data from %s.%s", workConf.getDBName(), catalog_tbl.getName())); <START> String sql = "truncate " + catalog_tbl.getEscapedName(); <END> st.execute(sql); } conn.commit(); }</code><technical_language>Is this comdb2 specific</technical_language>

Target:
public void unload(Catalog catalog) throws SQLException { conn.setAutoCommit(false); conn.setTransactionIsolation(workConf.getIsolationMode()); Statement st = conn.createStatement(); for (Table catalog_tbl : catalog.getTables()) { LOG.debug(String.format("Deleting data from %s.%s", workConf.getDBName(), catalog_tbl.getName())); String sql = "DELETE FROM " + catalog_tbl.getEscapedName(); st.execute(sql); } conn.commit(); }
Source:
<code>protected void buildScript(int age) { <START> if (!DeviceUtil.isOnline() && OfflineManager.hasCompilation()) { <END> if (age == 0) { addPendingClient(new SearchClient()); addPendingClient(new OfflineCompilationClient()); } addPendingClient(new ContinueReadingClient()); if (age == 0) { addPendingClient(new RandomClient()); } } else { if (age == 0) { addPendingClient(new SearchClient()); addPendingClient(new AnnouncementClient()); } addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new ContinueReadingClient()); if (age == 0) { addPendingClient(new MainPageClient()); } addPendingClient(new BecauseYouReadClient()); if (age == 0) { addPendingClient(new RandomClient()); } } }</code><technical_language>Totally optional: tighten code a bit boolean for !DeviceUtil.isOnline() passing in a new param conditionallyAddPendingClient: void conditionallyAddPendingClient(FeedClient c, boolean cond) { if (cond) pendingClients.add(c); }</technical_language>

Target:
protected void buildScript(int age) { boolean online = DeviceUtil.isOnline(); conditionallyAddPendingClient(new SearchClient(), age == 0); conditionallyAddPendingClient(new OfflineCompilationClient(), age == 0 && !online); conditionallyAddPendingClient(new AnnouncementClient(), age == 0 && online); conditionallyAddPendingClient(new AggregatedFeedContentClient(), online); addPendingClient(new ContinueReadingClient()); conditionallyAddPendingClient(new MainPageClient(), age == 0 && online); conditionallyAddPendingClient(new BecauseYouReadClient(), online); conditionallyAddPendingClient(new RandomClient(), age == 0); }
Source:
<code>public void createLoansAccount(LoansPayload loansPayload) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManagerLoan.createLoansAccount(loansPayload) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<Loans>() { @Override public void onCompleted() { getMvpView().showProgressbar(false); } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); <START> getMvpView().showMessage(R.string.generic_failure_message, "fail"); <END> } @Override public void onNext(Loans loans) { getMvpView().showProgressbar(false); getMvpView().showMessage(R.string.loan_creation_success, "success"); } })); }</code><technical_language>Remove hard coded string</technical_language>

Target:
public void createLoansAccount(LoansPayload loansPayload) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManagerLoan.createLoansAccount(loansPayload) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<Loans>() { @Override public void onCompleted() { getMvpView().showProgressbar(false); } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showMessage(R.string.generic_failure_message); } @Override public void onNext(Loans loans) { getMvpView().showProgressbar(false); getMvpView().showMessage(R.string.loan_creation_success); } })); }
Source:
<code>public void errorSubscribeRace() throws Exception { for (int i = 0; i < 1000; i++) { final BehaviorProcessor<Object> p = BehaviorProcessor.create(); final TestSubscriber<Object> ts = new TestSubscriber<Object>(); final TestException ex = new TestException(); Runnable r1 = new Runnable() { @Override public void run() { p.subscribe(ts); } }; Runnable r2 = new Runnable() { @Override public void run() { p.onError(ex); } }; TestHelper.race(r1, r2); <START> ts.assertError(TestException.class); <END> } }</code><technical_language>assertFailure()? checks completion events emitted</technical_language>

Target:
public void errorSubscribeRace() throws Exception { for (int i = 0; i < 1000; i++) { final BehaviorProcessor<Object> p = BehaviorProcessor.create(); final TestSubscriber<Object> ts = new TestSubscriber<Object>(); final TestException ex = new TestException(); Runnable r1 = new Runnable() { @Override public void run() { p.subscribe(ts); } }; Runnable r2 = new Runnable() { @Override public void run() { p.onError(ex); } }; TestHelper.race(r1, r2); ts.assertFailure(TestException.class); } }
Source:
<code>private ActivityCommentMessage createMessage(UserDto sendingUser, UUID relatedUserAnonymizedId, IntervalActivity intervalActivityEntity, Optional<Message> repliedMessage, boolean isSentItem, String messageText) { ActivityCommentMessage message; <START> BuddyInfoParameters buddyInfoParameters = new BuddyInfoParameters(sendingUser.getId(), relatedUserAnonymizedId, <END> sendingUser.getPrivateData().getNickname(), sendingUser.getPrivateData().getUserPhotoId()); if (repliedMessage.isPresent()) { message = ActivityCommentMessage.createInstance(buddyInfoParameters, intervalActivityEntity, isSentItem, messageText, repliedMessage.get()); } else { message = ActivityCommentMessage.createThreadHeadInstance(buddyInfoParameters, intervalActivityEntity, isSentItem, messageText); } messageRepository.save(message); return message; }</code><technical_language>patch 10 lines, slight variations. create a createInstance methods BuddyMessageDto create instance of BuddyInfoParamaters for scenarios? solely based a user DTO, another user entity, another user DTO related user anonymized ID (that called here) a for sending "account deleted" message. takes long statements</technical_language>

Target:
private ActivityCommentMessage createMessage(UserDto sendingUser, UUID relatedUserAnonymizedId, IntervalActivity intervalActivityEntity, Optional<Message> repliedMessage, boolean isSentItem, String messageText) { ActivityCommentMessage message; BuddyInfoParameters buddyInfoParameters = BuddyMessageDto.createBuddyInfoParametersInstance(sendingUser, relatedUserAnonymizedId); if (repliedMessage.isPresent()) { message = ActivityCommentMessage.createInstance(buddyInfoParameters, intervalActivityEntity, isSentItem, messageText, repliedMessage.get()); } else { message = ActivityCommentMessage.createThreadHeadInstance(buddyInfoParameters, intervalActivityEntity, isSentItem, messageText); } messageRepository.save(message); return message; }
Source:
<code>private @Nullable ByteBuffer parsePacketISB(ByteBuffer pcapPacketHeader, int blockLength) throws IOException { ByteBuffer pcapPacketData; pcapPacketHeader.getInt(); pcapPacketHeader.getInt(); pcapPacketHeader.getInt(); pcapPacketData = ByteBuffer.allocate(blockLength - <START> 20); <END> pcapPacketData.clear(); SeekableByteChannel fFileChannel; ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); try { fFileChannel = getFileChannel(); fFileChannel.read(pcapPacketData); } catch (BadPcapFileException e) { } pcapPacketData.flip(); return pcapPacketData; }</code><technical_language>I 28 bytes read packet header (incorrectly...), read next block</technical_language>

Target:
private @Nullable ByteBuffer parsePacketISB(ByteBuffer pcapPacketHeader, int blockLength) throws IOException { ByteBuffer pcapPacketData; pcapPacketHeader.getInt(); pcapPacketHeader.getInt(); pcapPacketHeader.getInt(); pcapPacketData = ByteBuffer.allocate(blockLength - 20); pcapPacketData.clear(); SeekableByteChannel fileChannel; ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); try { fileChannel = getFileChannel(); fileChannel.read(pcapPacketData); } catch (BadPcapFileException e) { } pcapPacketData.flip(); return pcapPacketData; }
Source:
<code>public void leaseShouldExpireBeforeReapingLocks() { LeasableLockToken result = lock(REQUEST_1, LOCK_A).get(); assertThat(result.lease().isValid(service.identifiedTime())).isTrue(); <START> waitForTimeout(TimeLimit.of( <END> LockLeaseConstants.SERVER_LEASE_TIMEOUT.minus(LockLeaseConstants.BUFFER).toMillis())); assertThat(result.lease().isValid(service.identifiedTime())).isFalse(); assertLocked(LOCK_A); }</code><technical_language>in tests; recommend stubbing out time sleeping - tests unnecessarily long-running</technical_language>

Target:
public void leaseShouldExpireBeforeReapingLocks() { Leased<LockToken> result = lock(REQUEST_1, LOCK_A).get(); assertThat(result.lease().isValid(service.leaderTime())).isTrue(); waitForTimeout(TimeLimit.of( LockLeaseContract.CLIENT_LEASE_TIMEOUT.toMillis())); assertThat(result.lease().isValid(service.leaderTime())).isFalse(); assertLocked(LOCK_A); }
Source:
<code>public String configList(File workingDirectory, List<String> extraArgs) throws IOException, InterruptedException { List<String> args = new ArrayList<>(extraArgs); <START> args.remove("--json=false"); <END> args.add("-s"); return runCommand(workingDirectory, new String[]{"c", "ls", "--json"}, args); }</code><technical_language>work on: --json false --json false etc. I args.add("--json") removing "--json" line 82 do work</technical_language>

Target:
public String configList(File workingDirectory, List<String> extraArgs) throws IOException, InterruptedException { List<String> args = new ArrayList<>(extraArgs); args.add("-s"); args.add("--json"); return runCommand(workingDirectory, new String[]{"c", "ls"}, args); }
Source:
<code>public String toString() { String id = getNodeID() == null ? "" : getNodeID(); String addr64 = get64BitAddress() == null || get64BitAddress().equals(XBee64BitAddress.UNKNOWN_ADDRESS) ? "" : get64BitAddress().toString(); if (id.length() == 0 && addr64.length() == 0) <START> return super.toString(); <END> StringBuilder message = new StringBuilder(super.toString()); message.append(addr64); if (id.length() > 0) { message.append(" ("); message.append(id); message.append(")"); } message.append(" - "); return message.toString(); }</code><technical_language>This return connectionInterface.toString(); (and below)</technical_language>

Target:
public String toString() { String id = getNodeID() == null ? "" : getNodeID(); String addr64 = get64BitAddress() == null || get64BitAddress().equals(XBee64BitAddress.UNKNOWN_ADDRESS) ? "" : get64BitAddress().toString(); if (id.length() == 0 && addr64.length() == 0) return connectionInterface.toString(); StringBuilder message = new StringBuilder(connectionInterface.toString()); message.append(addr64); if (id.length() > 0) { message.append(" ("); message.append(id); message.append(")"); } message.append(" - "); return message.toString(); }
Source:
<code>private Node createClusterTree() { Node root = new Node(); root.setName("root"); root.setId(computeId("root")); root.setType(Types.ROOT.name()); for (String instance : _allInstances) { InstanceConfig insConfig = _instanceConfigMap.get(instance); LinkedHashMap<String, String> instanceTopologyMap = new LinkedHashMap<>(); if (computeInstanceTopologyMap(_clusterConfig, instance, insConfig, instanceTopologyMap)) { <START> int weight = insConfig.getWeight(); <END> if (weight < 0 || weight == InstanceConfig.WEIGHT_NOT_SET) { weight = DEFAULT_NODE_WEIGHT; } addEndNode(root, instance, instanceTopologyMap, weight, _liveInstances); } } return root; }</code><technical_language>I suggest Map interface type</technical_language>

Target:
private Node createClusterTree() { Node root = new Node(); root.setName("root"); root.setId(computeId("root")); root.setType(Types.ROOT.name()); for (String instanceName : _allInstances) { InstanceConfig insConfig = _instanceConfigMap.get(instanceName); try { LinkedHashMap<String, String> instanceTopologyMap = computeInstanceTopologyMap(_clusterConfig.isTopologyAwareEnabled(), instanceName, insConfig, _clusterTopologyKeys); int weight = insConfig.getWeight(); if (weight < 0 || weight == InstanceConfig.WEIGHT_NOT_SET) { weight = DEFAULT_NODE_WEIGHT; } addEndNode(root, instanceName, instanceTopologyMap, weight, _liveInstances); } catch (IllegalArgumentException e) { if (isInstanceEnabled(_clusterConfig, instanceName, insConfig)) { throw e; } else { logger .warn("Topology setting for instance is unset or invalid, ignore the instance!", insConfig.getDomainAsString(), instanceName); } } } return root; }
Source:
<code>public boolean isSelected() { <START> return (this.selected); <END> }</code><technical_language>add braces</technical_language>

Target:
public boolean isSelected() { return this.selected; }
Source:
<code>private void addMultiPointMethods(ParameterSignature sig, List<PotentialAssignment> list) throws Throwable { for (FrameworkMethod dataPointsMethod : getDataPointsMethods(sig)) { Class<?> returnType = dataPointsMethod.getReturnType(); if (returnType.isArray() && sig.canPotentiallyAcceptType(returnType.getComponentType())) { try { addArrayValues(sig, dataPointsMethod.getName(), list, dataPointsMethod.invokeExplosively(null)); } catch (Throwable t) { DataPoints annotation = dataPointsMethod.getAnnotation(DataPoints.class); <START> if (annotation != null) { <END> for (Class<? extends Throwable> ignored : annotation.ignoredExceptions()) { if (ignored.isAssignableFrom(t.getClass())) { return; } } } throw t; } } } }</code><technical_language>This is second, slightly different, version of this logic. extract a shared location? Thanks</technical_language>

Target:
private void addMultiPointMethods(ParameterSignature sig, List<PotentialAssignment> list) throws Throwable { for (FrameworkMethod dataPointsMethod : getDataPointsMethods(sig)) { Class<?> returnType = dataPointsMethod.getReturnType(); if (returnType.isArray() && sig.canPotentiallyAcceptType(returnType.getComponentType())) { try { addArrayValues(sig, dataPointsMethod.getName(), list, dataPointsMethod.invokeExplosively(null)); } catch (Throwable throwable) { DataPoints annotation = dataPointsMethod.getAnnotation(DataPoints.class); if (annotation != null && isAssignableToAnyOf(annotation.ignoredExceptions(), throwable)) { return; } else { throw throwable; } } } } }
Source:
<code>public boolean hasExplicitWriteIndex() { <START> return writeAlias != null && ! writeAlias.isEmpty(); <END> }</code><technical_language>space ! (several occurrences). StringUtils.isEmpty instead</technical_language>

Target:
public boolean hasExplicitWriteIndex() { return StringUtils.isNotBlank(writeAlias); }
Source:
<code>private void addTypes(List<String> files, List<SymbolAction> actions, Node node) { <START> Iterator<String> it = files.iterator(); <END> while(it.hasNext()) { String next = it.next(); if (next.endsWith(".class")) { String[] split = next.split("\\$\\d"); if (split.length == 1) { String asClass = next.replaceAll(File.separator, "\\."); String fullName = asClass.substring(0, asClass.length() - 6); addType(fullName, false, node, actions); } } } }</code><technical_language>other places: for loop instead of explicit iterator</technical_language>

Target:
private void addTypes(List<String> files, List<SymbolAction> actions, Node node) { for (String classFile: files) { if (isClassFile(classFile) && !isAnonymousClass(classFile)) { String asClass = classFile.replaceAll(File.separator, "\\."); String fullName = asClass.substring(0, asClass.length() - 6); addType(fullName, false, node, actions); } } }
Source:
<code>protected Object encodeCommand(Command command) { initDevicePassword(command, defaultDevicePassword); <START> String cmd = ""; <END> switch (command.getType()) { case Command.TYPE_CUSTOM: cmd = formatCommand(command, "${%s}", Command.KEY_DATA); break; case Command.TYPE_POSITION_SINGLE: cmd = formatCommand(command, "$AVREQ,{%s},1", Command.KEY_DEVICE_PASSWORD); break; case Command.TYPE_REBOOT_DEVICE: cmd = formatCommand(command, "$AVRESET,{%s},{%s}", Command.KEY_UNIQUE_ID, Command.KEY_DEVICE_PASSWORD); break; default: break; } if (cmd.length() > 0) { cmd += Checksum.nmea(cmd) + "\r\n"; return cmd; } return null; }</code><technical_language>full words</technical_language>

Target:
protected Object encodeCommand(Command command) { initDevicePassword(command, LaipacProtocolDecoder.DEFAULT_DEVICE_PASSWORD); switch (command.getType()) { case Command.TYPE_CUSTOM: return formatCommand(command, "{%s}", Command.KEY_DATA); case Command.TYPE_POSITION_SINGLE: return formatCommand(command, "AVREQ,{%s},1", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_REBOOT_DEVICE: return formatCommand(command, "AVRESET,{%s},{%s}", Command.KEY_UNIQUE_ID, Command.KEY_DEVICE_PASSWORD); default: return null; } }
Source:
<code>default Mono<ResponseEntity<Problem>> handleAuthentication(final AuthenticationException e, final ServerWebExchange request) { <START> if (e instanceof AuthenticationServiceException) { <END> return handleAuthenticationService((AuthenticationServiceException) e, request); } return create(UNAUTHORIZED, e, request); }</code><technical_language>Spring do this for automatically AuthenticationServiceException is more specific</technical_language>

Target:
default Mono<ResponseEntity<Problem>> handleAuthentication(final AuthenticationException e, final ServerWebExchange request) { return create(UNAUTHORIZED, e, request); }
Source:
<code>public String getReviewer() { final String footer = getFooter(); if (footer == null) { <START> return null; <END> } return footer.split(" on ")[0].trim(); }</code><technical_language>this happen? if so, throw exception? Try of java.util.Optional.ofNullable</technical_language>

Target:
public Optional<String> getReviewer() { return getFooter().map(footer -> footer.split(" on ")[0].trim()); }
Source:
<code>public void testDiffResults() throws Exception { <START> TestUtills.runRepairabilityPrint("ALL", "/dataset/commons-lang/"); <END> }</code><technical_language>/dataset/commons-lang/ pass CI test this repo is present local machine right error thrown CI server. repogit4testv0 maybe</technical_language>

Target:
public void testDiffResults() throws Exception { int count=0; FinalResult result = TestUtills.runRepairabilityGit("ALL", "repogit4testv0"); Map<IRevision, RevisionResult> revisionsMap = result.getAllResults(); assertEquals(13, revisionsMap.keySet().size()); for (Map.Entry<IRevision, RevisionResult> entry : revisionsMap.entrySet()) { RevisionResult rr = entry.getValue(); PatternInstancesFromRevision instances = (PatternInstancesFromRevision) rr.getResultFromClass(RepairabilityAnalyzer.class); List<DiffRow> row_list = instances.getRow_list(); switch (count){ case 1: assertEquals(row_list,null); case 9: assertEquals(row_list,null); case 2: assertEquals(row_list,"[[INSERT,, ], [INSERT,,package org.apache.commons.lang3;], [EQUAL,,], [INSERT,, ], [INSERT,,public class CharSequenceUtils {], [INSERT,,], [INSERT,, private static final int NOT_FOUND = -1;], [INSERT,,], [INSERT,, ], [INSERT,, public CharSequenceUtils() {], [INSERT,, super();], [INSERT,, }], [INSERT,,], [INSERT,, } } }
Source:
<code>public void traceUpdated(final TmfTraceUpdatedSignal signal) { if (signal.getTrace() == fTrace) { <START> setStartTime(fTrace.getStartTime().toNanos()); setEndTime(fTrace.getEndTime().toNanos()); refresh(); <END> } }</code><technical_language>setTimeBoundsAndRefresh()</technical_language>

Target:
public void traceUpdated(final TmfTraceUpdatedSignal signal) { if (signal.getTrace() == fTrace) { setTimeBoundsAndRefresh(); } }
Source:
<code>public void navigateToTitle(@NonNull PageTitle title, boolean inNewTab, int position) { if (!isAdded()) { return; } funnel.searchClick(position, searchLanguageCode); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_SEARCH); startActivity(inNewTab ? PageActivity.newIntentForNewTab(requireContext(), historyEntry, historyEntry.getTitle()) <START> : invokeSource == PAGE_ACTION_TAB ? PageActivity.newIntentForCurrentTab(requireContext(), historyEntry, historyEntry.getTitle(), false) <END> : PageActivity.newIntentForExistingTab(requireContext(), historyEntry, historyEntry.getTitle())); closeSearch(); }</code><technical_language>correctly fixing issue passing false squashBackstack parameter. do want do for PAGE_ACTION_TAB, for other cases</technical_language>

Target:
public void navigateToTitle(@NonNull PageTitle title, boolean inNewTab, int position) { if (!isAdded()) { return; } funnel.searchClick(position, searchLanguageCode); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_SEARCH); startActivity(inNewTab ? PageActivity.newIntentForNewTab(requireContext(), historyEntry, historyEntry.getTitle()) : PageActivity.newIntentForCurrentTab(requireContext(), historyEntry, historyEntry.getTitle(), false)); closeSearch(); }
Source:
<code>public DockerConnection query(String name, Object... values) { if (name == null) { <START> throw new IllegalArgumentException("Name is null"); <END> } if (values == null) { throw new IllegalArgumentException("Values are null"); } for (Object value : values) { if (value == null) { throw new IllegalArgumentException("Value is null"); } if (query.length() > 0) { query.append('&'); } query.append(name).append('=').append(value.toString()); } return this; }</code><technical_language><code>NullPointerException</code> thrown in this case, _60 Item_ _Effective Java 2nd ed_. Basically says: > If a caller passes null in some parameter for null values prohibited, convention dictates NullPointerException thrown IllegalArgumentException</technical_language>

Target:
public DockerConnection query(String name, Object... values) { if (name == null) { throw new NullPointerException("Name is null"); } if (values == null) { throw new NullPointerException("Values are null"); } for (Object value : values) { if (value == null) { throw new NullPointerException("Value is null"); } if (query.length() > 0) { query.append('&'); } query.append(name).append('=').append(value.toString()); } return this; }
Source:
<code>private void visitCatchBlock(DetailAST catchAst) { if (isEmptyCatchBlock(catchAst)) { final String commentContent = getCommentFirstLine(catchAst); if (isVerifiable(catchAst, commentContent)) { <START> log(EmptyBlockCheck.findLeftCurly(catchAst), MSG_KEY_CATCH_BLOCK_EMPTY); <END> } } }</code><technical_language>This is ok Checks depends other. do need method fuctrionality, please create local static method find SLIST token of catch block</technical_language>

Target:
private void visitCatchBlock(DetailAST catchAst) { if (isEmptyCatchBlock(catchAst)) { final String commentContent = getCommentFirstLine(catchAst); if (isVerifiable(catchAst, commentContent)) { log(catchAst.findFirstToken(TokenTypes.SLIST), MSG_KEY_CATCH_BLOCK_EMPTY); } } }
Source:
<code>private void tick() { recordCounter("tick", 1); final Instant now = _clock.instant(); if (_schedule.nextRun(_lastRun).map(run -> run.isBefore(now)).orElse(true)) { final LocalDate startDate = ZonedDateTime.ofInstant(now, _clock.getZone()).toLocalDate(); <START> final LocalDate endDate = startDate.plusDays(_lookahead); <END> final CreateForRange createPartitions = new CreateForRange.Builder() .setStart(startDate) .setEnd(endDate) .build(); getSelf().tell(createPartitions, getSelf()); } }</code><technical_language>nit: rename _lookahead _lookAheadDays</technical_language>

Target:
private void tick() { recordCounter("tick", 1); final Instant now = _clock.instant(); if (_schedule.nextRun(_lastRun).map(run -> run.isBefore(now)).orElse(true)) { final LocalDate startDate = ZonedDateTime.ofInstant(now, ZoneOffset.UTC).toLocalDate(); final LocalDate endDate = startDate.plusDays(_lookaheadDays); final CreateForRange createPartitions = new CreateForRange.Builder() .setStart(startDate) .setEnd(endDate) .build(); getSelf().tell(createPartitions, ActorRef.noSender()); } }
Source:
<code>public ASTValue eval(WordsEnvironment environment) throws WordsRuntimeException { ASTValue referenceObject = children.get(0).eval(environment); ASTValue identifier = children.get(1).eval(environment); AST message = children.get(2); ASTValue doNow = children.get(3) != null ? children.get(3).eval(environment) : null; WordsObject object; if (referenceObject.type.equals(ASTValue.ValueType.OBJ)){ WordsProperty property = referenceObject.objValue.getProperty(identifier.stringValue); if (property.type != WordsProperty.PropertyType.OBJECT) { throw new WordsInvalidTypeException(ASTValue.ValueType.OBJ.toString(), property.type.toString()); } object = property.objProperty; } else { object = environment.getObject(identifier.stringValue); } if (object == null) { <START> throw new WordsObjectNotFoundException(identifier.stringValue); <END> } WordsSay action = new WordsSay(message); if (doNow == null) { object.enqueueAction(action); } else { object.enqueueActionAtFront(action); } return null; }</code><technical_language>WordsEnvironment.getObject() throw this error if object found</technical_language>

Target:
public ASTValue eval(WordsEnvironment environment) throws WordsRuntimeException { ASTValue referenceObject = children.get(0).eval(environment); ASTValue identifier = children.get(1).eval(environment); AST message = children.get(2); ASTValue doNow = children.get(3) != null ? children.get(3).eval(environment) : null; WordsObject object; if (referenceObject.type.equals(ASTValue.ValueType.OBJ)){ WordsProperty property = referenceObject.objValue.getProperty(identifier.stringValue); if (property.type != WordsProperty.PropertyType.OBJECT) { throw new WordsInvalidTypeException(ASTValue.ValueType.OBJ.toString(), property.type.toString()); } object = property.objProperty; } else { object = environment.getObject(identifier.stringValue); } WordsSay action = new WordsSay(message); if (doNow == null) { object.enqueueAction(action); } else { object.enqueueActionAtFront(action); } return null; }
Source:
<code>void doesNotReopenCDataWithinCDataContent() throws Exception { UniqueId uniqueId = engineDescriptor.getUniqueId().append("test", "test"); engineDescriptor.addChild(new TestDescriptorStub(uniqueId, "test")); TestPlan testPlan = TestPlan.from(singleton(engineDescriptor)); XmlReportData reportData = new XmlReportData(testPlan, Clock.systemDefaultZone()); AssertionError assertionError = new AssertionError("<foo><![CDATA[bar]]></foo>"); reportData.markFinished(testPlan.getTestIdentifier(uniqueId.toString()), failed(assertionError)); <START> Writer assertingNullWriter = new Writer() { @Override public void write(char[] cbuf, int off, int len) { assertThat(new String(cbuf, off, len)) .doesNotContain("]]><![CDATA["); } @Override public void flush() { } @Override public void close() { } }; <END> writeXmlReport(testPlan, reportData, assertingNullWriter); }</code><technical_language>Please replace block following. java Writer assertingWriter = new StringWriter() { @Override public void write(char[] cbuf, int off, int len) { assertThat(new String(cbuf, off, len)).doesNotContain("]]><![CDATA["); } };</technical_language>

Target:
void doesNotReopenCDataWithinCDataContent() throws Exception { UniqueId uniqueId = engineDescriptor.getUniqueId().append("test", "test"); engineDescriptor.addChild(new TestDescriptorStub(uniqueId, "test")); TestPlan testPlan = TestPlan.from(singleton(engineDescriptor)); XmlReportData reportData = new XmlReportData(testPlan, Clock.systemDefaultZone()); AssertionError assertionError = new AssertionError("<foo><![CDATA[bar]]></foo>"); reportData.markFinished(testPlan.getTestIdentifier(uniqueId.toString()), failed(assertionError)); Writer assertingWriter = new StringWriter() { @Override public void write(char[] cbuf, int off, int len) { assertThat(new String(cbuf, off, len)).doesNotContain("]]><![CDATA["); } }; writeXmlReport(testPlan, reportData, assertingWriter); }
Source:
<code>private Element createSharedPoolElement(Document doc, String poolName, ServerSideConfiguration.Pool pool) { Element poolElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + COLON + SHARED_POOL_ELEMENT_NAME); poolElement.setAttribute(NAME_ATTRIBUTE_NAME, poolName); String from = pool.getServerResource(); <START> if (!(from == null || from.trim().length() == 0)) { <END> poolElement.setAttribute(FROM_ATTRIBUTE_NAME, from); } long memoryInBytes = MemoryUnit.B.convert(pool.getSize(), MemoryUnit.B); poolElement.setAttribute(UNIT_ATTRIBUTE_NAME, MemoryUnit.B.toString()); poolElement.setTextContent(Long.toString(memoryInBytes)); return poolElement; }</code><technical_language>declaring strings of white space characters requesting default pool</technical_language>

Target:
private Element createSharedPoolElement(Document doc, String poolName, ServerSideConfiguration.Pool pool) { Element poolElement = doc.createElement(TC_CLUSTERED_NAMESPACE_PREFIX + COLON + SHARED_POOL_ELEMENT_NAME); poolElement.setAttribute(NAME_ATTRIBUTE_NAME, poolName); String from = pool.getServerResource(); if (from != null) { if (from.trim().length() == 0) { throw new XmlConfigurationException("Resource pool name can not be empty."); } poolElement.setAttribute(FROM_ATTRIBUTE_NAME, from); } long memoryInBytes = MemoryUnit.B.convert(pool.getSize(), MemoryUnit.B); poolElement.setAttribute(UNIT_ATTRIBUTE_NAME, MemoryUnit.B.toString()); poolElement.setTextContent(Long.toString(memoryInBytes)); return poolElement; }
Source:
<code>public String getApiCall(int startingPoint, String channelId, DateTime dateTime) { DateTimeFormatter formatter = DateTimeFormat.forPattern("y-M-d'T'hh:mm:ss'Z'"); String baseUri = "<LINK_0>" + "?expand=watchable&from_time=%s&until_time=%s"; if (timeFrame == TimeFrame.TODAY) { DateTime todayStartDateTime = dateTime.withTimeAtStartOfDay(); DateTime todayEndDateTime = todayStartDateTime .plusDays(1) .withTimeAtStartOfDay() <START> .minusMinutes(1); <END> String todayStart = todayStartDateTime.toString(formatter); String todayFinish = todayEndDateTime.toString(formatter); return String.format(baseUri, channelId, todayStart, todayFinish); } else if (timeFrame == TimeFrame.PLUS_MINUS_7_DAYS) { DateTime weekAgo = dateTime.minusDays(7); DateTime weekAhead = weekAgo.plusDays(14); String sevenDaysAgo = weekAgo.toString(formatter); String sevenDaysAhead = weekAhead.toString(formatter); return String.format(baseUri, channelId, sevenDaysAgo, sevenDaysAhead); } else { return String.format("%s/shows?offset=%d&limit=%d", BASE_API_URL, startingPoint, LIMIT); } }</code><technical_language>minusMinutes(1) .minusMillis(1)? if API considers date exclusive (needs checking) need subtract anything. set next midnight</technical_language>

Target:
String getApiCall(int startingPoint, String channelId, DateTime dateTime) { DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis(); String baseUri = "<LINK_0>" + "?expand=watchable&from_time=%s&until_time=%s"; if (timeFrame == TimeFrame.TODAY) { DateTime todayStartDateTime = dateTime .withTimeAtStartOfDay() .withZone(DateTimeZone.UTC); DateTime todayEndDateTime = todayStartDateTime .plusDays(1) .withTimeAtStartOfDay() .minusSeconds(1); String todayStart = todayStartDateTime.toString(formatter); String todayFinish = todayEndDateTime.toString(formatter); return String.format(baseUri, channelId, todayStart, todayFinish); } else if (timeFrame == TimeFrame.PLUS_MINUS_7_DAYS) { DateTime weekAgo = dateTime.minusDays(7); DateTime weekAhead = weekAgo.plusDays(14); String sevenDaysAgo = weekAgo.toString(formatter); String sevenDaysAhead = weekAhead.toString(formatter); return String.format(baseUri, channelId, sevenDaysAgo, sevenDaysAhead); } else { return String.format( "%s/shows?offset=%d&limit=%d", BASE_API_URL, startingPoint, LIMIT ); } }